Skip to content

db: readThreadRunState and thread-run-state queries block the main event loop 18× longer by recompiling SQL on every thread lifecycle transition #8364

Description

@Tiberriver256

Summary

readThreadRunState, hasThreadStartTurnRequest, and the fixed SELECT/DELETE queries in writeThreadLifecycleStateInTransaction (packages/db/src/data/thread-run-state.ts) execute synchronously on Node's main event loop on every thread lifecycle transition (apps/server/src/services/threads/lifecycle/run.ts#L85,L268, apps/server/src/services/threads/thread-lifecycle.ts#L674,L1003), yet rebuild their Drizzle SQL ASTs and call sqlite3_prepare_v2 (better-sqlite3 prepare()) on every single call.

On clean origin/main (b0ddaad731), 1,000 calls take 10.4 ms for getThread (1 prepare), versus 182.5 ms (18× slower, 2,000 prepares) for readThreadRunState, 69.3 ms (1,000 prepares) for hasThreadStartTurnRequest, and 275.3 ms (1,000 prepares) for a no-op writeThreadLifecycleStateInTransaction.

Versions & Environment

  • Commit: b0ddaad731565d7e4de68d824120d802fc78f7d5 (origin/main)
  • Node: v26.13.1
  • OS: Linux x64

Root Cause

The lifecycle hot-path queries in packages/db/src/data/thread-run-state.ts construct fresh Drizzle query builders on every call instead of compiling once per connection via prepareCachedQuery + placeholder("threadId") (matching sibling modules threads.ts, hosts.ts, and events.ts):

Reproduction

Run from repo root at b0ddaad731565d7e4de68d824120d802fc78f7d5:

node --conditions=source --import tsx -e '
import { performance } from "node:perf_hooks";
import { createMigratedConnection } from "./packages/db/src/testing.ts";
import { ensurePersonalProject } from "./packages/db/src/data/projects.ts";
import { createThread, getThread } from "./packages/db/src/data/threads.ts";
import { readThreadRunState, hasThreadStartTurnRequest, writeThreadLifecycleStateInTransaction } from "./packages/db/src/data/thread-run-state.ts";
import { noopNotifier } from "./packages/db/src/notifier.ts";

function measure(n: number, fn: (db: ReturnType<typeof createMigratedConnection>, threadId: string) => void) {
  const db = createMigratedConnection();
  const project = ensurePersonalProject(db);
  const thread = createThread(db, noopNotifier, { projectId: project.id, providerId: "codex", status: "idle" });
  let prepares = 0;
  const orig = db.$client.prepare.bind(db.$client);
  db.$client.prepare = ((sql: string) => { prepares++; return orig(sql); }) as typeof db.$client.prepare;
  const t0 = performance.now();
  for (let i = 0; i < n; i++) fn(db, thread.id);
  const ms = +(performance.now() - t0).toFixed(1);
  db.$client.close();
  return { prepares, ms };
}

console.log(JSON.stringify({
  getThread_cached: measure(1000, (db, id) => getThread(db, id)),
  readThreadRunState: measure(1000, (db, id) => readThreadRunState(db, id)),
  hasThreadStartTurnRequest: measure(1000, (db, id) => hasThreadStartTurnRequest(db, id)),
  writeThreadLifecycleStateInTransaction: measure(1000, (db, id) => db.transaction((tx) => writeThreadLifecycleStateInTransaction(tx, {
    threadId: id,
    expectedStatus: "idle",
    failureKind: null,
    previous: { heldCompletion: null, requests: [], stop: null },
    next: { status: "idle", heldCompletion: null, requests: [], stop: null },
  }))),
}));
'

Actual output

{"getThread_cached":{"prepares":1,"ms":10.4},"readThreadRunState":{"prepares":2000,"ms":182.5},"hasThreadStartTurnRequest":{"prepares":1000,"ms":69.3},"writeThreadLifecycleStateInTransaction":{"prepares":1000,"ms":275.3}}

Expected behavior

  • readThreadRunState (2 prepares), hasThreadStartTurnRequest (1 prepare), and the fixed SELECT/DELETE statements in writeThreadLifecycleStateInTransaction (1 prepare each) should compile once per connection via prepareCachedQuery with placeholder("threadId").
  • Scope is limited to these lifecycle hot-path queries in packages/db/src/data/thread-run-state.ts (the 3 infrequent sweep/reconnect queries at #L248-L301 are intentionally out of scope).

What was ruled out

  • Confirmed prepareCachedQuery shares the connection's compiledQueries map across DbTransaction instances (packages/db/src/connection.ts#L437-L445), so transactional calls in writeThreadLifecycleStateInTransaction reuse prepared statements safely.

AGENT GENERATED

Activity

  1. added theissue type on Nov 29, 2026
  2. added
    threads
    confirmed-repro
    on Nov 29, 2026
  3. bb-slop-cop commented on Nov 29, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Priority Medium · Effort Low. Applied labels: threads, perf, confirmed-repro.
    • Reproduction report: REPRODUCED, with high root-cause confidence. Two clean trusted-main checkouts produce the same failure.
    • Root cause: fixed lifecycle SELECT/DELETE builders bypass the connection's prepared-query cache, repeatedly compiling and preparing synchronous SQL.
    • Evidence: the authored regression records 48 compilations and 48 preparations after warm-up before the fix, and zero afterward while verifying fresh reads and transactional cleanup. All 763 database tests, typecheck, type-aware lint, and the repository build pass. The original precise timing multiplier was not verified.
    • Ready fix: PR #8368, 201 changed text lines across two database files; no dependency, schema, protocol, or stored-data changes. Not merged.

    AGENT GENERATED

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

    confirmed-reproperfthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions