Skip to content

sql(sqlite): serialize queries behind an open transaction - #33581

Closed
robobun wants to merge 9 commits into
mainfrom
farm/d82cb17e/sqlite-sql-begin-isolation
Closed

robobun wants to merge 9 commits into
mainfrom
farm/d82cb17e/sqlite-sql-begin-isolation

Conversation

@robobun

@robobun robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator

What

Bun.SQL with the SQLite adapter shares a single underlying connection across the whole handle, but sql.begin() ran with no isolation from the rest of the process. A query issued on the outer handle while a begin() callback was awaiting ran directly on the same connection, interleaving with the open transaction.

Reproduction

const sql = new Bun.SQL(":memory:");
await sql`create table t(v)`;

const txn = sql
  .begin(async tx => {
    await tx`insert into t values ('inside')`;
    await Bun.sleep(20);
    throw new Error("business-logic rollback");
  })
  .catch(() => {});

await Bun.sleep(5);
// unrelated work on the same handle, awaited to success:
await sql`insert into t values ('outside')`;
console.log("mid_read      ", (await sql`select v from t`).map(r => r.v));
// => [ "inside", "outside" ]   <-- dirty read of the txn's uncommitted row

await txn;
console.log("after_rollback", (await sql`select v from t`).map(r => r.v));
// => []   <-- the fulfilled 'outside' insert was silently rolled back

Three symptoms, all from the same cause:

  • an awaited, fulfilled write on the outer handle is silently erased by the transaction's rollback
  • outer reads observe the transaction's uncommitted rows (dirty read)
  • a second concurrent begin() rejects with "cannot start a transaction within a transaction" instead of queuing

Cause

SQLiteAdapter.connect() handed the single connection to every caller synchronously. Nothing marked it as held while a transaction was in flight, and begin() acquired it with useReserved = false.

Fix

