Skip to content

db: hot-path thread search indexing and startup lookups in threads.ts recompile SQL on every call #8438

Description

@Tiberriver256

Summary

packages/db/src/data/threads.ts already imports prepareCachedQuery (used by getThread, getThreadStatus, and listActiveHostThreads) to avoid synchronous Drizzle AST compilation and SQLite statement preparation on Node's main event loop. However, four fixed-shape hot-path queries in the same file were missed and still recompile and re-prepare SQL on every invocation:

Versions & Environment

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

Root Cause

All four functions build fresh Drizzle query objects and call .run() / .get() directly instead of using prepareCachedQuery with sql.placeholder(...) bindings like sibling functions getThread (#L461), listActiveHostThreads (#L1882), and getThreadStatus (#L2588). prepareTransaction (packages/db/src/connection.ts#L443-L455) shares the per-connection compiledQueries cache across tx instances, so caching works inside write transactions too.

Reproduction

Run from repo root at 272957819d:

pnpm exec tsx -e '
import { createMigratedConnection } from "./packages/db/src/testing.ts";
import { noopNotifier } from "./packages/db/src/notifier.ts";
import { createThread, getThread, upsertThreadSearchSegments, getThreadStartupContext, isThreadCopyingForkHistory } from "./packages/db/src/data/threads.ts";
import { ensurePersonalProject } from "./packages/db/src/data/projects.ts";

const db = createMigratedConnection();
const project = ensurePersonalProject(db);
const thread = createThread(db, noopNotifier, { projectId: project.id, providerId: "codex" });

function countPrepares(fn: () => void) {
  let count = 0;
  const orig = db.$client.prepare.bind(db.$client);
  db.$client.prepare = ((...a: Parameters<typeof orig>) => { count++; return orig(...a); }) as typeof orig;
  try { fn(); return count; } finally { db.$client.prepare = orig; }
}

getThread(db, thread.id);
const control10 = countPrepares(() => { for (let i = 0; i < 10; i++) getThread(db, thread.id); });

upsertThreadSearchSegments(db, { segments: [{ threadId: thread.id, sourceKind: "user-message", sourceKey: "k-w", sourceSeq: 1, text: "warm" }] });
const upsert10 = countPrepares(() => {
  for (let i = 0; i < 10; i++) {
    upsertThreadSearchSegments(db, { segments: [{ threadId: thread.id, sourceKind: "user-message", sourceKey: `k-${i}`, sourceSeq: i + 2, text: `hello ${i}` }] });
  }
});

upsertThreadSearchSegments(db, { segments: [{ threadId: thread.id, sourceKind: "user-message", sourceKey: "k-d", sourceSeq: 1, text: "" }] });
const delete10 = countPrepares(() => {
  for (let i = 0; i < 10; i++) {
    upsertThreadSearchSegments(db, { segments: [{ threadId: thread.id, sourceKind: "user-message", sourceKey: `k-${i}`, sourceSeq: i + 2, text: "" }] });
  }
});

getThreadStartupContext(db, thread.id);
const startup10 = countPrepares(() => { for (let i = 0; i < 10; i++) getThreadStartupContext(db, thread.id); });
isThreadCopyingForkHistory(db, thread.id);
const fork10 = countPrepares(() => { for (let i = 0; i < 10; i++) isThreadCopyingForkHistory(db, thread.id); });

console.log(JSON.stringify({ getThread_control_10warm: control10, upsertSearch_10warm: upsert10, deleteSearch_10warm: delete10, getStartupContext_10warm: startup10, isCopyingFork_10warm: fork10 }));
db.$client.close();
'

Actual output

{"getThread_control_10warm":0,"upsertSearch_10warm":10,"deleteSearch_10warm":10,"getStartupContext_10warm":10,"isCopyingFork_10warm":10}

Expected behavior

  • All four fixed-shape functions reuse per-connection prepared statements via prepareCachedQuery with sql.placeholder(...) bindings (keeping upsertThreadSearchSegmentBatch untouched).
  • Warm calls execute 0 new SQLiteSyncDialect.prototype.sqlToQuery compilations and 0 new db.$client.prepare() calls, matching the getThread control.

What was ruled out

  • Confirmed all four queries have static SQL structure and fixed parameter counts; no dynamic IN (...) lists or optional WHERE clauses.

AGENT GENERATED

Activity

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

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Bug · Medium priority · Low effort. Applied threads, perf, and confirmed-repro; no existing classifications were replaced.
    • Report: https://get-bb.github.io/reports/issues/8438.html — REPRODUCED, high root-cause confidence. Repeated the reproduction in clean trusted checkouts without running issue-provided code.
    • Root cause: Four fixed-shape thread queries bypass the connection-level statement cache, recompiling SQL and preparing SQLite statements on every call.
    • Verification: Four regression cases fail before the fix; afterward, all 188 affected tests pass, including zero warm compilations/prepares. Database typecheck and type-aware lint pass. Two unrelated queue-plan guard failures also reproduce on unchanged main; the baseline full build separately lacks built Plugin SDK entries.
    • Fix: Ready PR Cache prepared statements for thread indexing and startup reads #8451 — 215 changed text lines across two database files; no dependency, schema, migration, or protocol 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