Skip to content

fix(archive): stop reading attachment acquisition as revision divergence - #3394

Merged
Sinity merged 3 commits into
masterfrom
feature/fix/attachment-acquisition-is-not-a-branch
Jul 30, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/fix/attachment-acquisition-is-not-a-branch

Conversation

@Sinity

@Sinity Sinity commented Jul 30, 2026

Copy link
Copy Markdown
Owner

Summary

Membership authority was labelling a lazily-fetched attachment's second acquisition as a branch, refusing to order the two revisions, and quarantining the whole cohort as ambiguous. For aistudio-drive that is 151 of 151 cohorts and it cost 14 sessions outright. This splits attachment identity from attachment acquisition state so a dominance test can say what is actually true — same attachments, strictly more of their bytes now known — while still refusing genuine downgrades and contradictions.

Problem

Investigating why aistudio-drive dropped from 239 to 88 sessions across an index rebuild, the residue looked like durable authority debt needing operator judgment. It is not. Verified as a census, not a sample, over all 157 two-member cohorts in the live archive:

157/157  file_mtime_ms IDENTICAL (both carry Drive modifiedTime)
157/157  earlier blob has NO _polylogue_drive_live_bytes_b64
157/157  later blob HAS it
157/157  the two payloads are byte-equal after stripping that key
157/157  later blob is larger

Each pair is one Drive document acquired twice. The second pass never re-downloaded anything — it took the cache-hit branch and ran _inject_live_drive_attachment_bytes, which by design runs on every read to backfill caches written before that feature existed (sources/drive/__init__.py:242-256). Same transcript, same events, same attachment references; only the bytes of those attachments are newly in hand.

Reproduced deterministically with production code on one pair:

bare     604,853 B  msgs=60 events=61 atts=4   inline=None, size_bytes=None
enriched 5,602,664 B msgs=60 events=61 atts=4   same 4 Drive file ids, bytes fetched

message_hashes equal: True
event_hashes   equal: True
attachment sets: n1=4 n2=4 intersection=0 subset=False
_strictly_dominates(bare -> enriched) = False
classify_membership_revisions -> ambiguous

Two causes compose:

  1. _attachment_hash_payload (pipeline/ids.py:152) folds acquisition state into attachment identity — it appends inline_content_hash only once bytes exist, and size_bytes flips None to real at the same moment. One attachment therefore hashes two ways either side of a fetch, and the two revisions end up with equal-cardinality disjoint attachment hash sets. _strictly_dominates sees no growth on any axis and no subset relation, so it refuses.
  2. With every frontier axis equal, _frontier's sort fell through to raw_id, so the dominance test ran in whichever direction the hex happened to order — half the time backwards, against the revision that does dominate.

Neither escape hatch applies: both revisions have browser_snapshot_fidelity=None, and _direct_export_precedence requires a browser-capture sibling.

Solution

SessionRevisionProjection projects attachments on two axes instead of one:

  • attachment_identities — which attachment this is (provider id, anchoring message, name, media type). Stable across acquisition.
  • attachment_contents — an (identity, content) pair, present only for attachments whose bytes are actually read.

_frontier gains the acquisition count, so a bytes-only advance can no longer tie and fall through to raw_id. _strictly_dominates counts newly-read bytes as growth, and _attachment_evidence_preserved refuses two distinct regressions: bytes in hand disappearing (a fidelity downgrade), and one attachment identity carrying different bytes on both sides (a genuine conflict no ordering rule can settle).

Deliberately unchanged: session_hash still covers the full attachment payload, acquisition included. If acquiring bytes did not change a session's content hash, a re-ingest carrying newly-fetched attachments would be skipped as unchanged and the bytes would never land. The equivalence-grouping key likewise keeps acquisition state, or two revisions differing only by fetched bytes would group as identical content and the one holding the bytes could be discarded as a duplicate.

size_bytes is excluded from identity on purpose: for lazily-fetched attachments the provider states no size until the bytes are read. The cost is that two attachments differing only in size under one provider id would share an identity; the contradiction guard catches that case, since differing bytes under one identity is refused rather than ordered.

Verification

Census over the real cohorts this fixes. Replayed the production classifier over all 157 live two-member aistudio-drive cohorts:

