Skip to content

Seek item events directly when carrying settlements across a message edit - #7287

Merged
ymichael merged 2 commits into
mainfrom
bb/seek-suffix-settlement-item-events
Nov 9, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/seek-suffix-settlement-item-events

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Editing a message deletes the event suffix after it. listThreadEventSuffixBackgroundSettlementRows finds the background-task and delegation settlements in that suffix that must be carried forward. Each candidate settlement runs three correlated probes: is there an earlier item/started for the item, an earlier settlement, or a later one? The probes filter on thread_id and item_id. The only indexes that lead with those two columns are partial, and the probes' bound parameters can't prove their predicates. So SQLite used events_thread_turn_type_item_sequence_idx (thread_id=?) and walked the whole thread's index once per settlement:

SEARCH events USING INDEX events_thread_sequence_idx (thread_id=? AND sequence>? AND sequence<?)
CORRELATED SCALAR SUBQUERY 2
SEARCH suffix_settlement_prefix USING COVERING INDEX events_thread_turn_type_item_sequence_idx (thread_id=?)
CORRELATED SCALAR SUBQUERY 3
SEARCH suffix_settlement_later USING COVERING INDEX events_thread_turn_type_item_sequence_idx (thread_id=?)

Found by a prototype query-plan audit of every statement the db and server test suites run.

What changed

packages/db/src/data/events.ts: the query runs once per item kind, and the results are merged by sequence.

  • Background-task settlements probe through events_background_task_thread_type_item_sequence_idx with the literal item_kind = 'backgroundTask'.
  • Delegation settlements probe through events_delegating_item_lookup_idx with the literal item_kind IN ('toolCall', 'delegation'). This is the same pattern listStoredDelegatingItemRowsByItemIds uses.

Every probe now seeks thread, item and sequence:

SEARCH events USING INDEX events_thread_type_sequence_idx (thread_id=? AND type=? AND sequence>? AND sequence<?)
SEARCH item_event USING COVERING INDEX events_background_task_thread_type_item_sequence_idx (thread_id=? AND type=? AND item_id=? AND sequence<?)
SEARCH item_event USING INDEX events_delegating_item_lookup_idx (thread_id=? AND item_id=? AND sequence<?)
  • Probe types. Each kind's probes look only for its own settlement type (a backgroundTask item can only be settled by item/backgroundTask/completed, a delegation by item/delegation/completed).
  • Item kind invariant. The new probes require started and settlement events to share the item's kind. On a production-data subset, all 1,911 background-task and 70 delegation settlements have a started event of the same kind.

How you verified

  • Same results, faster. I ran the old SQL and the new function side by side on a production-data subset (325k events). The test covered the 6 threads with the most settlements, with edit cutoffs at 10–95% of each thread. All 36 cases returned identical rows.
    • Warm: 9–197 ms before, 0.3–2.8 ms after.
    • Cold first runs of the old query took 0.4–1.4 s.
  • vitest run apps/server/test/threads/thread-edit-message.test.ts: 55 passed.
  • vitest run packages/db/test/data/events.test.ts packages/db/test/query-plans.test.ts: 154 passed.
  • turbo run typecheck --filter=@bb/db --filter=@bb/server passed.

AGENT GENERATED

🤖 Generated with Claude Code

@ymichael
ymichael force-pushed the bb/seek-suffix-settlement-item-events branch from 83fe8bd to 947ba75 Compare November 9, 2026 19:22
ymichael and others added 2 commits November 9, 2026 13:06
…edit

listThreadEventSuffixBackgroundSettlementRows probed for each settlement's
started and earlier/later settlement events with only thread_id usable, so
every settlement in the edited suffix walked the whole thread's index. Split
the query by item kind so each probe seeks thread and item through the
backgroundTask or delegation partial index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The edit test now carries a delegation settlement alongside a background
task, interleaved by sequence, so it fails if the per-kind results are
not merged in order. The query-plan test fails if any settlement probe
falls back to a thread-only index seek.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 9, 2026
## Human comments

## What was wrong

Slow query plans were caught one at a time, after the fact.
`packages/db/test/query-plans.test.ts` holds 43 hand-written plan tests,
each added after a slow query surfaced, against about 420 query
functions. The production slow log is no substitute: only 109 of 4,438
logged slow statements were mostly CPU time, so plan regressions in the
1–10 ms range never reach it.

