Repository navigation
feat(sources): acquire live Drive attachment bytes into the blob store - #3073
Conversation
|
Warning Review limit reached
Next review available in: 35 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 (12)
✨ 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: f2e0f2bb17
ℹ️ 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".
|
Addressed all 3 Codex findings in 74da2f3:
200 focused tests pass ( Re: |
Problem: Drive-hosted attachment references (driveDocument/driveImage/ driveAudio/driveVideo) were never fetched by the live ingest pipeline. The only code that called DriveSourceClient.download_bytes for an attachment (_apply_drive_attachments + iter_drive_sessions) had zero callers — the real path (iter_drive_raw_data -> generic dispatch parse) never wired it in, and that dead code wrote to attachment.path/local disk rather than inline_bytes, so even if revived it would not reach the existing true-hash blob-publish path. Solution: iter_drive_raw_data already owns the one live DriveSourceAPI client instance per file, inside the iterator scope, before the acquire and parse stages decouple for memory-bounded streaming. A new module (sources/drive/attachment_fetch.py) walks the raw session JSON for Drive-hosted doc/media references *at that point*, downloads each via the same live client, and injects the fetched bytes as base64 under a sidecar key (DRIVE_LIVE_FETCH_DATA_KEY). attachment_from_doc (the existing chunk parser) decodes that sidecar into ParsedAttachment.inline_bytes with no other parser changes, so the already-shipped publish-then-write path (ingest_batch/_core.py) picks it up as a real content-addressed blob with a true SHA-256 and acquisition_status='acquired' — zero downstream changes needed. Fetch failures/oversize files leave the attachment honestly unfetched, never fabricating a hash. Removed the dead _apply_drive_attachments/ iter_drive_sessions path they replace (zero live callers). Scope: this lands only the Drive sub-case of polylogue-83u.2. The export-zip-member and local-path sub-cases have no current producer (no parser ever emits a zip-embedded or local-filesystem attachment) — tracked as a parent-epic note rather than speculative beads. Verification: devtools test tests/unit/sources/test_drive_ops.py tests/unit/sources/test_drive_attachment_fetch.py tests/unit/storage/test_attachment_acquisition.py tests/unit/sources/test_source_laws.py -> 143 passed. devtools verify --quick -> exit 0 (ruff format/check, mypy --strict, render all --check, topology, layering, closure-matrix, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly all green). devtools test tests/unit/sources/ -> 1705 passed, 2 pre-existing failures in test_chatgpt_normalization_survivors.py confirmed unrelated (same failures reproduce with this change stashed out). Ref polylogue-83u.2 Co-Authored-By: Claude <[email protected]>
Drive live attachment byte acquisition (this branch, commit above) is the Drive sub-case of polylogue-83u.2. Export-zip-member and local-path sub-cases have no current producer (no parser has ever emitted an attachment with real zip-member or local-filesystem bytes) -- noted on parent polylogue-83u as inapplicable rather than deferred. Hand-merged the two touched records from a fresh `bd export` rather than copying the whole file: bd resolves its export target independent of invocation cwd, so it also carries unrelated concurrent-session bead activity that doesn't belong on this branch. Co-Authored-By: Claude <[email protected]>
Problem: Codex/CodeRabbit review of the Drive live attachment byte acquisition change (previous commit) found three real gaps. - P1: the live-fetch sidecar (DRIVE_LIVE_FETCH_DATA_KEY) survived unstripped into ContentBlock.raw for driveDocument/driveImage/ driveAudio/driveVideo blocks (gemini_message.py's _drive_media_content_block), unlike inlineData/inlineFile/inlineImage which already strip their `data` payload via _without_inline_bytes. Every acquired Drive attachment would duplicate its full base64 bytes into block metadata -- persisted in index.db, which is not content-addressed, up to the 50MB cap. - P2: the live-fetch file-id resolution tried `id` before `fileId` (and fell back to `driveId`, a shared-drive CONTAINER id, never a file id), the reverse of attachment_from_doc's own native-id precedence (#1252: `fileId` is the real Drive file id DriveSourceClient.download_bytes needs; `id` is a provider attachment handle). Payloads carrying both fields would request the wrong handle and silently fail live. - P2: the injector only ran on a fresh download; a cache_path.exists() hit skipped it entirely, so a cache file written before this feature (or where a Drive-hosted attachment failed/was oversize at the time) stayed unfetched forever even on repeated re-ingest. What changed: - _drive_media_content_block strips DRIVE_LIVE_FETCH_DATA_KEY from the record before building ContentBlock.raw, mirroring _without_inline_bytes's existing treatment of inline data. - _doc_file_id now tries `fileId` before `id` and never considers `driveId`. - _inject_live_drive_attachment_bytes now returns (bytes, mutated) and iter_drive_raw_data runs it unconditionally on every read (cache hit or fresh download), refreshing the cache file only when something new was actually resolved. Verification: devtools test tests/unit/sources/test_drive_ops.py tests/unit/sources/test_drive_attachment_fetch.py tests/unit/sources/test_parsers_drive.py tests/unit/storage/test_attachment_acquisition.py tests/unit/sources/test_source_laws.py tests/unit/sources/test_gemini_chunked_prompt_contract.py -> 200 passed (4 new tests covering each finding). devtools verify --quick + public-claims -> exit 0. devtools test tests/unit/sources/ -> 1709 passed (same 2 pre-existing unrelated failures). Co-Authored-By: Claude <[email protected]>
74da2f3 to
74ba3f4
Compare
…3453) ## 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 at `user_version=46`, 12 versions behind `master`'s v50 with v47-v50 all `SEMANTIC_REPARSE`, i.e. current contents reflect pre-fix parsing until the next reset+reingest): - `aistudio-drive` origin: 239 sessions, 12063 messages. - Of 3146 attachments, only 26 (0.8%) are `acquisition_status='acquired'`. All 3094 `upload_origin='drive'` attachments (Drive-hosted references, the ones #3073 added live fetching for) are `unfetched` -- 0% acquired. - `schema_drift_samples`: 100% of 302 `aistudio-drive` records ingested since 2026-07-01 classify as `unseen_shape` (the gemini schema catalog package has no real candidate for the actual wire shape -- real `chunkedPrompt` payloads have no top-level `id`/`title`/`createTime`, only `chunkedPrompt`/`runSettings`/`systemInstruction`). Root cause for the attachment non-acquisition, confirmed by direct inspection, not guessed: 1. The live-fetch mechanism (`polylogue/sources/drive/attachment_fetch.py`, landed 2026-07-18) **does work**. 157 of 244 cached `~/.local/share/polylogue/drive-cache/gemini/*.json` files carry the fetched `_polylogue_drive_live_bytes_b64` payload on disk today. Re-parsing one of those files directly with the current parser (`polylogue.sources.parsers.drive.parse_chunked_prompt`) produces a real 4MB `ParsedAttachment.inline_bytes` for `1_1M_Reddit_...json` -- proven by running it, not inferred. 2. But each fetch produced a **second, unlinked `raw_sessions` row** (different content hash) instead of a revision of the prior one: `revision_kind='unknown'`, empty `logical_source_key`, `revision_authority='quarantined'` on both rows for every duplicate `source_path`. `iter_drive_raw_data` never establishes `predecessor_raw_id`/`logical_source_key` linkage for a same-path re-read the way the governed "live" batch path (`sources/live/batch.py` / `append_ingest.py`) does for tailed origins, so `raw_revision_heads` never forms a cohort for it. 3. Because the injected attachment bytes don't change any message 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-drive` source_paths, the **older, pre-fetch revision won 157/157 times (100%)**. This was independently cross-checked two ways ("which raw_id is linked from `sessions.raw_id`" and "which raw_id has the later `parsed_at_ms`") -- last-parsed-wins predicts the winner in all 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 freshness tie 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 None` on 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_heads` arbitrates it the way tailed origins already get -- is recorded as follow-up on `polylogue-ixry`, along with the `unseen_shape` schema-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-exercised live in this pass; `DriveAuthManager.load_credentials` already raises `DriveAuthError` loudly on missing/invalid credentials in non-interactive mode (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, 56 passed. The 2 failures (`test_primary_mode_projects_revision_after_allowed_durable_receipt`, `test_primary_mode_keeps_unconfirmed_revision_out_of_index_and_fts`) are pre-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"). - Anti-vacuity: the two new tests (`test_write_session_freshness_tie_keeps_acquired_attachment`, `test_write_session_freshness_tie_allows_attachment_improvement`) were run against the pre-fix code (same revert) -- the regression test fails (`assert True is False`) exactly as expected, and the improvement-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 via the 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 a real, 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-ixry` carries the durable-fix follow-up and the schema-catalog follow-up so they aren't lost. Ref polylogue-ixry
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Implements the Drive sub-case of
polylogue-83u.2: live Drive-hosted attachment references (driveDocument(s)/driveImage/driveAudio/driveVideo) are now fetched during ingest and land in the content-addressed blob store with a true SHA-256, instead of never being acquired.Problem
A 2026-07-08 investigation (recorded on the bead) found the only code that ever called
DriveSourceClient.download_bytesfor an attachment —_apply_drive_attachments+iter_drive_sessions— had zero live callers. The real ingest path (iter_drive_raw_data→ generic dispatch parse) never wired attachment acquisition in at all. Even if that dead code had been revived, it wrote bytes toattachment.path/local disk rather thanParsedAttachment.inline_bytes, so it would not have reached the existing true-hash blob-publish path anyway (schema v13'sacquisition_status).Solution
iter_drive_raw_data(polylogue/sources/drive/__init__.py) already owns the one liveDriveSourceAPIclient instance per file, inside the iterator scope, before the acquire and parse stages decouple for memory-bounded streaming. A new module,polylogue/sources/drive/attachment_fetch.py, walks the raw session JSON for Drive-hosted doc/media references at that exact point, downloads each via the same live client, and injects the fetched bytes as base64 under a sidecar key (DRIVE_LIVE_FETCH_DATA_KEY, defined inpolylogue/sources/parsers/drive_support_attachments.py). The existing chunk parser (attachment_from_doc) decodes that sidecar intoParsedAttachment.inline_bytes— no other parser changes — so the already-shipped publish-then-write path (ingest_batch/_core.py) picks it up as a real content-addressed blob withacquisition_status='acquired', with zero downstream changes needed.Fetch failures and oversize files (50MB cap) leave the attachment honestly
upload_origin="drive"with noinline_bytes— never a fabricated hash.Removed
_apply_drive_attachments/iter_drive_sessions(and the now-deadsources/__init__.pyre-export) — the obsolete, zero-caller path this change replaces, per surgical-renewal doctrine.Non-goals (explicitly out of scope)
polylogue-83u.2also named export-zip-member and local-path attachment sub-cases. Both were re-confirmed to have zero current producer — no parser has ever emitted an attachment whose bytes live as a sibling zip member or a real local filesystem path. There is nothing live to un-bypass for either, so this PR does not touch them; noted on parentpolylogue-83urather than filing speculative follow-up beads with no defined producer.Verification
devtools test tests/unit/sources/test_drive_ops.py tests/unit/sources/test_drive_attachment_fetch.py tests/unit/storage/test_attachment_acquisition.py tests/unit/sources/test_source_laws.py→ 143 passeddevtools verify --quick→ exit 0 (ruff format/check, mypy --strict, render all --check, topology, layering, closure-matrix, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly)devtools test tests/unit/sources/→ 1705 passed, 2 pre-existing failures intest_chatgpt_normalization_survivors.pyconfirmed unrelated (reproduce identically with this change stashed out)Ref polylogue-83u.2
Co-Authored-By: Claude [email protected]