Skip to content

db: hot-path queue-drain queries in queued-thread-messages.ts block the main event loop 17×–27× longer by recompiling multi-alias SQL on every call #8363

Description

@Tiberriver256

Summary

Four hot-path queue inspection functions in packages/db/src/data/queued-thread-messages.ts run synchronously on Node's main event loop on every queue drain, turn completion, send, and steer (queued-thread-messages.ts#L1583-L1645, apps/server/src/services/threads/queued-message-dispatch.ts#L85,L264,L278,L356,L360,L394, apps/server/src/services/threads/dispatch-attempt.ts#L869), 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 empty-table lookups take 17.8 ms for getThread (1 prepare), versus 297–480 ms (17×–27× slower, 1,000 prepares each):

  • isThreadQueueAutoSendPaused (4-table-alias nested NOT EXISTS (EXISTS (...))): 480.2 ms
  • listQueuedThreadMessagesWaitingOnKind: 335.9 ms
  • listQueuedThreadMessages: 296.8 ms
  • hasClaimedQueuedThreadMessages: 70.4 ms

Versions & Environment

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

Root Cause

Unlike 9 sibling packages/db/src/data/*.ts modules that compile fixed-shape queries once per connection via prepareCachedQuery (packages/db/src/connection.ts#L71-L84), these 4 functions construct fresh Drizzle query builders on every invocation:

Note: manuallyStoppedQueuePauseQuery currently accepts string | typeof threads.id (for its column-correlated caller at L1496); widening that parameter to also accept ReturnType<typeof sql.placeholder> (or SQLWrapper) allows isThreadQueueAutoSendPaused to compile it once via prepareCachedQuery without duplicating the 55-line subquery.

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 {
  listQueuedThreadMessages,
  isThreadQueueAutoSendPaused,
  listQueuedThreadMessagesWaitingOnKind,
  hasClaimedQueuedThreadMessages,
} from "./packages/db/src/data/queued-thread-messages.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)),
  isThreadQueueAutoSendPaused: measure(1000, (db, id) => isThreadQueueAutoSendPaused(db, id)),
  listQueuedThreadMessages: measure(1000, (db, id) => listQueuedThreadMessages(db, id)),
  listQueuedThreadMessagesWaitingOnKind: measure(1000, (db, id) => listQueuedThreadMessagesWaitingOnKind(db, { threadId: id, kind: "plugin" })),
  hasClaimedQueuedThreadMessages: measure(1000, (db, id) => hasClaimedQueuedThreadMessages(db, id)),
}));
'

Actual output

{"getThread_cached":{"prepares":1,"ms":17.8},"isThreadQueueAutoSendPaused":{"prepares":1000,"ms":480.2},"listQueuedThreadMessages":{"prepares":1000,"ms":296.8},"listQueuedThreadMessagesWaitingOnKind":{"prepares":1000,"ms":335.9},"hasClaimedQueuedThreadMessages":{"prepares":1000,"ms":70.4}}

Expected behavior

All 4 functions should prepare their SQL once per connection (prepares: 1 for 1,000 calls), eliminating synchronous AST recompilation and sqlite3_prepare_v2 overhead on the main event loop. Only packages/db/src/data/queued-thread-messages.ts needs changes (pnpm exec turbo run test --filter=@bb/db).

What was ruled out

  • Confirmed all 4 queries have fixed SQL shapes with only scalar parameters (threadId, and kind for listQueuedThreadMessagesWaitingOnKind).
  • Confirmed prepareCachedQuery shares compiledQueries across DbConnection and DbTransaction (packages/db/src/connection.ts#L437-L445).

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, high root-cause confidence. In two clean trusted-main checkouts, each affected inspection prepares SQL 40 times for 40 reads, rather than once. The original timing ratios were not measured.
    • Root cause: four fixed-shape synchronous queue queries rebuild their Drizzle builders and native prepared statements on every call instead of reusing the existing connection-local cache.
    • Fix: ready PR #8367 caches placeholder statements without changing query semantics. All four regression cases now pass; 766 database tests, typecheck, type-aware lint, and diff checks pass. 149 changed text lines across three files. The PR is 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