Repository navigation
perf(sources): skip full parse for byte-proven superseded revisions - #3146
Conversation
Problem: `_census_historical_revision_evidence` fully JSON-parsed every retained raw in a cohort, including full snapshots that byte comparison alone already proves are a strict prefix of a later capture of the same file. On a real restore this wasted ~45GB/46% of parse work re-decoding superseded snapshots whose content is discarded by replay's `plan_revision_replay` (only the newest full raw + byte-proven append tail ever becomes `accepted_chain`). Solution: group never-typed (`revision_kind='unknown'`) retained raw candidates by `source_path` (an established cohort-equivalence edge elsewhere in this codebase) before parsing. New `ArchiveStore.classify_untyped_full_revision_groups` reuses the existing `classify_historical_full_revision_streams` byte-prefix proof (zero parse cost) to find a unique linear growth chain within each group. Only the newest member is parsed, to learn `logical_source_key`; older members are bound to that same key via a cheap `bind_raw_revision` call with no independent parse. Ambiguous/branching groups, or a head parse that doesn't cleanly resolve to a single-session key, fall back to parsing every member individually -- identical to today's behavior. `classify_raw_revision_cohort` (called later, during replay) is untouched and still independently re-derives byte-provenness from raw bytes for every raw -- this is a census-time parse-cost optimization, never a shortcut on authority. Already-typed raws are excluded from the new grouping by construction, so retry/resume behavior is unchanged. Two tests encoded the old "every raw in a chain gets census-parsed" assumption and are updated with the new (lower) parse-call counts: `test_backfill_replay_reparses_when_spill_cache_absent`, `test_backfill_replay_reuses_spill_cache_when_bound_explicitly`. Verification: devtools test tests/unit/sources/test_revision_backfill.py tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py tests/unit/storage/test_repair.py -- 103 passed. mypy --strict and ruff clean on both changed source files. Ref polylogue-nh44 Co-Authored-By: Claude <[email protected]>
Adds build_revision_chain_corpus/REVISION_CHAIN_SHAPE to the shared benchmark infra (50 superseded captures + 1 winner, ~1MB final size -- shaped after the bead's own live-source.db evidence of a re-scanned Codex rollout file), and a regression test pinning that census parses only the winner at this scale. Measured before/after on this exact corpus (temporarily reverting polylogue/sources/revision_backfill.py + archive.py to the prior commit and rerunning the same script): 52->2 parse calls (51->1 unique raw parsed), 0.303s->0.091s wall time for backfill_historical_revision_evidence over the cohort (~3.3x). Real archives see a larger effect since parse cost grows with payload size while the byte-streaming proof stays I/O-only (the bead's own evidence: one real Codex rollout cohort was 800 revisions/6.2GB for an ~8MB final file). Ref polylogue-nh44 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. |
|
Warning Review limit reached
Next review available in: 45 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (4)
✨ Finishing Touches🧪 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 |
#3164) ## Summary Design-only lane for polylogue-vzn6: a reference-blob representation that lets byte-proven strict-prefix superseded raw-payload blobs be reclaimed without breaking any consumer that reads them by hash. No code/schema changes are applied in this PR — implementation is deferred to follow-up work. ## Problem `raw_sessions` stores every observed file snapshot as an independent full blob. When a live-captured file only grows (Codex rollouts, Claude Code transcripts), every capture before the last is a byte-proven strict prefix of a later one — #3146's `classify_historical_full_revision_streams` already proves this with zero heuristics — so the old bytes are redundant by construction, but blob GC correctly refuses to collect them since `raw_sessions`/`blob_refs` still point at them. The bead (and #3146's own problem statement) cited **45.2GB of 97.4GB (46%)** as the reclaimable scale. That number assumes every non-newest member of a same-identity growth cohort is a clean append chain, without actually running the byte-proof. Running the real proof against the live archive shows this assumption is mostly wrong: **the verified, strict byte-proof reclaimable total is 17.65GB (18.12% of the archive)** — most same-identity cohorts (96%+ of those checked) are non-monotonic (edits, resegmentation, coincidental identity reuse) and are correctly quarantined by the existing classifier, not silently reclaimable. ## Solution `docs/design/prefix-blob-reclamation.md` covers: 1. **Evidence pack** — three buckets measured read-only against the live archive (already-classified byte_proven chains: 10.48GB/992 rows; typed cohorts needing a fresh streamed proof: 7.17GB/318 rows from 50 of 3,432 cohorts checked; untyped/legacy cohorts: 0.0006GB/11 rows from 4 of 3,240 checked). Top cohorts and an origin distribution (86.4% codex-session, 13.6% claude-code-session) are included. Reproduction scripts are preserved for audit. 2. **Reference-blob representation** — a new additive `blob_prefix_references` table (own hash / byte_length / successor hash), not `blob_refs` (a different axis: referrer identity vs. content-reconstruction recipe). Chained rather than always-flattened-to-leaf resolution, justified by `BlobStore`'s write-once immutability removing the TOCTOU class entirely. 3. **Read-path audit** — found 15+ non-publisher `BlobStore`/`get_blob_store()` callers beyond the "publisher" surface the bead named (backup, validation, revision backfill, retention, artifact inspection, sampling/validation corpora, blob integrity, source parsing, live batch, repair, reconciler, ingest worker). Decision: push reference-resolution into the shared `BlobStore` base class (not just `ArchiveBlobPublisher`), so all 15+ callers become reference-aware through one change. Flags `blob_path()`'s permanent-path contract as the single riskiest open item — some callers assume a stable, reusable CAS file, and a reference-backed hash can only offer a bounded ephemeral spill file. 4. **GC/lease interaction** — reuses `blob_gc.py`'s existing hardened deletion path via one added exclusion clause in `_reference_surfaces`, rather than a parallel deletion mechanism. Crash-window analysis at every step (write reference row → verify → mark collectible → existing GC collects → confirmation sweep), including the one new race the added clause could introduce (resolved by SQLite's existing WAL snapshot isolation). 5. **Consent gate** — reuses the existing verified-backup-manifest tooling (`daemon/backup.py`) ahead of the first real physical reclamation pass; the schema addition itself is ordinary additive DDL needing no special gate. 6. **Verification plan** — sampled and full byte-identity + read-path-parity modes. 7. **Forward-fix sibling** — traced why acquisition-side append-delta storage only activates ~2.3% of the time: `_append_plan`'s cursor continuity is anchored to `ops.db` (the disposable tier), so every `ops.db` reset forces every currently-growing file back onto a full capture. Sketches a fix (durable-tier cursor reconstruction fallback) and records the decision to file it as a follow-up rather than implement it in this design-only lane. 8. **Anti-goals** — no heuristic similarity reclamation, no reclamation of a quarantined/ambiguous chain, retired-generation cleanup out of scope. ## Verification - `python -m devtools render all --check` — clean (the new doc needed a `devtools/docs_surface.py` entry; added and regenerated `docs/README.md`). - `python -m devtools verify --quick` (format + lint + mypy + render-all-check) — passed via the pre-push hook, `exit_code: 0`. - Evidence-pack numbers were computed with three read-only probe scripts (`evidence_pack.py`, `prove_mixed.py`, `prove_unknown.py`, `final_evidence.py`) run against the live archive's `source.db` (`mode=ro`) and blob store, importing the project's own `classify_historical_full_revision_streams` rather than reimplementing the proof. No writes were made to the live archive. Ref polylogue-vzn6 --------- Co-authored-by: Claude <[email protected]>
…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
Census-phase historical revision replay (
sources/revision_backfill.py) nolonger fully JSON-parses every retained raw in a growing-file cohort — only
the newest (winner) member is parsed; older members that byte comparison
already proves are a strict prefix are bound to the winner's learned
identity without independent parsing.
Problem
Live evidence (2026-07-19, source.db): 101,095 raw rows, 97.4GB total blob
bytes, but the newest-revision-per-cohort total is only 52.2GB — 45.2GB
(46%) is superseded full snapshots of files that grew over time via repeated
re-capture (one Codex rollout file alone: 800 stored revisions / 6.2GB for a
file whose final size is ~8MB).
backfill_historical_revision_evidenceparsed every uncensused revision in a cohort even though
plan_revision_replay(archive/revision_replay.py) only ever keeps thenewest full raw (+ byte-proven append tail) as
accepted_chain— everyolder full snapshot is marked
SUPERSEDEDand its parsed content is neverread again. So a restore parsed ~97GB where a fresh import of the live
files parses ~34GB once.
Separately,
classify_raw_revision_cohort(storage/sqlite/archive_tiers/archive.py)already proves a unique byte-prefix growth chain among same-cohort "full"
raws via pure streamed byte comparison (
classify_historical_full_revision_streams,zero parse cost) — but it only runs after census, per
logical_source_key,which itself only gets assigned by fully parsing every raw. Chicken-and-egg.
Solution
ArchiveStore.classify_untyped_full_revision_groups(archive.py):groups never-typed (
revision_kind='unknown') retained raw candidates bysource_path— an established cohort-equivalence edge elsewhere in thiscodebase (see
raw_membership_selection_components_sync's docstring) — andruns the existing byte-prefix chain proof within each group of ≥2. Read-only,
no writes.
_census_historical_revision_evidence(sources/revision_backfill.py) nowcalls this before dispatching parses. For a proven chain: only the head
(newest) is parsed to learn
logical_source_key; every older member isbound to that same key via a cheap
bind_raw_revisioncall with noindependent parse. Ambiguous/branching groups, or a head parse that doesn't
cleanly resolve to a single-session key (e.g. a coincidental byte-prefix
among unrelated multi-session bundles), fall back to parsing every member
individually — identical to today's behavior, zero regression risk.
classify_raw_revision_cohort(called later, during replay) isuntouched and still independently re-derives byte-provenness from raw
bytes for every raw — this is a census-time parse-cost optimization, never
a shortcut on authority. Already-typed raws are excluded from the new
grouping by construction (
WHERE revision_kind='unknown'), so retry/resumebehavior for previously-typed raws is byte-for-byte unchanged.
Two existing tests hard-coded parse-call counts that assumed every raw in a
2-member growth chain gets independently census-parsed — exactly the
assumption this fix removes (
test_backfill_replay_reparses_when_spill_cache_absent,test_backfill_replay_reuses_spill_cache_when_bound_explicitly); both areupdated with the new (lower) counts and a comment explaining why. No other
test in
test_revision_backfill.py/test_raw_authority_restart_proof.py/
test_raw_authority_scale_proof.py/test_repair.pyasserts per-rawparse-derived content for a superseded raw in a growth chain (verified by
reading all of them — restart_proof's 6-raw fixture uses 6 distinct
source_pathvalues so never triggers this path).Added
build_revision_chain_corpus/REVISION_CHAIN_SHAPEto the sharedbenchmark infra (
tests/infra/revision_backfill_benchmark.py, 50superseded captures + 1 winner, ~1MB final size — shaped after the bead's
own live-source.db evidence) plus a scale regression test pinning that only
the winner is ever parsed at this scale.
Verification
devtools test tests/unit/sources/test_revision_backfill.py tests/unit/devtools/test_raw_authority_restart_proof.py tests/unit/devtools/test_raw_authority_scale_proof.py tests/unit/storage/test_repair.py— 103 passed (24 intest_revision_backfill.pyafter adding the new scale test).mypy --strictandruff check/format --checkclean on all changed files.devtools verify --quick(format+lint+mypy+render-all-check) — passed, ran automatically on push via the pre-push hook.REVISION_CHAIN_SHAPE(51 raws, ~1MB final payload): revertedrevision_backfill.py+archive.pyto the parent commit, ran the identical script both ways —backfill_historical_revision_evidence.Acceptance criteria (polylogue-nh44)
classify_raw_revision_cohort/plan_revision_replayuntouched, still the sole source of replay authority.source_paths per session) are a separate axis not covered by this fix and were out of scope for this lane.Ref polylogue-nh44