begin() now holds the single connection exclusively (via a new supportsTransactionReservation() adapter hook, so Postgres/MySQL are unaffected). While a transaction holds the connection, connect() distinguishes:

  • Concurrent acquisitions (from another task): queued in FIFO order and drained on release(). The repro above now serializes the outer write after the rollback, so it survives.
  • Nested acquisitions (the outer sql handle used from inside the callback's own async context, e.g. a helper closing over the module-level sql): detected with AsyncLocalStorage and allowed to participate in the open transaction as before. A nested outer-handle sql.begin() rejects with ERR_SQLITE_INVALID_TRANSACTION_STATE instead of queueing and deadlocking.

sql.reserve() stays unsupported on SQLite (supportsReservedConnections() is still false); with only one connection a tx.reserve() could never acquire a second one, so the existing rejection is preserved.

Verification

bun bd test test/js/sql/sqlite-sql.test.ts is 236/236 under debug+ASAN.

New tests in the existing SQLite SQL suite:

  • outer queries do not interleave with an open transaction (no dirty read, no lost write)
  • a second begin() queues behind the first instead of erroring
  • reserve() inside a transaction rejects instead of hanging
  • outer-handle query from inside the callback participates in the transaction (does not deadlock)
  • outer-handle begin() from inside the callback rejects instead of hanging

The serialization tests fail on the unfixed build and pass with the fix. Also scaled the pre-existing 10k-iteration prepared-statement test down under isDebug so the file is green under debug+ASAN (it timed out on main too).

@github-actions github-actions Bot added the claude label Jul 7, 2026
@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:18 PM PT - Jul 8th, 2026

❌ @robobun, your commit 5eac0f2 has 4 failures in Build #70810 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33581

That installs a local version of the PR into your bun-33581 executable, so you can run:

bun-33581 --bun

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: cb10572e-47b1-4284-95b5-481db7c5abb1

📥 Commits

Reviewing files that changed from the base of the PR and between 38e8d40 and 5eac0f2.

📒 Files selected for processing (2)
  • src/js/internal/sql/sqlite.ts
  • test/js/sql/sqlite-sql.test.ts

Walkthrough

SQLite transaction handling now uses adapter capability hooks plus reservation-aware connection queuing to serialize transactions on the single SQLite connection. SQL transaction entry points select the new capability, transaction callbacks can run in a transaction context, and tests cover the updated ordering and rejection behavior.

Changes

SQLite transaction reservation flow

Layer / File(s) Summary
Adapter hooks and transaction selection
src/js/internal/sql/shared.ts, src/js/bun/sql.ts
Adds optional adapter hooks for transaction reservation and transaction-context execution, and updates beginDistributed/begin to prefer the new reservation capability when choosing reserved access.
Transaction callback context
src/js/bun/sql.ts
Runs transaction callbacks through a runCallback wrapper and dispatches them through pool.runInTransactionContext() when available.
SQLite reservation queueing
src/js/internal/sql/sqlite.ts
Adds reservation state, FIFO queued acquisitions, async transaction-context tracking, reservation-aware connect() routing, queue draining on release, and close-time rejection of pending acquisitions.
SQLite transaction serialization tests
test/js/sql/sqlite-sql.test.ts
Adds coverage for serialized transaction execution, nested reservation and nested transaction rejection, transaction-context participation, context leakage, queued acquisition draining, and a reduced debug-only stress iteration count.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: serializing SQLite queries during an open transaction.
Description check ✅ Passed The description covers the PR purpose and verification clearly, with all required information present despite using different headings than the template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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: 3

🤖 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 `@src/js/internal/sql/sqlite.ts`:
- Around line 485-496: Queued acquisition failures in the connection-close path
are using a plain Error instead of the same coded SQLiteError used elsewhere.
Update the close-handling logic in the connection queue cleanup so the pending
callbacks in the connect queue receive connectionClosedError() (the same error
shape used by connect() and `#drainConnectQueue`()), ensuring the rejection
carries code: "ERR_SQLITE_CONNECTION_CLOSED" consistently.

In `@test/js/sql/sqlite-sql.test.ts`:
- Around line 1888-1908: Dispose the locally created SQL instance in the reserve
test: the `new SQL("sqlite://:memory:")` handle inside `test("reserve gives
exclusive use of the connection", ...)` is never cleaned up, so switch it to
`await using` (or equivalent try/finally disposal) so the connection is released
even if an assertion fails. Keep the rest of the test logic unchanged and ensure
the cleanup applies to the local `sql` symbol in that test body.
- Around line 1154-1161: The transaction test relies on timing via Bun.sleep
instead of a deterministic handoff. Update the sql.begin() scenario in
sqlite-sql.test.ts to use an explicit deferred promise inside the transaction
callback so the outer write waits on the real transaction boundary, and remove
the sleep-based padding around the rollback/write sequence. Keep the assertion
flow in the same test case, using the existing sql.begin and awaited UPDATE path
as the key symbols to anchor the change.
🪄 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: 23901b07-82b9-44d0-9239-c71c7beb2c97

📥 Commits

Reviewing files that changed from the base of the PR and between a780f57 and 339eb27.

📒 Files selected for processing (2)
  • src/js/internal/sql/sqlite.ts
  • test/js/sql/sqlite-sql.test.ts

Comment thread src/js/internal/sql/sqlite.ts Resolved
Comment thread test/js/sql/sqlite-sql.test.ts Resolved
Comment thread test/js/sql/sqlite-sql.test.ts Resolved
Comment thread src/js/internal/sql/sqlite.ts Resolved
Comment thread test/js/sql/sqlite-sql.test.ts Resolved
@robobun
robobun force-pushed the farm/d82cb17e/sqlite-sql-begin-isolation branch from 339eb27 to 0214098 Compare July 7, 2026 00:59
@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

CodeRabbit's walkthrough above is stale (it summarized the first push and then hit a rate limit). In the current commit 0214098, supportsReservedConnections() still returns false for SQLite and sql.reserve() still rejects; only the new supportsTransactionReservation() hook is true, which is what the PR body describes.

@robobun

robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is ready. The only red CI lane is darwin-26 aarch64 test-bun failing on buildkite-agent artifact download timed out after 120s for step 'darwin-aarch64-build-bun' (both build 69520 and build 69566). No tests ran on that lane; it is the artifact download step timing out. sqlite-sql.test.ts is green everywhere it ran, and the new tests fail before the fix and pass after.

robobun added 2 commits July 8, 2026 23:56
The SQLite adapter backs a Bun.SQL handle with a single connection, but
connect() handed that connection to every caller synchronously with no
serialization. Because supportsReservedConnections() returned false,
begin() acquired the connection non-exclusively, so any query (or a
second begin()) issued on the handle while a transaction callback was
awaiting ran directly on the same connection. An awaited, fulfilled
write could then be undone by the transaction's rollback, reads saw the
transaction's uncommitted rows, and a concurrent begin() failed with
"cannot start a transaction within a transaction".

Make the adapter support reserved connections: a transaction or reserved
connection now holds the single connection exclusively, and other
acquisitions queue until it is released, draining in FIFO order.
The 10000-iteration prepared-statement test and the 50MB-identifier test
time out under debug+ASAN (each awaited query and the per-character SQL
scan are 10-100x slower). These timeouts exist on main too; scale the
workloads down with isDebug so the file is green under debug+ASAN while
release coverage stays unchanged.
@robobun
robobun force-pushed the farm/d82cb17e/sqlite-sql-begin-isolation branch from c1e3bec to b7d5755 Compare July 9, 2026 00:04
Comment thread src/js/internal/sql/sqlite.ts Resolved
robobun and others added 2 commits July 9, 2026 00:28
…nsaction

Serializing the single connection made a helper that closes over the
outer sql handle deadlock when called from inside a begin() callback:
its acquisition was queued behind the transaction that was awaiting it.

Track the transaction callback's async context with AsyncLocalStorage so
connect() can tell a nested acquisition (inside the callback) apart from
a concurrent one (another task). Nested queries participate in the open
transaction as they did before, a nested begin() via the outer handle
rejects instead of hanging, and concurrent work still queues.
@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is ready at 7a882d9. sqlite-sql.test.ts is green everywhere it ran (236/236 under debug+ASAN locally).

The only hard-failed lane on build 70735 (and previously 70715) is Windows 2019 x64-baseline, where test/js/sql/postgres-binary-array-bounds.test.ts and other mock-server tests (postgres wire-frames, TLS) are getting ECONNREFUSED to their own localhost mock servers. That test does not use begin() (the only shared sql.ts path this PR touches), and the sql.ts/shared.ts changes fall back to the existing behavior for postgres/mysql (optional adapter hooks, unused by those adapters).

Comment thread test/js/sql/sqlite-sql.test.ts Resolved
…fail

A single await Promise.resolve() left the outerRan check one microtask
short of observing the broken-build state, so the intermediate assertion
was vacuous. Bun.sleep(0) drains the whole microtask chain first.
Comment thread src/js/internal/sql/sqlite.ts Resolved
…oken

Storing the literal true for every transaction meant connect() could not
tell "nested in the current transaction" apart from async context that
leaked out of a prior one. A fresh Symbol per transaction and an
identity comparison in connect() closes that gap so a leaked continuation
queues behind the later transaction instead of running inside it.

@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: 3

🤖 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 `@src/js/internal/sql/sqlite.ts`:
- Around line 302-306: Trim the explanatory comments in sqlite.ts to fit the
repo’s 3-line maximum while preserving the async-context/transaction invariant.
Shorten the comment blocks near the transaction token logic and the other
referenced comment block so they still mention why the token exists and how
connect() uses it, but in fewer lines. Keep the guidance attached to the
relevant transaction-handling code paths in the sqlite module.
- Around line 484-495: The draining logic in `#drainConnectQueue` currently uses
Array#shift(), which makes queued acquisitions O(n²) and violates the FIFO queue
guideline. Update the connectQueue handling in sqlite.ts to use the in-tree FIFO
helper (createFIFO) or a head-index approach instead of shifting, while
preserving FIFO order and the existing reservedConnection/_closed behavior in
`#drainConnectQueue` and `#handConnection`.

In `@test/js/sql/sqlite-sql.test.ts`:
- Around line 1148-1183: The transaction in this test can stay blocked if the
assertion fails, because `releaseTxn.resolve()` happens after
`expect(outerRan).toBe(false)`. Move the cleanup in `outer queries do not
interleave with an open transaction` so the `releaseTxn` promise is always
resolved via a `try/finally` or equivalent before any assertion can throw,
ensuring `sql.begin(...)` in the `txn` flow always releases the connection.
🪄 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: 7c7f7182-d806-419b-80eb-e0011865db56

📥 Commits

Reviewing files that changed from the base of the PR and between 339eb27 and 38e8d40.

📒 Files selected for processing (4)
  • src/js/bun/sql.ts
  • src/js/internal/sql/shared.ts
  • src/js/internal/sql/sqlite.ts
  • test/js/sql/sqlite-sql.test.ts

Comment thread src/js/internal/sql/sqlite.ts Resolved
Comment thread src/js/internal/sql/sqlite.ts Resolved
Comment thread test/js/sql/sqlite-sql.test.ts Resolved
- trim comments over the 3-line limit
- drain the connect queue with a head index instead of Array#shift
- release the held transaction before the mid-test assertion so a
  failure doesn't leave the callback blocked
@robobun

robobun commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is ready at bad1431. bun bd test test/js/sql/sqlite-sql.test.ts is 237/237 under debug+ASAN locally and the fail-before is clean (ASAN without fix: 4 FAILED, release without fix: 4 FAILED in the gate output). The gate's "with fix" lanes are reporting BUILD FAILED with no junit output; the logs are truncated mid-codegen with no compiler error shown. The only src changes in this PR are JS builtins (sql.ts, shared.ts, sqlite.ts) which bundle cleanly, so this looks like gate build infra rather than the diff.

Comment thread src/js/internal/sql/sqlite.ts Resolved
A queued reserved acquisition (a begin with an invalid option, or a
beginDistributed) hits pool.release() synchronously in
onTransactionConnected's error path before its first await. With the
head-index drain from bad1431 the recursive drain re-read the still-
unspliced queue from index 0 and recursed to stack overflow. Skip the
recursive call so the outer drain keeps its progress.
Comment thread test/js/sql/sqlite-sql.test.ts Resolved
The lazy Query did not reach pool.connect() until awaited after the
transaction had already released, so it never entered the drain queue.

@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.

All prior review feedback is addressed and the bug hunter found nothing on 5eac0f2, but the ALS-based nested-vs-concurrent detection and the drain re-entrance handling are subtle enough that a human should sign off on the design.

Extended reasoning...

Overview

This PR changes Bun.SQL's SQLite adapter so that sql.begin() holds the single underlying connection exclusively, queueing concurrent outer-handle work behind the transaction and using AsyncLocalStorage with a per-transaction Symbol token to distinguish nested acquisitions (from inside the callback's async context) from concurrent ones. It touches src/js/bun/sql.ts (two new optional adapter hooks consulted by begin()/beginDistributed() and a runInTransactionContext wrapper around the callback), src/js/internal/sql/shared.ts (interface additions), src/js/internal/sql/sqlite.ts (~110 new lines: reservation state, FIFO connect queue, ALS store, re-entrance-guarded drain, close-time queue rejection), and adds seven tests to test/js/sql/sqlite-sql.test.ts.

