Skip to content
This repository was archived by the owner on Nov 7, 2026. It is now read-only.

fix(opencode): continue turns through SQLite contention - #411

Merged
brentyates-swx merged 30 commits into
swxtchfrom
fm/oc-sqlite-busy-retry-370
Nov 6, 2026
Merged

brentyates-swx merged 30 commits into
swxtchfrom
fm/oc-sqlite-busy-retry-370

Conversation

@brentyates-swx

@brentyates-swx brentyates-swx commented Nov 4, 2026 •

Copy link
Copy Markdown

Fixes https://github.com/swxtchio/swx-opencode/issues/370.

Behavior and policy

  • Generic SQLite statements keep a 10-second retry window. Turn-dependent V1 session work shares a 60-second RetryWindow from packages/effect-sqlite-node/src/retry.ts.
  • A session window starts at the first native SQLITE_BUSY or 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.
  • Statements inside a transaction do not reset its budget; a successful outermost commit does, not a nested savepoint release.
  • Ordinary statements and failed BEGIN attempts 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 failed BEGIN attempts. The writer holds no connection or reservation during that backoff; a successful BEGIN transfers 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.
  • Persistent contention becomes a named Database is locked (SQLITE_BUSY) after N ms failure. 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.prompt covers admission and preparation; SessionPrompt.loop and its shared drain owner cover direct loops and all loop-started work (queue restore/send-now, summarize, AskRecovery, and manual compaction).
  • SessionQueue.writable covers queue mutations; prepareExecutable covers command/shell admission before the command reaches prompt.
  • SessionRunState.startShell covers the separate shell-run path.

Queue-consume budget

SessionQueue.consume shares 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 late BEGIN solely 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 ee11d8478643aa2f1e8136ebf7575cab0b5b5fe8

  • From packages/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 transaction BEGIN. All six fail on the prior permit-held-through-backoff behavior. The three permit-wait-bound cases pass for ordinary reads and transaction BEGIN; the old transaction acquirer is red at the 2-second control deadline.
  • From 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 elapsed SQLITE_BUSY failure 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 abandoned BEGIN after refusal and proves it never deletes the queued row.
  • From 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 typecheck passes in packages/effect-sqlite-node, packages/core, and packages/opencode; the pre-push bun turbo typecheck passes all 30 package tasks. PR_NUMBER=411 bun script/changeset-check.ts accepts the fix(opencode): continue turns through SQLite contention #411 entry.

Round 2 response at fad37d964a

  • Recovered-window proof: from packages/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.
  • fix(core): prevent SQLite permit leaks and restrict DB files #395 controls were not edited. From 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.
  • Command admission: from 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 only prepareExecutable's retry window makes this test fail its still-pending assertion at the 12-second boundary with SQLITE_BUSY; the general writable window remains unchanged.
  • Full Core SQLite verification: bun test test/sqlite-busy.test.ts test/sqlite-lock-diagnostics.test.ts passes 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.
  • The push hook’s bun turbo typecheck passes all 30 package tasks. PR_NUMBER=411 bun script/changeset-check.ts accepts the entry.

Round 3 response at d10b79993c

  • Before a transaction's BEGIN IMMEDIATE succeeds, 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 retries BEGIN 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.
  • fix(core): prevent SQLite permit leaks and restrict DB files #395's five controls remain unedited and pass (5 / 22); unrelated-SQL fairness remains green (6 / 24). The full Core SQLite suites now pass 80 tests / 1,844 assertions, 0 failures.
  • processor-effect.test.ts adds a producer-path test through Session.updatePartDelta and assertWritable: 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 package bun run test test/session/processor-effect.test.ts passes 51 tests / 418 assertions.
  • The command-admission window now owns the retry budget through durable admitLocked; this write inherits the prepareExecutable budget rather than opening a fresh writable window. Focused custody test passes (1 / 11), and removing only the prepareExecutable wrapper 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).
  • Typechecks pass in packages/effect-sqlite-node, packages/core and packages/opencode; the fix(opencode): continue turns through SQLite contention #411 changeset check accepts the updated entry. A full prompt.test.ts invocation exceeded the 15-minute tool limit and emitted provider-start/readiness timeouts; the focused affected cases passed separately.

Round 4 response: shared SQLite ownership

makeRetryOwnership in packages/effect-sqlite-node/src/retry.ts is 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):

Old #395 control Revised round-4 control
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 transactions

The 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.ts suite passes 51 / 418 with a 15-second test timeout and single-test concurrency; four SQLite contention/admission prompt cases pass 4 / 58. bun turbo typecheck passes 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.raceFirst could cancel the acquisition branch after the semaphore granted its lease but before acquireTransactionLease registered 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.mjs sweep uses real Semaphore and Scope leases across five MaxOpsBeforeYield values and 64 release offsets. It fails on d61d73102d at maxOps=4, offset=0 with 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 typecheck passes in packages/effect-sqlite-node and packages/core. A local full processor-effect.test.ts attempt had one 30-second timeout (50 passed, 1 failed) in processor 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#53704 and #59521 remain open; #42539 is 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.

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

Copy link
Copy Markdown
Author

Session ID: ses_e57af750bffe57cyTiemL9q7rg
Working repo: /home/byates/fm-worktrees/fm-llmrouter/oc-sqlite-busy-retry-370/swx-opencode

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
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

An agent turn ends on SQLITE_BUSY ("Database is locked") under write contention instead of retrying

1 participant