Skip to content

fix(storage): refuse a same-source_path raw pair split across two byte-revision keys - #3396

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/ambiguous-raw-materialization-leak
Jul 30, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/ambiguous-raw-materialization-leak

Conversation

@Sinity

@Sinity Sinity commented Jul 30, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes a proven silent fidelity downgrade: two raws of the same physical
document, censused under different raw_sessions.logical_source_key
values, were each independently accepted as a byte-proven singleton
baseline and raced to materialize the same (origin, native_id) session
with no comparison ever happening between them.

Problem

Read-only queries against the live 99 GB archive (/realm/db/polylogue)
and the blob store, cross-checked against production parser code, showed
5 aistudio-drive sessions
(Implementing-066bb070/13ced1c8/37edfeb3/845dd573/d4d7fbab) with
attachments reporting unfetched despite the bytes existing in the blob
store:

  • Each affected document has two raws at the SAME source_path — a bare
    and an attachment-enriched Drive re-acquisition — but with DIFFERENT
    raw_sessions.logical_source_key values ("...4c69" vs "...4c69-0").
  • raw_authority_parser_census proves the -0 suffix was produced by the
    pre-fix(demo): converge daemon import --demo path with direct seeder #3179/z1c6 dispatch.py bug (_lower_drive_like_payload's
    _looks_like_chunked_session_list branch always appended -{index}
    regardless of list length, fixed 2026-07-20 in b473d92). Reparsing
    both raw blobs with the CURRENT parser gives the identical, correct,
    unsuffixed identity for both — verified directly against the real
    blobs.
  • raw_authority_parser_census's quiescence gate only checks the
    parser_fingerprint STRING (unchanged across the fix), so the stale,
    buggy identity was never re-derived.
  • ArchiveStore.classify_raw_revision_cohort classifies a byte-revision
    key in isolation. Neither raw's key ever surfaces the other as a
    sibling (raw_membership_retired_full_revision_siblings only matches
    the EXACT key), so each was accepted as a trivial one-member "chain" —
    no raw_session_memberships row was ever created for either raw, so
    neither ever reached the ambiguous-decision machinery. Both then raced
    to write the shared (origin, native_id) session row; the smaller,
    attachment-unfetched raw happened to write last.

Solution

  • ArchiveStore.classify_raw_revision_cohort gains an opt-in
    check_source_path_identity_split guard: refuse unconditional
    singleton acceptance when another 'full' raw shares this raw's
    source_path under a DIFFERENT (or already-retired) key, folding both
    into membership governance instead, where the real content-based
    classifier (classify_membership_revisions) weighs them jointly.
    Opt-in only — the live watcher (sources/live/batch.py) does NOT
    set it: a watched path can legitimately be atomically replaced with a
    different session's content, which must not be quarantined as
    "divergent evidence" (proven by
    test_full_ingest_does_not_advance_cursor_across_same_size_replacement
    et al., which regressed under an unconditional guard). Only
    revision_backfill.py's offline backfill/rebuild replay loop — the
    path that actually produced this defect — opts in.
  • revision_backfill.py's retire-to-membership-governance fallback now
    buckets membership_candidates/membership_keys by the identity the
    retirement reparse actually recomputes, not the stale outer-loop key
    either raw was originally censused under. Without this, two
    same-document raws retired from different stale keys would land in
    SEPARATE membership cohorts and each be accepted as an independent
    singleton — reproducing the exact defect one layer down (confirmed
    empirically: reverting just this half makes replayed_logical_sources
    come back as 1 instead of 0).

Non-goals / follow-up

  • The live archive's 5 already-downgraded sessions are NOT repaired by
    this PR (code-only fix, per scope; live remediation is a separate,
    explicitly out-of-scope lane).
  • polylogue-9dxn (filed by a parallel lane) addresses the sibling
    problem — a persisted ambiguous verdict has no classifier-version
    column and is treated as terminal forever, so a classifier fix like
    polylogue-bu1i's is inert on existing data. That fix does not, by
    itself, heal this defect: 9dxn's proposed quiescence gate stays
    permissive for any KNOWN fingerprint (to avoid forcing a blanket
    re-census), so a stale-but-complete (not ambiguous) census receipt
    like the one that caused this bug would stay "already observed"
    forever even after a fingerprint bump. This PR's guard is independent
    of fingerprint versioning and closes the general case regardless of
    how two same-document raws ended up under different keys.
  • Filed polylogue-eqnv with the full evidence chain and the
    relationship to polylogue-9dxn/polylogue-bu1i/polylogue-7ilr.

