Repository navigation
feat(storage): add raw-admission chokepoint mechanism + atomic-read contract - #3668
Conversation
Problem: a live source file can be mid-rewrite when acquisition opens it (provider CLI truncating+rewriting in place, sync client replacing a cache file). A naive read_bytes() can silently return torn bytes -- live evidence of this shape: a Codex rollout file recaptured 15-16x with blob_size growing then suddenly dropping from 427MB to 10KB in one read (polylogue-2t0vp). Adds read_source_bytes_atomic()/try_read_source_bytes_atomic(): capture (size, mtime_ns) before reading, read to EOF, re-stat; retry a bounded number of times on disagreement; raise TornReadError (or return None for the non-raising variant) rather than ever persisting a torn read. Part of polylogue-1fijp (raw-admission chokepoint). Standalone utility, not yet wired into any acquisition call site in this commit. Ref polylogue-1fijp
Problem: raw_sessions rows are currently written from several scattered call sites (batch import, live daemon watcher, drive lineage bind) each independently deciding revision_kind/revision_authority, with no single typed decision point. polylogue-sp72's merged fix (#3656) documents the live proof this is needed: iter_drive_raw_data's Drive re-acquisition path writes revision_kind=unknown + quarantined directly on ambiguous bytes, with no shared arm-resolution logic to route through. What changed: polylogue/storage/sqlite/archive_tiers/raw_admission.py adds admit_raw_observation(), a single decision function implementing the bead's five typed, exhaustive resolution arms over a (prior head bytes, new bytes) comparison -- skip-duplicate, append, supersede, artifact (never an index-tier session row), and an opportunistic-reacquire-then- typed-refusal ambiguous arm (per the operator's 2026-08-03 arm-5 correction: re-acquire is opportunistic, never depends on source persistence for correctness). It composes the existing write_source_raw_session()/RawRevisionEnvelope primitives rather than reimplementing raw-row persistence. Scope: this commit lands the decision function itself with full arm coverage under test, but does NOT yet rewire every acquisition call site (sources/live/batch.py, sources/drive/__init__.py, browser-capture receiver, maintenance backfill) -- see the PR body for the full call-site-by-call-site status and why full consolidation is deferred. Ref polylogue-1fijp
…gh the chokepoint Problem: archive_ingest.py's _admit_non_session_origin_artifacts already computes an ArtifactClassification for configured Claude Code OriginSpec fact artifacts (tool-results, workflow journal, etc), but discarded it -- it called ArchiveStore.write_raw_payload() directly, which writes only a bare raw_sessions row with no raw_artifacts classification. Classification was left to the next offline materialize_artifact_observations sweep, never attached at admission time. What changed: added ArchiveStore.admit_raw_artifact_payload() (backed by a new revision_governance.admit_raw_artifact_payload(), which handles blob publication then delegates to raw_admission.admit_raw_observation()'s ARTIFACT arm) and routed this one call site through it. The already- computed classification now produces an immediate raw_artifacts row using the same deterministic artifact_observation_id() scheme the offline sweep uses, so a later materialize pass upserts onto the same row instead of colliding. This is the one production call-site migration landed in this PR -- see the PR body for the full call-site status (sources/live/batch.py, sources/drive/__init__.py, browser-capture receiver remain unrouted, with reasoning for each). Verification: tests/integration/test_claude_workflow_admission.py (the existing end-to-end test asserting a 224-row raw_artifacts count through this exact path) still passes unchanged -- the upsert-safe artifact_id scheme means this change is additive, not count-altering. Ref polylogue-1fijp
|
Warning Review limit reached
Next review available in: 35 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 (7)
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 |
…okepoint (#3688) ## Summary Migrates one real production call site (`antigravity_conversation_acquisition.py`) off the direct `write_raw_and_parsed_result()` writer onto polylogue-1fijp's raw-admission chokepoint (`admit_raw_observation()`, mechanism landed in #3668), and audits the bead/PR's own cited call-site list against current source. ## Problem PR #3668 landed `admit_raw_observation()` with one routed call site (Claude Code fact-artifact admission) and surveyed 11+ other `write_source_raw_session` call sites as not-yet-migrated. Re-grepping current source for this dispatch found that survey has drifted: `codex_title_census.py`, `context/codex_spawn_edge_correlation.py`, `context/hermes_delivery_correlation.py`, `daemon/antigravity_conversation_acquisition.py` (as originally listed), `sources/hooks.py`, `storage/repair.py`, `storage/raw_reconciler.py`, and `storage/hook_payload_ref_reconciliation.py` do **not** call `write_source_raw_session` or any raw-write wrapper at all today — they only read/reference the `raw_sessions` table (SELECT queries, comments). The real remaining direct callers of `write_source_raw_session` are exclusively the two generic writer primitives inside `revision_governance.py` itself (`write_raw_payload`, `write_raw_and_parsed_result`); production feature code reaches raw writes only through those or `sources/live/*`. ## Solution - `polylogue/storage/sqlite/archive_tiers/raw_admission.py`: widened `admit_raw_observation()` to accept and forward `additional_blob_refs` (attachment blob refs) to its four session-content `write_source_raw_session` calls (BASELINE/APPEND/SUPERSEDE/REFUSED_AMBIGUOUS). The chokepoint previously silently dropped this parameter relative to `write_source_raw_session`'s own capability — migrating any attachment-bearing call site without this fix would have quietly lost attachment blob refs on the raw row. - `polylogue/storage/sqlite/archive_tiers/revision_governance.py`: added `admit_raw_and_parsed_result()`, a narrower sibling of `write_raw_and_parsed_result()` that resolves `admit_raw_observation()`'s typed arms against `prior_head=None` and raises if the caller's BASELINE-only contract is violated. Wired an `ArchiveStore.admit_raw_and_parsed_result` wrapper (mirrors the existing `admit_raw_artifact_payload` shape from #3668). - `polylogue/daemon/antigravity_conversation_acquisition.py`: switched `acquire_antigravity_conversations_once` to the new entrypoint. This call site is structurally BASELINE-only — it pre-filters to `.pb` cascade ids not already present in `raw_sessions`, so no prior head ever exists to compare against. - `docs/plans/layering.yaml`: declared the new entrypoint (`devtools verify layering`'s writer-module-entrypoint-inventory check requires it). ## Scope / call-site status (acceptance-criteria honesty) - **Migrated**: `daemon/antigravity_conversation_acquisition.py` (arm: BASELINE only). - **Reviewed, NOT migrated** (documented, not force-fit): - `sources/live/append_ingest.py` / `sources/live/batch.py` — both resolve real prior-head revision chains (`bind_raw_revision`/`classify_raw_revision_cohort_for_live_watch`) that require a *parsed* session's `provider_session_id` to derive `logical_source_key`, i.e. the decision depends on content only available *after* parsing. `admit_raw_observation` is a single synchronous pre-parse call — architecturally incompatible. The bead itself calls this family "mostly compliant"; explicitly out of scope per the dispatch. - `pipeline/services/archive_ingest.py`'s main session-ingest path (`write_pair`'s `write_raw_and_parsed_result` call) — uses content-addressed `deterministic_raw_session_id` + `shared_raw_ids` in-batch dedup, a different idempotency mechanism than revision-chain byte comparison against a mutable head. Forcing it through the typed arms would be an architecture mismatch, not a mechanical swap, and it's the highest-traffic write path in the system. - `storage/repair.py`'s `raw_sessions` INSERT (browser-origin repair `copy_forward`) — constructs a synthetic row from already byte-proven evidence during repair, not a fresh acquisition observation; doesn't fit the "compare fresh payload to prior head" model at all. - `sources/drive/__init__.py` / `pipeline/services/ingest_batch/_core.py` Drive lineage bind — explicitly excluded per dispatch (separate JSON-structural-diff classifier lane, per #3668's own scope notes). - `codex_title_census.py`, `context/*_correlation.py`, `sources/hooks.py`, `storage/raw_reconciler.py`, `storage/hook_payload_ref_reconciliation.py` — verified via grep against current source: **no `write_source_raw_session`/raw-write-wrapper calls exist in these files at all**. The bead/PR #3668's cited list had drifted; nothing to migrate here. ## AC status (polylogue-1fijp) - (a) grep proves no raw_sessions INSERT outside the chokepoint module: still **partially satisfied** — one additional real call site now routed; the batch-import, live-watcher, and repair paths remain direct writers for the architecture-mismatch reasons above, not because they were skipped. ## Verification - `devtools test tests/unit/daemon/test_antigravity_conversation_acquisition.py tests/unit/storage/test_raw_admission.py` -> 13 passed - `devtools test -k "revision_governance or raw_admission or archive_ingest or antigravity"` -> 132 passed - `mypy --strict` on `raw_admission.py`, `revision_governance.py`, `archive.py`, `antigravity_conversation_acquisition.py` -> `Success: no issues found in 4 source files` - `devtools verify --quick` -> `exit_code: 0` - `devtools verify layering` -> `No layering violations found` (306 pre-existing baselined-import violations / 2 stale-baseline entries unchanged from before this PR, unrelated) Ref polylogue-1fijp --------- Co-authored-by: Claude <[email protected]>
…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
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_sessionsrows are currently written from several independent call sites (one-shot batch import, live daemon watcher, Drive lineage bind), each decidingrevision_kind/revision_authorityon 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 writesrevision_kind=unknown+ emptylogical_source_key+quarantineddirectly 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-2t0vpfound live evidence of a torn-read failure mode: a Codex rollout file recaptured 15-16x withblob_sizegrowing 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; raisesTornReadError(or returnsNonefor 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 optionalPriorRawHead(caller-resolved), resolves exactly one of:SKIP_DUPLICATE-- byte-equal to the accepted head.APPEND-- bytes extend the head as a strict byte-prefix;revision_kind=appendwith a realpredecessor_raw_id.SUPERSEDE-- the incoming bytes are themselves a strict prefix of the accepted head (a proven-dominated, older/shorter read); recordedFULL/BYTE_PROVENwithpredecessor_raw_idpointing 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.ARTIFACT-- payload classifiednot parse_as_sessionby the omsw artifact taxonomy. Still writes araw_sessionsrow (the acquisition-evidence ledger;raw_artifacts.raw_idhas aNOT NULL REFERENCES raw_sessionsFK) but attaches an immediateraw_artifactsclassification row via the same deterministicartifact_observation_id()scheme the offlinematerialize_artifact_observationssweep uses (upsert-safe, no collision). This arm structurally cannot reach an index-tiersessionsrow -- the module has zero imports of any index-tier writer (asserted in a test).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 suppliedreacquirecallback 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-readablerefusal_reason-- never a decision that depends on source persistence, never a silent drop.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, recordedFULL/ASSERTED.Composes the existing
write_source_raw_session()/RawRevisionEnvelopeprimitives rather than reimplementing raw-row persistence.polylogue/storage/sqlite/archive_tiers/revision_governance.py+archive.py:admit_raw_artifact_payload()(module function +ArchiveStorewrapper), mirroring the existingwrite_raw_payload()shape (blob publish +_ensure_source_conn()), delegating toadmit_raw_observation()'s ARTIFACT arm.polylogue/pipeline/services/archive_ingest.py:_admit_non_session_origin_artifacts()now callsarchive.admit_raw_artifact_payload(...)instead of the barearchive.write_raw_payload(...)it previously discarded its own already-computedArtifactClassificationinto -- this one real call site now gets an immediateraw_artifactsrow 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"):
archive_ingest.py's_admit_non_session_origin_artifacts(configured Claude Code fact-artifact admission, arm 4).sources/live/batch.py-- the bead calls this "mostly compliant"; confirmed it already calls intorevision_governance'sclassify_raw_revision_cohort_for_live_watch/bind_raw_revisionmachinery for real lineage tracking. Rewiring its write path ontoadmit_raw_observationwould touch the daemon's live-watcher hot path and itsRawRevisionGovernanceHostProtocol 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 fix(drive): let proven revision lineage bypass Drive freshness tie-break #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_bytesre-serializes the whole JSON document rather than byte-appending, sosecond_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 fix(drive): let proven revision lineage bypass Drive freshness tie-break #3656 fix. Building a JSON-structural classifier is materially larger scope, left as explicit follow-up.grep -rln write_source_raw_session(11 non-test call sites acrosscodex_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
iter_drive_raw_datapath: 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).test_admit_raw_observation_arm4_artifact_never_touches_index_dbasserts both the behavioral outcome (raw_artifacts row,parse_as_session=0, nosessionstable insource.dbat all) and the structural guarantee (noarchive_tiers.write/archive_tiers.indeximport inraw_admission.py).tests/unit/sources/test_atomic_read.pybuilds a real fixture that mutates the file's stat identity between pre/post-read checks, provingTornReadErroron persistent instability and correct stabilized-bytes recovery when a retry succeeds.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 passeddevtools 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 fix(drive): let proven revision lineage bypass Drive freshness tie-break #3656's own verification notes reproducing the identical failure viagit stashbefore that change; not touched by this PRdevtools test -k "archive_ingest or revision_governance or admit_raw or raw_admission"-> 26 passedmypy(strict) on every touched/added file ->Success: no issues found in 7 source filesdevtools verify --quick->exit_code: 0Ref polylogue-1fijp