Repository navigation
fix(storage): preserve byte heads during membership replay - #2718
Conversation
Production catch-up exposed older membership snapshots whose accepted semantic head was absent from the membership cohort because append evidence kept the source under byte governance. Include the indexed head in semantic classification, but pin it while source-tier byte governance remains. This lets proven older prefixes terminate without allowing divergent or newer membership evidence to create a rebuild-unstable cross-route transition. Ref polylogue-rgh2. Co-Authored-By: Codex <[email protected]>
|
Warning Review limit reached
Next review available in: 23 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 (3)
✨ 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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7a81c96ea9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| member_raw_ids = list(archive.raw_membership_raw_ids(logical_source_key)) | ||
| accepted_head_raw_id = archive.raw_revision_head_raw_id(logical_source_key) | ||
| if accepted_head_raw_id is not None and accepted_head_raw_id not in member_raw_ids: | ||
| member_raw_ids.append(accepted_head_raw_id) |
There was a problem hiding this comment.
Preserve parse state for injected accepted heads
When the accepted head is not already in raw_session_memberships (the byte-governed case this adds), appending it here makes apply_raw_membership_classification() include that raw ID in decisions; since there is no raw_membership_census row for it, the final completeness check treats it as incomplete and clears raw_sessions.parsed_at_ms for the already-indexed head. That leaves the live head pending via pending_raw_revision_logical_keys() and also bypasses cursor-restore paths that require parsed_at_ms IS NOT NULL, so a successful older-bundle replay can make the current file get reprocessed repeatedly. Please keep the injected head out of the source membership parse-state loop or preserve its existing parse state.
Useful? React with 👍 / 👎.
## Summary The one-shot `polylogue import` pipeline now caches raw_ids per physical raw acquisition (origin, source_path, source_index, blob_hash) so multiple sessions split from ONE grouped JSONL file's identical bytes (Claude Code resume/fork carryover chains, Gemini/Drive bundles) share a single raw row computed WITHOUT native_id -- matching the live daemon watcher's own single-raw-per-file scheme -- instead of each split session deriving its own native_id-differentiated raw_id and creating a duplicate. ## Problem Live daemon catch-up was repeatedly failing full ingest of two Claude Code session files with `RuntimeError: membership replay cannot retire an unrelated accepted head` (archive.py:2255, the rgh2/#2718 safety guard). Root cause (refined via direct evidence against the live archive, polylogue-sjf6): the one-shot importer and the live daemon watcher used different raw-identity schemes for the same physical bytes (native_id included vs. always NULL), so re-processing a resume/fork file across the two pipelines produced two different raw_ids for identical content -- which the membership guard then correctly refused to silently reconcile. ## Solution `write_pair` in `pipeline/services/archive_ingest.py` now indexes every session sharing one raw acquisition against the SAME raw_id via a new `ArchiveStore.write_parsed_for_retained_raw_result`, computed the same way the daemon computes it (no native_id). The membership guard itself (archive.py:2255) is untouched -- this fixes the root inconsistency instead of weakening the safety check. ## Known gap (tracked separately) This prevents the duplicate-raw pattern from recurring going forward. It does NOT retroactively reconcile the two raw rows already duplicated on the live production host before this fix existed -- those two specific files will keep hitting the guard until a dedicated one-time remediation runs. Filing a follow-up bead for that. ## Verification - devtools test tests/unit/pipeline/test_archive_ingest_shared_raw.py tests/unit/pipeline/test_archive_ingest_commit_batching.py tests/unit/storage/test_revision_replay.py tests/unit/sources/test_live_batch_support.py -> 91 passed, 6 pre-existing failures in test_live_batch_support.py confirmed identical on unmodified master via git stash (unrelated to this change). - devtools verify --quick -> 14/14 steps green. - Anti-vacuity: reverted the diff, reran the two new tests -- both failed exactly as predicted (2 raw rows instead of 1). - GitHub Actions CI blocked repo-wide by an account billing lock (unrelated to this diff); GitGuardian passed; CodeRabbit hit its per-PR rate limit both times so this was independently manually reviewed against the full diff. Ref polylogue-sjf6 Co-Authored-By: Claude <[email protected]>
…ULL (#3193) ## Summary Narrows the polylogue-emx2 deferred-membership fix (PR #3129, commit de0b2df) so it applies only to the genuinely async-pending case (`decision IS NULL`), restoring the fail-closed invariant for decided `'ambiguous'`/`'deferred'` membership conflicts that de0b2df's shipped code had accidentally started treating as successes. ## Problem The polylogue-lvz6 clean-master triage bisected 5 failing tests in `tests/unit/sources/test_live_batch_support.py` to de0b2df: - `test_rewrite_plus_growth_before_planning_fails_closed_to_full_route` - `test_live_multi_session_divergence_reopens_raw_authority` - `test_bundle_replay_respects_unconvertible_single_session_head[bundle_texts1-False-False]` - `test_single_session_full_cannot_overwrite_divergent_membership_head` - `test_append_cursor_redetects_source_rewrite_after_handoff[in-place-prefix]` de0b2df's intent was narrow: treat only `raw_session_memberships.decision IS NULL` (genuinely async-pending, arbitrated later by the raw-materialization conveyor, `sources/revision_backfill.py`) as not-a-failure. The shipped code used the pre-existing coarse boolean `ArchiveStore.raw_membership_authority_complete()`, which returns `False` for `decision IS NULL` **or** `'ambiguous'` **or** `'deferred'` -- three distinct states collapsed into one. Net effect: genuinely divergent/ambiguous raws (rewrites, multi-session divergence, unconvertible bundle heads, divergent membership heads) were recorded as `SUCCEEDED` instead of `FAILED`, defeating the fail-closed invariants pinned by #2684/#2716/#2718/#2837. A second injection point (`classify_raw_revision_cohort(...).accepted_raw_ids` empty, in the non-membership single-session route) was also treated as deferred, but that classification is synchronous byte comparison with no conveyor revisiting -- "empty" there is always terminal, never pending. I also traced (direct DB inspection, see Verification) that de0b2df's own regression test exercises `decision = 'ambiguous'`, not `NULL` -- its assertion that this must defer was itself an instance of the bug this PR fixes. ## Solution - `polylogue/storage/sqlite/archive_tiers/archive.py`: new `ArchiveStore.raw_membership_decision_pending(raw_id)` isolates the `decision IS NULL` case. `raw_membership_authority_complete` had exactly one caller in the whole tree (audited via grep), so it stays as-is for its original "fully complete" semantics -- no other legitimate caller to preserve. - `polylogue/sources/live/batch.py`: - The membership-governed injection point now branches: complete -> succeeded; `raw_membership_decision_pending` -> deferred (unchanged behavior for the true async-pending case); otherwise (decided `ambiguous`/`deferred`) -> falls through to the caller's existing failed-set aggregation in `_ingest_full_paths_sync`, now with a `logger.warning` (the pre-fix path failed silently, no exception, no log at all -- part of what made the original bug invisible in production). - The `classify_raw_revision_cohort` injection point drops the `deferred_raw_ids` branch entirely (empty accepted cohort is always terminal there) and logs a warning too. - `tests/unit/sources/test_live_watcher.py`: corrected `test_live_full_ingest_over_ambiguous_membership_defers_instead_of_failing` -> `..._fails_closed_with_diagnostic`. Its two-conflicting-browser-snapshot scenario produces `decision = 'ambiguous'`, not `NULL` (verified by direct DB inspection); the original assertion that it must defer was wrong. It now asserts the corrected fail-closed outcome, the diagnostic log line, and that the first accepted snapshot's content is untouched. - `tests/unit/sources/test_live_batch_support.py`: added `test_raw_membership_decision_pending_distinguishes_null_from_ambiguous`, a focused archive-tier regression test for the exact narrow scoping (NULL -> pending; ambiguous -> decided/not-pending). This is archive-tier rather than a full watcher scenario because `LiveBatchProcessor`'s two call sites into `_apply_membership_sessions` both pass `allow_current_complete_raw=True`, which always resolves a raw's own decision synchronously within the same call -- so NULL is never observed at that exact checkpoint via the live watcher path. Genuine NULL persistence happens only across the conveyor's decoupled census-then-classify phases (`census_historical_revision_evidence` / `backfill_historical_revision_evidence` in `sources/revision_backfill.py`), which this test reproduces directly. ## Verification - `devtools test tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_cursor_persistence.py tests/unit/sources/test_live_watcher.py` -- 160 passed (was 5 failed on clean master before this fix). - `devtools verify --quick` -- exit 0 (format, lint, mypy --strict, render all --check, topology/layering/manifest/doc-commands/clock-hygiene/timeout/degrade-loudly gates). - Direct DB-state inspection (ad hoc script against the archive tier, not committed) confirmed the emx2 regression test's second observation produces `raw_session_memberships.decision = 'ambiguous'` for both raws, not `NULL`, before deciding how to correct that test. - Not run: the heavy `test` suite (skipped per-PR by CI policy, runs post-merge). Ref polylogue-emx2 Ref polylogue-lvz6 Co-authored-by: Claude <[email protected]>
) ## Summary Fixes 2 test failures reported on current master (`test_bundle_replay_respects_unconvertible_single_session_head[bundle_texts2-False-False]` and `[bundle_texts3-False-True]` in `tests/unit/sources/test_live_batch_support.py`). Root cause is **not** related to `messages_fts_identity`/polylogue-miwv's earlier work (PR #3239) — diagnosis below. ## Problem The working hypothesis (from another lane) was that PR #3239's `messages_fts_identity` `INSERT OR REPLACE` fix removed an `IntegrityError` abort that had been accidentally masking this test failure. That hypothesis is **disproven**: the exact same failure reproduces identically on commit `b3429fae6` (#3234), the commit immediately *before* `messages_fts_identity` (#3235) was even introduced. Bisecting by direct commit checkout (not `git stash`) traced the real regression to PR #3211 ("tree-byte decoded layer + in-cohort head-retire drift fix", 2026-07-20, ~10.5h before #3235). That PR removed a byte-governance refusal from `ArchiveStore.apply_raw_membership_classification` on the premise that its branch is only reachable after a real membership-governance conversion — but `_apply_membership_sessions` (`sources/live/batch.py`) unconditionally injects the *current* accepted head into the comparison cohort even when it was never converted (exactly PR #2718's original scenario: a byte-governed head compared against membership-discovered content for the first time). With the guard gone, a later-discovered bundle raw whose content happened to strictly extend the byte-governed head's content silently replaced the head via membership governance — confirmed with a standalone diagnostic script: `message_count` moved 2→3, `accepted_raw_id` changed, even though the head still had a live, unresolved `QUARANTINED` append raw blocking ordinary byte-chain conversion. The fail-closed contract was genuinely violated, not merely a reporting-list discrepancy. #3211 shipped this bundled into an unrelated perf PR without running `test_live_batch_support.py` in its own verification. ## Solution Restored a byte-governance refusal in `apply_raw_membership_classification`, narrower than #2718's original blanket `logical_source_key IS NOT NULL` check so #3211's own interrupted-pass-drift resumption keeps working: refuse only when (a) replay is about to *change* which raw is accepted, and (b) a live `raw_sessions` row elsewhere in this logical identity still chains a `predecessor_source_revision` off the existing head's own `source_revision` and isn't already part of the classified cohort — genuine unresolved byte-append evidence, not merely "was this raw ever membership-converted". ## Verification - Bisected via direct commit checkout: reproduced on `b3429fae6` (pre-#3235); traced the introducing diff to `996a3d6d3` (#3211) via `git log -S` on the removed guard string. - `devtools test tests/unit/sources/test_live_batch_support.py -k test_bundle_replay_respects_unconvertible_single_session_head` → 4 passed (all parametrizations, including the `succeeds=True` case) - `devtools test tests/unit/sources/test_live_batch_support.py tests/unit/storage/test_revision_replay.py tests/unit/sources/test_revision_backfill.py` → 136 passed - `devtools test tests/unit/storage/test_raw_retention.py` → 59 passed - `mypy --strict polylogue/storage/sqlite/archive_tiers/archive.py tests/unit/sources/test_live_batch_support.py` → Success, no issues - `devtools verify --quick` → exit 0 (also regenerated `docs/topology-status.md`, already out of sync on unmodified `origin/master` before this branch — unrelated pre-existing drift, picked up incidentally) - Anti-vacuity: reverted just the new guard body to a no-op and reran the 4-case test → 2 of 4 failed with the exact original symptom; restored and reran → 4 passed ## AC matrix | AC | Status | | --- | --- | | Diagnose true mechanism (bisect between the 3 merged changes) | Satisfied — root cause is #3211, not messages_fts_identity/miwv | | Determine whether content actually lands or reporting-only | Satisfied — content genuinely landed before this fix | | Fix production path to preserve explicit refusal | Satisfied | | `head_after == head_before` + `message_count` stays `(2,)` for `succeeds=False` | Satisfied (already asserted by the pre-existing test, now passing) | Ref polylogue-miwv Co-authored-by: Claude <[email protected]>
…#3646) ## Summary `apply_raw_membership_classification`'s two head-conflict guards (`storage/sqlite/archive_tiers/revision_governance.py`) now raise a dedicated `MembershipReplayConflictError(RuntimeError)` instead of a plain `RuntimeError`, and `storage/repair.py`'s raw-materialization retry-candidate logic (both the SQL query and the `_raw_materialization_retryable_missing_blob_error` Python gate) recognizes that type by its stable `parse_error` prefix as retry-eligible. ## Problem A production Codex session (native_id `019f49d8-0185-7c43-8793-db6e57db13e1`, 804 `raw_sessions` rows from incremental full-snapshot capture of a growing `rollout.jsonl`) has zero sessions in `index.db`. Its largest revision (90,822,451 bytes) has never been parsed; the next-largest (90,156,590 bytes, confirmed byte-for-byte prefix of the largest) carries `parse_error = 'RuntimeError: membership replay cannot replace an unconvertible byte head'` from PR #2718 (2026-07-12). That exact message string no longer exists anywhere in the codebase — PR #3211 and the later polylogue-miwv fix narrowed and reworded both of `apply_raw_membership_classification`'s head-conflict guards. Reading the live archive read-only (`/realm/db/polylogue`, `mode=ro`) confirmed three things: 1. The actual codex parser handles the real 90.8MB blob fine: `codex.parse_stream()` on the raw bytes succeeds, 29,280 messages, no crash. 2. `raw_revision_heads` has zero rows for this `logical_source_key` today, so the guards' `existing_head is not None` branches cannot currently fire for this session on a fresh attempt. 3. `storage/repair.py`'s raw-materialization candidate query excludes any `parse_error` other than two hardcoded exact-match transient-error strings (`'OperationalError: database is locked'`, `'decode:...No such file or directory'`) as permanently terminal. So the bug is not a live crash loop — it is a stale, retry-blocking `parse_error` frozen under message wording that predates two subsequent refactors, with no mechanism that ever re-evaluates or clears it. `repair.py`'s retry-candidate query permanently excludes this raw from every future rebuild, independent of whether the underlying governance conditions that produced the error still apply. ## Solution - Added `MembershipReplayConflictError(RuntimeError)` in `revision_governance.py`, following the existing `ActiveByteRevisionChainError` precedent, and changed both head-conflict `raise` sites to use it. - Exported it from `archive.py`'s imports and `__all__`. - `mark_raw_parse_failed` records `parse_error` as `f"{type(exc).__name__}: {exc}"`, so this gives `repair.py`'s retry logic a message-wording-independent marker instead of an allowlist of brittle exact-message strings. - Updated both the SQL candidate query and `_raw_materialization_retryable_missing_blob_error` (the real single source of truth — the SQL clause is a pre-filter, not merely an optimization; a row that clears the SQL `WHERE` is independently re-checked in Python) to recognize a `'MembershipReplayConflictError:'` `parse_error` prefix as retry-eligible. **Alternatives rejected**: matching on the existing message text more broadly (e.g. a regex over "cannot retire"/"cannot replace") was rejected because it re-creates the exact fragility that caused this bug — any future rewording of the guard's message silently breaks the match again. A dedicated exception type is the only marker guaranteed stable across message edits. **Scope note**: this fixes the *retry-eligibility* bug (the reason this raw is permanently excluded from every rebuild). It does not itself guarantee the retried classification succeeds for every one of the 804 rows — the live evidence (no `raw_revision_heads` row, parser succeeds on the real bytes) strongly suggests the largest two revisions will now classify and index successfully on the next `polylogue ops maintenance rebuild-index` pass, but I did not run that pass against the live archive (read-only access only, per task constraints) and cannot claim the full 804-row churn compacts without that live evidence. ## Verification - `devtools test tests/unit/sources/test_live_batch_support.py -k test_bundle_replay_respects_unconvertible_single_session_head` — red before the fix (2 failed: `parse_error` was plain `"RuntimeError: ..."`), green after (4 passed). - `devtools test tests/unit/storage/test_repair.py -k test_raw_materialization_retries_membership_replay_conflict_failure` — new test; confirms a `MembershipReplayConflictError`-prefixed `parse_error` is retry-eligible while a sibling row carrying the OLD plain-`RuntimeError` text (anti-vacuity control) remains excluded. - `devtools test tests/unit/storage/test_repair.py tests/unit/sources/test_live_batch_support.py` — 142 passed, 3 failed; confirmed by reverting this fix and rerunning the same 3 tests that they fail identically on unmodified code (`test_append_multi_session_payload_is_rejected_before_index_write`, `test_full_ingest_skips_durably_excised_content_without_aborting_batch`, `test_full_ingest_writes_archive_with_route_observability` — all fail with an unrelated `"did not replay to exactly one session"` `RuntimeError` from `_parse_raw_revision_chain`, pre-existing and untouched by this change). - `devtools verify --quick` — `20260803T113615Z-quick-2698640-140a86d3`, 22/22 steps passed, exit 0. - Read-only against the live archive (`/realm/db/polylogue`, `mode=ro`): confirmed the actual `codex.parse_stream()` call succeeds on the real 90,822,451-byte blob (29,280 messages), and confirmed `raw_revision_heads`/`raw_revision_applications` have zero rows for this `logical_source_key` today. Ref polylogue-5iz4
…cale (#3666) ## Summary Adds a regression test reproducing the real production shape behind polylogue-5iz4 (many incremental full-snapshot captures of one growing Codex session, plus a same-identity duplicate arriving from a second "incident recovery" path) and demonstrates that `MembershipReplayConflictError` is a transient, recoverable refusal, not a permanent one. ## Problem polylogue-5iz4's AC required a redacted structural fixture reproducing the real 804-revision Codex session's crash shape before the retry-eligibility fix in PR #3646 could be verified against something closer to the real shape than the original small #2718 pin (2-3 message sessions). PR #3646 fixed the retry-eligibility bug (a stale `parse_error` text that permanently excluded the raw from every future rebuild) but did not add the growth-chain-scale fixture the bead's AC calls for, and its own scope note said it could not claim the retried classification actually succeeds without live evidence. Reading the live archive read-only (`/realm/db/polylogue`, `mode=ro`) confirmed the real 22 full-revision blobs for this session form ONE clean, unforked byte-prefix chain (every smaller blob is an exact prefix of every larger one, verified pairwise) and that `raw_revision_heads`/`sessions` are empty for this identity today. Reproducing the actual `MembershipReplayConflictError` needed the same mechanism as the existing `test_bundle_replay_respects_unconvertible_single_session_head` pin (a same-identity bundle arriving at a second path, colliding with a QUARANTINED dangling append fragment hanging off the accepted head), scaled up to a growth chain with many messages instead of 2-3. ## Solution Added `test_growing_file_incident_recovery_duplicate_recovers_after_head_advances` to `tests/unit/sources/test_live_batch_support.py`. It: 1. Establishes an accepted head via 25 real incremental single-session ingests (growth-chain scale). 2. Introduces a same-identity "incident recovery" bundle at a second path plus a dangling QUARANTINED append fragment, reproducing `MembershipReplayConflictError` (fail-closed, correct behavior). 3. Confirms the recorded `parse_error` carries the retry-eligible `MembershipReplayConflictError:` marker `storage/repair.py` recognizes (polylogue-5iz4 / #3646). 4. Clears the interfering accepted head (matching the live archive's own empty `raw_revision_heads` row for this identity) and retries — the same durable raw now succeeds and reaches the index with the expected message_count. Notable finding during construction: `storage/repair.py`'s offline `repair_raw_materialization` reprocesses every retained typed-`'full'` raw for a `logical_source_key` on every pass (including the accepted head's own cohort), which re-establishes the interfering head before ever reaching the colliding raw in the same pass — so the recovery in this test is demonstrated via the live watcher's own retry path (`_ingest_full_paths_sync` again), not via `repair_raw_materialization`. That offline-repair gap is noted directly in the test as a real follow-up rather than papered over. **Root cause conclusion for the live production session**: the retry-eligibility fix already merged in #3646 is the actual fix. #3646's own read-only investigation already confirmed the codex parser succeeds on the real 90.8MB blob and that `raw_revision_heads` has zero rows for this identity today, so a fresh rebuild-index pass over the real archive should reach the simple byte-chain replay path directly (the real content is one clean chain) without ever re-tripping the membership-governance guard. No further production code change was found necessary this session; this PR is fixture/regression-test work only. ## Verification - `devtools test tests/unit/sources/test_live_batch_support.py -k test_growing_file_incident_recovery_duplicate_recovers_after_head_advances` — 1 passed, verified stable across 4 repeated runs. - `devtools test tests/unit/sources/test_live_batch_support.py -k "revision_replay or membership"` — 7 passed. - `devtools test tests/unit/storage/test_repair.py -k membership` — 2 passed. - `devtools verify --quick` — exit 0. Ref polylogue-5iz4 Co-authored-by: Claude <[email protected]>
Summary
Preserve an accepted byte-governed session head while older multi-session raw snapshots are classified, without allowing membership replay to create a rebuild-unstable cross-route transition.
Problem
Production catch-up after PR #2717 reached duplicated Codex recovery snapshots for
019f49d8-0185-7c43-8793-db6e57db13e1. The current 83.9 MB accepted full raw was absent from the 18-row membership cohort because append evidence kept the logical session under byte governance. Membership replay therefore could not relate the older snapshot to the accepted head and failed withmembership replay cannot retire an unrelated accepted head.A naive replacement based on membership census presence is unsafe: backfill can census a byte-governed raw without retiring its append chain, while cold rebuild still treats the byte chain as authoritative.
Solution
Ref polylogue-rgh2.
Verification
devtools test tests/unit/sources/test_live_batch_support.py -k 'bundle_replay_respects_unconvertible_single_session_head or single_session_full_terminally_supersedes_older_membership_prefix or single_session_full_cannot_overwrite_divergent_membership_head'6 passed, 53 deselecteddevtools verify --quick20260711T223845Z-quick-1560566-2b7f5fce,13/13steps passedAnti-vacuity: the regression fixture creates append evidence so the accepted full raw cannot migrate into membership governance and asserts it is absent from membership. Removing the accepted-head injection makes the older-prefix case fail; removing the byte-governance guard lets the newer dual-census case replace the pinned head.