Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): thread list reads no longer freeze the server on large databases #19226

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 2 commits intomain fromrefs/pull/19226/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Problem

Users keep getting kicked to "reconnecting". The server runs node:sqlite on its main thread. Every client connect, and a pull request sweep once a minute, read the whole thread list in one transaction, which takes seconds on large databases. During that read the event loop is stuck, heartbeats miss their timeout, and every reconnect runs the same read again (#14701).

Change

The heavy read snapshots now run on a second, read-only SQLite connection in a worker thread. Writes and all other reads stay on the main connection as before, so write ordering does not change.

  • nodeSqliteClient gets a readerWorker option and a readOnly marker. A transaction run under readOnly goes to the reader: read-only open, WAL required, deferred BEGIN, its own lock.
  • Two callers are marked: the WebSocket connect shell snapshot (active and archived) and the once-a-minute pull request discovery pass.
  • If the reader can't start, finds a non-WAL database, or doesn't report ready within 10 s, it is turned off with one warning, and reads use the main connection. In-memory databases (tests) and reads inside an open write transaction also stay on the main connection. If the reader crashes, its in-flight reads fail and the next read starts a new worker.

This takes over #14703 by @saphid. Their two commits are cherry-picked unchanged onto current main. It replaces #19211, which moved all SQLite into a worker (from #18736 by @not-compromised). That approach changed timing across orchestration: about 18 server tests failed, and the order in which a user message and an agent-queued message became runs changed. Keeping writes on the main thread avoids all of that. #19205 already removed most of the per-commit fsync stalls on the write side.

Scope and approval

Fixes the read stall in #14701, which was triaged as a bug. Theo chose this narrow design over the full worker. No wire contract or schema changes.

Verification

  • Benchmark on a 3.6 GB copy of a real database (427 threads, 70k turn items), using the real ProjectionStore and persistence layer. It ran 8 parallel shell snapshots while a writer inserted every 5 ms, alternating runs, 6 rounds per side:

    mainthis PR
    Max event-loop gap54–67 ms12–18 ms
    Event-loop delay p9954–62 ms8–16 ms
    Writes completed during the snapshots289–93
    Wall time551–705 ms534–664 ms

    #14703's own A/B on a 33 GB database measured a 1.4–2.2 s gap on main and 13–17 ms with this change. It also includes GCP stress and failure tests.

  • Real server: a dev server on seeded real data loads the thread list and a large thread from the web client through the reader. The server runs one reader worker and logs no fallback warning.

  • Tests: the shared SQLite client, server persistence, ShellStream, ThreadPullRequestService, ws.test, scheduled tasks, ThreadLaunchService, ProviderSessionManager, ProjectService, and title regeneration all pass (46 files, 360 tests). The integration suites that broke under the full worker (OrchestratorReplayFixtures, ClaudeAutomaticDelivery, OrchestratorReplayRecovery) pass 146 of 146. Scoped typecheck and lint pass.

  • Review: GPT-6.1 Sol and Muse Wonder Full both approved. They checked interruption safety (the transaction acquire stays uninterruptible), that the snapshot and live tail cannot miss or double-apply events, and the reader worker lifecycle.

  • Follow-ups, not in this PR:

    • A worker that dies before it is ready makes each later marked read spawn a new worker, with no warning. Reads still fall back correctly.
    • Full per-thread snapshots still read on the main connection. Mark them only if profiling shows event-loop delay.

Original work by @saphid in #14703. Takeover, rebase, and verification by Claude Opus 5.5 in Claude Code, running in T3 Code.

Co-authored-by: Alex Southwell <saphid@gmail.com>

🤖 Generated with Claude Code

Fixes #14701

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — The PR introduces substantial shared SQLite worker-thread infrastructure and changes production read routing and defaults, rather than making a narrowly scoped fix. It also adds a line-level lint suppression, so the operational and static-analysis impacts warrant human review.

      Notes:

      • Diff unchanged. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. juliusmarminge added labelsmacroscope-review

    4. Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB4.9 KiB−23 B (−0.5%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB−23 B (−1.9%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.8 KiB−41 B (−0.2%)29.3 KiB✅
      CodexLive turn messages21−1 (−50.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB0 B (0.0%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB0 B (0.0%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: aba3a6d · PR result: febd5c2 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 108.5 KiB
      • Claude decoded thread snapshot: 108.8 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    5. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Team
      • Run ID: 48d0c9e7-9780-4f97-b73d-817fa2ce4549
      📥 Commits

      Reviewing files that changed from the base of the PR and between aba3a6ddc0d2625739cb65c333f6052a4a35bc71 and febd5c2c3ca54bbae86127c987abd641014b7f15.

      📒 Files selected for processing: 5
      • apps/server/src/orchestration-v2/ShellStream.ts
      • apps/server/src/orchestration-v2/ThreadPullRequestService.ts
      • apps/server/src/persistence/Sqlite.ts
      • packages/shared/src/nodeSqliteClient.test.ts
      • packages/shared/src/nodeSqliteClient.ts

      Included review availability: This review used your included allowance. 9 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 10 reviews per hour.

      📝 Walkthrough

      The SQLite client adds an opt-in reader worker for read-only transactions, with fallback to the writer. Server snapshot reads now use the read-only wrapper, and tests cover routing, transaction behavior, and worker lifecycle.

      Changes: SQLite Read-Only Reader Workers

      Layer / File(s)Summary
      Read-only transaction contract and worker connection
      packages/shared/src/nodeSqliteClient.ts
      The client adds reader configuration and a readOnly wrapper. It implements worker-side query execution and a worker connection that handles requests and failures.
      Reader lifecycle, routing, and fallback
      packages/shared/src/nodeSqliteClient.ts, apps/server/src/persistence/Sqlite.ts, packages/shared/src/nodeSqliteClient.test.ts
      The client starts and manages reader workers, routes eligible read-only transactions to them, and falls back to the writer when needed. Tests cover transaction snapshots, write rejection, fallback, startup failures, cancellation, and concurrent reads.
      Server snapshot reads use read-only routing
      apps/server/src/orchestration-v2/ShellStream.ts, apps/server/src/orchestration-v2/ThreadPullRequestService.ts
      Shell stream snapshot-parts reads and all-thread active shell snapshots use NodeSqliteClient.readOnly. Single-thread snapshot behavior is unchanged.

      Priority: ➖ Normal

      Estimated code review effort: 4 (Complex) | ~45 minutes

      Change: Bug fix

      Sequence Diagram(s)

      sequenceDiagram
        participant Caller as Snapshot caller
        participant Client as NodeSqliteClient
        participant Reader as Reader worker
        participant Writer as Writer connection
        Caller->>Client: Mark transaction read-only
        Client->>Reader: Start worker and check WAL readiness
        alt Reader ready and database uses WAL
          Client->>Reader: Execute read-only transaction
          Reader-->>Client: Return query result
        else Reader unavailable or database is not in WAL mode
          Client->>Writer: Execute transaction
          Writer-->>Client: Return query result
        end

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to febd5

      Selected large snapshot reads now run on a read-only worker connection and fall back to the main connection when the worker is unavailable. No concrete merge-blocking issue was identified.

      Pre-merge checks: Passed 4
      Passed Passed checks: 4 passed
      Check nameStatusExplanation
      Linked Issues checkPassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes checkPassedCheck skipped because no linked issues were found for this pull request.
      Title checkPassedThe title clearly and concisely describes the primary change: moving large thread-list reads to prevent server freezes.
      Description checkPassedThe description includes the required Problem, Change, Scope and approval, and Verification sections. It explains the cause, implementation, scope, approval, fallback behavior, benchmarks, tests, and …
      ✨ Finishing Touches
      📝 Generate docstrings
      • Commit to this branch
      • Create a new PR
      🧪 Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Comment `@coderabbitai help` to get the list of available commands.
    6. Understood. The full-worker repair branch is parked as reference; I am following the narrower design in #19226. No candidate has been installed locally.

      I confirmed the independent ingestion defect on current main, 11fd54fcbbfb39f824bb4c908d428c20d801267c, and filed the focused reproduction in #19228. Only the test file changes, with no SQLite worker or new provider-event fields. Both ownership cases immediately fail with queued child output missing, and server typecheck passes. The issue includes the exact regression patch and command.

      The replacement's six server shards and mobile fingerprint check have passed. I will track its remaining review and CI results.

      Written by GPT-6.1 Sol in Codex.

Sign in to join this conversation.