157  accepted-chain, enriched last

157/157 now resolve to an accepted chain with the byte-carrying revision at its head. Previously 157/157 were ambiguous, and ordering was decided by hex.

Regression check against cohorts that already worked. Sampled 207 cohorts across 8 origins, ran the old and new predicates over the same parsed sessions, and compared all 810 ordered pairs:

792  agree
 18  DISAGREE new=True old=False acquisition_delta=True

Every disagreement is in the accept direction and every one involves an acquisition delta — i.e. exactly the intended change, nothing else. Zero disagreements in the regression direction (new=False old=True). Honest gap: claude-code-session and codex-session cohorts were not replayable in that harness (their JSONL stream shape needs the real grouped lowering with sidecar joins), so those two origins are uncovered by this particular check.

Anti-vacuity. Each of the three parts of the fix was mutated independently and the suite re-run:

mutation result
drop the acquisition axis from content_grew 2 failed (..._byte_acquisition_as_growth..., ..._byte_loss_as_a_fidelity_downgrade)
drop the acquisition axis from _frontier 2 failed (same two)
stop checking byte agreement in _attachment_evidence_preserved 1 failed (..._contradicted_bytes_even_when_the_revision_otherwise_grew)

The third mutation initially passed, which showed the conflict test was vacuous — the equal-cardinality conflict case is already refused by the growth test, leaving the byte-agreement clause unexercised. test_refuses_contradicted_bytes_even_when_the_revision_otherwise_grew was added for the shape that genuinely needs it (the newer revision adds a second attachment, so the identity axis really does grow, while contradicting the bytes of the attachment both share).

devtools test tests/unit/archive/test_session_revision_membership.py   15 passed
devtools test tests/unit/pipeline/test_pipeline_ids.py                 11 passed
devtools test tests/unit/storage/test_revision_replay.py \
             tests/unit/storage/test_browser_capture_origin_repair.py  49 passed
mypy --strict (ids.py, session_revision_membership.py, archive.py)     Success
pre-push devtools verify --quick                                       exit_code 0

devtools verify with testmon selection is still seeding its baseline on this checkout and will be reported before merge; the affected files above were run directly in the meantime.

Follow-ups (filed, not in this PR)

  • polylogue-9dxn — this fix is inert on the existing archive. A persisted raw_session_memberships.decision='ambiguous' is TERMINAL for the replay planner (storage/repair.py:4432-4462) and the table carries no classifier version, so a corrected classifier cannot re-derive the verdicts it corrects. That also means every future classifier improvement is silently inert on existing data. Compounding it, RAW_AUTHORITY_PARSER_FINGERPRINT exists as a constant but sources/revision_backfill.py hardcodes the literal eight times, so a version bump would only half-apply.
  • polylogue-ck5v — attachment byte backfill only runs inside the Drive acquisition iterator, so the 11 aistudio-drive raws that arrived via a legacy zip import can never be backfilled regardless of convergence. Must land after this PR: backfilling bytes for an already-indexed session creates a new revision, which is only safe now that acquisition is read as an upgrade.
  • Separately observed and not fixed here: 5 live sessions currently report unfetched attachments because both members of their cohort were materialized and the byte-less one won on ordering. That is a materialization-path defect, owned by another lane.

Ref polylogue-bu1i

Sinity and others added 2 commits July 30, 2026 14:03
Problem

All 151 aistudio-drive cohorts that membership authority had recorded as
'ambiguous' were not branches. Each is one Drive document acquired twice,
where the second acquisition merely resolved the attachment bytes the first
had left as bare Drive references. Verified as a census, not a sample: across
all 157 two-member cohorts in the live archive the two payloads are
byte-equal after stripping the injected attachment key, carry an identical
Drive modifiedTime, and hold the same message and event chains.

The classifier could not see that because acquisition state was folded into
attachment identity. _attachment_hash_payload appends inline_content_hash
only once bytes are in hand, and size_bytes flips None -> real at the same
moment, so one attachment hashed two ways either side of a fetch. The two
revisions ended up with equal-cardinality *disjoint* attachment hash sets:
_strictly_dominates saw no growth on any axis and no subset relation, so it
refused to order them and quarantined the cohort. Neither revision was
indexed, and aistudio-drive lost 14 sessions outright.

