Skip to content

Prune redundant event snapshots with resumable maintenance - #3766

Merged
ymichael merged 7 commits into
mainfrom
bb/events-table-pr-1-pruning-and-maintenance-thr_8cc2kknqu3
Sep 16, 2026
Merged

ymichael merged 7 commits into
mainfrom
bb/events-table-pr-1-pruning-and-maintenance-thr_8cc2kknqu3

Conversation

@ymichael

@ymichael ymichael commented Sep 16, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

Redundant snapshots accumulated in event history. Existing cleanup used unexplained retention windows, bounded delta cleanup could repeatedly inspect retained first deltas, and hourly scheduling made backlog cleanup slow. The live ingestion path also ran every cleanup category synchronously: full-copy measurements found long event-loop pauses, including calls that deleted nothing.

What changed

All event cleanup shares a latest-stored-event safeguard. The same retention rules apply live and in the background:

  • Rate limits: keep the latest snapshot per thread while unarchived; delete when archived, subject to the shared safeguard. No provider grouping or keeper table.
  • Usage: keep the latest root token snapshot and the latest root context snapshot plus its capacity fallback. Remove the 1,000/300/120-position retention windows.
  • Diffs: skip incoming daemon snapshots before allocating a sequence and remove historical snapshots; retain file-change items.
  • Resolved deltas/background progress: retain existing completion, scope, first-delta and output guards, with resumable support probes.

One new thread_pruning_cursors table stores global and per-thread progress. No bookmark table or rate-limit keeper table. Migration 0124_thread_pruning follows current main; no events-table columns/indexes or daemon wire changes.

Each live invocation now advances only one policy, with 32-candidate pages and a 32-unit support budget. Rotation and progress persist in the existing scoped cursors, so active ingestion progresses without waiting for global idleness. Candidate discovery uses existing type/sequence indexes to skip unrelated history. Live work omits payload-byte accounting and uses a zero busy timeout, restored afterward. Deletions and progress commit together; notifications follow commits.

Background pruning runs every ten seconds when idle, yielding between advances and starting no more after 64 advances or 50 ms elapsed. Active cleanup retains its existing frequency throttle. A single live invocation no longer completes every category; cleanup may lag event production, and inactive threads can still wait for a globally idle sweep. Details and limits are documented in docs/events-table-pruning.md.

How you verified

  • Full Turbo DB suite: 554 tests passed after merging main.
  • Targeted Turbo server suites: 66 tests passed, covering live/background pruning, scheduling, cached timeline selection, retry and ingestion ownership.
  • Turbo DB/server typechecks passed. Query-plan regressions confirm existing indexes.
  • New real-SQLite regressions cover scoped fair rotation across restart, progress on active threads without global cleanup, competing-writer refusal, timeout restoration, rollback, commit-only notifications, and discovery beyond 2,000 unrelated events.
  • Private sanitized full copies, 2,326 threads treated as unarchived: final live wrapper backlog p95/max 5.58/39.64 ms across 37,216 calls; already-cleaned p95/max 3.59/20.81 ms, zero deletions. No calls exceeded 50 ms in these final samples; zero cleanup failures. Queued-heartbeat maxima were 39.66/20.84 ms. No benchmark backup, profiling, tests or verification overlapped timing; no app/server/Connect client used the copies, and Connect records remained zero.
  • The previous full live wrapper at 2651033 measured backlog p95/max 36.65/106.19 ms and cleaned 32.94/199.20 ms across 4,652 calls each in this rerun. Old calls ran two passes; final calls ran sixteen/four policy rotations. This measures per-call responsiveness, not equal-work throughput. Backlog deletions were 158,793 old versus 158,431 final. The first final backlog pass alone had p95/max 20.88/37.62 ms.
  • All 2,326 complete timelines and context indicators matched after measured live cleanup. Every surviving event column/payload, high-water mark, provider recovery result and retained sidecar matched the baseline.

These measurements do not establish a hard latency cap or a regression relative to pre-PR code. Synchronous SQLite statements/commits, host I/O, logging and connected clients can produce larger pauses. The parent's original 455/228 ms maxima were not reproduced or fully explained.

AGENT GENERATED

@ymichael
ymichael marked this pull request as ready for review September 16, 2026 18:21
@ymichael
ymichael merged commit c663ff1 into main Sep 16, 2026
16 checks passed
@ymichael
ymichael deleted the bb/events-table-pr-1-pruning-and-maintenance-thr_8cc2kknqu3 branch September 16, 2026 19:37
SawyerHood added a commit that referenced this pull request Sep 25, 2026
## Human comments

## What was wrong

Many server, db, domain and contract tests duplicated a stronger test at
the owning boundary. Examples:
- three "Unsupported tool" variants that hit the same fallback branch;
- twin public-thread and thread-parent tests;
- ten "ships X enabled/disabled" builtin tests.

Others pinned incidental literals, such as exact gzip byte counts in
`payload-size.test.ts` and copied icon and logo lists. Some couldn't
fail at all: a check for a connect route that doesn't exist, and a
"migrates without throwing" test that every db test already repeats.

A few kept dead production code alive:
- `hasCompletedEventLoopWorkForTests` (no callers since #4259)
- `pruneThreadEventsBeforeSequence` (no callers since #3766)
- `claimQueuedThreadMessage`
- `createHostDaemonClient` in the host-daemon-contract source

## What changed

Found by a read-only test audit using the repo `test-audit` skill
(#4361).

- **Dead production code removed, with its tests:**
  - `hasCompletedEventLoopWorkForTests`
- `pruneThreadEventsBeforeSequence` and its transaction variant. The
other prune wrappers are unchanged.
- `claimQueuedThreadMessage`. Test call sites use
`claimQueuedThreadMessageGroup` with `{ kind: "explicit-send" }`.
  - `isAgentDelegatedChildThread`, inlined.
- **Tests rewritten or moved:**
- The randomized `timeline-context-order-cache` test now prunes through
the live `advanceThreadPruning` path, and asserts that rows are actually
pruned.
- `createHostDaemonClient` moves into its only user,
`internal-session-protocol-version.test.ts`. The wire schema is
unchanged, so no `HOST_DAEMON_PROTOCOL_VERSION` bump.
- **Duplicates folded into their keepers or tables:** the builtin plugin
defaults, `requestMatchesEntityTag` cases and pending-interaction
`reason`.
- **Not in this PR:** the `thread_dynamic_context_file_states` table (no
writer since #2140) and its schema test. Dropping it needs a migration
decision.

Production +1/−117, tests +137/−1555.

## How you verified

- `pnpm exec turbo run test lint typecheck` passes for `@bb/server`,
`@bb/db`, `@bb/domain`, `@bb/server-contract` and
`@bb/host-daemon-contract`.
- The only failures were `@bb/server` timeouts at load average 40. The
base commit shows them too, and they pass when rerun alone.
  - oxlint's `no-comments` errors match base.
- An independent verifier used before and after worktrees on 175d5ac.
For each removed test it wrote the bug that test catches as a production
change, then checked that the old test fails and a remaining test also
fails.
  - Result: 44 OK, 5 with no unique failure mode, 0 lost.
- Builtin plugin icon names stay covered by `PluginIcon.test.tsx`
("resolves every named branding.icon the shipped plugins declare").
  - Both `isParentNotifiableChildThread` clauses stay caught.

> 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