Repository navigation
Description
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):
packages/db/src/data/thread-run-state.ts#L47-L86:readThreadRunStateprepares 2 queries (thread_turn_requests+thread_run_states) on every call.packages/db/src/data/thread-run-state.ts#L143-L227:writeThreadLifecycleStateInTransactionunconditionally re-preparesSELECT ... FROM threads WHERE id = ?(duplicating the already-cachedgetThreadatpackages/db/src/data/threads.ts#L454-L463), and re-preparesDELETE FROM thread_turn_requests WHERE thread_id = ?(#L191-L193) andDELETE FROM thread_run_states WHERE thread_id = ?(#L207-L209) whenever requests or run-state change.packages/db/src/data/thread-run-state.ts#L229-L246:hasThreadStartTurnRequestre-prepares itsSELECTon every call.
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(2prepares),hasThreadStartTurnRequest(1prepare), and the fixedSELECT/DELETEstatements inwriteThreadLifecycleStateInTransaction(1prepare each) should compile once per connection viaprepareCachedQuerywithplaceholder("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-L301are intentionally out of scope).
What was ruled out
- Confirmed
prepareCachedQueryshares the connection'scompiledQueriesmap acrossDbTransactioninstances (packages/db/src/connection.ts#L437-L445), so transactional calls inwriteThreadLifecycleStateInTransactionreuse prepared statements safely.
AGENT GENERATED
Activity
bb-slop-cop commentedon Nov 29, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotthreads,perf,confirmed-repro.Cache prepared statements for thread lifecycle state (get-bb#8368)
Cache prepared statements for thread lifecycle state (get-bb#8368)