Skip to content

sqlite: add AsyncDatabase - #34863

Open
ninjaasmoke wants to merge 11 commits into
oven-sh:mainfrom
ninjaasmoke:claude/async-sqlite
Open

ninjaasmoke wants to merge 11 commits into
oven-sh:mainfrom
ninjaasmoke:claude/async-sqlite

Conversation

@ninjaasmoke

Copy link
Copy Markdown

What does this PR do?

Fixes #978

bun:sqlite executes every statement on the calling thread. A query that runs
long — a big aggregate, a slow join — blocks the isolate's event loop for its
full duration, and wrapping the call in a Promise would not change that, since
the work still runs where it was called.

This adds AsyncDatabase, a separate connection type that runs the SQLite work
on Bun's WorkPool. It opens its own sqlite3* and shares no handle, cache, or
statement with Database. The synchronous Database/Statement path is
unchanged — no async branch, lock, or allocation was added to it. The surface is
the usual open/exec/run/get/all/values/close plus async disposal,
with per-operation AbortSignal and strict/safeIntegers options.

Each async connection owns one sqlite3*, a bounded FIFO, and an
active-operation ID; only the FIFO head runs at a time. Bindings are copied off
JS values before admission, and rows and errors are copied out of SQLite before
finalize, so a WorkPool job holds no Promise, JSValue, VM, global object, or
event-loop pointer. Completion is routed back by
ScriptExecutionContextIdentifier, which is what lets an operation outlive a
force-terminated Worker: the VM can be gone before the job finishes, and the job
never dereferences it. Cancellation removes a queued operation by ID, or
interrupts a running one only while that same ID owns the active slot. Close
fences admission, drains accepted work, and closes once.

The bun:sqlite (173) and node:sqlite (112) suites pass unchanged, alongside
ASAN, VM-destruction, Worker-teardown, GC, and close/cancel-race checks.

Availability, five-run release medians — one slow query while 100 /ping
requests hit the same server:

mode slow query pings during query ping p50 ping p95
synchronous Database 419.08 ms 0 / 100 419.93 ms 426.42 ms
AsyncDatabase 417.30 ms 100 / 100 3.87 ms 15.44 ms

Same query time; the sync server completes zero pings before it returns, the
async server all 100.

Full technical write-up: Async SQLite design and performance

Note: Parts of this PR were co-authored with GitHub Copilot (GPT-5.6).

How did you verify your code works?

The full bun:sqlite suite was run under debug ASAN with JSC exception checks and forced VM destruction:

BUN_JSC_validateExceptionChecks=1 \
BUN_JSC_dumpSimulatedThrows=1 \
BUN_DESTRUCT_VM_ON_EXIT=1 \
bun bd -j2 test test/js/bun/sqlite/sqlite.test.js --timeout 60000

173 passed, 0 failed.

The new coverage includes FIFO ordering, queue limits, copied bindings, open and close races, GC, natural and explicit process exit, running and queued cancellation, cancellation versus close, lock contention, result ownership, and repeated Worker termination with active and queued work.

The existing compatibility and type suites also pass:

• node:sqlite : 112 passed, 4 expected skips, 0 failed
• bun-types: 13 passed, 0 failed
• rust:check  and  rust:check-all 
• Darwin lazy-SQLite compile path
• LLVM 21 C++ formatting, Rust formatting, Prettier, and  git diff --check 

The availability numbers above come from five runs of the non-LTO release build. The synchronous and async servers execute the same recursive query and validate the same result.

@ninjaasmoke
ninjaasmoke requested a review from alii as a code owner July 20, 2026 23:49

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The change adds Bun’s asynchronous SQLite API, including native worker execution, FIFO scheduling, cancellation, lifecycle management, typed declarations, documentation, comprehensive tests, and benchmarks comparing event-loop and HTTP availability.

Changes

Asynchronous SQLite API