Security risks

None identified. No auth/crypto/permissions surface. The ALS store holds only an opaque Symbol per transaction, and the queue holds only connection callbacks; no user data flows through new paths.

Level of scrutiny

High. The mechanism is genuinely subtle: this PR went through three rounds of red-severity fixes during review (nested reserve() deadlock → split supportsTransactionReservation from supportsReservedConnections; nested outer-handle deadlock → ALS-based context detection; #drainConnectQueue stack overflow on synchronous release() → re-entrance guard), plus a follow-up to key the ALS store on a per-transaction token so leaked contexts from a prior transaction aren't misclassified as nested-in-current. Each fix is now covered by a test and the current revision looks correct to me, but the design space here — particularly "outer-handle query inside a transaction callback silently joins the transaction" and the ALS propagation semantics — is a product decision a maintainer should confirm.

Other factors

The sql.ts changes are additive for Postgres/MySQL (optional hooks with fallback to existing behavior), so the blast radius outside SQLite is small. Test coverage is good: serialization, queued second begin(), nested reserve() rejection, nested outer-handle query participation, nested outer-handle begin() rejection, leaked-ALS-context isolation, and drain re-entrance on sync-rejecting queued items. The one drive-by change (scaling the 10k-iteration stress test to 1k under isDebug) is reasonable given it timed out on main too.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-09, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant