Repository navigation
perf(storage): seed planner stats at fresh index bootstrap, re-analyze per rebuild page - #3141
Conversation
…nalyze per rebuild page Problem: a freshly bootstrapped index tier has no sqlite_stat1, and without it the query planner prefers low-cardinality equality indexes over session-scoped ones for writer-hot queries. Measured live on the 2026-07-19 emergency rebuild: action_pairs_refresh_sql planned three idx_blocks_type_tool (block_type=?) scans per session write — every refresh walked the archive's whole tool_use population (181K blocks), 72% of replay CPU, O(N^2) over the bulk rebuild. A manual ANALYZE on the running generation flipped the plan to idx_blocks_session_position and replay went from ~2.9 to ~60 sessions/min sustained (>20x). The bad plan reproduces on an EMPTY fresh database, so every fresh bootstrap (generations, ops reset --index, first init) started life with quadratic session writes until the daemon's daily PRAGMA optimize eventually ran with data present; bootstrap's existing PRAGMA optimize is a no-op on an empty database. What changed: - schema_bootstrap.py: PLANNER_STAT1_SEED_SQL — representative index selectivities (captured from a live ~470K-block archive, rounded; only relative magnitudes matter) inserted into sqlite_stat1 and loaded via ANALYZE sqlite_master at create_fresh time, in both the sync and async bootstrap paths. Existing databases are untouched. - rebuild_index.py: bounded ANALYZE (analysis_limit=1000) on the generation after each replayed page, so measured stats replace the seeds as tables grow during bulk rebuilds. Failures are non-fatal by design. - tests/unit/storage/test_planner_statistics_seed.py: fresh-bootstrap plan assertion (all block searches in the action-pairs refresh use idx_blocks_session_position), seed presence in sync+async paths, per-page refresh behavior. 3/5 tests fail on pre-fix code (verified via stash). Not changed: action_pairs_refresh_sql text (embedded in trigger DDL — a derived-schema bump; deterministic planner steering recorded as an option on the bead), daemon steady-state (daily bounded optimize already covers it). Ref polylogue-l3tk Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughFresh SQLite databases now seed planner statistics in sync and async schema setup. Rebuilt indexes refresh statistics after non-empty replay passes, while SQLite errors during refresh are ignored. Tests cover seeded statistics, query-plan index selection, async setup, regeneration, and missing files. ChangesPlanner statistics lifecycle
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant SchemaBootstrap
participant SQLiteDatabase
participant ActionPairsRefresh
SchemaBootstrap->>SQLiteDatabase: execute schema and planner seed SQL
ActionPairsRefresh->>SQLiteDatabase: plan refresh using sqlite_stat1
participant RebuildIndex
RebuildIndex->>SQLiteDatabase: run ANALYZE after replay
SQLiteDatabase-->>RebuildIndex: commit statistics or raise sqlite3.Error
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
…3494) ## Summary Two beads, one branch: (1) a P1 correctness-of-contract bug fix — a resumable rebuild pass's deadline is now checked *between* REPLAY-phase cohorts, not only after the whole page's replay call returns — and (2) the small remaining slice of a P2 observability bead, a durable "selection phase" timing on every rebuild receipt. ## Problem **polylogue-uhgm** (P1): live recovery evidence — operation `3f8fa7b0` configured `pass_deadline_ms=300000` (5 minutes), yet 100-row pages ran roughly 8-9 minutes, because `rebuild_index_from_source` (`maintenance/rebuild_index.py`) checked elapsed time only *after* `replay_source(...)` — the whole page's census + every cohort + planner-stats refresh — returned. A page can also expand into a much larger authority cohort, making the overshoot unbounded in the worst case. The advertised bounded-pass contract was not enforced at the work boundary. **polylogue-6mvg** (P2, remaining slice): a live full index rebuild spent ~86s of one CPU core selecting which raws to replay before the inactive generation held a single session, and nothing durable recorded where that time went. Most of this bead's original scope (planner stats #3141, byte-skip #3146, batched commits #3147, pool floor #3149, dedup #3151) had already shipped via sibling beads; the bead's own notes call out durable phase-timing telemetry — specifically a selection-phase breakdown — as the one still-unowned piece. ## Solution - `polylogue/sources/revision_backfill.py`: `backfill_historical_revision_evidence` gains an optional `deadline_check: Callable[[], None] | None` parameter, called at the top of every REPLAY-phase cohort iteration (both the byte-cohort and membership-cohort loops) — between cohorts, not only after the whole call returns. New `RebuildDeadlineExceededError` is the expected interrupt signal. - `polylogue/maintenance/replay.py`: threads `deadline_check` through unchanged to `backfill_historical_revision_evidence`. - `polylogue/maintenance/rebuild_index.py`: - Builds a `_check_pass_deadline` closure from the resumable transaction's `pass_deadline_ms`, wired only when a durable transaction exists (never for non-resumable `--raw-id`/`--only-missing`/`--max-blob-mb` selections, matching existing validation). - Catches `RebuildDeadlineExceededError` around the `replay_source()` call. On interrupt it deliberately does **not** advance the transaction's cursor/processed counters — the next pass re-derives from the exact same source-order position, safe by the existing content-hash idempotency invariant (re-applying an already-committed cohort is a no-op upsert, never a duplicate) and consistent with the crash-recovery contract an open replay batch already has. - The deferred receipt's `replay` dict is zero-shaped like a normal replay dict (not a bare marker), so every existing consumer that indexes replay-dict keys unconditionally (the daemon-mode CLI text formatter, the daemon HTTP route's raw `receipt.to_dict()` response) keeps working. - `RebuildPassCost.selection_s` (polylogue-6mvg) extends the *existing* timings vocabulary — the same `RebuildPassCost`/`timings_s` shape every other phase (`parse_s`/`apply_s`, the `terminal.*` stages from polylogue-o56w) already uses — rather than inventing a parallel one. Measured around `next_raw_page` (resumable path) and `select_rebuild_raw_ids` (one-shot path), threaded into all three receipt-building call sites (deadline-interrupt, deferred/paused post-hoc, final materialized). **Alternatives rejected:** proactive page-sizing against a throughput estimate (checks only *before* a page starts, so still misses a mid-page-expanding cohort — the exact worst case the bead names) and per-raw interruption inside `apply_raw_revision_replay` itself (would interrupt mid-transaction-write, risking corruption of the owned-inactive- generation state). Both were flagged and deliberately deferred in the bead's own prior investigation as too risky for the intended scope. ## Conflict avoidance note for the merge conductor `polylogue/sources/revision_backfill.py` is flagged as owned by another live lane. This PR's addition there is the smallest possible: one new exception class, one new optional parameter, and two `if deadline_check is not None: deadline_check()` call sites at the top of the two existing cohort loops — no other line touched. The branch was rebased onto current `master` (`90d4df67e`, which includes the sibling lane's `polylogue-5q2u` lineage-order replay change, `_lineage_aware_replay_order`); the rebase conflict was exactly the loop header line and was resolved by keeping the new `ordered_logical_keys` iteration and re-adding the `deadline_check()` call — verified with a fresh test run post-rebase. ## Acceptance-criteria matrix **polylogue-uhgm:** - "A transaction with a short pass deadline stops before starting work that would exceed its remaining budget, commits a valid cursor, and reports deadline deferral." — **Satisfied.** `test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication`. - "Restarting resumes exactly at the next source-order raw/cohort with no duplicates or omissions." — **Satisfied** (by construction: the cursor is never advanced on interrupt, and resumption re-derives from the identical keyset position; idempotent re-application makes any redone cohort safe). Proven end-to-end by the same test (interrupted pass → resume → exact final session count). - "A deliberately slow/expanded cohort proves the deadline is checked inside production replay work rather than only after the outer call returns." — **Satisfied.** `test_deadline_check_invoked_between_replay_cohorts_not_only_after_return` proves the interrupt fires after exactly one cohort durably commits (not zero, not all three) at the direct `backfill_historical_revision_evidence` boundary. - "Final terminal readiness checks remain exact and either have their own bounded receipt or are explicitly separately scheduled." — **Unchanged**: no terminal-stage code was touched; `terminal.*` timings (polylogue-o56w) remain as before. **polylogue-6mvg** (remaining slice only — full bead AC already satisfied by sibling beads per its own 2026-07-19/27 notes): - Durable selection-phase timing receipt — **Satisfied.** `RebuildPassCost.selection_s` / `terminal_timings_s["selection_s"]`, present on every receipt shape (deferred, paused, replayed). - Cohort/parse/write/insight phase timings — **Already delivered** by prior work (`stage_timings_s` from `revision_backfill.py`, `parse_s`/`apply_s` split, `terminal.*` stages) — not re-touched here. - Daemon catch-up shares the improvement — **Satisfied by construction**: `daemon/bulk_rebuild.py`'s `run_daemon_bulk_rebuild_pass` returns the exact same `RebuildIndexReceipt` from the same `rebuild_index_from_source_sync` engine, so both the deadline fix and the selection-phase timing apply automatically with zero daemon-side changes needed. ## Anti-vacuity - Deadline fix: production caller is `rebuild_index_from_source_sync` (the real offline/daemon rebuild engine, no reimplementation). The mutation that makes `test_deadline_check_invoked_between_replay_cohorts_not_only_after_return` fail is moving the `deadline_check()` calls out of the cohort loops back to a single call after `backfill_historical_revision_evidence` returns (the pre-fix bug shape) — the mock would then never be called before the function's own natural completion. The mutation that makes `test_rebuild_index_deadline_stops_mid_page_and_resumes_without_omission_or_duplication` fail is either reverting to the post-hoc-only check (the fake clock would never interrupt anything mid-replay, so the first pass would report `status="replayed"` instead of `"deferred"`) or advancing the transaction's cursor on interrupt (the resumed pass would then skip or duplicate a raw, and the final session count would not equal 3). - Phase timing: production caller is the same `rebuild_index_from_source_sync`. The mutation that makes `test_rebuild_index_phase_timing.py`'s two tests fail is reverting `selection_elapsed_s`'s measurement or its `selection_s=selection_elapsed_s` threading — the `"selection_s"` key would then be absent from `receipt.timings_s` (a dict-key assertion failure, not merely a zero value). ## Verification ``` python -m devtools test tests/unit/maintenance/test_rebuild_index_deadline.py \ tests/unit/maintenance/test_rebuild_index_phase_timing.py \ tests/unit/daemon/test_bulk_rebuild_ownership.py \ tests/unit/cli/test_archive_maintenance_cli.py \ tests/unit/daemon/test_route_contracts.py \ tests/unit/maintenance/test_rebuild_index_bulk_build.py \ tests/unit/maintenance/test_rebuild_index_ownership.py \ tests/unit/maintenance/test_rebuild_index_selection.py \ tests/unit/maintenance/test_rebuild_parse_apply_split.py \ tests/unit/storage/test_index_generation.py # 212 passed python -m devtools verify --quick # exit_code: 0, all 18 steps ok ``` **Known pre-existing failure, unrelated to this branch** — filed as `polylogue-s0ug`: `tests/unit/storage/test_incremental_rebuild_equivalence.py::test_incremental_restart_and_fresh_generation_rebuild_are_equivalent` fails deterministically on current `origin/master` (`90d4df67e`) in isolation, introduced by `0d27e3da7` (#3484, tightened Codex CONTINUATION lineage evidence) landing after this branch was cut — the test's hand-built fixture predates that tightening. `git diff origin/master...HEAD` for this branch touches neither `codex.py`, `revision_backfill.py`'s classification logic, nor that test file, confirming it is not caused by this change. Not run: `devtools verify` (full testmon suite) — the coordinator directed a synchronous quick-gate + focused-test path instead of the backgrounded testmon seed, since a fresh worktree has no testmon seed to run the default affected-selection path against. Ref polylogue-uhgm Ref polylogue-6mvg Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
Summary
Fresh index tiers bootstrap with no
sqlite_stat1, so the query planner picks low-cardinality equality indexes over session-scoped ones for writer-hot maintenance queries — turning per-sessionaction_pairsrefresh into whole-archivetool_usescans that grow with archive size. This PR seeds representative planner statistics atcreate_fresh(sync + async paths) and re-analyzes the generation after each bulk-rebuild page.Problem
Found live during the 2026-07-19 emergency restore (
Ref polylogue-l3tk, umbrellaRef polylogue-5jak): py-spy showed 72% of replay CPU insiderefresh_action_pairs;EXPLAIN QUERY PLANshowed all three subqueries ofaction_pairs_refresh_sqlusingidx_blocks_type_tool (block_type=?)(~100K rows/key) instead ofidx_blocks_session_position(~350 rows/key), scanning 181K tool_use blocks per session write. A manualANALYZEon the running generation flipped the plans and replay went from ~2.9 to ~60 sessions/min sustained (>20x, +134K messages in 146s). The bad plan reproduces on an EMPTY fresh database; bootstrap's existingPRAGMA optimizeis a no-op there because optimize needs query history and data.Solution
storage/sqlite/schema_bootstrap.py:PLANNER_STAT1_SEED_SQL— representative selectivities forblocks/messages/action_pairsindexes (captured from a live ~470K-block archive, rounded; only relative magnitudes matter), applied atcreate_freshin both sync and async bootstrap. Existing databases untouched; later ANALYZE/optimize passes replace seeds with measured values.maintenance/rebuild_index.py: boundedANALYZE(analysis_limit=1000) on the generation after each replayed page — stats track table growth during bulk rebuilds; failures non-fatal (stale stats degrade speed, never correctness).action_pairs_refresh_sqltext (embedded in trigger DDL — would be a derived-schema bump; deterministic unary-plus steering recorded on the bead as a future option), daemon steady-state (daily bounded optimize covers it).Verification
devtools test tests/unit/storage/test_planner_statistics_seed.py— 5 passed. Anti-vacuity: with the schema changes stashed, 3/5 fail (fresh-bootstrap plan assertion shows theidx_blocks_type_toolplan; seed-presence sync + async fail).devtools test tests/unit/storage/test_schema_policy_contracts.py tests/unit/storage/test_schema_safety.py tests/unit/storage/test_planner_statistics_seed.py— 44 passed, 1 failed:test_fresh_init_creates_canonical_fts_trigger_set, classified pre-existing on clean master via stash-and-rerun (ohbx trigram triggers missing from the canonical set; filed as its own bead).devtools verify --quick— exit 0.Ref polylogue-l3tk
Summary by CodeRabbit
Performance
Reliability