The miss behind this work is #7238. An events query filtered `type IN
(...)` with `ORDER BY sequence DESC LIMIT 1` walked a whole 20k-event
turn through `events_thread_sequence_idx` instead of seeking
`events_thread_type_sequence_idx`. That plan is an indexed SEARCH, so a
"no full scan" rule can't see it. Without `sqlite_stat1`, which
production never creates, SQLite assumes `thread_id = ?` matches about
10 rows, so walking a thread to skip a sort looks cheap.

## What changed

**Guard.** A Vitest setup file in `@bb/db` and `@bb/server`
(`@bb/db/query-plan-guard`) patches better-sqlite3's `prepare` in test
workers.
- **What it checks.** Every statement a non-test `src/` function
prepares; migrations are skipped. On execution it is explained with its
real bound values against a pristine migrated schema. With no stats,
that is the plan production gets from the same SQLite build.
- **Partial indexes.** Bound values matter for partial indexes, so each
distinct parameter shape is planned. Strings that appear in a
partial-index predicate keep their value; everything else collapses to
its type.

**Rules** (`packages/db/src/query-plan-audit.ts`). Large tables are
those over 20k rows in production: `events`, `thread_search_segments`,
`prompt_history_entries` and `terminal_sessions`.
- **weaker-index.** For each plan step on a large table, the statement
is re-planned with `INDEXED BY` for every other index on that table. The
step is flagged when another index uses more equality terms without
losing range terms. This flags the #7238 SQL; there is a unit test.
- **full-scan** of a large table.
- **automatic index.**
- Temp B-trees are not checked: 126 statements use one, and the plan
alone can't say which matter.

**Allowlist** (`packages/db/src/query-plan-allowlist.ts`). Entries are
keyed by rule, table and `file#function`, each with a measured reason,
18 in total.
- Seven are known-slow with fixes in flight: #7287, #7288 and #7289.
Those entries go once the fixes merge.
- Two are new findings: the timeline backfill reads walk the thread,
about 10 ms per call on a 53k-event thread.
- Any finding not in the allowlist fails the test file, printing the
function, plan and SQL.

**Report mode.** `BB_QUERY_PLAN_REPORT=<file>` writes every finding,
including allowed ones, instead of failing.
- `pnpm --filter @bb/db check:query-plan-allowlist <report>...` fails on
missing entries and on entries no run reported. Feed it reports from an
unsharded db + server run.
- Turbo hashes the variable so report runs never replay a cached result.

**New test.** `packages/db/test/data/timeline-item-backfill.test.ts`
exercises the timeline backfill reads, which no suite ran before.

**Limits.**
- It only sees statements tests execute.
- It doesn't judge result volume.
- It's inactive on Windows shards, because the stack-path matching is
POSIX-only.

## How you verified

- **Full report run.** db + server in report mode gave 84 finding rows,
all allowlisted, and `check:query-plan-allowlist` reported no stale
entries.
- **Negative check.** Removing one allowlist entry fails `@bb/db` with a
readable violation.
- **Measured findings.** On a production-data subset with a seeded
20k-event turn:
- the weaker-index findings ranged from real 17–245× slowdowns to one
case where the chosen index was faster;
- `getUnfinishedCommandItemData` took 2–6 s on production turns (#7289).
- **Unit tests.** `query-plan-audit.test.ts` covers the #7238 shape,
planning partial indexes with bound values, and unique-key lookups.
- **Cost.** The guard adds about 5 s to a local `@bb/db` run: 13.3 s and
15.9 s with it, 8.8 s and 10.2 s without (two runs each, `vitest run` in
`packages/db`). The `@bb/server` CI shards took about as long as on main
(server-1 165 s vs 156 s, server-2 121 s vs 179 s).
- **Checks.** `turbo run typecheck lint` passes for `@bb/db` and
`@bb/server`.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/seek-suffix-settlement-item-events branch from 124454a to 72ae27b Compare November 9, 2026 21:07
@ymichael
ymichael merged commit 4a62387 into main Nov 9, 2026
55 of 57 checks passed
@ymichael
ymichael deleted the bb/seek-suffix-settlement-item-events branch November 9, 2026 21:19
ymichael added a commit that referenced this pull request Nov 9, 2026
## Human comments

## What was wrong

#7254 capped each pruning advance at a 20 ms wall-clock budget
(`THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS`). Several tests still assert
how much a single advance removes, and they ran against the real clock.
When a runner is slow, the budget runs out after fewer 16-row chunks and
the counts come up short. The Windows host packages job has failed on
main this way since `bf09c7c5af`:

- `thread-pruning.test.ts` › "preserves the current latest row when
resuming after truncation": `expected 304 to be 500` (`bf09c7c5af`),
`496` (`60f81b3476`), `256` (`11175a0d52`), and `272`, then `128` on
#7287's run and its re-run.
- `query-plans.test.ts` › "does not parse agentMessage/reasoning
completion payloads for retention support" (`60f81b3476`).

## What changed

These tests now freeze `performance.now`, so the budget never expires
and each advance does its full batch:

- `packages/db/test/data/thread-pruning.test.ts`: the whole describe
block.
- `packages/db/test/query-plans.test.ts`: the three tests that advance
resolved-item pruning.
- `apps/server/test/system/thread-pruning-sweep.test.ts`: the whole
describe block. The two elapsed-budget tests still install their own
clocks over it.
- `apps/server/test/services/threads/timeline-selection-memo.test.ts`:
only inside `advanceSettledThreadPruning`.
- `apps/server/test/system/event-pruning.test.ts` and
`thread-pruning-invalidation.test.ts`: only in the one test in each that
counts live-advance removals.

Spies are restored in `afterEach` (or `finally`).
`resolved-item-pruning-resume.test.ts` still covers the budget itself
with its own fake clock. No production code changes.

## How you verified

- **Reproduced the failure locally.** I set
`THREAD_PRUNING_ADVANCE_WORK_BUDGET_MS` to 1 ms to stand in for a slow
runner. On main this fails the CI test exactly (`expected 16 to be
500`), and 13 tests fail in total:
  - db: 3 in `thread-pruning.test.ts` and 3 in `query-plans.test.ts`.
- server: 4 in `thread-pruning-sweep.test.ts`, 1 in
`timeline-selection-memo.test.ts`, 1 in `event-pruning.test.ts` and 1 in
`thread-pruning-invalidation.test.ts`.
- **At 1 ms with this change:** all of these pass. Across the db and
server suites, the only remaining 1 ms failure is
`resolved-item-pruning-resume.test.ts` › "stops an advance at its time
budget…", which is designed around the real 20 ms value and uses its own
fake clock.
- **At the real 20 ms budget:** `@bb/db` 700/700 passed (`turbo run test
--filter=@bb/db`), and the five server pruning test files 56/56 passed.
- `turbo run typecheck --filter=@bb/db --filter=@bb/server` passed.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 9, 2026
…7299)