Verification

  • devtools test tests/unit/storage/test_revision_replay.py tests/unit/sources/test_revision_backfill.py tests/unit/sources/test_live_watcher.py tests/unit/sources/test_live_batch_support.py — 235 passed (one
    unrelated pre-existing timing flake in
    test_end_to_end_hidden_root_file_creation_triggers_ingest, confirmed
    to reproduce on master without this change, in isolation, and
    disappear on repeated reruns of the same combined selection with this
    change applied — classified as pre-existing/flaky, not caused by this
    PR).
  • devtools verify --quick — exit 0 (also ran automatically via the
    pre-push hook).
  • mypy polylogue/storage/sqlite/archive_tiers/archive.py polylogue/sources/revision_backfill.py — Success: no issues found in 2 source files.
  • Anti-vacuity: reverting archive.py's guard (via git stash) makes
    test_same_source_path_full_siblings_under_different_keys_are_not_independently_accepted
    fail (accepted_raw_ids becomes non-empty instead of ()). Reverting
    revision_backfill.py's fresh-key bucketing alone makes
    test_stale_pre_fix_identity_split_folds_into_one_ambiguous_cohort
    fail (replayed_logical_sources == 1 instead of 0). Both confirmed
    by direct revert + rerun, restored afterward.

Ref polylogue-eqnv, polylogue-bu1i, polylogue-7ilr, polylogue-9dxn

Co-Authored-By: Claude [email protected]

…e-revision keys

Problem: 5 aistudio-drive sessions (Implementing-066bb070/13ced1c8/
37edfeb3/845dd573/d4d7fbab) show attachments downgraded to unfetched in
the live archive despite the bytes existing in the blob store. Root cause
traced with read-only queries against source.db + the blob store: each
affected document has two raws at the SAME source_path (a bare and an
attachment-enriched Drive re-acquisition), but they carry DIFFERENT
raw_sessions.logical_source_key values ("...4c69" vs "...4c69-0").
raw_authority_parser_census proves the "-0" suffix was assigned by the
pre-#3179/z1c6 dispatch.py bug (fixed 2026-07-20, b473d92) -- reparsing
both raw blobs with the CURRENT parser gives the identical, correct,
unsuffixed identity for both. Because raw_authority_parser_census's
quiescence gate only checks the parser_fingerprint STRING (unchanged
across the fix), the stale pre-fix identity was never re-derived.
classify_raw_revision_cohort then classified each key in isolation and
unconditionally accepted BOTH as independent byte-proven singleton
baselines -- no raw_session_memberships row was ever created for either,
so neither ever reached the ambiguous-decision machinery. Both sessions
then raced on the shared (origin, native_id) upsert; the smaller/bare raw
happened to write last.

Solution:
- ArchiveStore.classify_raw_revision_cohort gains an opt-in
  check_source_path_identity_split guard: refuse unconditional singleton
  acceptance when another 'full' raw shares this raw's source_path under a
  different (or already-retired) logical_source_key, folding both into
  membership governance instead, where the real content-based classifier
  weighs them jointly. Opt-in only -- the live watcher (sources/live/
  batch.py) must NOT apply this: a watched path can legitimately be
  atomically replaced with a different session's content (proven by
  test_full_ingest_does_not_advance_cursor_across_same_size_replacement
  et al., which regressed when the guard was unconditional).
  revision_backfill.py's offline backfill/rebuild replay loop opts in.
- revision_backfill.py's retire-to-membership-governance fallback now
  buckets membership_candidates/membership_keys by the identity the
  retirement reparse actually recomputes, not the stale outer-loop key
  either raw was originally censused under -- otherwise two same-document
  raws retired from different stale keys would land in separate membership
  cohorts and each be accepted as an independent singleton, reproducing
  the same defect one layer down (verified failing without this half of
  the fix: replayed_logical_sources == 1 instead of 0).

Verification:
- devtools test tests/unit/storage/test_revision_replay.py
  tests/unit/sources/test_revision_backfill.py
  tests/unit/sources/test_live_watcher.py
  tests/unit/sources/test_live_batch_support.py -- 235 passed (one
  unrelated pre-existing timing flake in test_end_to_end_hidden_root_file_
  creation_triggers_ingest, reproduces on master without this change too).
