Skip to content

feat(sources): acquire live Drive attachment bytes into the blob store - #3073

Merged
Sinity merged 3 commits into
masterfrom
feature/attachments/drive-live-byte-acquisition
Jul 18, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/attachments/drive-live-byte-acquisition

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner

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_bytes for 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 to attachment.path/local disk rather than ParsedAttachment.inline_bytes, so it would not have reached the existing true-hash blob-publish path anyway (schema v13's acquisition_status).

Solution

iter_drive_raw_data (polylogue/sources/drive/__init__.py) 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, 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 in polylogue/sources/parsers/drive_support_attachments.py). The existing chunk parser (attachment_from_doc) decodes that sidecar into ParsedAttachment.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 with acquisition_status='acquired', with zero downstream changes needed.

Fetch failures and oversize files (50MB cap) leave the attachment honestly upload_origin="drive" with no inline_bytes — never a fabricated hash.

Removed _apply_drive_attachments/iter_drive_sessions (and the now-dead sources/__init__.py re-export) — the obsolete, zero-caller path this change replaces, per surgical-renewal doctrine.

Non-goals (explicitly out of scope)

polylogue-83u.2 also 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 parent polylogue-83u rather 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 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)
  • devtools test tests/unit/sources/ → 1705 passed, 2 pre-existing failures in test_chatgpt_normalization_survivors.py confirmed unrelated (reproduce identically with this change stashed out)

Ref polylogue-83u.2

Co-Authored-By: Claude [email protected]

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 35 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 881e5197-bc7f-4d23-87b3-5742643d256b

📥 Commits

Reviewing files that changed from the base of the PR and between 05fbaa8 and 74ba3f4.

📒 Files selected for processing (12)
  • .beads/interactions.jsonl
  • .beads/issues.jsonl
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/sources/__init__.py
  • polylogue/sources/drive/__init__.py
  • polylogue/sources/drive/attachment_fetch.py
  • polylogue/sources/parsers/drive_support_attachments.py
  • polylogue/sources/providers/gemini_message.py
  • tests/unit/sources/test_drive_attachment_fetch.py
  • tests/unit/sources/test_drive_ops.py
  • tests/unit/sources/test_parsers_drive.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/attachments/drive-live-byte-acquisition

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/sources/drive/__init__.py Resolved
@Sinity

Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner Author

Addressed all 3 Codex findings in 74da2f3:

  • P1 (sidecar leaking into block metadata): _drive_media_content_block now strips DRIVE_LIVE_FETCH_DATA_KEY before building ContentBlock.raw, mirroring _without_inline_bytes's existing treatment of inlineData/inlineFile/inlineImage. Covered by a new end-to-end test (test_live_fetched_drive_attachment_bytes_reach_inline_bytes_not_block_metadata).
  • P2 (fileId vs id precedence): _doc_file_id now tries fileId before id (matching attachment_from_doc's own refactor(schema): first-class attachment native identifiers (#864 slice B) #1252 precedence) and never falls back to driveId (a shared-drive container id, not a file id). Covered by two new tests.
  • P2 (cached payloads bypass the injector): the injector now runs on every read (cache hit or fresh download), refreshing the cache file only when something new was actually resolved. Covered by a new test seeding a stale pre-injector cache file and proving the next run backfills it.

200 focused tests pass (test_drive_ops.py, test_drive_attachment_fetch.py, test_parsers_drive.py, test_attachment_acquisition.py, test_source_laws.py, test_gemini_chunked_prompt_contract.py), devtools verify --quick + public-claims green.

Re: ci/circleci: quick-gate failing — confirmed pre-existing/unrelated: it also fails on 4053787ab (master itself, PR #3064, already merged), consistently ~18s in, well before any real lint/mypy/render step would complete. Not something this PR introduced.

Sinity and others added 3 commits July 18, 2026 05:20
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]>
@Sinity
Sinity force-pushed the feature/attachments/drive-live-byte-acquisition branch from 74da2f3 to 74ba3f4 Compare July 18, 2026 03:22
@Sinity
Sinity merged commit 1501536 into master Jul 18, 2026
1 of 3 checks passed
@Sinity
Sinity deleted the feature/attachments/drive-live-byte-acquisition branch July 18, 2026 03:22
Sinity added a commit that referenced this pull request Jul 31, 2026
…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
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

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.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 71.F041 / P2: fixed-already at the checked revision: The obsolete raw-JSON attachment injector is no longer the acquisition boundary. polylogue/operations/attachment_convergence.py:375 selects unfetched indexed refs independently of whether the owning document came from a cache or download, then streams and publishes the attachment bytes, so cached documents do not require deletion to fetch their attachments.
  • 71.F042 / P2: stale at the checked revision: polylogue/sources/drive/attachment_fetch.py was deleted in d2e7214 (fix(drive): one attachment owner and a revision-keyed document cache (fix(drive): one attachment owner and a revision-keyed document cache #5649)); the cited code no longer exists at 5ebcfe5.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant