Skip to content

db: insertStoredEventRow and markThreadPruningWork re-prepare static SQL on every single event write #8437

Description

@Tiberriver256

Summary

packages/db/src/data/events.ts already uses prepareCachedQuery / prepareCachedQueryVariant across 20+ read queries to avoid synchronous main-thread SQLite statement compilation, yet the single highest-frequency write path in the server—insertStoredEventRow and markThreadPruningWork—was missed.

Every persisted thread event (streaming tokens, tool calls, user messages, system notices) runs both functions inside BEGIN IMMEDIATE write transactions via uncached Drizzle db.run(sql\...`)calls, which recompile SQL and invokebetter-sqlite3's db.$client.prepare()` synchronously on Node's main event loop on every single event write.

Versions & Environment

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

Root Cause

  • packages/db/src/data/events.ts#L463-L481: insertStoredEventRow calls db.run(sql\...`)for its fixed 13-columnINSERT INTO events/INSERT OR IGNORE INTO eventsstatement on every event append instead of caching the two static variants per connection viaprepareCachedQueryVariant`.
  • packages/db/src/data/thread-pruning-work.ts#L7-L15: markThreadPruningWork calls db.run(sql\INSERT OR IGNORE INTO thread_pruning_work (policy, thread_id) VALUES (${THREAD_PRUNING_PENDING_POLICY}, ${threadId})`)on every iteration instead of caching the statement per connection viaprepareCachedQuery(siblingmarkThreadPruningPolicyWorkat#L17-L27` has the same pattern).
  • Production callers: every daemon event batch (appendDaemonEventsInTransaction at events.ts#L904, #L948) and every server-side event append (appendStoredThreadEvent / appendStoredThreadEventsInTransaction at events.ts#L1174, #L1217, #L1245, #L1254-L1268, plus insertEvents at #L543).
  • Both events and threadPruningWork (packages/db/src/schema.ts#L1503) are Drizzle sqliteTables, and prepareTransaction (packages/db/src/connection.ts#L443-L455) already shares the root compiledQueries cache across tx instances, so prepareCachedQuery / prepareCachedQueryVariant works automatically across write transactions with no changes to connection.ts or callers.

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 { appendStoredThreadEvent } from "./packages/db/src/data/events.ts";
import { markThreadPruningWork } from "./packages/db/src/data/thread-pruning-work.ts";
import { createThread } 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; }
}

const args = { threadId: thread.id, scope: { kind: "thread" as const }, type: "system/error" as const, data: { message: "hi" } };
appendStoredThreadEvent(db, noopNotifier, args);
const appendPrepares = countPrepares(() => {
  for (let i = 0; i < 10; i++) appendStoredThreadEvent(db, noopNotifier, args);
});
markThreadPruningWork(db, [thread.id]);
const markPrepares = countPrepares(() => {
  for (let i = 0; i < 10; i++) markThreadPruningWork(db, [thread.id]);
});
console.log(JSON.stringify({ appendStoredThreadEvent_10warm: appendPrepares, markThreadPruningWork_10warm: markPrepares }));
db.$client.close();
'

Actual output

{"appendStoredThreadEvent_10warm":20,"markThreadPruningWork_10warm":10}

Expected behavior

  • insertStoredEventRow (both INSERT and INSERT OR IGNORE variants) and markThreadPruningWork (and markThreadPruningPolicyWork in the same file) reuse per-connection prepared statements via prepareCachedQuery / prepareCachedQueryVariant.
  • Warm calls execute 0 new db.$client.prepare() calls ({"appendStoredThreadEvent_10warm":0,"markThreadPruningWork_10warm":0}).

What was ruled out

  • Confirmed neither query has variable placeholder counts or dynamic column lists; both are fixed-shape SQL statements with constant parameter arity (13 columns for events, 2 columns for thread_pruning_work).

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 · Priority: Medium · Effort: Low. Applied labels: threads, perf, confirmed-repro.
    • Reproduction report: REPRODUCED, high confidence. Two clean trusted-main checkouts produce identical extra prepare counts: 12 / 18 / 6 / 6 across four regression cases.
    • Root cause: fixed-shape event and pruning writes bypass the existing transaction-shared prepared-query cache.
    • Ready fix: PR #8449, not merged. Three database files, 215 changed lines; no dependency, migration, or public protocol change. The regression now passes with zero warm prepares; 163 relevant tests, database typecheck, and diff checks pass.
    • Baseline caveat: the broad database run has 785 passing tests but an unrelated queued-message query-plan guard failure, also reproduced on unchanged main. The broad build also encounters an existing plugin SDK-dist ordering failure; scoped database verification succeeds.

    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