- devtools verify --quick -- exit 0.
- mypy polylogue/storage/sqlite/archive_tiers/archive.py
  polylogue/sources/revision_backfill.py -- Success, no issues.
- Anti-vacuity: reverting archive.py's guard makes
  test_same_source_path_full_siblings_under_different_keys_are_not_independently_accepted
  fail (accepted_raw_ids becomes non-empty instead of ()); reverting
  revision_backfill.py's fresh-key bucketing alone makes
  test_stale_pre_fix_identity_split_folds_into_one_ambiguous_cohort fail
  (replayed_logical_sources == 1 instead of 0). Both confirmed by direct
  git-stash revert + rerun.

Ref polylogue-eqnv, polylogue-bu1i, polylogue-7ilr, polylogue-9dxn

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 30, 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: 9 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 Plus

Run ID: 3dc861e5-fd47-4ba4-a581-5f920bbc6506

📥 Commits

Reviewing files that changed from the base of the PR and between 2b54f2b and 93dce33.

📒 Files selected for processing (4)
  • polylogue/sources/revision_backfill.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/sources/test_revision_backfill.py
  • tests/unit/storage/test_revision_replay.py

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: 93dce33302

ℹ️ 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 on lines +2261 to +2266
if (
full_rows
and check_source_path_identity_split
and self._raw_revision_source_path_has_divergent_evidence(logical_source_key)
):
full_rows = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve append chains when applying the cross-key guard

When a logical key has a quarantined full baseline plus one or more append rows, and another full row at the same source_path uses a different key, this guard empties full_rows before the baseline can become byte-proven, so the append cannot be promoted and the returned replay plan has no accepted chain. The backfill fallback cannot recover it because convertible_full_revision_raw_ids() returns an empty tuple whenever the cohort contains an append, despite the caller's stated intent that append chains remain byte-governed; on a cold rebuild this leaves the otherwise valid chain unmaterialized. Limit this identity-split fallback to full-only cohorts, or preserve/promote the append chain separately.

Useful? React with 👍 / 👎.