The frontier tie made it worse. With every axis equal, sort fell through to
raw_id, so the dominance test ran in whichever direction the hex happened to
order -- half the time backwards, against the revision that does dominate.

What changed

SessionRevisionProjection projects attachments on two axes instead of one.
attachment_identities answers which attachment this is and is stable across
acquisition; attachment_contents carries an (identity, content) pair only for
attachments whose bytes are actually read. _frontier gains the acquisition
count so a bytes-only advance can no longer tie. _strictly_dominates counts
newly-read bytes as growth, and refuses both fidelity downgrades (bytes in
hand disappearing) and contradictions (the same attachment identity carrying
different bytes on both sides).

session_hash still covers the full attachment payload, acquisition included,
so acquiring bytes still changes a session's content hash and still triggers
a re-write. Only revision comparison separates the axes.

The equivalence-grouping key keeps acquisition state, otherwise two revisions
differing only by fetched bytes would group as identical content and the one
holding the bytes could be discarded as a duplicate.

Verification

Replayed the production classifier over all 157 real cohorts from the live
archive: 157/157 now resolve to an accepted chain with the enriched revision
at its head. Previously 157/157 were ambiguous.

Ref polylogue-bu1i

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

The golden projection test asserted a single `attachment_hashes` set. It now
pins both axes separately, and the independent-recomputation test derives them
from the attachment payload the same way production does -- so a change to
which fields count as identity fails here rather than silently altering how
revisions are ordered.

The session, message and event digests are deliberately untouched, which is
the evidence that the split did not move the content-hash boundary. The
docstring now says why pinning `session_hash` matters: excluding acquisition
state from the content hash as well would make a newly-fetched attachment look
like an unchanged session and skip its re-ingest.

Ref polylogue-bu1i

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: 27 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: 62121023-d521-459d-820c-89e7d35031f7

📥 Commits

Reviewing files that changed from the base of the PR and between 5e23e6a and 5df9a9b.

📒 Files selected for processing (6)
  • .beads/issues.jsonl
  • polylogue/archive/session_revision_membership.py
  • polylogue/pipeline/ids.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/archive/test_session_revision_membership.py
  • tests/unit/pipeline/test_pipeline_ids.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: 41b5b5bf03

ℹ️ 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".

…indings

polylogue-9dxn records that a persisted ambiguous verdict is terminal with no
classifier version, so the classifier correction in this branch cannot
re-derive the verdicts it corrects -- and no future classifier improvement can
either. polylogue-ck5v records that attachment byte backfill runs only inside
the Drive acquisition iterator, so payloads that arrived by any other route are
never backfilled.