Layer / File(s) Summary
Public API contract
packages/bun-types/sqlite.d.ts, src/js/bun/sqlite.ts, docs/runtime/sqlite.mdx
Adds AsyncDatabase, async query methods, open options, cancellation, queue limits, closing, and async disposal.
Native data and SQLite contracts
src/jsc/bindings/sqlite/AsyncSQLiteDatabase.h, src/jsc/bindings/sqlite/JSSQLStatement.*, src/jsc/bindings/sqlite/lazy_sqlite3.h
Defines native result, binding, connection, cancellation, error, and dynamically loaded SQLite interfaces.
Runtime and scheduler wiring
src/jsc/AsyncSQLiteTask.rs, src/js/internal-for-testing.ts, src/jsc/lib.rs, src/jsc/bindings/..., scripts/build/unified.ts
Connects native jobs to the work pool, JavaScript bindings, global teardown, testing hooks, build isolation, and private identifiers.
Native execution and lifecycle
src/jsc/bindings/sqlite/AsyncSQLiteDatabase.cpp
Implements FIFO connection execution, binding snapshots, result materialization, cancellation, interruption, promise settlement, cleanup, and host functions.
API and native behavior validation
test/integration/bun-types/fixture/sqlite.ts, test/js/bun/sqlite/sqlite.test.js
Adds type assertions and coverage for API semantics, queueing, lifecycle, cancellation, teardown, owned results, errors, and bindings.
SQLite availability benchmarks
bench/sqlite/*
Adds sync, worker-backed, and async SQLite benchmarks measuring throughput, timer availability, HTTP responsiveness, and latency percentiles.

Suggested reviewers: alii

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR implements an async SQLite API backed by a thread pool alongside the synchronous interface, matching #978.
Out of Scope Changes check ✅ Passed The changes appear focused on async SQLite support, tests, docs, types, and build wiring needed for that feature.
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding AsyncDatabase to sqlite.
Description check ✅ Passed The description matches the required template and includes both the PR summary and verification details.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@bench/sqlite/http-availability.js`:
- Line 2: Update the serverPath initialization to convert the file URL with
fileURLToPath() rather than reading URL.pathname, ensuring the resulting path is
OS-correct for Bun.spawn’s cmd invocation. Add or reuse the appropriate
URL-to-path import while preserving the existing http-availability server
target.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 79a1d644-c8fa-4e20-9033-f46d8f9fc134

📥 Commits

Reviewing files that changed from the base of the PR and between a4c1ddd and 82b4156.

📒 Files selected for processing (23)
  • bench/sqlite/async-availability-worker.js
  • bench/sqlite/async-availability.js
  • bench/sqlite/http-availability-server.js
  • bench/sqlite/http-availability.js
  • docs/runtime/sqlite.mdx
  • packages/bun-types/sqlite.d.ts
  • scripts/build/unified.ts
  • src/js/builtins/BunBuiltinNames.h
  • src/js/bun/sqlite.ts
  • src/js/internal-for-testing.ts
  • src/jsc/AsyncSQLiteTask.rs
  • src/jsc/bindings/ErrorCode.ts
  • src/jsc/bindings/ZigGlobalObject.cpp
  • src/jsc/bindings/sqlite/AsyncSQLiteDatabase.cpp
  • src/jsc/bindings/sqlite/AsyncSQLiteDatabase.h
  • src/jsc/bindings/sqlite/JSSQLStatement.cpp
  • src/jsc/bindings/sqlite/JSSQLStatement.h
  • src/jsc/bindings/sqlite/lazy_sqlite3.h
  • src/jsc/bindings/webcore/DOMClientIsoSubspaces.h
  • src/jsc/bindings/webcore/DOMIsoSubspaces.h
  • src/jsc/lib.rs
  • test/integration/bun-types/fixture/sqlite.ts
  • test/js/bun/sqlite/sqlite.test.js

Comment thread bench/sqlite/http-availability.js Resolved
@ninjaasmoke

Copy link
Copy Markdown
Author

@alii could you please start a @claude review

@ninjaasmoke ninjaasmoke changed the title Add async SQLite support and connection management sqlite: add AsyncDatabase Jul 25, 2026
@robobun

robobun commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

A note on one overlap with #43281.

snapshotBindingValue in src/jsc/bindings/sqlite/AsyncSQLiteDatabase.cpp mirrors the number dispatch of rebindValue in JSSQLStatement.cpp: value.isAnyInt() gives Integer, and any other number gives Double. isAnyInt() is JSC's Int52 test, so an integer from 2^51 to 2^53-1 binds as REAL. SELECT typeof(?) returns 'real' for 2 ** 51.

#43281 changes the sync path to value.isInt32(), then JSC::isSafeInteger() with -0 kept as REAL. If both PRs land, the async path needs the same test. Without it, the two APIs bind such a value in different ways.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Asynchronous SQLite API

2 participants