Repository navigation
Conversation
|
Updated 11:18 PM PT - Jul 8th, 2026
❌ @robobun, your commit 5eac0f2 has 4 failures in
🧪 To try this PR locally: bunx bun-pr 33581That installs a local version of the PR into your bun-33581 --bun |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughSQLite 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. ChangesSQLite transaction reservation flow
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/js/internal/sql/sqlite.tstest/js/sql/sqlite-sql.test.ts
339eb27 to
0214098
Compare
|
CodeRabbit's walkthrough above is stale (it summarized the first push and then hit a rate limit). In the current commit 0214098, |
|
Diff is ready. The only red CI lane is |
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.
c1e3bec to
b7d5755
Compare
…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.
|
Diff is ready at 7a882d9. The only hard-failed lane on build 70735 (and previously 70715) is Windows 2019 x64-baseline, where |
…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.
…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.
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
src/js/bun/sql.tssrc/js/internal/sql/shared.tssrc/js/internal/sql/sqlite.tstest/js/sql/sqlite-sql.test.ts
- 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
|
Diff is ready at bad1431. |
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.
The lazy Query did not reach pool.connect() until awaited after the transaction had already released, so it never entered the drain queue.
There was a problem hiding this comment.
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.
|
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. |
What
Bun.SQLwith the SQLite adapter shares a single underlying connection across the whole handle, butsql.begin()ran with no isolation from the rest of the process. A query issued on the outer handle while abegin()callback was awaiting ran directly on the same connection, interleaving with the open transaction.Reproduction
Three symptoms, all from the same cause:
begin()rejects with "cannot start a transaction within a transaction" instead of queuingCause
SQLiteAdapter.connect()handed the single connection to every caller synchronously. Nothing marked it as held while a transaction was in flight, andbegin()acquired it withuseReserved = false.Fix
begin()now holds the single connection exclusively (via a newsupportsTransactionReservation()adapter hook, so Postgres/MySQL are unaffected). While a transaction holds the connection,connect()distinguishes:release(). The repro above now serializes the outer write after the rollback, so it survives.sqlhandle used from inside the callback's own async context, e.g. a helper closing over the module-levelsql): detected withAsyncLocalStorageand allowed to participate in the open transaction as before. A nested outer-handlesql.begin()rejects withERR_SQLITE_INVALID_TRANSACTION_STATEinstead of queueing and deadlocking.sql.reserve()stays unsupported on SQLite (supportsReservedConnections()is stillfalse); with only one connection atx.reserve()could never acquire a second one, so the existing rejection is preserved.Verification
bun bd test test/js/sql/sqlite-sql.test.tsis 236/236 under debug+ASAN.New tests in the existing SQLite SQL suite:
begin()queues behind the first instead of erroringreserve()inside a transaction rejects instead of hangingbegin()from inside the callback rejects instead of hangingThe serialization tests fail on the unfixed build and pass with the fix. Also scaled the pre-existing 10k-iteration prepared-statement test down under
isDebugso the file is green under debug+ASAN (it timed out on main too).