← reports

#6786 · Compaction admission chooses a thread-wide event index

BugHigh Effort: Lowthreads · perf · confirmed-repro GitHub issueNovember 1, 2026

Trusted base: 916d684ac23d0b0de82c09cfc7553a50287d2188 · Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

Sending into an already-running thread checks whether a provider compaction is active before admitting input. The database predicate is logically restricted to one turn, but SQLite selects an index that is restricted only to the thread. When the current turn contains no compaction, this synchronous lookup must inspect the thread's entire retained event history before returning false. Two clean checkouts of trusted main reproduce the same plan and growing warm-memory lookup time: about 0.02 ms with no history, 4.2 ms with 20,000 old events, and 34 ms with 100,000 old events. Forcing the existing turn index makes the same missing-compaction query stay near 0.02–0.03 ms in these fixtures, without changing its answer. The reported multi-second production stalls were not recreated or independently measured; this report confirms the underlying unbounded lookup, not those particular wall times.

2. Claims vs findings

ClaimStatusEvidence
The compaction check can seek by thread only instead of by turn.VerifiedThe real exported function emits the query below; EXPLAIN shows the thread-only index in both runs.
Cost grows with old events even when the current turn is unchanged.VerifiedThree fixtures differ only in historical event count; all have one ordinary current-turn row and no compaction. Measurements below.
An existing turn-selective index can avoid this scan.Verified, narrow caseA separately prepared SQL alternative returns the same missing row and seeks by thread, turn and type. No production code is modified.
The check occurs on active-turn send and child-report admission.Verified staticallyTrusted server callers shown in the root-cause section.
The regression was introduced with provider-compaction queuing.VerifiedGit blame attributes the predicate to commit 7421e656d63 (PR #6420).
Specific macOS production stalls last seconds; cold storage magnifies them.Unverified hereNo reporter database, device, logs, or runtime data was accessed. No cold-cache or HTTP-send experiment was run.

3. Environment

4. Minimal reproduction

  1. Create a clean checkout of trusted main at the recorded commit, install frozen dependencies, and build the owning dependency graph:
    git clone https://github.com/get-bb/bb.git bb-admission-repro
    cd bb-admission-repro
    git checkout --detach 916d684ac23d0b0de82c09cfc7553a50287d2188
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=@bb/db...
  2. Save the following newly authored patch as /tmp/admission-regression.patch and apply it. This adds a test only; production code stays unchanged. It extends the trusted query-plan test's existing migration, capture and plan helpers.
    diff --git a/packages/db/test/query-plans.test.ts b/packages/db/test/query-plans.test.ts
    index 806c2d299e..344b8c8642 100644
    --- a/packages/db/test/query-plans.test.ts
    +++ b/packages/db/test/query-plans.test.ts
    @@ -31,6 +31,7 @@ import {
       listStoredEventRowsInSequenceRange,
       getLastStoredProviderThreadId,
       insertEvents,
    +  isStoredTurnProviderCompactionRunning,
       listActiveBackgroundTaskCountsByThreadIds,
       listItemEventSpansByItems,
       listLatestBackgroundTaskStateRowsByItemIds,
    @@ -263,6 +264,96 @@ function expectNoThreadOnlyEventSeek(details: string): void {
     }
     
     describe("slow query index plans", () => {
    +  it.each([0, 20_000, 100_000])(
    +    "bounds compaction admission to the active turn with %i historical events",
    +    (historySize) => {
    +      const { db, thread } = setup();
    +      try {
    +        const seed = db.$client.prepare(`INSERT INTO events
    +          (id, thread_id, scope_kind, turn_id, sequence, type, item_id, item_kind, data, created_at)
    +          VALUES (?, ?, 'turn', ?, ?, 'item/completed', ?, 'agentMessage', ?, 0)`);
    +        const payload = JSON.stringify({ text: "content".repeat(146) });
    +        db.$client.transaction(() => {
    +          for (let sequence = 1; sequence <= historySize; sequence += 1) {
    +            seed.run(
    +              `admission-event-${sequence}`,
    +              thread.id,
    +              `historical-turn-${Math.floor(sequence / 20)}`,
    +              sequence,
    +              `admission-item-${sequence}`,
    +              payload,
    +            );
    +          }
    +          seed.run(
    +            "active-event",
    +            thread.id,
    +            "active-turn",
    +            historySize + 1,
    +            "active-item",
    +            payload,
    +          );
    +        })();
    +        const captured = captureStatements(db, () => {
    +          expect(
    +            isStoredTurnProviderCompactionRunning(db, {
    +              threadId: thread.id,
    +              turnId: "active-turn",
    +            }),
    +          ).toBe(false);
    +        });
    +        expect(captured).toHaveLength(1);
    +        const query = captured[0]!;
    +        const details = queryPlanDetails({ db, ...query });
    +        const alternativeSql = query.sql.replace(
    +          'from "events"',
    +          'from "events" INDEXED BY events_thread_turn_type_item_sequence_idx',
    +        );
    +        const alternativePlan = queryPlanDetails({
    +          db,
    +          ...query,
    +          sql: alternativeSql,
    +        });
    +        const current = db.$client.prepare(query.sql);
    +        const alternative = db.$client.prepare(alternativeSql);
    +        expect(current.get(...query.params)).toEqual(
    +          alternative.get(...query.params),
    +        );
    +        const measure = (statement: typeof current) => {
    +          const samples = Array.from({ length: 9 }, () => {
    +            const started = performance.now();
    +            statement.get(...query.params);
    +            return performance.now() - started;
    +          }).sort((left, right) => left - right);
    +          return Number(samples[4]!.toFixed(4));
    +        };
    +        console.info(
    +          JSON.stringify({
    +            historySize,
    +            result: false,
    +            sql: query.sql,
    +            plan: details,
    +            alternativePlan,
    +            currentMedianMs: measure(current),
    +            alternativeMedianMs: measure(alternative),
    +            sqlite: db.$client
    +              .prepare("SELECT sqlite_version() AS version")
    +              .get(),
    +            statistics: db.$client
    +              .prepare(
    +                "SELECT name FROM sqlite_master WHERE name = 'sqlite_stat1'",
    +              )
    +              .all(),
    +          }),
    +        );
    +        expect(alternativePlan).toMatch(/thread_id=\? AND turn_id=\?/);
    +        expect(details).toMatch(/thread_id=\? AND turn_id=\?/);
    +        expectNoThreadOnlyEventSeek(details);
    +      } finally {
    +        db.$client.close();
    +      }
    +    },
    +  );
    +
       it("checks spawn-agent history without reading unrelated event payloads", () => {
         const { db, thread } = setup();
         try {
    
    git apply /tmp/admission-regression.patch
    pnpm exec turbo run test --filter=@bb/db --force -- test/query-plans.test.ts -t 'bounds compaction admission'
  3. Expected invariant: the emitted query seeks by both thread and turn, independent of old history. Actual: the false result is correct, but all three turn-bound plan assertions fail; the failure is intentional and demonstrates the performance regression, not incorrect compaction state.
    AssertionError: expected 'SEARCH events USING INDEX events_thre…' to match /thread_id=\? AND turn_id=\?/
     Test Files  1 failed (1)
          Tests  3 failed | 49 skipped (52)
    Expected plan constraint: thread_id=? AND turn_id=?
    Actual plan: SEARCH events USING INDEX events_thread_sequence_idx (thread_id=?)
    Alternative plan: SEARCH events USING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=?)
    USE TEMP B-TREE FOR ORDER BY

The test captures the real function's SQL, rather than reconstructing its predicate. Timings are medians of nine sequential warm samples per prepared statement; they are diagnostic output, not flaky timing assertions. Current-plan samples run before alternative-plan samples, so these are not randomized performance trials.

RunHistorical eventsEmitted query medianTurn-index alternative median
First checkout00.0213 ms0.0192 ms
First checkout20,0004.1972 ms0.0184 ms
First checkout100,00033.9767 ms0.0344 ms
Second clean checkout00.0189 ms0.0224 ms
Second clean checkout20,0004.2445 ms0.0185 ms
Second clean checkout100,00034.1868 ms0.0189 ms

5. Root cause

isStoredTurnProviderCompactionRunning executes this synchronous query before deciding whether a compaction is running:

select "type" from "events" where (("events"."thread_id" = ? and "events"."turn_id" = ?) and "events"."type" in (?, ?) and "events"."item_kind" = ? and "events"."parent_tool_call_id" is null) order by "events"."sequence" desc limit ?

The unique (thread_id, sequence) index satisfies the ordering, but cannot seek by turn. With no matching compaction in the current turn, SQLite walks all rows for that thread and consults their table records to reject them. The existing (thread_id, turn_id, type, item_id, sequence) index can narrow to the current turn and lifecycle types, at the cost of a temporary ORDER BY sort.

Trusted server evidence: isManualCompactionActive calls the predicate for the active stored turn; non-start dispatch admission calls that helper before proceeding. The same helper appears in queued message admission and child report admission, including a transaction-backed read.

Because better-sqlite3's .get() finishes synchronously, time spent scanning also occupies the server's JavaScript thread. This explains the direction of the reported responsiveness impact, although this reproduction does not measure an HTTP request or event-loop stall.

The later accepted-input probe cannot prevent the first query's scan. Reordering alone would also leave provider-started turns without accepted input exposed. Separately, getStoredTurnRequestEventForTurn has its own ORDER BY accepted-input lookup; its performance was not reproduced in this report.

6. Proposed fix

Make the compaction lifecycle lookup deterministically turn-bounded, using the already-migrated turn index or an equivalently selective query shape. Preserve the lifecycle ordering, top-level-only compaction condition and accepted-input behavior. Keep a regression at the DB query-plan owner boundary; it must catch a thread-only seek without relying on wall-clock thresholds.

Tradeoffs: forcing an index binds the query to its name, so dropping or renaming it must update this query. This index does not satisfy the complete ordering and therefore sorts the current turn's candidate rows. Large current turns and started/completed/nested/accepted-input semantics still need normal CI coverage.

7. Linked PR review and fix decision

PR #6787 was OPEN and linked via GitHub's closing-issue metadata to #6786. Its diff was read as untrusted data only, after the fresh reproduction test was designed. No PR branch or test was checked out or executed.

Static finding: the change in packages/db/src/data/events.ts:3745 selects the existing turn index and adjusts the projection type while retaining the predicate and descending limit. This directly addresses the verified access-path cause. The added query-plan/lifecycle coverage targets the right owning package. No blocker was identified by this limited static review; the explicit-index rename risk and current-turn sort cost remain.

Verdict: consistent with the verified root cause, static review only—not runtime validation of the PR. The alternative-SQL experiment proves selectivity and equal results only for the missing-compaction fixture. PR CI must establish complete lifecycle correctness.

No duplicate fix branch or PR was created because an open linked fix already exists. No production changes were made in either reproduction checkout.

8. Verification

The same agent repeated the reproduction in a second clean temporary checkout at exactly 916d684ac23d0b0de82c09cfc7553a50287d2188, with a separate dependency installation and fresh migrated databases. Before adding the newly authored test, git status --short was empty and the unmodified query-plan suite passed 49/49.

pnpm exec turbo run test --filter=@bb/db -- test/query-plans.test.ts
Result on unchanged second checkout: 1 file passed; 49 tests passed.

pnpm exec turbo run test --filter=@bb/db --force -- test/query-plans.test.ts -t 'bounds compaction admission'
Result after adding only the reproduction test: 1 file failed; 3 failed; 49 skipped.
All three failures: emitted plan lacks turn_id in the index seek.

git diff --check
Result in both reproduction checkouts: passed.
git diff --numstat
Result in both: 91 additions, 0 deletions; packages/db/test/query-plans.test.ts only.

Both runs show the same SQL, the same thread-only baseline plan, a turn-bounded alternative, and the same false predicate result. No report correction was needed after the second run. This is a repeated clean verification by the same agent, not an independent review. The first checkout's test file was formatted with the existing oxfmt tool before either recorded run.

9. Related issues

The relevant open fix is #6787; introduction history identifies #6420. Other performance reports cited by the issue were not independently investigated and are not needed to establish this lookup's defect.

10. Appendix and trust boundary

The issue and linked PR were treated as untrusted claims. No issue-supplied code, patch, script, URL target, or branch was run. The regression above was authored from trusted main's exported function, schema and existing test helpers. Read-only GitHub metadata established repository visibility, issue classification and the open linked PR.

Evidence retained locally includes the complete Turbo output, authored test diff, build output and read-only metadata. Repository policy forbids publishing separate log/test/diff artifacts, so the complete reproduction patch and relevant measured output are inline above. No database, private path, account identity, credential, real thread identifier, or provider transcript is published.

Investigation commands included git fetch of the trusted target main, git clone --shared --no-hardlinks for each clean local checkout, git rev-parse HEAD, git status --short, git blame -L 3737,3777, the frozen installs, Turbo build/type-generation/test commands recorded above, pnpm exec oxfmt packages/db/test/query-plans.test.ts, and git diff --check. No dependency was added.