Ref polylogue-bu1i

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity merged commit e86e1e2 into master Jul 30, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/attachment-acquisition-is-not-a-branch branch July 30, 2026 12:34
Sinity added a commit that referenced this pull request Jul 30, 2026
…elation (#3401)

## Summary

Membership classification
(`polylogue/archive/session_revision_membership.py` +
`polylogue/pipeline/ids.py`) treated provider-volatile export artifacts
as content identity: message array order, provider-reported generation
duration, attachment id presence, and attachment acquisition state (the
last already fixed by bu1i, #3394). Live-archive census (read-only, no
mutation) over the full `claude-ai-export`/`chatgpt-export`
ambiguous-cohort populations shows this quarantined 587 and 135 cohorts
respectively as "ambiguous" branches when they were almost entirely the
same conversation re-exported.

This PR replaces the growing set of special-cased fixes with one
invariant (polylogue-aggz): **a conversation is a SET of items
(messages, attachments, events) keyed by content-derived identity, each
carrying only content-bearing fields.** Two revisions are `equal`, one
`contains` the other, or they `conflict` — total and decidable, no
residual category.

## Problem

- **c429**: Claude.ai's own export array order is not stable across
export vintages. A strict positional-prefix dominance test refused both
directions for a bare reorder of byte-identical messages.
- **nuec**: ChatGPT's `generation_lifecycle` event re-derives
`elapsed_duration_ms` from the raw export's own timing metadata on every
export request; the value is not stable across requests for the SAME
generation.
- **d8al**: Claude.ai does not consistently emit a real attachment id
across export vintages of the same conversation — one vintage carries a
real UUID, the other has none. No id-minting scheme can make a real id
and a synthetic hash collide.
- All three (plus bu1i's already-merged attachment-acquisition-state
fix) are symptoms of one thing: the comparison value contained things
that are not properties of the conversation.

## Solution

- `SessionRevisionProjection` (`ids.py`) now projects
`message_contents`/`attachment_contents`/`event_contents` as
`frozenset`s of `(identity, content)` pairs — never ordered tuples,
never the array index.
- Attachment identity drops the provider id unconditionally
(`message_id, name, mime_type` only) instead of using it when present
and falling back when absent. The strict/loose duality and its pairwise
correlation machinery (`_correlate_attachments`,
`_attachments_equivalent`, `AttachmentRecord`) are **deleted**, not
bypassed.
- Event content is built from an explicit per-event-type **allowlist**
(`_EVENT_CONTENT_PAYLOAD_ALLOWLIST`), not a denylist of fields
discovered volatile after shipping: a new field a parser adds later is
excluded from comparison by construction. Only `generation_lifecycle`
has a registered allowlist (`state`, `evidence_source`, `fidelity`);
every other event type still compares its full payload.
- `classify_membership_revisions` collapses what used to be four layered
mechanisms (positional-prefix message test, denylist-stripped ordered
event-hash prefix test, strict/loose attachment correlation,
session-hash/metadata-timestamp tiebreak) into one `_relation` function
applied uniformly to all three axes, plus a simple
representative-collapse + adjacent-pair containment check.
- `session_hash` (idempotency) is **unchanged**: it still covers the
full, order-sensitive, unstripped payload, so a real reorder, duration
change, or id change still triggers a re-write. Only the *comparison*
layer is content-only.

**Kept, not deleted**: `_provider_ordered_browser_snapshots`.
Browser-captured DOM/native snapshots synthesize their own local
message/attachment ids from DOM structure, not stable provider identity,
so the content-only relation genuinely cannot correlate a DOM-to-native
fidelity upgrade — deleting it risked silently breaking real
browser-capture archival behavior this lane has no fixture coverage to
verify independently.

**Designed, tested, not wired**: `_maximal_evidence_fallback` — a
deterministic (frontier + raw_id tiebreak, proven order-independent)
presence-guarantee pick for a genuine, irreducible conflict, so a
document is never simply absent from the archive. Wiring it into
`classify_membership_revisions`'s return path trips a real, documented
`archive.py` write-back invariant ("never retire an unrelated accepted
head", with production incident history — polylogue-miwv, #3397/#3398)
whenever the fallback pick differs from an already-established head.
Proven by two failing integration tests during verification
(`test_divergent_bundle_member_preserves_last_accepted_session` and its
sibling) — not a theoretical concern. Landing it safely needs either the
classifier/caller to carry existing-head context, or the write-back
guard to accept a re-affirmed-quarantined outcome; both belong to
`archive.py`'s write path, out of this lane's scope. A genuine conflict
still quarantines exactly as before (`accepted_raw_ids == ()`,
everything in `ambiguous_raw_ids`).

## Verification

**Unit tests**: `devtools test
tests/unit/archive/test_session_revision_membership.py
tests/unit/pipeline/test_pipeline_ids.py
tests/unit/sources/test_revision_backfill.py
tests/unit/storage/test_revision_replay.py
tests/unit/storage/test_browser_capture_origin_repair.py` — `129
passed`.

**`devtools verify --quick`** — `exit_code 0` (format, lint, mypy
--strict, render-all-check, layering, hash-boundary-census,
schema-versioning, all clean).

**Anti-vacuity**: mutated the core content-conflict clause in
`_axis_relation` (dropped the "content disagrees under a shared
identity" check) — 8 tests failed, confirming it is exercised and
load-bearing.

**Live-archive census** (read-only against `/realm/db/polylogue`, no
mutation; full population, not a sample — replaying `parse_payload` →
`session_revision_projection` → `classify_membership_revisions` for
every ambiguous cohort, comparing this branch against `origin/master`):

| origin | cohorts | old resolved | new resolved | regressed |
|---|---|---|---|---|
| `claude-ai-export` | 587 | 0 (0%) | **554 (94.4%)** | **0** |
| `chatgpt-export` | 135 | 1 (0.7%) | **119 (88.1%)** | **0** |

Zero regressions against cohorts that already resolved under the old
logic, for both origins. The residual 33 + 16 = 49 cohorts are not
resolved by this PR (the presence-guarantee fallback that would resolve
genuine conflicts deterministically is designed/tested but not wired,
per above) — consistent with the small number of real forks (message
content genuinely edited, not just reordered) found during manual
inspection of sampled residue.

## Acceptance-criteria honesty (polylogue-aggz)

- ✅ Comparison value built from an explicit content-only allowlist
(events) / content-derived-only identity (attachments/messages) — a
volatile field added to a parser later is excluded by construction,
tested directly
(`test_non_allowlisted_event_type_keeps_its_full_payload_as_content`
proves the allowlist boundary; every new-field-volatility test in this
PR is the "add a volatile field, comparison unaffected" shape the bead
asked for).
- ✅ `superseded_prefix`/`superseded_equivalent` vocabulary distinction:
confirmed (via research, not touched — `archive.py` is outside this
lane's scope) that both already map to the identical
`ApplicationDecision.SUPERSEDED` / `revision_authority = "byte_proven"`
downstream; the only place they differ is a free-text audit `detail`
string. No `archive.py` change was needed to satisfy this.
- ✅ At least two special-case paths deleted:
`_merge_attachment_id_presence_variants`, `_correlate_attachments`,
`_attachments_equivalent`, `_attachment_evidence_preserved`,
`_attachment_axis_grew`, `AttachmentRecord`/`attachment_records`, the
`by_content`/`by_session_hash`/`metadata_variants`/timestamp-tiebreak
layering, `_message_evidence_preserved`, `_strictly_dominates` — net
**-255 lines** across the two production files.
- ⏸️ Deferred, explicitly not silently dropped: the presence-guarantee
fallback (needs `archive.py` write-path coordination) and
`_provider_ordered_browser_snapshots` deletion (needs browser-capture
parser id-stability verification this lane could not do safely in
scope).
- Invariant 2 (single write chokepoint) and Invariant 3 (versioned
derived state) from polylogue-aggz are explicitly out of this lane's
scope (owned by the `ingest_batch`/`archive.py`-owning lanes per this
task's file boundaries) and not addressed here.

## Review follow-up: four defects fixed (chatgpt-codex-connector)

Automated review found the content-only relation did not yet fully hold
the
invariant it claims, in four concrete ways. All four are fixed on this
branch:

- **P1 — source authority lost when collapsing equal revisions**
  (`session_revision_membership.py`). When a direct export and a browser
capture projected to equal content, the equal-content collapse picked
its
  representative by provider timestamp (then raw_id) BEFORE any
source-authority ordering ran, so a browser capture could outrank its
own
  authoritative export. New `_equal_content_representative` decides by
  authority first (direct export over browser capture, native over DOM),
  mirroring the ordering `_direct_export_precedence`/
`_browser_snapshot_dominates` already apply to the non-equal
growth-chain
  case, falling back to timestamp/raw_id only when neither side's
  provenance outranks the other's.
- **P2 — event identity unstable under a sibling appearing** (`ids.py`,
the
most serious of the four: it reintroduced exactly the
identity-instability
  bug class this PR exists to eliminate). An event's canonical identity
  shifted from `base_identity` to `hash(base_identity, content)` purely
  because a SECOND event later shared its base identity, in the SAME
  revision — so an ordinary event-growth revision could compare as a
  disjoint conflict instead of containment. Now always
`hash(base_identity, content)`, unconditionally: an item's identity must
  not depend on what else is in the set.
- **P2 — colliding attachment identities silently dropped content**
(`session_revision_membership.py`). Two acquired attachments sharing one
  identity (same message/name/mime, different bytes) fed a plain
  `dict(contents)`, so the second content hash silently overwrote the
first — a real conflict could compare as equal, worse than either honest
outcome. New `_content_by_identity` groups every content hash under its
  identity into a set, so a collision now always degrades to `conflict`.
- **P2 — duration stripping keyed on `event_type` alone** (`ids.py`).
The
  `generation_lifecycle` allowlist strip applied to every event of that
  type, including browser-capture's own DOM/UI observations
(`duration_semantics` values like `dom_observed_wall`), which are a real
  first-party measurement, not the ChatGPT-parser-remeasured value nuec
targeted. Now gated on `duration_semantics ==
"provider_reported_elapsed"`
(wiring up the previously-dead `_PROVIDER_REPORTED_ELAPSED_MARKER_KEY`/
  `_VALUE` constants).

Both `_provider_ordered_browser_snapshots` (kept, not deleted) and
`_maximal_evidence_fallback` (designed/tested, not wired — `archive.py`
write-back invariant, out of scope) are unchanged per explicit
instruction.

**Tests**: one regression test per finding in
`tests/unit/archive/test_session_revision_membership.py`, each verified
by
manually mutating the corresponding production line back to the buggy
behavior and observing the exact expected failure (see commit
`test(archive): cover the four aggz identity-invariant defects with
mutation-proof tests` for the anti-vacuity detail per finding).

**Re-run live census** (read-only, same methodology, apples-to-apples
A/B on
the identical ambiguous-cohort population — this branch's fixed
`classify_membership_revisions` vs. the pre-fix `39591e17d`/`78d884b8c`
state, same input rows for both runs):

| origin | population | pre-fix resolved | fixed resolved | regressed |
|---|---|---|---|---|
| `claude-ai-export` | 587 | 554 (94.4%) | **554 (94.4%)** | **0** |
| `chatgpt-export` | 136 | 119 (87.5%) | **120 (88.2%)** | **0** |

(Population here is 136/587 for chatgpt-export/claude-ai-export —
measured
directly from `raw_session_memberships` without the earlier
equal-message-count
pre-filter, vs. this PR's original 135/587; the claude-ai-export count
is
unaffected either way.)

The counts barely move — none of the four fixes change *whether* a
cohort
resolves for the vast majority of cases, only the P1 fix changes *which*
raw
is materialized as the accepted head for already-resolving equal-content
cohorts (verified directly: the one real flip below is a P1 case, not
P2).
Zero regressions in either origin, confirmed by diffing the exact
unresolved-cohort key sets between the two runs, not just the aggregate
counts.

One concrete flip, traced to root cause: `chatgpt:69d5383e-…` (4368
messages, 4 raw revisions — 1 direct export + 3 native browser captures,
all
pairwise-`equal` or `conflict` identically under old and new code).
Pre-fix,
the equal-content collapse of the export + 2 of the 3 natives picked the
LATER-timestamped native as representative (losing the export's
`browser_snapshot_fidelity=None` marker), so `_direct_export_precedence`
then found zero non-browser candidates among the representatives and the
cohort stayed quarantined. Post-fix, the export always survives that
collapse, `_direct_export_precedence` fires as designed, and the cohort
resolves. This is exactly the shape P1 describes, confirmed against a
real
archive row, not just the unit-test fixtures.

**Residual population** (33 claude-ai-export + 16 chatgpt-export
cohorts,
unchanged in count from the original measurement modulo the one flip
above)
is the same population the unwired `_maximal_evidence_fallback` exists
to
serve: genuine, irreducible conflicts (real forks — content edited, not
just reordered/re-measured/re-captured) where no containment chain
exists
at all. **This PR does not resolve them and does not claim to** — wiring
the fallback needs `archive.py` write-path coordination
(`_maximal_evidence_fallback`'s docstring states the concrete blocking
invariant), which is explicitly out of this lane's scope; the residual
count will not reach zero without that follow-up landing.

Ref polylogue-aggz
Ref polylogue-bu1i
Ref polylogue-c429
Ref polylogue-nuec
Ref polylogue-d8al
Ref polylogue-hith

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

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.
@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.

  • 75.F061 / P2: fixed-already at the checked revision: Membership comparison includes attachment contents as a growth axis at polylogue/archive/session_revision_membership.py:490. After a valid cohort is selected, application removes the prior cohort-owned head at polylogue/storage/sqlite/archive_tiers/revision_governance.py:4141-4144 before issuing the new semantic receipt, so an attachment-only advance no longer submits an equal-frontier cross-raw receipt against that old head.

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