Repository navigation
fix(drive): let proven revision lineage bypass Drive freshness tie-break - #3656
Conversation
Problem: PR #3639 bound raw revision lineage (logical_source_key, predecessor_raw_id, revision_authority) for Drive re-acquisitions in _write_session, but discarded classify_raw_revision_cohort_for_live_watch's RevisionReplayPlan result -- the #3453 freshness-tie safety net (_incoming_write_regresses_attachment_coverage) still solely decided whether a governed Drive revision landed, even when governance had already independently proven which raw is the legitimate accepted-chain head. No test exercised the exact tie shape (identical message timestamps, differing attachment coverage) together with lineage governance, so this gap had no red/green evidence either way. Solution: - _bind_drive_revision_lineage (ingest_batch/_core.py) now returns the RevisionReplayPlan it computes instead of discarding it. - _write_session captures drive_revision_proven_winner (true when payload.raw_id is in the plan's accepted_chain) and skips the #3453 tie-break only when governance has proven this exact raw is the legitimate successor -- the heuristic stays the deciding factor for every ungoverned case (no source_conn/blob_publisher, non-Gemini identity, or classification failure). - New tests: test_write_session_drive_lineage_proven_winner_bypasses_freshness_tie (red-first: fails without the bypass) and test_write_session_freshness_tie_regression_without_lineage_still_blocks (negative control: safety net still fires absent governance evidence). - New end-to-end test through the real acquisition path, test_iter_drive_raw_data_two_revision_fixture_gets_real_lineage (tests/unit/sources/test_drive_ops.py): threads two genuine iter_drive_raw_data passes (attachment fetch fails, then succeeds, backfilling and re-serializing the whole cached JSON) through ArchiveStore.write_raw_payload + parse_payload + _write_session. Finding: the true iter_drive_raw_data backfill mechanism re-serializes the WHOLE JSON document (injecting resolved attachment bytes into a nested dict), not a byte-append at the document's end -- confirmed the second raw is NOT a byte-prefix superset of the first (`not second_bytes.startswith(first_bytes)`). classify_raw_revision_cohort's classifier (archive/revision_authority.py) is strictly byte-prefix based, so this realistic shape lands revision_authority='quarantined' with no predecessor_raw_id, same as before PR #3639 for this shape -- what changed is real: both raws now carry a non-NULL logical_source_key and revision_kind='full' (never 'unknown'), so a future consumer (or a classifier taught to recognize JSON-structural supersets, not just byte-literal ones) can still find and arbitrate the cohort. Scope notes / deferred (per bead notes: "absorbed by polylogue-1fijp, individual fix remains legitimate if 1fijp stalls"): - Full AC1 "predecessor-linked, not quarantined" for the realistic mid-document JSON mutation shape needs a JSON-structural-diff-aware classifier, not a byte-prefix one -- that is materially larger scope, correctly deferred to polylogue-1fijp's raw-admission-chokepoint rewrite. This PR's bypass is real and tested for whatever cases DO produce a genuine byte-prefix relationship (the existing test_write_session_binds_drive_revision_lineage fixture, and any future append-shaped Drive acquisition). - The 157 already-contaminated aistudio-drive raw pairs need a live re-measure after deploy -- not attempted here, per bead note (3): retroactive durable-tier cleanup needs its own explicit-consent process. Verification: - devtools test -k drive -- 281 passed, 1 failed (tests/integration/test_blob_lifecycle_e2e.py::TestOrphanedBlobsCatalogRouting::test_catalog_resolution_drives_end_to_end_cleanup) confirmed pre-existing/unrelated: reproduced identically on HEAD~1 (before this change) via `git stash`. - devtools test tests/unit/pipeline/test_ingest_batch.py -- 68 passed. - Red-first: temporarily reverted the `not drive_revision_proven_winner` guard and reran test_write_session_drive_lineage_proven_winner_bypasses_freshness_tie -- failed with `assert False is True`; reapplied and reran green. - mypy polylogue/pipeline/services/ingest_batch/_core.py tests/unit/sources/test_drive_ops.py tests/unit/pipeline/test_ingest_batch.py -- Success: no issues found in 3 source files. - devtools verify --quick -- exit_code 0. Ref polylogue-sp72 Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 46 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. 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 (3)
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 |
…ontract (#3668) ## Summary Adds the mechanism for polylogue-1fijp's raw-admission chokepoint: `admit_raw_observation()`, a single typed decision function implementing the bead's five exhaustive resolution arms over a (prior-head-bytes, new-bytes) comparison, plus the atomic-read contract that feeds it stable, torn-read-proof bytes. Routes one real production call site (configured Claude Code fact-artifact admission) through it as proof and regression coverage. ## Problem `raw_sessions` rows are currently written from several independent call sites (one-shot batch import, live daemon watcher, Drive lineage bind), each deciding `revision_kind`/`revision_authority` on its own. polylogue-sp72's merged fix (#3656, this session) is the live proof this scatter causes real gaps: `iter_drive_raw_data`'s Drive re-acquisition path writes `revision_kind=unknown` + empty `logical_source_key` + `quarantined` directly on ambiguous bytes, with no shared typed-arm resolution to route through, and that PR's own scope notes explicitly defer the general fix to this bead. Separately, `polylogue-2t0vp` found live evidence of a torn-read failure mode: a Codex rollout file recaptured 15-16x with `blob_size` growing then suddenly dropping from 427MB to 10KB in one read -- no acquisition path in the codebase currently proves it isn't reading a source file mid-rewrite. ## Solution - `polylogue/sources/atomic_read.py`: `read_source_bytes_atomic()` / `try_read_source_bytes_atomic()`. Captures `(size, mtime_ns)` before reading, reads to EOF, re-stats; retries a bounded number of times on disagreement; raises `TornReadError` (or returns `None` for the non-raising variant) rather than ever persisting a torn read. Standalone utility, not yet wired into any acquisition call site. - `polylogue/storage/sqlite/archive_tiers/raw_admission.py`: `admit_raw_observation()`. Given atomically-read bytes, origin evidence, and an optional `PriorRawHead` (caller-resolved), resolves exactly one of: 1. `SKIP_DUPLICATE` -- byte-equal to the accepted head. 2. `APPEND` -- bytes extend the head as a strict byte-prefix; `revision_kind=append` with a real `predecessor_raw_id`. 3. `SUPERSEDE` -- the incoming bytes are themselves a strict prefix of the accepted head (a proven-dominated, older/shorter read); recorded `FULL`/`BYTE_PROVEN` with `predecessor_raw_id` pointing at the fuller head. **Interpretation note**: the bead's arm-3 text ("head is byte-prefix of prior full -> supersede") admits more than one reading; this is the one implemented and tested here, flagged in the module docstring as not independently confirmed against operator intent beyond the bead text. 4. `ARTIFACT` -- payload classified `not parse_as_session` by the omsw artifact taxonomy. Still writes a `raw_sessions` row (the acquisition-evidence ledger; `raw_artifacts.raw_id` has a `NOT NULL REFERENCES raw_sessions` FK) but attaches an immediate `raw_artifacts` classification row via the same deterministic `artifact_observation_id()` scheme the offline `materialize_artifact_observations` sweep uses (upsert-safe, no collision). This arm structurally cannot reach an index-tier `sessions` row -- the module has zero imports of any index-tier writer (asserted in a test). 5. `REFUSED_AMBIGUOUS` -- neither equal, forward-extension, nor backward-prefix. Per the operator's 2026-08-03 correction on the bead: re-acquisition is opportunistic, never doctrinal. A supplied `reacquire` callback is invoked at most once; if it resolves to arms 1-3 that wins, otherwise (source absent/unreadable, or still ambiguous) this falls through to a typed refusal row (`revision_kind=unknown`, `revision_authority=quarantined`) with a machine-readable `refusal_reason` -- never a decision that depends on source persistence, never a silent drop. 6. `BASELINE` (not one of the 5 named arms -- they all presuppose a prior head): the bootstrap case, first-ever observation for a logical source key, recorded `FULL`/`ASSERTED`. Composes the existing `write_source_raw_session()`/`RawRevisionEnvelope` primitives rather than reimplementing raw-row persistence. - `polylogue/storage/sqlite/archive_tiers/revision_governance.py` + `archive.py`: `admit_raw_artifact_payload()` (module function + `ArchiveStore` wrapper), mirroring the existing `write_raw_payload()` shape (blob publish + `_ensure_source_conn()`), delegating to `admit_raw_observation()`'s ARTIFACT arm. - `polylogue/pipeline/services/archive_ingest.py`: `_admit_non_session_origin_artifacts()` now calls `archive.admit_raw_artifact_payload(...)` instead of the bare `archive.write_raw_payload(...)` it previously discarded its own already-computed `ArtifactClassification` into -- this one real call site now gets an immediate `raw_artifacts` row instead of waiting on the next offline materialize sweep. ## Scope / call-site status (acceptance-criteria honesty) The bead is explicitly a multi-session mechanism-plus-migration effort; this PR lands the mechanism and one real call-site migration, not full consolidation. Per the bead's own fallback guidance ("completely acceptable to land a smaller, real, well-tested slice... do NOT attempt a big-bang rewrite of every acquisition path in one shot"): - **Routed**: `archive_ingest.py`'s `_admit_non_session_origin_artifacts` (configured Claude Code fact-artifact admission, arm 4). - **Reviewed, NOT routed**: - `sources/live/batch.py` -- the bead calls this "mostly compliant"; confirmed it already calls into `revision_governance`'s `classify_raw_revision_cohort_for_live_watch`/`bind_raw_revision` machinery for real lineage tracking. Rewiring its write path onto `admit_raw_observation` would touch the daemon's live-watcher hot path and its `RawRevisionGovernanceHost` Protocol contract -- deferred as a separate, carefully-tested follow-up rather than risked here. - `sources/drive/__init__.py` (`iter_drive_raw_data`) / `pipeline/services/ingest_batch/_core.py` (`_bind_drive_revision_lineage`) -- this is the bead's own cited proof case. PR #3656 (merged this session) already closed the byte-prefix-provable subset of this gap and its own scope notes explicitly documented the remaining gap needs a **JSON-structural-diff-aware classifier**, not a byte-prefix one: `_inject_live_drive_attachment_bytes` re-serializes the whole JSON document rather than byte-appending, so `second_bytes.startswith(first_bytes)` is false for the realistic case even when the same underlying session grew. `admit_raw_observation`'s byte-prefix comparison (arms 2/3) cannot resolve that shape either -- routing Drive through it today would not close the residual gap and risks destabilizing the just-merged, well-tested #3656 fix. Building a JSON-structural classifier is materially larger scope, left as explicit follow-up. - Browser-capture receiver spool and maintenance backfill call sites -- surveyed via `grep -rln write_source_raw_session` (11 non-test call sites across `codex_title_census.py`, `context/*_correlation.py`, `daemon/antigravity_conversation_acquisition.py`, `hooks.py`, `storage/repair.py`, `storage/raw_reconciler.py`, `storage/hook_payload_ref_reconciliation.py`); not individually routed in this pass -- each is a distinct acquisition shape (hook events, sidecar reconciliation, offline repair) that deserves its own read-and-decide pass rather than a blind mechanical swap. ## AC status - (a) grep proves no raw_sessions INSERT outside the chokepoint module: **partially satisfied** -- true for the one routed call site; NOT true globally (11+ other call sites still write directly, listed above). - (b) drive re-acquire with changed bytes produces typed lineage, not quarantined-unknown, through the real `iter_drive_raw_data` path: **not attempted this session** -- would require the JSON-structural-diff classifier noted above; `admit_raw_observation`'s own APPEND/SUPERSEDE arms are tested against synthetic byte-prefix fixtures instead (`tests/unit/storage/test_raw_admission.py`). - (c) tool-results file ingest creates zero session rows, proven structurally: **satisfied** -- `test_admit_raw_observation_arm4_artifact_never_touches_index_db` asserts both the behavioral outcome (raw_artifacts row, `parse_as_session=0`, no `sessions` table in `source.db` at all) and the structural guarantee (no `archive_tiers.write`/`archive_tiers.index` import in `raw_admission.py`). - (d) simulated mid-rewrite produces retry-then-refusal, never a stored torn blob: **satisfied** -- `tests/unit/sources/test_atomic_read.py` builds a real fixture that mutates the file's stat identity between pre/post-read checks, proving `TornReadError` on persistent instability and correct stabilized-bytes recovery when a retry succeeds. - (e) zero NEW quarantined rows under 72h of normal daemon operation: **not this session's job** (explicitly out of scope per the dispatch -- needs live daemon time this session cannot provide). ## Verification - `devtools test tests/unit/storage/test_raw_admission.py tests/unit/sources/test_atomic_read.py tests/integration/test_claude_workflow_admission.py tests/unit/pipeline/test_archive_ingest_shared_raw.py` -> 21 passed - `devtools test -k "drive or artifact_taxonomy or tool_result_history"` -> 299 passed, 1 failed (`test_catalog_resolution_drives_end_to_end_cleanup`) -- pre-existing/unrelated, confirmed by PR #3656's own verification notes reproducing the identical failure via `git stash` before that change; not touched by this PR - `devtools test -k "archive_ingest or revision_governance or admit_raw or raw_admission"` -> 26 passed - `mypy` (strict) on every touched/added file -> `Success: no issues found in 7 source files` - `devtools verify --quick` -> `exit_code: 0` Ref polylogue-1fijp
…e-acquisition (#3687) ## Summary Adds a JSON-structural growth classifier for Drive/Gemini re-acquisition bytes and wires it into `_bind_drive_revision_lineage` so a genuine Drive re-acquisition growth (the live-attachment-backfill shape, not a byte-append) gets typed, predecessor-linked lineage instead of falling straight through to the byte-prefix classifier's ambiguous/quarantined outcome. This satisfies polylogue-1fijp AC (b) ("drive re-acquire with changed bytes produces typed lineage, not quarantined-unknown"), which PR #3668 explicitly left unattempted and PR #3656 explicitly deferred. ## Problem `iter_drive_raw_data`'s live-attachment backfill (`_inject_live_drive_attachment_bytes`) re-serializes the WHOLE Gemini/AI-Studio JSON document on every re-acquisition pass that resolves a Drive-hosted attachment reference, rather than byte-appending at the document's end. PR #3656 (polylogue-sp72) proved this concretely with a real fixture threaded through the production write path (`test_iter_drive_raw_data_two_revision_fixture_gets_real_lineage`): the second raw's bytes are not a byte-prefix superset of the first's (`not second_bytes.startswith(first_bytes)`), so the archive's existing byte-prefix revision classifier (`classify_historical_full_revision_streams`, `archive/revision_authority.py`) lands `revision_authority='quarantined'` with no `predecessor_raw_id` for this exact, realistic shape — even though the underlying conversation genuinely only grew. ## Solution - `polylogue/sources/drive/structural_diff.py`: `classify_drive_structural_relation(old_bytes, new_bytes)` decodes both payloads as JSON and proves whether `new` is a *structural extension* of `old` — every dict key/value and list element `old` asserts is still present, unchanged, in `new`; new dict keys, new trailing list elements (a conversation growing a `chunkedPrompt.chunks` entry), and null-to-populated values are allowed growth. Any changed or removed existing value breaks the proof and the relation is `AMBIGUOUS` — the same fail-closed posture as the byte-prefix classifier it complements, proven a different way. Pure function, no SQLite/archive coupling. - `polylogue/pipeline/services/ingest_batch/_core.py`: `_bind_drive_revision_lineage` now tries `_drive_structural_growth_predecessor` first — it looks for exactly one existing `revision_kind='full'` sibling raw for the logical source key whose bytes are a proven structural predecessor of the new raw's bytes. A unique match is bound directly as a `FULL`/`ASSERTED` revision with a real `predecessor_raw_id` and `baseline_raw_id` (`ASSERTED`, not `BYTE_PROVEN` — the proof is JSON-structural, not byte-level, and that vocabulary distinction is deliberate: `BYTE_PROVEN` is reserved for the `bytes.startswith()` relation elsewhere in `archive/revision_authority.py`/`storage/sqlite/archive_tiers/raw_admission.py`). Zero or multiple structural matches fall through unchanged to the existing byte-prefix quarantine-then-classify dance — strictly additive, no existing behavior narrowed. - Updated `test_iter_drive_raw_data_two_revision_fixture_gets_real_lineage` (PR #3656's own end-to-end fixture, through the real `_write_session` production path) to assert the now-typed predecessor link instead of the documented residual gap it previously proved. - `tests/unit/sources/test_drive_structural_diff.py`: 15 focused tests on the classifier's semantics directly — trailing-append growth, dict-enrichment growth, combined growth, null→populated growth, new top-level keys, and the ambiguous/rejection cases (scalar mutation, removed/reordered elements, unrelated documents, non-JSON bytes, populated→null regression) — including one fixture built through the *real* production `fetch_live_drive_attachment_bytes` injector (not a hand-rolled approximation) and a two-generation sequential-fetch fixture. ## Scope / what's not attempted Per the bead's own fallback guidance, this is a scoped, real, well-tested slice, not the full raw-admission-chokepoint migration: - The new structural pre-check lives only in the Drive-specific `_bind_drive_revision_lineage` adapter function — it does not touch the shared `_classify_raw_revision_cohort`/`classify_historical_full_revision_streams` byte-prefix machinery used by every other origin's live-watch/rebuild-repair paths. That shared function's blast radius (every provider, both live-watch and rebuild-repair callers) made it too risky to modify for a Drive-only concern in this pass. - Drive acquisition is still not routed through `admit_raw_observation()` (PR #3668's chokepoint) — it continues to use the `bind_raw_revision`/`classify_raw_revision_cohort_for_live_watch` adapter path, now with the structural pre-check inserted ahead of it. Full chokepoint migration for Drive remains open scope on polylogue-1fijp. - The 157 already-contaminated `aistudio-drive` raw pairs mentioned in PR #3656 need a live re-measure/backfill after deploy — not attempted here (retroactive durable-tier cleanup needs its own explicit-consent process per this repo's schema regime). ## Verification - `mypy --strict polylogue/sources/drive/structural_diff.py polylogue/pipeline/services/ingest_batch/_core.py tests/unit/sources/test_drive_structural_diff.py tests/unit/sources/test_drive_ops.py` — `Success: no issues found in 4 source files`. - `devtools test tests/unit/sources/test_drive_structural_diff.py tests/unit/sources/test_drive_ops.py tests/unit/pipeline/test_ingest_batch.py` — 89 passed. - `devtools test -k "drive or revision_governance or raw_admission"` — 308 passed, 1 failed (`tests/integration/test_blob_lifecycle_e2e.py::TestOrphanedBlobsCatalogRouting::test_catalog_resolution_drives_end_to_end_cleanup`), confirmed pre-existing/unrelated: reproduces identically on a clean checkout with no changes applied (same failure PR #3656 already documented as pre-existing). - `devtools verify --quick` — `exit_code: 0`. Ref polylogue-1fijp Co-Authored-By: Claude <[email protected]>
Summary
Drive revision-lineage bookkeeping (added in #3639 for polylogue-sp72) computed a
RevisionReplayPlanbut discarded it, so the #3453 freshness-tie safety net still solely decided whether a governed Drive revision landed even when governance had already proven the winner. This closes that gap for the cases governance CAN prove, and adds an honest end-to-end test through the realiter_drive_raw_dataacquisition path that documents a real residual limitation.Problem
_bind_drive_revision_lineage(polylogue/pipeline/services/ingest_batch/_core.py, added in #3639) callsclassify_raw_revision_cohort_for_live_watchto bind real lineage (logical_source_key/predecessor_raw_id/revision_authority) for Drive re-acquisitions, but never used the returnedRevisionReplayPlan. The #3453 tie-break (_incoming_write_regresses_attachment_coverage) — which fires when two raws share an identical content-derived timestamp but differ in acquired-attachment coverage — kept deciding the outcome on its own heuristic even in cases where governance had already independently proven which raw is the legitimate accepted-chain successor. No existing test exercised the exact tie shape (identical message timestamps + differing attachment coverage) together with lineage governance, so this gap had no red/green evidence either way (confirmed: adding the test first and reverting the fix producesassert False is True).Separately, while building an honest test through the real
iter_drive_raw_dataacquisition path (not a hand-crafted byte-append fixture), I found that_inject_live_drive_attachment_bytes's live-attachment backfill re-serializes the WHOLE JSON document (injecting resolved bytes into a nested dict), not a byte-append at the document's end. The second raw is therefore NOT a byte-prefix superset of the first (not second_bytes.startswith(first_bytes), verified).classify_raw_revision_cohort's classifier (archive/revision_authority.py) is strictly byte-prefix based, so this realistic shape still landsrevision_authority='quarantined'with nopredecessor_raw_id— same as before #3639 for this shape. What #3639 genuinely changed: both raws now carry a non-NULLlogical_source_keyandrevision_kind='full'(never'unknown'), so a future consumer — or a classifier upgraded to recognize JSON-structural supersets, not just byte-literal ones — can still find and arbitrate the cohort.Solution
_bind_drive_revision_lineagenow returns theRevisionReplayPlanit computes (Noneon any early-return or swallowed failure) instead of discarding it._write_sessioncapturesdrive_revision_proven_winner(true whenpayload.raw_idis in the plan'saccepted_chain) and skips the fix(pipeline): stop attachment fetches from losing a freshness tie #3453 tie-break only when governance has proven this exact raw is the legitimate successor. The heuristic remains the deciding factor for every ungoverned case (nosource_conn/blob_publisher, non-Gemini identity, or a classification failure) — this is a strict narrowing of when the safety net applies, never an unconditional bypass.tests/unit/pipeline/test_ingest_batch.py:test_write_session_drive_lineage_proven_winner_bypasses_freshness_tie— byte-append fixture (same shape as fix: give Drive re-acquisition real revision lineage #3639's own lineage test), identical timestamps, an attachment-coverage regression that the old tie-break would have blocked; asserts the write lands anyway.test_write_session_freshness_tie_regression_without_lineage_still_blocks— negative control: the identical regression shape, but nosource_conn(so no governance evidence); asserts the safety net still blocks it.tests/unit/sources/test_drive_ops.py:test_iter_drive_raw_data_two_revision_fixture_gets_real_lineage— threads two genuineiter_drive_raw_datapasses (attachment fetch fails, then succeeds) throughArchiveStore.write_raw_payload+parse_payload+_write_session, the real production path. Asserts both raws getlogical_source_keypopulated andrevision_kind='full', and documents (via an explicit assertion + docstring) thatpredecessor_raw_idis NOT established for this realistic non-append shape.Scope notes / deferred
Per the bead's own notes ("absorbed by polylogue-1fijp ... individual fix remains legitimate if 1fijp stalls"):
aistudio-driveraw pairs need a live re-measure after deploy — not attempted here (retroactive durable-tier cleanup needs its own explicit-consent process per this repo's schema regime).Verification
devtools test -k drive— 281 passed, 1 failed (tests/integration/test_blob_lifecycle_e2e.py::TestOrphanedBlobsCatalogRouting::test_catalog_resolution_drives_end_to_end_cleanup), confirmed pre-existing/unrelated by reproducing identically withgit stashbefore this change applied.devtools test tests/unit/pipeline/test_ingest_batch.py— 68 passed.not drive_revision_proven_winnerguard and rerantest_write_session_drive_lineage_proven_winner_bypasses_freshness_tie— failed withassert False is True; reapplied and reran green.mypy polylogue/pipeline/services/ingest_batch/_core.py tests/unit/sources/test_drive_ops.py tests/unit/pipeline/test_ingest_batch.py—Success: no issues found in 3 source files.devtools verify --quick—exit_code: 0.Ref polylogue-sp72
Co-Authored-By: Claude [email protected]