Skip to content

db: hot-path turn and event-state queries in events.ts block the main event loop 13×–47× longer by recompiling SQL on every call #8362

Description

@Tiberriver256

Summary

Six hot-path query functions in packages/db/src/data/events.ts run synchronously on Node's main event loop during every turn lifecycle transition, daemon event batch, and send/steer check, yet rebuild their Drizzle SQL AST and call sqlite3_prepare_v2 (better-sqlite3 prepare()) on every single invocation.

On clean origin/main (b0ddaad731), 1,000 calls on an empty thread take 10.0 ms for the already-compiled getLatestThreadSequence (1 prepare), versus 102–468 ms (13×–47× slower, 1,000 prepares each) for these 6 functions:

  • listOpenTurnInputAcceptedRowsByThreadIds (single-thread [threadId] calls): 468.0 ms
  • getStoredProviderSession / readNewestStoredProviderThreadIdentity (empty exclusion list): 285.7 ms
  • getLastStoredTurnRequestEvent / listStoredTurnRequestEventRowsByType (unfiltered 3-way UNION ALL): 206.9 ms
  • getActiveStoredTurnId: 129.6 ms (2 queries when an active turn exists)
  • isTurnAimedAtByEarlierStop: 101.9 ms (4 queries when a turn exists)
  • getHighWaterMarks (single-thread [threadId] calls, duplicating prepareLatestThreadSequence in the same file): 37.1 ms

Versions & Environment

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

Root Cause

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 } from "./packages/db/src/data/threads.ts";
import {
  getActiveStoredTurnId,
  isTurnAimedAtByEarlierStop,
  getLastStoredTurnRequestEvent,
  getStoredProviderSession,
  getHighWaterMarks,
  listOpenTurnInputAcceptedRowsByThreadIds,
  getLatestThreadSequence,
} from "./packages/db/src/data/events.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({
  getLatestThreadSequence_cached: measure(1000, (db, id) => getLatestThreadSequence(db, { threadId: id })),
  getActiveStoredTurnId: measure(1000, (db, id) => getActiveStoredTurnId(db, id)),
  isTurnAimedAtByEarlierStop: measure(1000, (db, id) => isTurnAimedAtByEarlierStop(db, { threadId: id, turnId: "t1" })),
  getLastStoredTurnRequestEvent: measure(1000, (db, id) => getLastStoredTurnRequestEvent(db, id)),
  getStoredProviderSession: measure(1000, (db, id) => getStoredProviderSession(db, id)),
  getHighWaterMarks_single: measure(1000, (db, id) => getHighWaterMarks(db, [id])),
  listOpenTurnInputAcceptedRows_single: measure(1000, (db, id) => listOpenTurnInputAcceptedRowsByThreadIds(db, { threadIds: [id] })),
}));
'

Actual output

{"getLatestThreadSequence_cached":{"prepares":1,"ms":10},"getActiveStoredTurnId":{"prepares":1000,"ms":129.6},"isTurnAimedAtByEarlierStop":{"prepares":1000,"ms":101.9},"getLastStoredTurnRequestEvent":{"prepares":1000,"ms":206.9},"getStoredProviderSession":{"prepares":1000,"ms":285.7},"getHighWaterMarks_single":{"prepares":1000,"ms":37.1},"listOpenTurnInputAcceptedRows_single":{"prepares":1000,"ms":468}}

Expected behavior

  • Each of these 6 functions should prepare its static SQL once per connection (prepares: 1 for the repro above, and 1 per executed branch in getActiveStoredTurnId / isTurnAimedAtByEarlierStop when events exist), cutting synchronous event-loop latency to match getLatestThreadSequence.
  • Scope is strictly limited to packages/db/src/data/events.ts (leaving multi-thread threadIds.length > 1, non-empty excludedProviderThreadIds, and non-null filter paths unchanged) and verified via pnpm exec turbo run test --filter=@bb/db.

What was ruled out

  • Confirmed prepareCachedQuery and prepareCachedQueryVariant are already imported in events.ts#L51-L52, shared safely across DbTransaction instances (packages/db/src/connection.ts#L437-L445), and cleared on sqlite.close() (packages/db/src/connection.ts#L482-L487).

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; labels: threads, perf, confirmed-repro.
    • Report: https://get-bb.github.io/reports/issues/8362.html — REPRODUCED, high root-cause confidence; repeated in a second clean trusted checkout.
    • Root cause: Six stable event-query paths rebuild and prepare synchronous SQL on every read instead of reusing the existing per-connection cache.
    • Evidence: Six regression cases fail before the fix; the cached control passes. Afterward, all 769 database tests and typechecking pass. Empty-thread reads drop from 500 preparations per 500 calls to one; original absolute timing claims were not assumed.
    • Ready fix PR: Cache compiled SQL for static thread event reads #8369 — 2 files, 435 changed text lines; no schema, protocol, or dependency 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