Repository navigation
fix(pipeline): stop attachment fetches from losing a freshness tie - #3453
Conversation
Problem: Drive-hosted attachment bytes (#3073, 2026-07-18) fetched into ~/.local/share/polylogue/drive-cache/gemini/*.json were being silently reverted -- the live archive showed 0.8% of aistudio-drive attachments acquired (26/3146) despite the fetch mechanism working correctly. Direct inspection of the live archive (read-only, index.db/source.db/ops.db) found 157 of 244 cached Drive files carry the fetched `_polylogue_drive_live_bytes_b64` payload on disk, and re-parsing one directly with the current parser produces a real 4MB inline attachment -- but each fetch created a second, unlinked `raw_sessions` row (`revision_kind='unknown'`, no `logical_source_key`) rather than a governed revision. Because the fetch only adds bytes and never changes any message timestamp, `_write_session`'s freshness check ties exactly between the pre-fetch and post-fetch revisions, and a tie fell through to "whichever raw this batch happens to (re)parse last wins" -- measured to pick the pre-fetch (unfetched) revision in all 157/157 duplicate source_paths on the live archive. Solution: `polylogue/pipeline/services/ingest_batch/_core.py` -- on an exact freshness tie between two different raw_ids for the same session, compare acquired-attachment counts (existing acquired attachments in the archive vs `inline_bytes is not None` on the incoming parsed session) and skip the incoming write only when it would regress attachment coverage. Ties or improvements still write through unchanged. This is a narrow safety net, not the durable fix -- Drive re-acquisition still never establishes `predecessor_raw_id`/`logical_source_key` revision lineage the way the governed "live" batch path does for tailed origins, so `raw_revision_heads` never arbitrates it; that gap and further findings (100% `unseen_shape` schema-drift rate on aistudio-drive since 2026-07-01, the archive-wide 79% unfetched-attachment rate) are recorded on polylogue-ixry. Verification: `devtools test tests/unit/pipeline/test_ingest_batch.py` (58 tests; 2 pre-existing failures unrelated to this change -- `test_primary_mode_projects_revision_after_allowed_durable_receipt` and `test_primary_mode_keeps_unconfirmed_revision_out_of_index_and_fts` fail identically with this patch reverted, "Sinex publication payload rejected before accepted-revision write"); the two new tests were confirmed to fail without the fix (anti-vacuity: `assert True is False` when the fetched revision writes first and the pre-fetch revision follows). Also ran `devtools test tests/unit/sources/test_parsers_drive.py tests/unit/sources/test_drive_attachment_fetch.py` (44 passed) and `devtools verify --quick` (exit 0). Ref polylogue-ixry
|
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: 39 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 (2)
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 |
… path (#3639) ## Summary Drive re-acquisition now gets real revision lineage (`logical_source_key` / `predecessor_raw_id` / a non-quarantined `revision_authority`) via the same byte-prefix revision-governance classifier the "live" tailed-watcher batch path already uses, instead of being invisible to it entirely. ## Problem `iter_drive_raw_data` (`polylogue/sources/drive/__init__.py`) backfills live-fetched attachment bytes into cached Drive JSON on every ingest pass. When the bytes change, it mints a brand-new `raw_id` for the SAME logical session. That raw is written through `_write_session` (`polylogue/pipeline/services/ingest_batch/_core.py`), the generic ingest_batch write path used by every non-tailed-watcher provider, which only ever compares content-hash and freshness timestamps -- it never computes `logical_source_key` or calls the revision-governance cohort classifier the way the governed "live" batch path does for tailed origins (`sources/live/batch.py`, `sources/live/append_ingest.py`). Confirmed live: every one of 157 duplicate `aistudio-drive` raw pairs carried `revision_kind='unknown'`, `logical_source_key=NULL`, `revision_authority='quarantined'` -- no predecessor/baseline linkage at all. PR #3453 added a narrow tie-break in `_write_session` (`_incoming_write_regresses_attachment_coverage`) that stops a richer revision from being clobbered by a poorer one on a freshness tie, but its own docstring names this missing-lineage gap directly as the real, unaddressed cause. ## Solution - Added `_bind_drive_revision_lineage` and a minimal `_DriveRevisionGovernanceAdapter` to `polylogue/pipeline/services/ingest_batch/_core.py`. The adapter satisfies `RawRevisionGovernanceHost` (`storage/sqlite/archive_tiers/revision_governance.py`) structurally -- every function in the `bind_raw_revision`/`classify_raw_revision_cohort` call graph only touches `_ensure_source_conn()` and (inside `classify_raw_revision_cohort`) `_blob_publisher`, so the adapter implements the rest of the Protocol (`_conn`, `commit`, `_preacquire_attachment_blobs`, `_write_counts`, `_skipped_counts`) as typed stubs/placeholders never actually exercised by this call path. - `_bind_drive_revision_lineage` is called unconditionally at the top of `_write_session`, before any of its skip-path early returns -- mirroring `live/batch.py`'s own precedent of binding lineage before the write decision is made, so a raw `_write_session` ultimately skips as stale/duplicate still gets its lineage recorded (useful for future arbitration/rebuild consumers, e.g. polylogue-x1gd). It guards against double-governing an identity already owned by membership-census governance via `raw_membership_raw_ids`, same as `live/batch.py`. - **Gate deviates from the bead's literal wording**: the bead/task brief named `Provider.DRIVE`, but every real config and test fixture configures Drive acquisition as `Source(name="gemini", folder=...)`, and `iter_drive_raw_data`'s `provider_hint = Provider.from_string(source.name)` means a parsed Drive session's `source_name` is actually `Provider.GEMINI` on the wire (both `Provider.GEMINI` and `Provider.DRIVE` map to the same `Origin.AISTUDIO_DRIVE`, see `core/sources.py`). Gated on the value actually observed, not the enum member whose name reads "Drive". - Non-fatal, best-effort: any failure (including `classify_raw_revision_cohort` requiring a writable blob publisher) is logged (`drive_revision_lineage_bind_failed`) and swallowed, never breaking the session write. - Does not replay/apply the classifier's winning revision plan -- `_write_session`'s own freshness/content-hash comparison, plus the #3453 attachment-coverage tie-break (left in place, unchanged), still solely decides what actually lands in `sessions` from this call site. ## Verification - `devtools test tests/unit/pipeline/test_ingest_batch.py` -- 66 passed, including new `test_write_session_binds_drive_revision_lineage`. Confirmed red-first: temporarily reverted the production call and re-ran the new test -- it failed with `assert None == 'gemini:drive-lineage-tie'` (both raws' `logical_source_key` came back NULL). Re-applied the fix and reran green. - `.venv/bin/mypy polylogue/pipeline/services/ingest_batch/_core.py` -- `Success: no issues found in 1 source file`. - `devtools verify --quick` -- `exit_code: 0` (ruff format/check, mypy, render all --check, layering, closure-matrix, schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, pytest-timeout-overrides, degrade-loudly, hash-boundary-census, schema-versioning, classifier-fingerprints, demo-tour-freshness, raw-payload-hash-purity, position-derived-identity, raw-authority-frontier-executability, schema-promotion-audit all `ok`). ## Scope notes / deferred - `sources/drive/__init__.py` untouched -- the fix resolves entirely post-parse in the write path, matching `live/batch.py`'s own precedent; no acquire-side change was needed. - No other provider is wired into this governance path in this PR -- out of scope per the bead. - The #3453 `_incoming_write_regresses_attachment_coverage` tie-break is left in place unchanged, as a safety net for any `_write_session` call site without a `source_conn`/`blob_publisher` (e.g. tests, or a future caller). - Cleanup of the 157 already-contaminated `raw_sessions` rows is explicitly out of scope -- retroactive durable-tier cleanup needs its own explicit-consent process per this repo's schema regime. Ref polylogue-sp72 Co-authored-by: Claude <[email protected]>
…eak (#3656) ## Summary Drive revision-lineage bookkeeping (added in #3639 for polylogue-sp72) computed a `RevisionReplayPlan` but 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 real `iter_drive_raw_data` acquisition path that documents a real residual limitation. ## Problem `_bind_drive_revision_lineage` (`polylogue/pipeline/services/ingest_batch/_core.py`, added in #3639) calls `classify_raw_revision_cohort_for_live_watch` to bind real lineage (`logical_source_key`/`predecessor_raw_id`/`revision_authority`) for Drive re-acquisitions, but never used the returned `RevisionReplayPlan`. 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 produces `assert False is True`). Separately, while building an honest test through the real `iter_drive_raw_data` acquisition 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 lands `revision_authority='quarantined'` with no `predecessor_raw_id` — same as before #3639 for this shape. What #3639 genuinely changed: both raws now carry a non-NULL `logical_source_key` and `revision_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_lineage` now returns the `RevisionReplayPlan` it computes (`None` on any early-return or swallowed failure) 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 remains the deciding factor for every ungoverned case (no `source_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. - New tests in `tests/unit/pipeline/test_ingest_batch.py`: - `test_write_session_drive_lineage_proven_winner_bypasses_freshness_tie` — byte-append fixture (same shape as #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 no `source_conn` (so no governance evidence); asserts the safety net still blocks it. - New test in `tests/unit/sources/test_drive_ops.py`: - `test_iter_drive_raw_data_two_revision_fixture_gets_real_lineage` — threads two genuine `iter_drive_raw_data` passes (attachment fetch fails, then succeeds) through `ArchiveStore.write_raw_payload` + `parse_payload` + `_write_session`, the real production path. Asserts both raws get `logical_source_key` populated and `revision_kind='full'`, and documents (via an explicit assertion + docstring) that `predecessor_raw_id` is 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"): - Full closure of AC1's literal "predecessor-linked, not quarantined" wording for the realistic mid-document JSON mutation shape needs a JSON-structural-diff-aware classifier, not a byte-prefix one — 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 157 already-contaminated `aistudio-drive` raw 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 with `git stash` before this change applied. - `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]> Co-authored-by: Claude <[email protected]>
Summary
Investigated the operator's hypothesis that "aistudio/Drive ingestion and its
attachment handling are completely broken." Partly true, and more precisely
scoped than the hypothesis: ingestion of conversations works; the attachment
fetch mechanism (#3073) also genuinely works; but every successful fetch was
being silently reverted by a raw-revision race in the shared session-write
path, with 100% reproducibility on the live archive. This PR fixes that race.
A sibling lane owns the separate Claude-Code-shaped-drive-cache-file
misrouting bug; this PR does not touch it.
Problem
Live-archive evidence (read-only queries against
index.db/source.db/ops.db, 2026-07-31; archive index atuser_version=46, 12 versions behindmaster's v50 with v47-v50 allSEMANTIC_REPARSE, i.e. current contentsreflect pre-fix parsing until the next reset+reingest):
aistudio-driveorigin: 239 sessions, 12063 messages.acquisition_status='acquired'.All 3094
upload_origin='drive'attachments (Drive-hosted references,the ones feat(sources): acquire live Drive attachment bytes into the blob store #3073 added live fetching for) are
unfetched-- 0% acquired.schema_drift_samples: 100% of 302aistudio-driverecords ingestedsince 2026-07-01 classify as
unseen_shape(the gemini schema catalogpackage has no real candidate for the actual wire shape -- real
chunkedPromptpayloads have no top-levelid/title/createTime,only
chunkedPrompt/runSettings/systemInstruction).Root cause for the attachment non-acquisition, confirmed by direct
inspection, not guessed:
polylogue/sources/drive/attachment_fetch.py,landed 2026-07-18) does work. 157 of 244 cached
~/.local/share/polylogue/drive-cache/gemini/*.jsonfiles carry thefetched
_polylogue_drive_live_bytes_b64payload on disk today.Re-parsing one of those files directly with the current parser
(
polylogue.sources.parsers.drive.parse_chunked_prompt) produces a real4MB
ParsedAttachment.inline_bytesfor1_1M_Reddit_...json-- proven by running it, not inferred.raw_sessionsrow(different content hash) instead of a revision of the prior one:
revision_kind='unknown', emptylogical_source_key,revision_authority='quarantined'on both rows for every duplicatesource_path.iter_drive_raw_datanever establishespredecessor_raw_id/logical_source_keylinkage for a same-pathre-read the way the governed "live" batch path
(
sources/live/batch.py/append_ingest.py) does for tailed origins,so
raw_revision_headsnever forms a cohort for it.timestamp,
_write_session's content-freshness check(
polylogue/pipeline/services/ingest_batch/_core.py, was line ~547)ties exactly between the pre-fetch and post-fetch revisions of the same
file, and a tie fell through to "whichever raw this batch happens to
(re)parse last wins" -- with no signal preferring the richer one.
Measured directly on the live archive: across the 157 duplicate
aistudio-drivesource_paths, the older, pre-fetch revision won157/157 times (100%). This was independently cross-checked two ways
("which raw_id is linked from
sessions.raw_id" and "which raw_id hasthe later
parsed_at_ms") -- last-parsed-wins predicts the winner inall 157 cases; raw_id lexical order does not (only 72/157). This is why
a feature that shipped 2026-07-18 shows 0% effect in the live archive
12 days later: it keeps working and keeps getting silently reverted.
Solution
polylogue/pipeline/services/ingest_batch/_core.py: on an exact freshnesstie between two different raw_ids for the same session, compare
acquired-attachment counts (existing acquired attachments already stored in
the archive vs
inline_bytes is not Noneon the incoming parsed session)and skip the incoming write only when it would regress attachment
coverage. Ties or genuine improvements still write through unchanged --
this only ever blocks a step backward.
This is a narrow, general safety net at the one place both revisions'
writes actually collide, not a Drive-specific patch (a Drive-only fix would
have needed to duplicate this comparison from outside the write path, or
reach into governance internals this PR deliberately does not touch). The
durable fix -- giving Drive re-acquisition real revision lineage so
raw_revision_headsarbitrates it the way tailed origins already get -- isrecorded as follow-up on
polylogue-ixry, along with theunseen_shapeschema-drift finding and a note that the archive-wide 79% unfetched-
attachment rate (chatgpt-export 6145, claude-ai-export 438, grok-export 37
also carry unfetched attachments) was not audited beyond aistudio-drive,
per the operator's ask.
Deliberately out of scope (owned by a sibling lane / other trackers):
the Claude-Code-shaped drive-cache-file misrouting (12 files, 6 colliding
with real local transcripts),
sources/parsers/claude/base_support.py,sources/parsers/codex.py,sources/live/tool_result_sidecars.py,maintenance/rebuild_index.py,cost/,devtools/verify_runs.py,tests/conftest.py, and the broader OriginSpec work (polylogue-2qx).Drive auth (
sources/drive/auth.py) was not independently re-exercisedlive in this pass;
DriveAuthManager.load_credentialsalready raisesDriveAuthErrorloudly on missing/invalid credentials in non-interactivemode (no silent-degradation code path found), and the 157/244 successful
on-disk fetches from 2026-07-18 are themselves evidence auth worked at
least once. No evidence of a currently broken/silently-degraded auth path
was found.
Verification
devtools test tests/unit/pipeline/test_ingest_batch.py-- 58 tests, 56passed. The 2 failures
(
test_primary_mode_projects_revision_after_allowed_durable_receipt,test_primary_mode_keeps_unconfirmed_revision_out_of_index_and_fts) arepre-existing and unrelated: verified by reverting this patch via a
standalone diff and re-running -- they fail identically
("Sinex publication payload rejected before accepted-revision write").
(
test_write_session_freshness_tie_keeps_acquired_attachment,test_write_session_freshness_tie_allows_attachment_improvement) wererun against the pre-fix code (same revert) -- the regression test fails
(
assert True is False) exactly as expected, and theimprovement-still-writes test still passes (correctly permissive).
devtools test tests/unit/sources/test_parsers_drive.py tests/unit/sources/test_drive_attachment_fetch.py-- 44 passed.devtools verify --quick-- exit 0 (ran twice: once manually, once viathe pre-push hook).
How broken was it, really
Not "completely broken." Detection, parsing, and the attachment-fetch
mechanism itself all function correctly today. The actual defect is a
single silent race in session-write precedence that consistently discarded
every successful attachment fetch before it could be observed -- which,
from the outside, is indistinguishable from "attachments don't work at
all" (0.8% acquired). The schema-drift signal (100%
unseen_shape) is areal, separate finding -- the schema catalog is stale relative to the
actual wire format -- but it did not, by itself, block parsing or
attachment extraction; both use structural checks (
looks_like_chunk),not the schema catalog.
polylogue-ixrycarries the durable-fix follow-upand the schema-catalog follow-up so they aren't lost.
Ref polylogue-ixry