Repository navigation
Description
Before submitting
- I searched existing issues and did not find an open duplicate. I read the related closed issues carefully:
- SQLite writes run on the server's event loop, so one slow transaction disconnects every client #30065 / PR fix(server): a slow database write no longer freezes the server #35728 — "SQLite writes run on the server's event loop, so one slow transaction disconnects every client" (fixed by moving file-backed writes to a worker thread)
- fix(server): V2 event writes no longer fail when another process commits mid-transaction #14365 — V2 EventSink deferred
BEGIN→SQLITE_BUSY_SNAPSHOT(fixed bywithWriteTransaction) - [Bug]: SQLite busy_timeout is never set — concurrent CLI/server writes fail with "database is locked" #5099 / PR fix(server): wait for concurrent SQLite writers instead of failing with SQLITE_BUSY #5134 —
busy_timeoutwas never set (fixed byPRAGMA busy_timeout = 5000) - fix(server): a locked database no longer leaves a thread stuck in "starting" #36635 / fix(server): a locked database no longer leaves a thread stuck in "starting" #26626 — node:sqlite iterator not reset after
SQLITE_BUSY, leaving a thread stuck in "starting" - [Bug]: Startup migration exits on "database is locked" instead of waiting, so a CLI holding statev2.sqlite crash-loops the desktop backend #21736, History-wide reads saturate the single SQLite reader on large databases (thread switches take 12-50 s) #24895, [Bug]: Each stored event costs ~66 ms of server CPU; SQLite cache is the 2 MB default on a 15.5 GB database, and t3_thread_read loads every run of a thread #37877, Retention for settled and archived threads: archiving frees nothing, and a 3-week-old database already stalls the server #42372 — large
statev2.sqlite, read/write pressure and retention
- I included the exact error, traces, span timings, and trace/span/fiber IDs needed to investigate.
Area
apps/server — orchestration-v2 EventSink / SQLite writer contention
What happens
During normal agent-thread activity, the user repeatedly sees this error in the UI, and the affected action is lost:
The T3 Code server database is busy (SQLITE_BUSY). Wait a moment, then retry.
If this keeps happening, check for another T3 Code process using the same data directory on the server.
Affected commands are all orchestration.dispatchCommand calls whose EventSink.commitCommand needs a write transaction:
respondToThreadUserInput(sending a message to a thread)visitThread(switching/opening a thread)runtime-request.respond(an agent responding to user input)
The failing command's BEGIN IMMEDIATE times out after 5 s (busy_timeout), so the turn's events are never appended and the user's message/action is dropped and must be retyped.
This is not caused by a second T3 process (see "Ruled out" below). The hint in the error text is a generic template.
Version / environment
- T3 Code Nightly 0.1.14-nightly.20261130.5508 (from
server-runtime.json,serverVersion) - Windows 11, desktop app using an external OpenCode Server (
opencode-cli.exe serve --service, separate from the T3 server) statev2.sqlite: 706 MB, WAL mode, ~208,000 rows inorchestration_events- Single T3 server: PID 31064, port 3773,
service.instance.id = e8d6e533-83e2-4673-8236-5a005a5f0faa(unique across all traces in the logs) - C: drive had ~45 GB free at the time (not a disk-space problem)
Regression check: does the next nightly fix it?
I checked the next nightly, 0.1.14-nightly.20261201.5530 (tag 772e3d4d, published 2026-12-01 04:00 UTC), which is 62 commits / 300 files ahead of 5508 (0f7ae4e8, published 2026-11-30 21:30 UTC):
- 0 of the 62 commit titles mention SQLite / lock / writer / busy / WAL / transaction / checkpoint.
- Of the 300 changed files, the only persistence-adjacent one is
apps/server/src/orchestration-v2/ProviderSessionManager.ts(+51/-10), touched by25769364 Replace the Grok ACP adapter with the Grok Build SDK integration (#46363). Its diff only addsexpectedDriver/checkCompatible(provider-driver compatibility checks) — it does not touchpersistProviderSessionUpdate, any write transaction, or locking. - The one plausibly related fix,
2f3a5ead fix(server): stalled preview viewers no longer wedge snapshots (#46472), was published at 2026-12-01 04:42 UTC, after 5530 was cut, so it is not in 5530 and is about preview viewers, not SQLite.
Conclusion: 5530 does not contain any fix for this issue. I am still on 5508 and the bug reproduces there.
Root cause (verified independently against the traces)
The root cause is in-process SQLite writer lock contention: one slow write transaction holds the single SQLite writer connection for seconds, while other commitCommand / ProviderCommitBatch write transactions wait on BEGIN IMMEDIATE and time out at busy_timeout = 5000, surfacing as SQLITE_BUSY.
Evidence:
- Every failing
BEGIN/sql.transactionhas the same cause chain — a standard SQLite busy timeout, not a snapshot conflict or a wedged statement:
effect/sql/SqlError: Failed to execute statement
at failed (.../composerTrigger-mlChcUbh.mjs:10399:47)
...
[cause]: effect/sql/SqlError/LockTimeoutError: Failed to execute statement
at classifySqliteError (.../composerTrigger-mlChcUbh.mjs:5330:18)
...
[cause]: Error: database is locked
I found 39 failed BEGIN spans; their durations are uniformly 5400–5524 ms (= 5000 ms busy_timeout + overhead). Higher-level sql.transaction / commitCommand spans take 9–30 s because they first wait for a writer connection and then hit the 5 s BEGIN timeout.
-
The
db.lock_owner_at_start.*/db.lock_wait_msspan attributes identify the actual lock holders — all inside the same server process:orchestrationV2.EventSink.write/ProviderSessionManager.persistProviderSessionUpdateheld the writer for 10704 ms (server.trace.ndjson.4:10992)name=untraceddirectory-treeSELECTandPRAGMA page_count/freelist_countqueries held the writer for 26560 ms (server.trace.ndjson.3:1738), 27638 ms (server.trace.ndjson.3:2887), and 31361 ms (server.trace.ndjson.4:8197)- A representative failed BEGIN with its successful counterpart, same trace, in chronological order:
server.trace.ndjson.1:L2904 sql.transaction dur=5496 FAILURE (waited 5.5 s)
server.trace.ndjson.1:L2903 BEGIN dur=5494 FAILURE
server.trace.ndjson.1:L3882 sql.transaction conn=writer dur=14291 SUCCESS <- held the writer
server.trace.ndjson.1:L3880 BEGIN dur=3322 SUCCESS <- acquired only after release
After that slow writer completes, subsequent ProviderCommitBatch.flush spans return to normal 3–130 ms — the classic signature of one slow writer serializing and starving all other writers.
-
A tempting but wrong conclusion, corrected here: a large
ProviderCommitBatch.flushspan (dur=67341 ms, trace1c41a1454118d574ff9f226803b3220e) hasbatch_wait_ms=67344,event_count=0,batch_writes=0. The 67 s is queue wait time, not lock hold time — it is a victim queued behind the lock, not the holder. It also starts ~95 s after the first failures, so it cannot be their cause. The1c41a145…trace ID is a long-lived server-level writer trace spanning hours, not a single request; a shared trace ID here does not imply causation. I called this out so nobody chases the wrong span. -
The SQL is already running in a worker thread in this build (stacks show
Worker.<anonymous> → Object.resume → EventSink.commitCommand), so the event-loop-freeze part of SQLite writes run on the server's event loop, so one slow transaction disconnects every client #30065 is fixed. What remains is writer-side lock serialization: a single writer connection, multiple fibers contending, each holder keeping the lock for 5–31 s, and contendedBEGINs failing at 5 s.
Ruled out (with evidence)
- Another T3 process / second server holding the database: no
ServerAlreadyRunningor ownership error anywhere in the logs;service.instance.idis unique; lock holders carry in-processtrace_id/span_id/fiber_id(e.g.fiber_id=182283, name=orchestrationV2.EventSink.write, trace41b1b5003c…). Only one server process was running. The "check for another T3 Code process" hint is a generic template. - fix(server): V2 event writes no longer fail when another process commits mid-transaction #14365
SQLITE_BUSY_SNAPSHOT: 0 occurrences of that error in all traces. - fix(server): a locked database no longer leaves a thread stuck in "starting" #36635 (node:sqlite iterator not reset): 0 occurrences of
cannot commit transaction - SQL statements in progressorcannot start a transaction within a transaction; the error is a cleanLockTimeoutError. - [Bug]: SQLite busy_timeout is never set — concurrent CLI/server writes fail with "database is locked" #5099 (busy_timeout missing): the logs show a clear ~5 s wait before failure, so
PRAGMA busy_timeout = 5000is present. - Disk full / slow disk: 45 GB free; no
server.eventLoop.stallentries near the incidents; the slow spans are SQLite writer transactions, not fsync stalls. - Reproduction with a plain SQLite harness: I reproduced the mechanism in isolation — a writer holding
BEGIN IMMEDIATEfor 20 s makes a second connection withtimeout=5.0fail after 5.50 s withdatabase is locked, while a 1 s hold lets it succeed after 1.11 s. This matches the 5.4 s failures in the real logs exactly, confirming the lock-timeout mechanism.
How to reproduce
This is an intermittent production-load issue, not a deterministic single-command repro. The conditions observed:
- Run 0.1.14-nightly.20261130.5508 with a large
statev2.sqlite(here 706 MB) and active agent threads. - Generate sustained orchestration event writes (agent turns producing
node.updated/message.updated/turn_item.updated/plan.updatedsnapshots) soProviderCommitBatchis actively batching. - While a write transaction is in progress, send a message to a thread (
respondToThreadUserInput) or switch threads (visitThread). - The command's
commitCommandcallsBEGIN IMMEDIATEon the shared writer connection; if another transaction has held it for more than ~5 s, the command fails with the user-facing SQLITE_BUSY error.
It is more likely when several things contend for the writer at once: EventSink.write / persistProviderSessionUpdate, directory-tree queries (PRAGMA page_count / freelist_count, SELECTs), and command commits. In the logs, 39 failed BEGINs occurred across the session; many clustered around heavy activity with many subscribeThread / subscribeVcsStatus reconnects.
A deterministic test hook would be to hold a write transaction on statev2.sqlite for >5 s from one fiber and issue EventSink.commitCommand from another, then assert it surfaces a LockTimeoutError — similar to the cross-process test added in #5134, but for two writers in the same server process.
Expected behavior
Concurrent writes should not abort the user's command. Options: a contended writer should queue/retry rather than fail at 5 s, or long write transactions should be broken up / moved off the single writer connection.
Actual behavior
One in-process write transaction holds the SQLite writer for 5–31 s; concurrent commitCommand / ProviderCommitBatch writers time out after 5 s and their commands fail with the SQLITE_BUSY error, losing the user's message/action.
Suggested improvement directions
- Queue contended writers instead of failing at 5 s within the same process, or apply a bounded retry/backoff on
LockTimeoutError(similar to the requeue retry in fix(server): a locked database no longer leaves a thread stuck in "starting" #26626) so a transient slow writer does not drop a command. - Identify and shorten the long holders.
EventSink.write/persistProviderSessionUpdateheld the writer 10.7 s, anduntraceddirectory-treeSELECT/PRAGMA page_count/freelist_countqueries held it 26–31 s. These should use the reader connection (cf. [Bug]: the other ProjectionStore reads take the write lock instead of the reader connection #23687 "the other ProjectionStore reads take the write lock instead of the reader connection" and perf(server): the projection read path takes the lock on the reader connection #23689), be indexed, or be moved out of write transactions. - Check SQLite cache defaults on large DBs. [Bug]: Each stored event costs ~66 ms of server CPU; SQLite cache is the 2 MB default on a 15.5 GB database, and t3_thread_read loads every run of a thread #37877 reported
cache_sizeleft at the 2 MB SQLite default andmmap_sizeunset on a largestatev2.sqlite; a 706 MB DB with default cache may make each write transaction slower. Consider settingcache_size/mmap_size, and/ort3 doctor-style VACUUM/retention for old events (Retention for settled and archived threads: archiving frees nothing, and a 3-week-old database already stalls the server #42372, orchestration_events grows without bound: streaming updates are stored as permanent events and never compacted #21154). - Add a regression test for two in-process writers contending on
statev2.sqlitewhere one holds the lock >busy_timeout, asserting the second writer is queued/retried rather than failing — to make sure the SQLite writes run on the server's event loop, so one slow transaction disconnects every client #30065/fix(server): a slow database write no longer freezes the server #35728 worker-thread move also covers writer-side lock contention.
Additional notes
- I am happy to provide the full
server.trace.ndjson*files (they total ~100 MB) or extract specific spans if that helps. The logs contain no credentials or tokens in the spans I quoted. - I did not modify any T3 state while investigating — this was a read-only analysis of logs, databases (opened read-only), and the
server.asarbundle.
Activity
juliusmarminge commentedon Dec 1, 2026
@srafyhucl-cpu When the SQLITE_BUSY error appears, which other programs have statev2.sqlite open? For example, check Resource Monitor → CPU → Associated Handles with a search for 'statev2', or run Sysinternals
handle.exe statev2. Is anything like thet3CLI run by an agent or terminal, a SQLite browser, or a backup/sync tool holding it besides the T3 server process?srafyhucl-cpu commentedon Dec 1, 2026
Thanks for the quick triage. I checked this directly, and the lock holders are inside the T3 server process itself — not another program.
What the traces actually record
The server trace already annotates the lock owner on every
sql.transactionthat waits. The attributes are:db.lock_wait_msdb.lock_owner_at_start.namedb.lock_owner_at_start.fiber_iddb.lock_owner_at_start.trace_iddb.lock_owner_at_start.span_idAcross
server.trace.ndjson*I found 200 spans that carrydb.lock_owner_at_start.name. The owners are all in-process Effect fibers/operations:nameorchestrationV2.EventSink.writeuntracedorchestrationV2.EventSink.commitCommandEffectOutbox.succeedorchestrationV2.EventSink.writeIfRunCurrentorchestrationV2.EventSink.providerBatchsqliteDatabaseStorage.reclaimTaskFolderStore.findContainingProjectionMaintenance.pruneEventStoreorchestrationV2.dispatch.withReceiptorchestrationV2.EventSink.writeIfProviderThreadOwnerDecisive check: of the 52 distinct
db.lock_owner_at_start.trace_idvalues, 52/52 are present in the sameserver.trace.ndjson*files — i.e. the lock owner is a span emitted by this same server process, not an external process. Theuntracedowners are the same thing (Effect fibers running a write transaction that didn't carry a span name); their fiber ids appear only underdb.lock_owner_at_start.fiber_id, and their transactions run 4–14 s (e.g.server.trace.ndjson.3:L3882sql.transactiondur=14290 ms, owner fiber 339447).The holder durations are exactly the problem:
EventSink.write/persistProviderSessionUpdateheld the writer 10.7 s, anduntraceddirectory-treeSELECT/PRAGMA page_count/freelist_countheld it 26–31 s. Meanwhile 39BEGINs each waited ~5.4 s and failed.The other programs (as you asked)
t3CLI: none running (not3process on the machine).opencode-cli.exe serve --serviceand OpenCode Desktop are running, but they only use their owndrafts.sqlite/history.sqliteunder%APPDATA%\ai.opencode.desktop. There is nostatev2.sqliteanywhere under the OpenCode data dirs — OpenCode never opens T3's state DB.service.instance.idis unique (e8d6e533-…) across all traces, noServerAlreadyRunning/ ownership error, and only one server process (PID 31064, port 3773) is running.handle.exeisn't installed here, andopenfiles.exelocal handle listing is disabled, so I can't produce a raw handle table right now. But the trace-level owner attribution above is stronger than a handle snapshot: it names the exact in-process fiber that holds the writer at the moment each waiter blocks, and every owner trace is from this same server process.Summary
So the "check for another T3 Code process" hint does not apply here. The contention is between write transactions inside one server process on the single SQLite writer connection: one slow writer (
EventSink.write, directory-tree queries,EffectOutbox,ProjectionMaintenance.pruneEventStore, etc.) holds the lock for 5–31 s, and concurrentcommitCommand/ProviderCommitBatchBEGINs time out atbusy_timeout = 5000and surface SQLITE_BUSY.If it helps, I can attach the full
server.trace.ndjson*set (~100 MB) or a trimmed extract of just the spans withdb.lock_owner_at_start.*so you can confirm the same-process attribution yourself. Want me to upload that?juliusmarminge commentedon Dec 1, 2026
@srafyhucl-cpu A slow write inside the T3 server can't produce this error. Writes in the same process wait in a queue with no timeout: I measured a 42 s wait that still succeeded on Windows. A BEGIN that fails after 5.4 s means some other SQLite connection held statev2.sqlite's write lock at that moment. Could you install Sysinternals Handle and, while the error is showing, send the output of
handle.exe -a statev2, together with the full server.trace.ndjson lines from 30 s before to 5 s after one failed BEGIN (for example around server.trace.ndjson.1 L2903)?srafyhucl-cpu commentedon Dec 1, 2026
You were right, and I was wrong. The lock holder was another SQLite connection — a third-party script on my machine, not anything inside the T3 server. Sorry for the earlier misdirection.
Why your point was correct
I re-checked the bundle:
makeWithDatabasehas a single writer connection with oneSemaphore(1)(packages/shared/src/nodeSqliteClient.ts:929,975-979), andtransactionAcquirerqueues on it with no timeout (:1082-1112). So an in-process slow write cannot produce a 5.4 sBEGINfailure. I should have taken your "another SQLite connection" explanation and looked outside the process instead of continuing to hunt inside it.The actual writer
A Windows Scheduled Task
T3Code-OpenCode-Syncran every 2 minutes:That script opened
statev2.sqlitewithsqlite3.connect(target_db, timeout=30, isolation_level=None)and issuedBEGIN IMMEDIATE, then wrote directly into the projection tables (orchestration_v2_projection_messages,..._turn_items,..._threads,orchestration_events) in one transaction — up to ~1,300 items in a single batch on some runs. It is not T3 code and does not use the T3 API.That also explains why
handle.exe -a statev2only showed pid 32624 (the T3 server): the script ran for only a few seconds every 2 minutes, so a snapshot taken between runs sees nothing.Decisive evidence
I grouped every failed
BEGINby wall-clock time: 56 of 63 (89%) occurred on even minutes, clustered at :02–:26 seconds — exactly the window after the 2-minute task fires at:00. That periodic signature is what finally pointed at an external timer.After ending the task and killing the script, no
SQLITE_BUSYsince.Conclusion
This is not a T3 server defect — it is a third-party process writing
statev2.sqlitedirectly, outside the official API. I have deleted the scheduled task and the script. I'm happy to close this issue as "not a T3 bug"; I only opened it because I initially misread the traces.Optional (small) suggestion
Not a bug, but two things would have made this easier to diagnose:
busy_timeoutis quickly exceeded by a short external writer; a longer/adaptive timeout (or a retry) would make this class of interference self-heal instead of failing the user's command.Thanks for your patience and for pointing me the right way twice.
juliusmarminge commentedon Dec 1, 2026
I tried to reproduce this on the current build and could not.
Not reproduced; no app run was attempted. The thread itself settled it: in their 2026-12-01 09:48 comment the reporter found the lock holder was a third-party Windows Scheduled Task (T3Code-OpenCode-Sync, run every 2 minutes) whose Python script opened statev2.sqlite directly and held BEGIN IMMEDIATE while bulk-inserting projection rows. 56 of their 63 failed BEGINs fell in the seconds after each even minute, when the task ran. With the task removed, the error stopped. On origin/main (8bfed05) I checked the code side of this: packages/shared/src/nodeSqliteClient.ts:929 serializes the in-process writer on a Semaphore(1) that queues with no timeout, and busy_timeout = 5000 (lines 216, 686) only applies to locks held by another SQLite connection. So a slow write inside the T3 server cannot cause a 5 s BEGIN failure, which matches the maintainer's measured 42 s in-process wait that still succeeded.
Closing as not planned. If it still happens for you, reply with the exact steps and the version you are on and it will be looked at again.