@Sinity
Sinity merged commit bc1f2f2 into master Jul 30, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/ambiguous-raw-materialization-leak branch July 30, 2026 12:51
Sinity added a commit that referenced this pull request Jul 30, 2026
…membership (#3397)

## Summary

Fixes a second, distinct materialization leak found while investigating
PR #3396: a raw whose OWN `raw_session_memberships.decision =
'ambiguous'`
was reaching `sessions` anyway through a write path that never consults
membership decisions at all.

## Problem

Live measurement against `/realm/db/polylogue`
(`origin='aistudio-drive'`):
28 cohorts have `raw_session_memberships.decision='ambiguous'` on BOTH
members under the SAME `logical_source_key` — genuinely arbitrated,
`classify_membership_revisions` correctly refused to pick a winner — yet
each cohort's session IS present in `index.db` with **zero acquired
attachments**: 641 attachments total across the 28, every one
`unfetched`, while the enriched sibling in the blob store holds the
bytes.

Traced by reading, not guessing:

- `ArchiveStore.apply_raw_membership_classification` (the
  `classify_membership_revisions` consumer) is innocent — for a
  fully-ambiguous cohort it explicitly clears
  `raw_sessions.parsed_at_ms` and never touches `sessions` at all (its
  own finalization block proves this).
- `repair.py:1075`/`repair.py:4432-4462` (the two gates this
  investigation started from) are both innocent too: neither sits on the
  actual write path. `repair.py:4432` (`_raw_replay_plan_outcome`) is a
  **read-only reporting classifier**, not an enforcement gate.
  `repair.py:1075` is a narrow inspector for an unrelated
  (`source-v7`/quarantined-accepted-raw) repair scenario.
- The actual writer is `_write_parsed_precedence_result`
  (`archive.py`), reached via
  `write_parsed_for_retained_raw`/`write_parsed_for_retained_raw_result`
  with `revision_authoritative=False` (the default — used by the
  one-shot importer `pipeline/services/archive_ingest.py` and other
  non-membership-governed callers). Its only revision-authority
  awareness before this fix was a check against `raw_revision_heads` —
  populated ONLY when a cohort has an **accepted** winner. A genuinely
  ambiguous cohort never gets one, so that check stays silent and the
  function falls through to its own browser-capture-precedence/
  freshness logic, writing the session unconditionally on the raw's
  next reparse — arbitrary last-writer-wins, independent of the
  recorded verdict.

## Solution

`_write_parsed_precedence_result` now also refuses to write when the
raw's own `raw_session_memberships.decision = 'ambiguous'`, alongside
the pre-existing `raw_revision_heads` check.

## Known sibling hole — not fixed here

`polylogue/pipeline/services/ingest_batch/_core.py` (the daemon's
default batch-ingest write path for most non-drive origins) has the
same shape — its own precedence/freshness logic, no
`raw_session_memberships` consultation. The coordinator's own
measurement (`revision_authority='quarantined'` with `parsed_at_ms`
set: chatgpt-export 7,050, codex-session 3,633, claude-code-session
2,450, claude-ai-export 1,562 — not all necessarily leaked
materializations, but the same shape) suggests this file matters for
most of the non-drive volume. Filed as `polylogue-c737`; not fixed here
— different file, out of this PR's ownership scope, needs its own
read-only census first.

## Verification

- `devtools test tests/unit/storage/test_revision_replay.py
  tests/unit/sources/test_revision_backfill.py
  tests/unit/sources/test_live_batch_support.py
  tests/unit/pipeline/test_archive_ingest_commit_batching.py
  tests/unit/pipeline/test_ingest_batch.py` — 213 passed.
- `devtools verify --quick` — exit 0.
- `mypy polylogue/storage/sqlite/archive_tiers/archive.py` — `Success:
  no issues found in 1 source file`.
- Anti-vacuity: temporarily short-circuiting the new guard
  (`if False and ambiguous_membership is not None`) makes
  `test_precedence_write_refuses_a_raw_recorded_ambiguous` fail
  (`assert (1,) == (0,)` — a session exists when it must not), restored
  afterward.

Ref polylogue-c737, polylogue-eqnv, polylogue-bu1i, polylogue-9dxn

Co-Authored-By: Claude <[email protected]>

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Prevented sessions with unresolved or ambiguous raw-record membership
from being written to the archive.
* Ensured these records are not silently resolved using standard
precedence rules.
* Preserved accurate skipped-record counts when a session write is
declined.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 30, 2026
…chive.py (#3406)

## Summary

Splits the raw-revision-authority and membership-classification concern
out
of `polylogue/storage/sqlite/archive_tiers/archive.py` (13,338 lines)
into a
new module,
`polylogue/storage/sqlite/archive_tiers/revision_governance.py`
(2,841 lines), so that concern stops living inside the query-surface
god-file.

## Problem

`docs/architecture-hotspots.md` documents `archive.py`'s public contract
as
"`ArchiveStore` — every SELECT-shaped query surface (sessions, messages,
blocks, insights reads, search)". The file also owned ~55 `raw_*`/write
methods implementing revision/membership write authority — a different
concern with different invariants, and the exact cluster where every
defect
found on 2026-07-30 lived (PRs #3394, #3396, #3397, #3398, #3401). Ref
polylogue-1r9c (decomposition epic), polylogue-c737 (a defect from this
cluster).

## Solution

- New module `archive_tiers/revision_governance.py` owns raw-revision
replay,
membership classification/census, and the narrow raw-write paths that
hand
  a parsed session to that authority — documented contract in the module
  docstring (what it owns / what it refuses).
- Every governance function takes `store: RawRevisionGovernanceHost` (a
  `Protocol`) as its first argument instead of being a method on
`ArchiveStore`. The protocol names exactly the seven `ArchiveStore`
members
governance code touches (`_conn`, `_ensure_source_conn`,
`_blob_publisher`,
  `_pending_raw_parse_states`, `_preacquire_attachment_blobs`,
  `_write_counts`, `_skipped_counts`). `ArchiveStore` satisfies it
structurally — no inheritance, no import of `ArchiveStore` from the new
  module (which would create an import cycle).
- `ArchiveStore` keeps one-line delegating methods with unchanged
signatures,
  so every external caller (`sources/live/batch.py`,
  `sources/live/append_ingest.py`, `sources/revision_backfill.py`,
`storage/repair.py`, `pipeline/services/archive_ingest.py`,
`api/archive.py`,
and every test holding an `ArchiveStore` instance) is untouched. This is
not
  a compatibility shim — there is exactly one implementation (in the new
module), and the delegator body is the call site, same shape as any
other
  extract-function-then-delegate refactor.
- Updated `docs/plans/layering.yaml`'s `writer_modules` inventory:
  `archive.py`'s only remaining direct writer is `delete_sessions`
(index-only); the `raw-membership-classification` twin-write contract
and
  its 11 entrypoints moved to the new module's own entry.
- Regenerated `docs/plans/topology-target.yaml` /
`docs/topology-status.md`;
  updated `docs/architecture-hotspots.md`'s line-count row and
`docs/plans/hash-boundary-registry.yaml`'s moved `hashlib.sha256` call
site.

### Connection-interface decision (the design question this task turns
on)

Considered and rejected two alternatives:
- **Bare `sqlite3.Connection`** — insufficient. Governance needs the
lazily-
opened `source.db` connection, the blob publisher, and the pending-raw-
  parse-state batch too, not just the index connection.
- **A mixin `ArchiveStore` inherits from** — rejected because
inheritance
gives every moved method unrestricted `self` access to the other ~9,000
  lines of read-surface internals, which is exactly the "reach back into
  ArchiveStore internals" this extraction is meant to make structurally
  impossible, not merely discouraged by convention.

The `Protocol` makes the dependency surface an explicit, readable,
narrow
contract instead of "whatever `self` happens to have".

### A real regression found and fixed mid-PR

Four tests monkeypatch an `ArchiveStore` method as a spy/crash-injection
point (`_index_parsed_for_retained_raw`,
`_write_parsed_precedence_result`,
`mark_raw_parse_succeeded`, `record_revision_application_sync`). Under
the
old single-class shape, sibling governance methods called each other via
`self.<method>()`, so patching the class attribute intercepted internal
calls too. After the move, sibling governance *functions* call each
other by
direct module-global reference, bypassing the `ArchiveStore` delegator
entirely — so those four tests silently stopped testing what they
claimed
to. Confirmed as a genuine regression (not pre-existing) by running the
exact failing tests against a detached checkout of the pre-extraction
parent
commit — all passed there. Fixed by patching the `revision_governance`
module attribute (the real internal call target) in the affected tests
instead of the `ArchiveStore` delegator, across
`tests/unit/storage/test_revision_replay.py`,
`tests/unit/sources/test_revision_backfill.py`,
`tests/unit/sources/test_live_batch_support.py`, and
`tests/unit/sources/test_live_cursor_persistence.py`. This is the signal
that behavior (specifically, internal call dispatch) moved, not a change
in
externally observable archive behavior.

## Non-goals / what was deliberately left alone

- `polylogue/pipeline/ids.py`,
`polylogue/archive/session_revision_membership.py`,
  `polylogue/sources/dispatch.py`, the parsers, and
  `polylogue/pipeline/services/ingest_batch/*` — untouched, per scope.
- `write_hook_event` stays in `archive.py` — hook-event ingest is a
different
  concern (evidence linked to a session, never itself a raw revision
  candidate; polylogue-31r1), not moved.
- No import cycle formed; the new module never imports `ArchiveStore`.

## Verification

- `mypy --strict` on every touched module: clean.
- `devtools test` — mission's targeted files plus every file discovered
by
grepping for `monkeypatch.setattr(...)` on any of the 24 governance
names
  called internally by a sibling governance function: **215 passed, 0
  failed** (`tests/unit/storage/test_revision_replay.py`,
  `tests/unit/sources/test_revision_backfill.py`,
  `tests/unit/storage/test_raw_authority_ledger.py`,
  `tests/unit/sources/test_live_batch_support.py`,
  `tests/unit/storage/test_raw_revision_authority.py`,
  `tests/unit/sources/test_live_cursor_persistence.py`,
  `tests/unit/pipeline/test_archive_ingest_commit_batching.py`). Note:
`tests/unit/storage/test_crud.py` named in the task no longer exists in
  this checkout (removed by prior test-infra churn) — confirmed via
  `git log --all -- tests/unit/storage/test_crud.py`, skipped.
- `devtools verify --quick`: green (ruff format/check, mypy --strict,
render
  all, topology, layering, hash-boundary-census, all other gates).
- `archive.py`: 13,338 → 11,324 lines (-15.1%). New module: 2,841 lines.

Not run: `devtools verify --all` (full suite) — out of scope for a
`--quick`
gate per repo convention; CI's post-merge `test` job will run it.
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