This repository was archived by the owner on Nov 7, 2026. It is now read-only.
Repository navigation
fix(opencode): continue turns through SQLite contention - #411
Merged
Merged
Conversation
Plan for swxtchio/swx-opencode#370: - Extend the shared asynchronous retry policy through existing SQLite clients; preserve the short native wait, stale-snapshot failure, permit ownership, and no transaction-body replay. - Keep the SessionPrompt run in its existing owner while bounded queue-consume recovery retries only writes that never began, preserving message, part, receipt, and reservation custody. - Add real second-connection WAL tests for release beyond the current policy window and persistent lock exhaustion, asserting exactly-once tool/queue continuation, elapsed lock diagnosis, idle status, and pending intent. - Verify upstream proposals and adapter/session controls, update CHANGESET.md, and run focused behavioral proofs and required package checks.
Author
|
Session ID: ses_e57af750bffe57cyTiemL9q7rg |
The opencode log confirms SessionProcessor.completeToolCall is the failing BEGIN IMMEDIATE owner. The regression test was holding its external lock while sessions.messages() blocked behind that same database client's transaction permit, so release came after the retry window. Read the in-flight tool state over a separate read-only connection and verify a fresh writer can acquire immediately after release.
Give the mock provider first-request wait its own 75-second fixture deadline under host load, without changing the lock-boundary waits. Capture the held-lock status before release, then release and prove a fresh writer can acquire before asserting so the pre-change red path also cleans up.
Give the shared tool-step setup an explicit provider-start deadline, use the host-load budget for the contention cases, and keep the transaction-body failure control on its short budget. Raise only the enclosing case caps; lock-acquisition and post-release deadlines are unchanged.
The shared session retry window can keep the first BEGIN attempt's connection reservation until expiry, so this stopped-run case cannot require a later BEGIN after the deferred holder releases. Assert the behavior it owns: refusal while held, unchanged queue/tool records, and later delivery on wake.
Claude-Session: ses_e57af750bffe57cyTiemL9q7rg
Claude-Session: ses_e57af750bffe57cyTiemL9q7rg
Claude-Session: ses_e57af750bffe57cyTiemL9q7rg
brentyates-swx
marked this pull request as ready for review
November 5, 2026 23:56
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes https://github.com/swxtchio/swx-opencode/issues/370.
Behavior and policy
RetryWindowfrompackages/effect-sqlite-node/src/retry.ts.SQLITE_BUSYor first contended in-process connection-permit acquisition, before waiting for that permit. The wait therefore counts against the same budget. A successfully recovered ordinary statement retires its contention episode, so later contention in the same turn starts a fresh budget.BEGINattempts acquire the process connection permit for one native attempt and release it before backoff. A cancellation-safe statement gate drains active ordinary retries for each native attempt, then reopens so deferred reads and ordinary statements can run between failedBEGINattempts. The writer holds no connection or reservation during that backoff; a successfulBEGINtransfers a Scope-owned connection lease through transaction completion (fix(core): prevent SQLite permit leaks and restrict DB files #395). Transaction callbacks are never replayed; stale snapshots fail immediately.Database is locked (SQLITE_BUSY) after N msfailure. Terminal-message persistence retries in fresh 10-second attempts so progress is reported at attempts 4 and 8 while the database remains unavailable.Entry-point coverage
SessionPrompt.promptcovers admission and preparation;SessionPrompt.loopand its shareddrainowner cover direct loops and all loop-started work (queue restore/send-now, summarize, AskRecovery, and manual compaction).SessionQueue.writablecovers queue mutations;prepareExecutablecovers command/shell admission before the command reachesprompt.SessionRunState.startShellcovers the separate shell-run path.Queue-consume budget
SessionQueue.consumeshares the 60-second session window, has a 20-second per-attempt acquisition backstop plus 250ms scheduling slack, and stops after at most five attempts or when the shared window expires. Only attempts whose transaction body never began can be retried. A backstopped attempt may finish a lateBEGINsolely to encounter its abandoned-body guard and roll back; its asynchronous permit wait holds no process connection permit, and it cannot delete a queued row after abandonment.Round 1 verification at
ee11d8478643aa2f1e8136ebf7575cab0b5b5fe8packages/core,bun test test/sqlite-busy.test.ts -t "lets an unrelated SQL statement progress"passes six cases / 24 assertions across Bun, Core Node, and standalone Node, including ordinary statements and transactionBEGIN. All six fail on the prior permit-held-through-backoff behavior. The three permit-wait-bound cases pass for ordinary reads and transactionBEGIN; the old transaction acquirer is red at the 2-second control deadline.packages/opencode,bun test test/session/prompt.test.ts -t "a loop-started tool result continues through a transient held SQLite lock"passes (1 / 14). Removing the loop/drain window makes it go idle while the second connection still holds the lock at the 12-second boundary. The persistent loop-started tool-result case passes (1 / 13): wait is 55–75 seconds, the runner is idle, the queue row remains pending, the shell side effect occurs once, and the terminal assistant records the elapsedSQLITE_BUSYfailure after release. With the session window wrappers removed, that case goes red on an approximately 10-second terminal error.bun test test/session/prompt.test.ts -t "a consume"passes five cases / 105 assertions with exact per-attempt log sequences. The connection-holder case verifies a late abandonedBEGINafter refusal and proves it never deletes the queued row.packages/opencode,bun test test/session/processor-effect.test.ts -t "processor keeps reporting a terminal write that a held lock keeps refusing"passes (1 / 8). Restoring the old 60-second terminal attempt window is red: the attempts 4/8 progress reports do not arrive within 120 seconds.bun typecheckpasses inpackages/effect-sqlite-node,packages/core, andpackages/opencode; the pre-pushbun turbo typecheckpasses all 30 package tasks.PR_NUMBER=411 bun script/changeset-check.tsaccepts the fix(opencode): continue turns through SQLite contention #411 entry.Round 2 response at
fad37d964apackages/core,bun test test/sqlite-busy.test.ts -t "retires a recovered permit-contention window before a later contention"passes all three adapters (3 tests / 15 assertions). The test performs two short in-process permit waits separated by more than the 500ms window; after the first statement succeeds, the second wait succeeds on a fresh budget.packages/core,bun test test/sqlite-busy.test.ts -t "cancels a queued reserve while its permit holder remains active|holds the connection permit across retry backoff before a transaction commits"passes all five controls (3 reserve-cancellation adapters and 2 transaction-order adapters). The six unrelated-SQL fairness cases pass across all three adapters. The native Node 24 runner also passes its 128-step Core Node and standalone Node permit-handoff sweeps; its failure message identifies the operation and delay.packages/opencode,bun test test/session/prompt.test.ts -t "a command admission under a real SQLite lock hands off custody and runs once after recovery"passes (1 / 11). The lock remains held for 12 seconds after shell expansion finishes and the admission write begins; after release the original message ID reaches history once, the command expansion marker appears once, and the provider is called once. Removing onlyprepareExecutable's retry window makes this test fail its still-pending assertion at the 12-second boundary withSQLITE_BUSY; the generalwritablewindow remains unchanged.bun test test/sqlite-busy.test.ts test/sqlite-lock-diagnostics.test.tspasses 77 tests / 1,829 assertions, 0 failures. The cases exercise Bun, Core Node and standalone Node adapters; the native Node fixture is an actual Node 24 subprocess.bun turbo typecheckpasses all 30 package tasks.PR_NUMBER=411 bun script/changeset-check.tsaccepts the entry.Round 3 response at
d10b79993cBEGIN IMMEDIATEsucceeds, its failed attempts release both the native connection lease and any exclusive gate before backoff. The new real-lock test holds an external write transaction, waits until a writer retriesBEGIN IMMEDIATE, then proves a separate deferred read transaction completes within one second while the writer remains blocked. It passes on Bun, Core Node and standalone Node (3 / 15); the native Node 24 fixture repeats the read case for both Node adapters.processor-effect.test.tsadds a producer-path test throughSession.updatePartDeltaandassertWritable: a first permit wait recovers, the stream pauses beyond its shortened 500ms window, then a later contended delta completes and the original text continues. The focused test passes (1 / 5); removing successful-operation retirement prevents the processor from continuing past the second delta. The full packagebun run test test/session/processor-effect.test.tspasses 51 tests / 418 assertions.admitLocked; this write inherits theprepareExecutablebudget rather than opening a freshwritablewindow. Focused custody test passes (1 / 11), and removing only theprepareExecutablewrapper turns it red. The package session prompt tests for admission/preparation, marked prompts, noReply, watcher ordering and TUI marking pass in focused runs (6 / 51).packages/effect-sqlite-node,packages/coreandpackages/opencode; the fix(opencode): continue turns through SQLite contention #411 changeset check accepts the updated entry. A fullprompt.test.tsinvocation exceeded the 15-minute tool limit and emitted provider-start/readiness timeouts; the focused affected cases passed separately.Round 4 response: shared SQLite ownership
makeRetryOwnershipinpackages/effect-sqlite-node/src/retry.tsis now the one ownership path called by Bun, Core Node and standalone Node. It owns ordinary per-attempt statement gating, retry backoff, reserved-connection leases, one-shot operations, the pre-BEGIN transaction acquisition and the lease transfer after successful BEGIN; adapter files retain only native connection setup and execution.The strict writer-first #395 test conflicted with the round-4 no-ownership-during-backoff rule. Its control text was revised per firstmate review decision (round 4):
holds the connection permit across retry backoff before a transaction commits; requires[writer-finished, transaction-started, transaction-committed]lets a deferred transaction finish during backoff and serves later arrivals after the writer; requires deferred work during backoff and writer commit within its remaining budget ahead of queued and continuously arriving later transactionsThe revised fairness test passes on Bun, Core Node and standalone Node (3 / 42); the native Node 24 fixture passes the normal/reserved backoff and writer-fairness proofs for Core Node and standalone Node. The three reserve-cancellation controls remain unchanged. Removing the ordinary per-attempt statement gate makes the Bun writer starve, exhausting the 10-second window; the mutant fails with
writer was starved by later transactions.Round-4 verification: the full Core SQLite suites pass 88 tests / 1,916 assertions; the full
processor-effect.test.tssuite passes 51 / 418 with a 15-second test timeout and single-test concurrency; four SQLite contention/admission prompt cases pass 4 / 58.bun turbo typecheckpasses all 30 package tasks, and the #411 changeset check accepts the entry.Round 5 response: FIFO lease acquisition
The new blocking defect was a lost grant in
makeStatementGate.withExclusive:Effect.raceFirstcould cancel the acquisition branch after the semaphore granted its lease but beforeacquireTransactionLeaseregistered the Scope finalizer. The fix removes the cancellable gate handoff and relies on FIFO semaphore admission; per-attempt gating remains, and the writer fairness invariant is preserved while each granted lease reaches its owner or is closed.The new
packages/core/test/fixture/sqlite-lease-grant-race.mjssweep uses real Semaphore and Scope leases across fiveMaxOpsBeforeYieldvalues and 64 release offsets. It fails ond61d73102datmaxOps=4, offset=0with the permit unavailable; the fixed sweep passes on Bun and in native Node 24 for both Core Node and standalone Node.Focused round-5 verification under checksum-verified Bun 1.4.4: the race/native-Node filter passes 2 tests / 10 expectations; four SQLite contention/admission prompt regressions pass 4 / 58; the isolated processor-halt test passes 1 / 8; and
bun typecheckpasses inpackages/effect-sqlite-nodeandpackages/core. A local fullprocessor-effect.test.tsattempt had one 30-second timeout (50 passed, 1 failed) inprocessor halt attributes a provider stream lock failure to the stream, not the last handled case; that case passes in isolation. Per captain ruling, the remaining full-suite and Turbo typecheck run is pending firstmate's leased-build-box verification.Upstream disposition
anomalyco/opencode#53704and#59521remain open;#42539is closed unmerged. Their transaction-replay, client-layout, or short-retry semantics are not compatible drop-ins, so no upstream commit was cherry-picked. This PR remains a draft for firstmate review; it has not been marked ready or merged.