## Root cause
The slow-query-plan guard (#7292) landed with seven `knownSlow`
allowlist entries for queries that had fixes in flight. Those fixes have
since merged: #7289 (getUnfinishedCommandItemData), #7288 (five
type-index queries plus getTurnInterruption), and #7287
(listThreadEventSuffixBackgroundSettlementRows). While the entries stay
in the allowlist, the guard would not catch a regression to the slow
plan for any of those queries.

## Change
Delete the seven entries and the now-unused `knownSlow` helper. The
accepted entries, which carry measurements, are unchanged.

## Verification
- `BB_QUERY_PLAN_REPORT=… pnpm exec turbo run test --filter=@bb/db
--filter=@bb/server --force`, then `pnpm --filter @bb/db
check:query-plan-allowlist <report>`: "Query plan allowlist matches the
report (46 findings)", meaning no finding is unallowed and no entry is
stale.
- That run hit two failures in `builtin-plugins.test.ts` hot-reload
timing tests (40 s and 22 s under load). Re-running the file alone
passed 27/27, and nothing in that file touches the allowlist.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Nov 9, 2026
…and diagnostics servers (#7302)

## Human comments

## What was wrong

The slow-query-plan guard from #7292 only judges queries that tests run,
and nothing noticed when an allowlist entry outlived its fix. #7288 and
#7289 merged just before #7292 and #7287 just after it, so main carries
seven entries for queries that are no longer slow.

## What changed

**Nightly coverage and stale-entry check.**
- A new `Query Plan Audit` workflow
(`.github/workflows/query-plan-audit.yml`, nightly on main and runnable
by hand) runs `@bb/db` and `@bb/server` tests unsharded in report mode.
It is not part of PR CI: an unsharded run took 5.2 min per PR push. PRs
still fail on new slow plans through the per-file guard in their
existing test shards.
- `check:query-plan-report` (renamed from `check:query-plan-allowlist`)
fails on:
  - findings missing from the allowlist;
  - allowlist entries no test reported;
- exported query functions in `packages/db/src/data` that no test runs.
- `packages/db/scripts/query-functions.ts` finds those functions with
the TypeScript AST: exported functions that call a query builder or
`prepare` on a connection. In report mode, the guard records the data
functions on each prepared statement's stack.
- Four functions never ran:
  - `getEarlyAdopter` had no callers and is deleted.
- `updateProject`, `getSkippedAppUpdate` and
`setPluginArtifactGitCheckoutRoot` gain tests.
- The seven fixed entries are removed.

**Per-PR check for changed query functions.**
- The Linux test shards set
`BB_QUERY_PLAN_EXECUTED=.query-plan/executed.jsonl`. The `@bb/db` and
`@bb/server` test guards record the data functions on each prepared
statement's stack while still failing on slow plans as before.
- The file is a Turbo test output (`.query-plan/**`), so a cached run
restores it.
- The shard that runs `@bb/db` also writes the query function list.
- A new `Query functions run in tests` job
(`scripts/check-pr-query-functions.mjs`) downloads both, installs
nothing, and fails when an exported query function in a
`packages/db/src/data` file the PR changed never ran. On this PR it took
11 s, and the server and packages-host shards showed no measurable
change.
- Untouched files and stale allowlist entries stay with the nightly
audit. Their tests may replay from cache, and a stale entry only
over-permits.

**Runtime audit on dev and diagnostics servers.**
- When `BB_QUERY_PLAN_AUDIT=1` or the `performanceDiagnostics`
experiment is on, the server logs `Slow SQLite query plan` once per
rule, table and caller for unallowed findings.
- `pnpm dev`, `pnpm start:worktree` and `pnpm desktop:worktree` default
`BB_QUERY_PLAN_AUDIT` to `1`. `start:worktree` runs its server with
`NODE_ENV=production`, so `NODE_ENV` can't identify dev servers.
- The connection's existing statement instrumentation
(`packages/db/src/connection.ts`) hands each new statement and parameter
shape to the auditor, which also covers cached statements. The auditor
captures the stack synchronously. It plans the statement on
`setImmediate` against a read-only connection to the same file
(`apps/server/src/services/system/query-plan-audit.ts`).
- Bundled frames are attributed through the `// path` module comments
esbuild writes into `apps/server/dist`, resolved against `apps/server`.
The bundle's 17 MB source map took about 0.9 s and 122 MB of heap to
load. Resolving against the filesystem would also misattribute an
npm-installed bb-app, whose bundle sits under `node_modules`.

**Test guard.**
- Audits are queued and run in each test file's `afterAll`, so EXPLAIN
work no longer runs inside time-budgeted code.
- The guard core now lives in `query-plan-guard.ts`, shared by tests and
the server. The prototype patch, report rows and report comparison live
in `query-plan-test-guard.ts`, exported as
`@bb/db/query-plan-test-guard`.

**Docs.**
- `docs/configuration.md`: the env var row and the
`performanceDiagnostics` description.
- `docs/debugging-and-qa.md`: a new "Slow SQLite query plans" section.
- The `bb guide` customization chapter.

**Windows.** Callers are read from POSIX stack paths, as in #7292, so
the runtime audit logs nothing on Windows and the bundle test skips
there.

**Server/daemon wire.** No daemon wire change.

## How you verified

- **Full report run** (db then server, report mode):
`check:query-plan-report` printed "Query plan report matches the
allowlist (45 findings) and runs all 362 query functions."
- Before removing the seven entries, the same check listed them as
unreported.
  - Before the new tests, it listed the four untested functions.
- **Live, `pnpm start:worktree` (ESM `dist` bundle):** with the
`listThreadSearchMatchRows` allowlist entry temporarily removed, `GET
/api/v1/threads/search?query=hello` logged `Slow SQLite query plan` with
`caller: "packages/db/src/data/threads.ts#listThreadSearchMatchRows"`.
  - A repeat search logged nothing more.
- **Experiment gate**, with `BB_QUERY_PLAN_AUDIT=0 pnpm start:worktree
--perf-diagnostics`: a search logged nothing while the experiment was
off. After `bb settings experiment performanceDiagnostics true`, the
same search logged the finding without a restart.
- **Overhead:** a microbenchmark of a cached lookup on a real connection
measured 1.2 µs per query with the audit off and 1.5 µs with it on, for
an already-audited shape (+0.33 µs across 3 rounds of 200k). Off, the
hook is one call that returns null.
- **Per-PR check, locally:** a temporary commit added an untested
`countAppSettingsRows` to `app-settings.ts`. The check named only that
function, given the db record plus server records. Against this PR's
real diff it passed: "Every query function in 1 changed data file(s)
runs in a test."
- **Per-PR check, on CI:** the job downloaded the packages-host,
server-1 and server-2 records and passed in 11 s.
- **Cache replay:** deleting `packages/db/.query-plan` and rerunning the
cached `@bb/db` test task restored all 603 rows.
- **Tests:**
- `query-plan-guard.test.ts` bundles a query function with esbuild and
loads it with Node's native `require`. It asserts the audit is deferred
until `flush()` and that the caller is attributed to
`apps/demo/src/latest-event.ts`. It fails when bundle-marker resolution
is disabled.
  - `ci-selection.test.mjs` covers the job selection.
  - The run-dev and run-desktop env tests cover the new default.
- `pnpm exec turbo run typecheck lint --filter=@bb/db
--filter=@bb/server --filter=@bb/config --filter=@bb/scripts` passes.
- **Local timing flakes:** under load averages above 100 on this
machine, `thread-pruning.test.ts` (with or without the guard) and
`builtin-plugins.test.ts` hot-reload failed once each. Both pass on
their own. #7298 since removed the pruning tests' dependence on the 20
ms budget.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant