Repository navigation
fix(sources): retire Codex append header, add live-source raw reconciliation - #3539
Conversation
Problem: sources/live/batch.py's _append_payload_for_provider always
prepended a synthetic {"type":"session_meta","payload":{"id":...}} line
ahead of every Codex append-mode capture before hashing/storing it, so
the stored blob was never a literal byte-slice of the live file. This
permanently defeats a live-source byte-identity verification check
(the mechanism polylogue-u19l's next commit adds) even when the live
file is completely untouched -- confirmed on the bead's own witness
session, where all 767 append rows "diverge" under a naive offset
comparison and all 767 match exactly once the synthetic header is
stripped.
What changed: the resolved provider session identity is now carried as
a sidecar hint (_AppendPlan.native_id_hint) instead of being spliced
into the hashed payload. It is persisted to the existing
raw_sessions.native_id column at write time and read back at replay
time (revision_backfill.parse_retained_raw_sessions and its _parse_one
/_parse_stream helpers now accept a fallback_id_override) to recover
the same identity the Codex parser used to get from the injected
header -- the parser only ever falls back to fallback_id when the
payload carries no session_meta record of its own, which is true for
every append delta, so the resolved identity still wins in exactly the
same cases.
Scope: this changes what gets hashed/stored for NEW writes going
forward only. Historical rows keep their synthetic header in stored
bytes and have no recorded native_id; parse_retained_raw_sessions falls
through to the unchanged filename-stem fallback for them. No
retroactive rehash or migration of existing committed raw rows is
attempted (durable-tier change, out of scope per CLAUDE.md's
content-hash idempotency rules).
Known residual gap: the bulk census/backfill parse fan-out
(revision_backfill.py's _parse_unique_retained_raws/
census_parse_worker, used by full-archive rebuild replay) does not yet
thread this identity hint through -- only the single-raw replay path
(parse_retained_raw_sessions, used by the live append hot path and
daemon convergence) does. This only affects re-parsing NEW-style Codex
append raws (created after this change) during a full index rebuild;
historical rows are unaffected either way.
Verification: devtools verify --quick (format/lint/mypy/render, all
green); devtools test tests/unit/sources/test_live_batch_support.py
tests/unit/sources/test_live_append_cursor_resynthesis.py -- 80 passed,
4 pre-existing order-dependent flakes reproduced identically against
unmodified master (test_full_ingest_skips_durably_excised_content_
without_aborting_batch, test_full_ingest_writes_archive_with_route_
observability, test_full_ingest_cursor_hands_off_captured_prefix_
after_growth_during_proof, test_append_multi_session_payload_is_
rejected_before_index_write), unrelated to this change.
Ref polylogue-u19l
Co-Authored-By: Claude <[email protected]>
Problem: ~59GB of raw_sessions rows sit at revision_authority= 'quarantined', an absorbing state the existing RawAuthorityReconciler revision-graph heuristics never resolve for most of them. A prior investigation on polylogue-u19l found a strictly stronger and cheaper proof available for the common case: the live source file still contains the exact archived bytes, no revision-graph reasoning required. It measured ~95% of quarantined row-GB directly re-verifiable this way against still-present live source files. What changed: a new, deliberately small and independent module, polylogue/storage/live_source_reconciliation.py -- NOT an extension of RawAuthorityReconciler or storage/raw_retention.py's revision-authority machinery, per the operator's explicit request for something simpler. - compare_raw_against_live_source: pure comparison of one raw row's archived bytes against its live source file, returning exact_match / diverged / source_missing. Compares the exact [append_start_offset:append_end_offset) byte range for append-kind rows, a byte prefix otherwise. For Codex append rows specifically, a second candidate strips the historical synthetic session_meta header (see the companion commit retiring it for new writes) so historical rows are not permanently misclassified as diverged by an artifact of the old write path. - plan_quarantined_live_source_reconciliation: a read-only "plan" function following raw_retention.py's plan_stale_supersession_reissue shape (report-first, no mutation) that scans every quarantined raw_sessions row and classifies it. - devtools workspace raw-live-source-reconciliation: a dry-run report command (--json for machine consumption) wired through devtools/command_catalog.py. Explicitly NOT included: no automatic live-mutation/prune path. Nothing here marks a row byte_proven, drops a blob, or otherwise mutates authority state -- acting on a "reconcilable" classification is a separate, explicitly operator-authorized follow-up once real numbers exist from running this against the live archive (this repo's yla8 bead gates exactly that kind of live authority-state mutation). Out of scope: zip-bundle exports (ChatGPT/Claude-ai GDPR exports) need a parsed-object-identity comparator, not a byte comparator -- the investigation covered those separately and found them 100% reconcilable by parsed conversation id already. Verification: devtools verify --quick (format/lint/mypy/render, all green); devtools test tests/unit/storage/test_live_source_ reconciliation.py -- 7 passed (exact match, diverged, source missing, Codex offset-window match, Codex historical-header-strip match, a real-session_meta-is-never-falsely-stripped guard, and the end-to-end plan-scan classification). Manually exercised `devtools workspace raw-live-source-reconciliation` against a small synthetic archive (text and --json output) -- never against the production archive. Ref polylogue-u19l Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 48 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 Plus Run ID: 📒 Files selected for processing (16)
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 |
…-live-source-reconciliation # Conflicts: # docs/plans/topology-target.yaml # polylogue/sources/live/batch.py
test_full_ingest_cursor_hands_off_captured_prefix_after_growth_during_proof still asserted the old spliced session_meta header bytes -- the prior commit's cleanup missed this one call site (3 siblings were updated, this 4th wasn't), so it was misclassified as a pre-existing flake in that commit's own verification. Confirmed against a clean origin/master checkout: 3 of the 4 originally-failing tests fail there too (genuinely pre-existing), this one does not -- it only failed here because of this branch's own change. Fixed the assertion to match the new no-header-splice behavior. Also declares INDEX_SCHEMA_VERSION v54 (SEMANTIC_REPARSE) for PR #3537's looks_like_ai tightening, matching the fix already pushed on feature/devtools/schema-commit-full-corpus -- both branches independently needed this until one of them merges to master. Co-Authored-By: Claude <[email protected]>
…story (#3559) ## Summary Fixes the census/plan-ledger side of the raw-authority obligation-guard defect: `prune_raw_authority_census_history`'s per-census plan-row window (`RAW_AUTHORITY_CENSUS_PLAN_RETENTION`) no longer stays permanently pinned by a structurally-unresolvable blocker. Census headers keep their guard (a real FK), plan-row detail now prunes on the ordinary retention window regardless of blocker state. ## Problem `polylogue-z7ko` and `polylogue-f4z9` describe the same mechanism from two angles: `raw_authority_census_plans`/`raw_authority_census_post_plans` (a durable `source.db` tier) grew ~100k rows/hour, reaching 709,264 rows and ~870 MiB, with only 41 of the ~112 most recent censuses (sequence 820-932) holding plan rows at all — far more than `RAW_AUTHORITY_CENSUS_PLAN_RETENTION=8` should allow. `fixed_point` never reached 1 on any of 256 censuses ever measured. Root cause: `prune_raw_authority_census_history`'s plan-row window required every blocker attached to a census to be resolved before that census's `raw_authority_census_plans`/`_post_plans` rows could be dropped. The dominant blocker reason ("accepted raw authority remains quarantined pending exact refinement proof", ~4,400 rows) is a structurally permanent fact about a raw's own data — nothing about it changes between census passes, so it never resolves. Continuous live ingestion keeps producing new instances of this same permanent obligation; each one anchors whichever census first observed it, and that census's entire plan-row snapshot stays pinned forever. Over time more and more censuses accumulate this pin, which is why the guard eventually stopped bounding growth at all despite existing. I verified this is a genuinely separate exception from `polylogue-wkc6` (PR #3530, already merged): that PR fixed pruning of *orphaned* `raw_authority_plans` rows (plans no census references at all). This PR's guard is a different code path in the same function — the *per-census plan-row retention window itself* refusing to advance while any attached blocker is open, which `wkc6` did not touch. I also checked `polylogue-u19l` (PR #3539, merged, `live_source_reconciliation.py`): that module is a read-only classifier over `raw_sessions.revision_authority='quarantined'`, entirely separate from the `raw_authority_blockers`/census obligation mechanism this bug lives in — it never marks a blocker resolved and isn't wired to this guard. It is not usable to unblock this issue's plans, because the underlying obligation here is not "unproven," it's provably permanent (see `_strategy_overrides`' ineligible branch in `raw_reconciler.py`, from the already-merged PR #3466). ## Solution `polylogue/storage/raw_authority.py`, `prune_raw_authority_census_history`: - The plan-row window (`raw_authority_census_plans`/`_post_plans`) now deletes purely by the `sequence_no` retention floor, unconditionally. A blocker's own `expected_json`/`observed_json` columns already carry a complete, self-contained snapshot of the plan and its evidence (written by `_reconcile_frontier_obligations`), and `resolve_raw_authority_blocker` reads that plus the census-independent `raw_authority_plans` table — never `raw_authority_census_plans`/`_post_plans`. So gating this window on blocker resolution bought nothing but the unbounded pin. - Already-*resolved* blockers tied to a pruned census are deleted in the same pass (nothing needs them once their census ages out); still-*unresolved* ones are left alone — deleting those would be the actual "silently report the obligation as cleared" failure mode the old guard existed to avoid. - The header window (`raw_authority_censuses`) keeps its existing guard unchanged: `raw_authority_blockers` has a real foreign key on `census_id`, so a header can only be dropped once nothing references it. No schema/DDL change: `source.db`'s table definitions are untouched, this is a behavior-only fix to an existing maintenance routine that already runs inside every census-recording transaction. ## What's intentionally out of scope - The underlying quarantine pile itself (why ~4,400 raws are permanently ineligible) is `polylogue-u19l`'s territory, already addressed there. - A full `RawAuthorityReconciler` rewrite (`polylogue-lkrc`/`hjpx`/`yla8`) remains explicitly gated on separate operator authorization. - I don't touch `_reconcile_frontier_obligations`'s blocker-insert path at all: I initially suspected `blocker_id` being keyed on `(census_id, plan_id)` caused duplicate unresolved rows per pass, but a pre-existing partial unique index (`idx_raw_authority_blockers_open_plan` on `plan_id WHERE resolved_at_ms IS NULL`) already prevents that — there is exactly one unresolved blocker row per `plan_id`, always. That hypothesis was wrong; I reverted the speculative change once I found the index and re-diagnosed against the actual mechanism above. ## Verification ``` devtools test tests/unit/storage/test_raw_authority_ledger.py tests/unit/storage/test_raw_retention.py devtools verify --quick ``` New test `test_census_plan_rows_prune_past_retention_even_with_an_unresolved_blocker` plants a durable, permanently-unresolved blocker on the first of nine census passes and asserts: the blocker itself is never silently marked resolved; its census header survives (the real FK); its plan-row detail prunes to the retention window like any other census's. Confirmed this test fails against the pre-fix code (`assert 'census:1:...' not in {...}` — the first census's rows were still present after 8 more passes) and passes after. 10 pre-existing failures in `test_raw_authority_ledger.py` are unchanged before and after this diff (verified against both the pre-fix and post-fix tree) — an unrelated `_write_codex_raw` test-fixture regression where an empty-text message is now rejected by dispatch ("no messages, no positive conversational evidence"). Not touched by this PR; filing a follow-up bead is worth doing separately. Ref polylogue-z7ko Ref polylogue-f4z9 Co-authored-by: Claude <[email protected]>
## Summary
Delivers polylogue-ds4b4 (raw-authority redesign Phase 3): a regression
test proving raw authority is already proven at capture time for the
common append case, a lab-policy lint generalizing the u19l Codex-header
byte-mutation fix into a standing guard, and a preventive lint against
position-derived synthetic identity in parsers.
## Problem
polylogue-ds4b4 asked for three things:
1. Prove raw authority at capture time instead of deferring to the async
reconciler, at least for the common case.
2. Generalize the u19l fix (Codex append captures used to splice a
synthetic `session_meta` header onto captured bytes before hashing,
permanently defeating live-source byte-identity verification for ~59GB
of raw rows) into a standing regression guard, not just a one-off fix.
3. Add a schema-lint rule flagging position-derived synthetic identity
in parser code, checking existing parsers for a concrete instance first.
## Solution
**Item 1 -- already implemented, now locked in by a test.**
`append_ingest.py`'s `_ingest_append_plans_archive` resolves the
byte-contiguous predecessor via `raw_append_revision_parent` and, once
found, classifies+applies the revision synchronously in the same ingest
call (`archive.classify_raw_revision_cohort` /
`apply_raw_revision_replay`) -- there is no code path where a normal
single-predecessor append is left `quarantined` for
`RawAuthorityReconciler` to pick up later.
`test_append_ingest_proves_byte_authority_at_capture_without_reconciler`
(`tests/unit/sources/test_live_batch_support.py`) proves: the append raw
is `revision_authority='byte_proven'` immediately, its content is
already in `index.db`, and the heavy
`raw_authority_censuses`/`raw_authority_blockers` tables (owned by the
async reconciler) have zero rows.
**Item 2 -- `devtools/verify_raw_payload_hash_purity.py`.** An AST lint
over the raw-capture write-path modules (`sources/live/batch.py`,
`batch_support.py`, `append_ingest.py`, the pipeline ingest/acquisition
modules, `archive_tiers/{archive,revision_governance}.py`) forbidding
the exact shape that produced u19l's bug: a synthesized literal
(bytes/str constant, f-string, `json.dumps()`/`.encode()` result)
concatenated onto a bare reference before it reaches the content hasher.
Confirmed it flags a fixture reproducing the historical bug and passes
clean against the current (fixed) code. No ack mechanism -- there is no
legitimate exception on this write path. Wired into `devtools lab policy
raw-payload-hash-purity` and `devtools verify --quick`/`--lab`.
**Item 3 -- `devtools/verify_position_derived_identity.py`.**
Investigated existing parsers first (per the bead's instruction) and
found a live, unfixed sibling of the already-fixed polylogue-hith/qkuq
attachment-id bug: `message_identity_hash` (`polylogue/pipeline/ids.py`)
hashes `provider_message_id` directly, and multiple parsers construct
that id as `f"msg-{index}"` when no provider-native id exists --
unstable across export vintages that reorder entries, the identical
hazard class hith/qkuq already fixed for attachments. Filed as
**polylogue-gysk3** (fixing every existing instance reworks a core
identity function used archive-wide -- separate, higher-risk follow-on,
not rushed into this PR per the bead's own conservative-scope
instruction). Shipped the preventive lint: an AST scan of
`polylogue/sources/parsers/` flagging new position-derived
`provider_message_id` construction (inline or via a local variable,
following the dominant `msg_id = ... or f"msg-{idx}"` shape), with an
ack-manifest (`docs/plans/position-derived-identity-acks.json`)
recording the 22 currently-known instances against polylogue-gysk3.
Wired into `devtools lab policy position-derived-identity` and `devtools
verify --quick`/`--lab`.
Item 4 (blob-GC invariant verification against Phase 2's verdict
vocabulary) is explicitly blocked on polylogue-w6hql (Phase 2, not yet
started) and is not attempted here.
## Verification
```
devtools test tests/unit/devtools/test_verify_position_derived_identity.py \
tests/unit/devtools/test_verify_raw_payload_hash_purity.py \
tests/unit/sources/test_live_batch_support.py \
-k "not (test_full_ingest_skips_durably_excised_content_without_aborting_batch or test_append_multi_session_payload_is_rejected_before_index_write or test_full_ingest_writes_archive_with_route_observability)"
# 91 passed
```
The 3 excluded tests are pre-existing order/parallelism-dependent
flakes, confirmed to reproduce identically against this branch's base
with the new files removed (`git stash`) -- unrelated to this change,
and the exact set PR #3539 already documented as pre-existing.
```
devtools verify --quick
# exit 0 -- format, lint, mypy --strict, render all --check, all lab policy
# checks including the two new ones (raw-payload-hash-purity,
# position-derived-identity)
```
Ref polylogue-ds4b4, polylogue-lb39z, polylogue-u19l, polylogue-hith
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude <[email protected]>
Replace an aggregate message-count-only check with a direct assertion on THINKING-block presence/shape, and replace substring checks on an append payload with an exact byte-slice equality check against the source file's own bytes (the property #3539/polylogue-u19l actually guarantees). Ref polylogue-id4n
Summary
Two related, scoped changes for polylogue-u19l's "quarantine is an absorbing state" investigation:
sources/live/batch.pyno longer splices a syntheticsession_metaheader into a Codex append capture's payload before hashing/storing it. The identity is now carried as sidecar metadata (raw_sessions.native_id) and used to override the parser'sfallback_idat replay time.polylogue/storage/live_source_reconciliation.py, classifies quarantinedraw_sessionsrows against their live source files ("does the live file still contain these exact bytes?"), plus a read-onlydevtools workspace raw-live-source-reconciliationreport command.Problem
~59GB of
raw_sessionsrows sit atrevision_authority='quarantined', an absorbing state the existingRawAuthorityReconcilerrevision-graph heuristics never resolve for most of them. A prior investigation on polylogue-u19l found ~95% of that (56GB) is directly re-verifiable against still-present live source files using plain byte or parsed-object equality, no revision-graph reasoning required.That investigation also found a concrete root-cause bug:
_append_payload_for_provideralways prepended a synthetic{"type":"session_meta","payload":{"id":...}}line ahead of every Codex append-mode capture before hashing/storing it, so the stored blob was never a literal byte-slice of the live file. This permanently defeats a naive byte-identity check even when the live file is completely untouched -- confirmed on the bead's own witness session, where all 767 append rows "diverge" under a naive offset comparison and all 767 match exactly once the synthetic header is stripped.Solution
Part B (header retirement,
polylogue/sources/live/batch.py,batch_support.py,append_ingest.py,revision_backfill.py,archive_tiers/{archive,revision_governance}.py):_append_payload_for_providernow returns(payload, native_id_hint)instead of splicing a header intopayload._AppendPlancarries the hint (native_id_hint);append_ingest.pypersists it viawrite_raw_payload(..., native_id=...)(an existing, previously-unused column onraw_sessions) and passes it as the parser'sfallback_idfor the live write path.revision_backfill.parse_retained_raw_sessionsrecovers the same hint at replay time via a newarchive.raw_native_id(raw_id)accessor and threads it through_parse_one/_parse_streamas an optionalfallback_id_override-- this is the path the daemon's append-chain replay (append_ingest.py'saccepted_raw_idsloop) and convergence use, so live append processing is fully covered.native_id; they fall through to the unchanged filename-stem fallback unaffected.Known residual gap (documented, not closed by this PR): the bulk census/backfill parse fan-out (
_parse_unique_retained_raws/census_parse_worker, used by a full-archive rebuild replay) does not yet thread this identity hint through. This only affects re-parsing NEW-style Codex append raws during a full index rebuild; historical rows are unaffected either way. Flagging as a follow-up rather than expanding this PR's surface further.Part A (
polylogue/storage/live_source_reconciliation.py,devtools/raw_live_source_reconciliation_report.py):compare_raw_against_live_source: pure comparison of one raw row's archived bytes against its live source file ->exact_match/diverged/source_missing. Uses the exact[append_start_offset:append_end_offset)byte range for append-kind rows, a byte prefix otherwise. For Codex append rows, a second candidate strips the historical synthetic header (case-insensitive to whether the row predates or postdates Part B) so historical rows aren't permanently misclassified as diverged by the old write-path artifact.plan_quarantined_live_source_reconciliation: a read-only "plan" function followingraw_retention.py'splan_stale_supersession_reissueshape (report-first, no mutation) that scans every quarantined row and classifies it.devtools workspace raw-live-source-reconciliation: a dry-run report command (--jsonfor machine consumption).Deliberately not an extension of
RawAuthorityReconcilerorraw_retention.py's revision-authority machinery -- a small, independent classifier, per the operator's explicit request for something simpler than the existing revision-graph heuristics.Explicitly not included: no automatic live-mutation/prune path. Nothing in this PR marks a row
byte_proven, drops a blob, or otherwise mutates authority state. Acting on a "reconcilable" classification is a separate, explicitly operator-authorized follow-up once real numbers exist from running this against the live archive -- this repo'syla8bead gates exactly that kind of live authority-state mutation. Out of scope for the classifier itself: zip-bundle exports (ChatGPT/Claude-ai GDPR exports), which need a parsed-object-identity comparator rather than a byte comparator (the investigation covered those separately and found them 100% reconcilable by parsed conversation id already).Verification
devtools verify --quick(format/lint/mypy/render) -- all green.devtools test tests/unit/storage/test_live_source_reconciliation.py-- 7 passed (exact match, diverged, source missing, Codex offset-window match, Codex historical-header-strip match, a real-session_meta-is-never-falsely-stripped guard, end-to-end plan-scan classification).devtools test tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_append_cursor_resynthesis.py-- 80 passed. 4 failures (test_full_ingest_skips_durably_excised_content_without_aborting_batch,test_full_ingest_writes_archive_with_route_observability,test_full_ingest_cursor_hands_off_captured_prefix_after_growth_during_proof,test_append_multi_session_payload_is_rejected_before_index_write) reproduce identically against unmodified master with the same command -- confirmed pre-existing, order/parallelism-dependent flakes unrelated to this change.devtools workspace raw-live-source-reconciliation(text and--json) against a small synthetic archive built for the purpose -- never against the production archive.Ref polylogue-u19l