fix(server): a locked database no longer leaves a thread stuck in "starting" #26626
main fromrefs/pull/26626/head·opened View on GitHubProblem#
After a server restart, a thread can sit in "starting" for good. Its next run never spawns a provider process, every message sent afterwards queues behind it, and stopping the stuck run only moves the hang to the next queued run. Only another restart clears it.
The cause is in the effect worker. When an effect fails, the worker writes the claim back to pending. If that write hits SQLite's lock timeout, the fallback in requeueClaim tries once more. If the second write also times out, the worker logs Failed to requeue effect after unexpected worker failure and drops the claim. The row stays running, owned by a live worker that no longer tracks it. claimableCandidatePredicate never lets an effect run while an earlier effect on the same thread is running, so that thread's provider-turn.start effects are never claimed. Stop cancels the stuck run's provider-turn.start but not the stranded row, so the next queued run gets a new start effect that waits behind the same row. Only reconcileAfterProcessLoss at the next startup requeues it.
In our case both lock timeouts came within 25 s of startup, and the effect that failed was the restart continuation (provider-runtime.continue) for the run the restart had interrupted.
Change#
requeueClaim and terminalizeClaim are the worker's last attempt to settle a claimed row. Both now retry their outbox write while the failure is a LockTimeoutError, with 100 ms between attempts so an immediate lock error cannot cause a busy loop. Other errors are handled as before. A dropped claim is never recovered in-process: only the claiming worker can settle its row. Effect's onError handlers mask interruption, so these retries explicitly restore it. Shutdown can stop them without waiting for the lock to clear, apart from an in-flight write's own wait; the next startup's reconcileAfterProcessLoss handles any row left running.
Scope and approval#
No prior issue. This fits the small-fix exception: the bug is a thread that stops working until a restart, and the change is a short helper and two calls to it in EffectWorker.ts. It does not change claim ordering, lease semantics or which effects are replay-safe.
Related: #25638 and #25675 fixed a hung delegated-tasks.stop that blocked its thread the same way, and #16848 discusses reclaiming abandoned leases in general. This PR covers a different way a row gets stranded: the effect has already finished, but the write that settles it fails. #6560 had the same symptom in the old ingestion pipeline.
Verification#
Seen on a Linux server running 0.1.4-nightly.20261028.3824 as a user service, Claude provider. EffectWorker.ts and EffectOutbox.ts are unchanged between that tag and main. From the server log and a read-only copy of statev2.sqlite:
15:57:35 server started (upgrade restart; the thread's run had been mid-turn)
15:57:48 WARN Orchestration effect execution failed effect:restart-continuation:run:<thread>:ordinal:2507
... EventSinkWriteError ... LockTimeoutError: database is locked
15:57:58 ERROR Failed to requeue effect after unexpected worker failure (same effect)
... EffectOutboxError: retry failed ... LockTimeoutError: database is locked
15:57:58 WARN Orchestration effect worker failed
Outbox rows for the thread:
| effect | status | attempts | created | completed |
|---|---|---|---|---|
provider-runtime.continue (source run 2507) | succeeded | 2 | 15:57:19 | 17:03:34, after the next restart |
provider-turn.start run 2508 | cancelled, never claimed | 0 | 15:58:16 | 16:59:02, "interrupted before its provider turn started" |
provider-turn.start run 2516 | cancelled, never claimed | 0 | 16:59:03 | 17:03:18, server shutdown |
provider-turn.start run 2517 | succeeded | 1 | 17:03:35 | 17:03:48 |
Run 2508 stayed starting from 15:58:16 until it was stopped at 16:59. Eight more runs (2509–2516) queued behind it. After the stop, the next one to start, run 2516, stalled the same way. The second restart requeued the stranded continuation, and the thread worked again. The same day, a second server showed the same symptom after an upgrade restart, and a further restart cleared it there too.
Regression test keeps requeueing a failed claim while the database is locked in apps/server/src/orchestration-v2/EffectWorker.test.ts mirrors this sequence: execution fails, the next three outbox writes return LockTimeoutError, and the fourth succeeds.
- Before the fix:
vp test run src/orchestration-v2/EffectWorker.test.tsgivesTests 1 failed | 11 passed (12);AssertionError: expected false to be truebecause the row was never requeued. - The original fix at
60511c1passed all 12 tests. The shutdown regressioninterrupts $name settlement retries when the worker shuts downcovers both requeue and terminalize: interrupt the real daemon while fallback writes remain locked, and require shutdown within 100 ms of test-clock time, before releasing the lock. WithEffectWorker.tsrestored to60511c1,vp test run src/orchestration-v2/EffectWorker.test.ts -t 'settlement retries when the worker shuts down'givesTests 2 failed | 12 skipped (14), both at the shutdown assertion. With this follow-up fix, both cases pass. - From
apps/server,vp test run src/orchestration-v2/EffectWorker.test.ts:Tests 14 passed (14), including the original lock regression, which also checks that immediate failures are spaced before eventual recovery. - From
apps/server,vp test run src/orchestration-v2/EffectWorker.test.ts src/orchestration-v2/FoundationPersistence.test.ts src/orchestration-v2/RestartContinuation.test.ts:Test Files 3 passed (3),Tests 104 passed (104). vp run check:changed: format, lint, both knip passes, GraphQL generation, typecheck (3 packages) and tests all pass.
Live reproduction#
Two servers built from source, base 9e09926d and this branch 60511c1, each with the same seeded thread whose previous run needs a restart continuation, and the Replay provider (no model calls). A separate process held a real write lock on statev2.sqlite, timed by a test preload hook to overlap the worker's settle and requeue of the continuation, so both builds hit genuine SQLITE_BUSY failures. The lock was then released and a new message sent.
Before (9e09926d) | After (60511c1) | |
|---|---|---|
| Thread | ||
Outbox and runs (read-only sqlite3) |
Not checked: what held the writer lock for over 15 s after startup in the original incident.
Merge danger#
Door: two-way. A revert restores the old give-up behaviour, and no data or schema changes.
Blast radius: narrow. The fallback settlement writes keep one worker occupied until the lock clears or shutdown interrupts it. The 100 ms spacing adds a short delay after each lock failure. Shutdown may leave its row running; startup reconciliation already handles that state. Claim ordering and lease semantics are unchanged.
After merge#
None.
Left out#
- The main-path
retry,succeedandfailwrites still give up on the first lock timeout before handing off to these fallbacks. That costs one more 5 s wait and the original backoff delay, but no row is stranded. - What held the lock after startup. That is a separate performance question.
- Reclaiming leases whose owner is gone (#16848).
Written with Claude Opus 5.5 in Claude Code; live reproduction, screenshots and shutdown retry fix with GPT-6.1 Sol in Codex.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:S
- @@ -654,3 +662,4 @@654662 delayMs: 0,655663 })656664 .pipe(665+ retryWhileLocked,
🟠 High
orchestration-v2/EffectWorker.ts:665If settlement fails while the lock remains busy,
retryWhileLockedin bothrequeueClaimandterminalizeClaimkeeps retrying after shutdown interrupts the worker, so the daemon's worker group can hang until the lock clears. TheCause.hasInterruptsOnly(cause)checks only the original failure; make these retries interruptible or otherwise bound their shutdown lifetime.🤖 Copy this AI Prompt to have your agent fix this:
In file @apps/server/src/orchestration-v2/EffectWorker.ts around line 665: If settlement fails while the lock remains busy, `retryWhileLocked` in both `requeueClaim` and `terminalizeClaim` keeps retrying after shutdown interrupts the worker, so the daemon's worker group can hang until the lock clears. The `Cause.hasInterruptsOnly(cause)` checks only the original failure; make these retries interruptible or otherwise bound their shutdown lifetime.Confirmed: Effect's
onErrorhandlers run uninterruptibly, so the original failure's interrupt check did not protect a later settlement retry. Inbcba32c, the shared retry helper explicitly restores interruption, so shutdown can stop both fallback paths while the lock is still held. The regressioninterrupts $name settlement retries when the worker shuts downfails for both requeue and terminalize on60511c1and passes with the fix; it interrupts the real daemon and requires it to stop within 100 ms of test-clock time before releasing the lock.Sorry, I'm unable to act on this request because you do not have permissions within this repository.
Approvability#
Verdict: Needs Human Approval
Macroscope's review found this PR requires human approval — The change retries database-lock failures during effect settlement so threads can recover from contention. The unresolved finding identifies retries that can hold up worker shutdown until the lock clears; their shutdown lifetime needs resolution.
Needs human approval because:
- 1 blocking correctness issue found at or above your repo's Minimum Blocking Severity
No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: main
- File: .coderabbit.config.ts
- Commit: 9e09926
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Advanced
- Run ID:
c440c78e-95eb-497a-87fc-4d6323e27922
Commits-
Reviewing files that changed from the base of the PR and between 60511c1384e2db2770afa74a73310e16c5332146 and bcba32c62043a2a0cb65b2e778e77d41e0e6469c.
Files selected for processing: 2-
apps/server/src/orchestration-v2/EffectWorker.test.tsapps/server/src/orchestration-v2/EffectWorker.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
-
Walkthrough
-
EffectWorker retries requeue and terminalization settlement operations when SQL lock timeouts occur. The retry loop is interruptible. Tests cover repeated timeouts and worker shutdown during settlement retries.
Changes: EffectWorker settlement retries
Priority:Layer / File(s) Summary Retry settlement after lock timeouts
apps/server/src/orchestration-v2/EffectWorker.ts,apps/server/src/orchestration-v2/EffectWorker.test.tsEffectWorker retries requeue and terminalization settlement operations after SQL lock timeouts. Tests cover repeated requeue timeouts and interruption of in-flight settlement retries during worker shutdown. NormalEstimated code review effort: 2 (Simple) | ~10 minutes
Change: Bug fix
Possibly related PRs
- pingdotgg/t3code#21092: Retries provider event writes when SQL lock timeouts occur. This covers a separate write path.
- pingdotgg/t3code#24571: Retries provider event writes after SQL lock timeouts. This covers a different persistence path.
Suggested reviewers:
juliusmarminge,t3dotgg,macroscopeapp
Merge Risk:
Minimal · up tobcba3-
Settlement retries are interruptible, and no merge-blocking issue was identified.
Pre-merge checks:
4-
Check name Status Explanation Title check The title clearly and concisely describes the main fix: preventing SQLite lock timeouts from leaving a server thread stuck in "starting". Description check The description includes complete Problem, Change, Scope and approval, and Verification sections. It explains the failure mode, implementation, scope rationale, regression tests, live reproduction, li… Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request. Full details: Description check
-
Explanation
The description includes complete Problem, Change, Scope and approval, and Verification sections. It explains the failure mode, implementation, scope rationale, regression tests, live reproduction, limitations, and merge impact.
-
Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
🔇 Additional comments: 1
-
apps/server/src/orchestration-v2/EffectWorker.ts-604-605: 1
-
604-605: Major · Performance & Scalability · Quick win⚠️ Unverified finding Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Add a delay between lock-timeout retries.
If SQLite returns a lock error without waiting,
Effect.retryimmediately repeats the settlement write. SQLite can bypass its busy handler when waiting could cause a deadlock. A sustained lock can therefore make this worker issue rapid database writes. Add a retry schedule with a delay; keep the lock-timeout predicate. (sqlite.org)
-
Review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: main
- File: .coderabbit.config.ts
- Commit: 9e09926
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Advanced
- Run ID:
007cfb6f-b413-4e3f-9f61-a303fc4cd5de
Commits-
Reviewing files that changed from the base of the PR and between 9e09926d97824179d97311d1a810c6b5bb60d2d1 and 60511c1384e2db2770afa74a73310e16c5332146.
Files selected for processing: 2-
apps/server/src/orchestration-v2/EffectWorker.test.tsapps/server/src/orchestration-v2/EffectWorker.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
-
-
Added 100 ms spacing between lock-timeout retry attempts, keeping the
isLockTimeoutpredicate. The existing lock regression now uses the test clock to check that immediate failures wait between attempts and that the claim is still requeued once the lock clears.tanstack-source added labelsbug
juliusmarminge added labelstakeover:in-progress
juliusmarminge added labelstakeover:ready
juliusmarminge removed labelstakeover:in-progress
juliusmarminge removed labelstakeover:ready
Thanks for this. It was finished and merged https://github.com/pingdotgg/t3code/pull/36635 as 5ba3a84db4, with your commits kept.
juliusmarminge closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed