Skip to content

[Bug]: SQLITE_BUSY on orchestration command commit still reproduces after #30065/#35728 — in-process SQLite writer lock contention #46557

Not planned

Description

@srafyhucl-cpu

Before submitting

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 in orchestration_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 by 25769364 Replace the Grok ACP adapter with the Grok Build SDK integration (#46363). Its diff only adds expectedDriver / checkCompatible (provider-driver compatibility checks) — it does not touch persistProviderSessionUpdate, 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:

  1. Every failing BEGIN / sql.transaction has 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.

  1. The db.lock_owner_at_start.* / db.lock_wait_ms span attributes identify the actual lock holders — all inside the same server process:

    • orchestrationV2.EventSink.write / ProviderSessionManager.persistProviderSessionUpdate held the writer for 10704 ms (server.trace.ndjson.4:10992)
    • name=untraced directory-tree SELECT and PRAGMA page_count / freelist_count queries 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.

  1. A tempting but wrong conclusion, corrected here: a large ProviderCommitBatch.flush span (dur=67341 ms, trace 1c41a1454118d574ff9f226803b3220e) has batch_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. The 1c41a145… 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.

  2. 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 contended BEGINs failing at 5 s.

Ruled out (with evidence)

  • Another T3 process / second server holding the database: no ServerAlreadyRunning or ownership error anywhere in the logs; service.instance.id is unique; lock holders carry in-process trace_id / span_id / fiber_id (e.g. fiber_id=182283, name=orchestrationV2.EventSink.write, trace 41b1b5003c…). 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 progress or cannot start a transaction within a transaction; the error is a clean LockTimeoutError.
  • [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 = 5000 is present.
  • Disk full / slow disk: 45 GB free; no server.eventLoop.stall entries 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 IMMEDIATE for 20 s makes a second connection with timeout=5.0 fail after 5.50 s with database 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:

  1. Run 0.1.14-nightly.20261130.5508 with a large statev2.sqlite (here 706 MB) and active agent threads.
  2. Generate sustained orchestration event writes (agent turns producing node.updated / message.updated / turn_item.updated / plan.updated snapshots) so ProviderCommitBatch is actively batching.
  3. While a write transaction is in progress, send a message to a thread (respondToThreadUserInput) or switch threads (visitThread).
  4. The command's commitCommand calls BEGIN IMMEDIATE on 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

  1. 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.
  2. Identify and shorten the long holders. EventSink.write / persistProviderSessionUpdate held the writer 10.7 s, and untraced directory-tree SELECT / PRAGMA page_count / freelist_count queries 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.
  3. 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_size left at the 2 MB SQLite default and mmap_size unset on a large statev2.sqlite; a 706 MB DB with default cache may make each write transaction slower. Consider setting cache_size / mmap_size, and/or t3 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).
  4. Add a regression test for two in-process writers contending on statev2.sqlite where 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.asar bundle.

Activity

  1. juliusmarminge commented on Dec 1, 2026

    @juliusmarminge
    Member

    @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 the t3 CLI run by an agent or terminal, a SQLite browser, or a backup/sync tool holding it besides the T3 server process?

  2. added
    needs more info
    on Dec 1, 2026
  3. srafyhucl-cpu commented on Dec 1, 2026

    @srafyhucl-cpu
    Author

    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.transaction that waits. The attributes are:

    • db.lock_wait_ms
    • db.lock_owner_at_start.name
    • db.lock_owner_at_start.fiber_id
    • db.lock_owner_at_start.trace_id
    • db.lock_owner_at_start.span_id

    Across server.trace.ndjson* I found 200 spans that carry db.lock_owner_at_start.name. The owners are all in-process Effect fibers/operations:

    owner name count
    orchestrationV2.EventSink.write 79
    untraced 43
    orchestrationV2.EventSink.commitCommand 23
    EffectOutbox.succeed 20
    orchestrationV2.EventSink.writeIfRunCurrent 17
    orchestrationV2.EventSink.providerBatch 7
    sqlite 5
    DatabaseStorage.reclaim 4
    TaskFolderStore.findContaining 3
    ProjectionMaintenance.pruneEventStore 2
    orchestrationV2.dispatch.withReceipt 2
    orchestrationV2.EventSink.writeIfProviderThreadOwner 3

    Decisive check: of the 52 distinct db.lock_owner_at_start.trace_id values, 52/52 are present in the same server.trace.ndjson* files — i.e. the lock owner is a span emitted by this same server process, not an external process. The untraced owners are the same thing (Effect fibers running a write transaction that didn't carry a span name); their fiber ids appear only under db.lock_owner_at_start.fiber_id, and their transactions run 4–14 s (e.g. server.trace.ndjson.3:L3882 sql.transaction dur=14290 ms, owner fiber 339447).

    The holder durations are exactly the problem: EventSink.write / persistProviderSessionUpdate held the writer 10.7 s, and untraced directory-tree SELECT / PRAGMA page_count / freelist_count held it 26–31 s. Meanwhile 39 BEGINs each waited ~5.4 s and failed.

    The other programs (as you asked)

    • t3 CLI: none running (no t3 process on the machine).
    • SQLite browser / DB tool: none.
    • Backup / sync tools (Dropbox/OneDrive/GoodSync etc.): none touching this path.
    • OpenCode: opencode-cli.exe serve --service and OpenCode Desktop are running, but they only use their own drafts.sqlite / history.sqlite under %APPDATA%\ai.opencode.desktop. There is no statev2.sqlite anywhere under the OpenCode data dirs — OpenCode never opens T3's state DB.
    • A second T3 server: no. service.instance.id is unique (e8d6e533-…) across all traces, no ServerAlreadyRunning / ownership error, and only one server process (PID 31064, port 3773) is running.
    • handle.exe isn't installed here, and openfiles.exe local 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 concurrent commitCommand / ProviderCommitBatch BEGINs time out at busy_timeout = 5000 and 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 with db.lock_owner_at_start.* so you can confirm the same-process attribution yourself. Want me to upload that?

  4. removed
    needs more info
    on Dec 1, 2026
  5. juliusmarminge commented on Dec 1, 2026

    @juliusmarminge
    Member

    @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)?

  6. added
    needs more info
    on Dec 1, 2026
  7. srafyhucl-cpu commented on Dec 1, 2026

    @srafyhucl-cpu
    Author

    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: makeWithDatabase has a single writer connection with one Semaphore(1) (packages/shared/src/nodeSqliteClient.ts:929,975-979), and transactionAcquirer queues on it with no timeout (:1082-1112). So an in-process slow write cannot produce a 5.4 s BEGIN failure. 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-Sync ran every 2 minutes:

    pythonw.exe D:\...\sync_opencode_to_t3.py --quiet
    

    That script opened statev2.sqlite with sqlite3.connect(target_db, timeout=30, isolation_level=None) and issued BEGIN 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 statev2 only 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 BEGIN by 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_BUSY since.

    Conclusion

    This is not a T3 server defect — it is a third-party process writing statev2.sqlite directly, 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:

    1. The error text "check for another T3 Code process" made me look for a second T3 instance; something like "another program may have the database open" would point at external writers too.
    2. A 5 s busy_timeout is 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.

  8. removed
    needs more info
    on Dec 1, 2026
  9. juliusmarminge commented on Dec 1, 2026

    @juliusmarminge
    Member

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions