Repository navigation
fix(storage): complete the raw-admission chokepoint with typed grouped and reconstruction arms - #4015
Conversation
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 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 |
|
Blocked on successor beads before this can go non-draft.
All three dispositions are honestly
No existing open bead covers any of them — |
|
Update — second census pass + gate substitution. Your intel was right that the invariant did not hold, and re-running the census at current HEAD sharpened it. Two corrections to the sites you listed:
The census also found two classes neither of us had listed: On Net: every anonymous Gate: Still draft, still blocked on the three successor beads from the earlier comment. |
…-804 matrix correction Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…ped arm Ref polylogue-1fijp Two defects, both proven red before the fix: - The BASELINE arm is the only arm that does not forward the caller's explicit raw_id to write_source_raw_session, so a route with its own identity scheme (hermes_profile_raw_id, or the grouped-capture deterministic key) addresses one raw row and gets another. - Grouped capture has no typed arm at all; admit_raw_and_parsed_result bypasses the chokepoint with a bare write_source_raw_session whenever shared_raw=True.
Ref polylogue-1fijp The BASELINE arm now forwards the caller's explicit raw_id like every other arm does, so hermes_profile_raw_id and the grouped-capture deterministic key address the row they actually write. admit_raw_and_parsed_result's shared_raw=True branch no longer issues its own write_source_raw_session call. It resolves a new SHARED_GROUPED arm instead. The persisted row is byte-for-byte what the bypass produced (native_id NULL, no revision envelope, source.db's revision_kind default): a grouped payload's identity is its acquisition coordinate and which sessions it speaks for lives in raw_session_memberships, so there is no single subject a revision chain could be about. That absence is now a decision the chokepoint makes and names.
…mption Ref polylogue-1fijp repair.py's browser-origin copy-forward built its raw_sessions row with a hand-assembled INSERT, which read like the last unmigrated call site. It is not one. A copy-forward reconstructs a row from evidence its repair plan already adjudicated, under a corrected identity, for a source that no longer exists -- every input admit_raw_observation needs to resolve an arm is absent, and routing it through the chokepoint would resolve BASELINE/asserted and discard the BYTE_PROVEN authority the plan proved. Replace the raw INSERT with insert_reconstructed_raw_row(), whose ReconstructedRawRow makes every envelope column a required field, so the no-nullable-limbo invariant holds by construction on this path too. The exemption is now a named constructor with its reasoning attached rather than an anonymous INSERT a future sweep would try to 'finish'. Existing coverage lives in tests/unit/storage/test_browser_capture_origin_repair.py (confirmed: an assert injected into the new constructor fires 24 times there). Add direct regressions pinning the BYTE_PROVEN authority a migration to the chokepoint would erase, plus the schema/digest refusals.
…y ledger Ref polylogue-2tfug, Ref polylogue-1fijp Drives the real head-establishing replay path, then reparses the SAME accepted raw into different content through the ordinary session-write path. sessions.content_hash moves; raw_revision_heads.accepted_content_hash does not. validate_raw_replay_application_receipt rejects exactly that mismatch, so a formal replay audit would report a legitimate parser correction as ledger inconsistency.
…es it Ref polylogue-2tfug, Ref polylogue-1fijp An ordinary write that reparses the raw which is ALREADY the accepted head into different content moved sessions.content_hash and left raw_revision_heads.accepted_content_hash behind. validate_raw_replay_application_receipt requires the two to agree, so a formal replay audit would report a legitimate parser correction as ledger inconsistency. Both ordinary write call sites now detect that exact shape -- same raw, same session, changed hash -- and reissue a receipt that moves the head. The detection runs BEFORE write_parsed_session_to_archive so both land in its transaction; running it afterwards leaves the head update uncommitted and silently lost, which is how the first attempt at this failed. The decision gets its own ApplicationDecision token, REPARSE_REAFFIRMATION, rather than borrowing SELECTED_BASELINE's 'this raw won a contest' meaning -- no contest happened. That widens raw_revision_applications.decision's generated CHECK, declared as index v68 / CONSTRAINT_ONLY (purely permissive, no stored row changes meaning, no parser semantics involved), so it fast-forwards rather than forcing a rebuild. The condition stays narrow on purpose: only when no competing raw claims the key is there nothing to adjudicate. Any other precedence question still belongs to the replay path.
…module Ref polylogue-1fijp insert_reconstructed_raw_row issues an INSERT, and raw_admission.py's own contract is that it composes source_write's writers rather than re-implementing raw-row persistence -- devtools verify layering caught the contradiction as writer_module_unmarked_mutation. Move the constructor to source_write.py, this tier's declared writer module, and leave a pointer to it in raw_admission's docstring so the exemption stays discoverable from the chokepoint that names it.
Ref polylogue-1fijp Second census pass over the whole tree, after the grouped-capture migration, found three remaining classes rather than the one the bead's note predicted. Delete write_raw_blob_and_parsed/_result and their two ArchiveStore facade methods. They are the blob-ref twin of write_raw_and_parsed_result -- the bare FULL/revision=None limbo write that admit_raw_and_parsed_result was built to replace -- and they have zero callers in polylogue/ or tests/. Keeping a dead public entrypoint that bypasses the chokepoint would leave the invariant merely bounded rather than true. Name durable_change_train's three probe INSERTs as _seed_probe_raw_row(). These are NOT the copy-forward class: every caller is a _probe_* function writing to a tempfile.TemporaryDirectory archive deleted on return, and each deliberately seeds an unusual shape (detected_provider disagreeing with origin, a parse_error row, a bare row) to prove a migrated reader still handles it. Routing them through admission or the reconstruction constructor would normalize away the exact condition under test, so the helper keeps the shapes and only names the class. Document write_raw_payload/write_raw_blob_ref's post_parse=False branch as a surveyed fixture-seeding path: no live acquisition route reaches it (append_ingest and batch both pass post_parse=True), and the note tells a future reader to treat a new production caller as a bypass, not precedent.
Ref polylogue-1fijp verify layering declares each writer module's entrypoint inventory, so removing write_raw_blob_and_parsed/_result without updating the manifest fails as writer_module_entrypoint_inventory_mismatch.
99c4c61 to
bcfa7a2
Compare
…on-vs-repair eligibility) Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC
… batch Ref polylogue-1fijp hermes_profile_raw_id is keyed per SNAPSHOT (profile dir + source_index + blob_hash) and deliberately excludes the session id, so one state.db yields N ParsedSessions sharing one acquisition raw id with N different native ids. parse_sources_archive admits each of them as its own BASELINE observation against that shared id. The second collides: the row already exists, so _assert_existing_raw_observation_identity refuses it as a substitution hazard, and write_pair catches only ContentExcisedError, so the whole import batch aborts and rolls back. Fails here with the exact production error -- 'raw id is already bound to different acquisition evidence' -- leaving 1 raw row and 0 indexed sessions where 3 sessions were parsed. No existing coverage could catch this: the raw-admission unit tests exercise admit_raw_observation in isolation, where a single admission never collides, and every existing Hermes fixture is single-session.
Ref polylogue-1fijp A Hermes state.db is a grouped capture and is now treated as one. Its acquisition identity, hermes_profile_raw_id, is keyed per SNAPSHOT (profile dir + source_index + blob_hash) and deliberately excludes the session id, so one snapshot legitimately carries N sessions under one raw id -- which is precisely what SHARED_GROUPED describes: one raw row keyed by the acquisition coordinate, native_id NULL, and session identity carried by raw_session_memberships. archive_ingest only computed shared_key when raw_id was still None, so a payload that already had a snapshot-scoped identity was pushed down the non-grouped path and admitted per session as BASELINE. The second session then collided with the first's row and the batch aborted. Two changes: shared_key is computed whenever a blob hash exists, and the generic native_id-free id is derived only when the route did not already supply one, so Hermes keeps hermes_profile_raw_id instead of having it overwritten. Chose this over dropping hermes_profile_raw_id from the BASELINE arm. That alternative restores master's behaviour, but master's behaviour is that the arm ignored the explicit id and derived a per-session one, so a single snapshot minted N raw rows for one set of bytes -- the same duplicate-raw pattern polylogue-sjf6 removed for Claude Code, and it left hermes_profile_raw_id computed and then discarded on this route. Routing the snapshot through the arm that matches its actual shape both fixes the abort and makes that identity mean what its docstring says. Scope: parse_sources_archive only (import/reprocess/demo). The live daemon Hermes route admits through POST_PARSE_PENDING and never reached this branch. Correction to this PR's earlier claim: the stated harm of the old BASELINE behaviour -- memberships recorded against a phantom raw id -- was wrong for this route. replace_raw_membership_census only runs under shared_key, which Hermes never had. The real harm was the duplicate raw rows described above.
…te path (#4022) ## Summary Topology edges now resolve a disagreement between acquired Codex hook evidence and transcript inference instead of letting both claims coexist unmarked. Hook evidence wins, the overruled inference is retained under a new typed exclusion status rather than deleted, an inference-only re-parse can no longer overwrite or erase the authoritative result, and an archive-verification check censuses the outcome. Absent hook evidence, every edge is byte-identical to today. ## Problem `polylogue-foee` acquired Codex `thread_spawn_edges` into the durable `source.db` hook spool as `codex_thread_spawn_edge` events (3,055 title + 1,030 spawn-edge rows live). Nothing consumed them for topology. The only artifact was `context/codex_spawn_edge_correlation.reconcile_codex_spawn_edges` — a read-only counter reachable solely through the API facade. That counter cannot express the problem it appears to address. It computes set differences over `(parent, child)` pairs, so a genuine contradiction — hook evidence and inference naming **different** parents for the **same** child — surfaces as one entry in `inferred_only` and one in `authoritative_only`, losing the fact that the two claims compete. `authoritative-hook-evidence`, the method token `polylogue-4ts.10`'s design doc anticipated, had zero occurrences anywhere in the tree. Three structural facts made this worse than a missing feature: 1. **Contradictions coexisted silently.** `session_links`' primary key is `(src_session_id, dst_origin, dst_native_id, link_type)`, so two contradictory parents are two rows, not an overwrite. Both resolved, and `_refresh_session_projection` then picked one by `observed_at_ms` ordering — an arbitrary, arrival-order-dependent parent with no recorded decision. 2. **A re-parse silently downgraded evidence.** `_write_session_link` used a bare `INSERT OR REPLACE`, which rewrites every column of a matching key, resetting `method` and `status`. 3. **A full replace destroyed it outright.** The session purge ran `DELETE FROM session_links WHERE src_session_id = ?` unconditionally, so an ordinary re-parse deleted an authoritative edge and — with no source handle to re-derive it — silently reinstated the inferred parent. This is the most destructive form of the hole and the one a write guard alone would **not** have caught; it surfaced only when a red twin failed. ## Design **Where authority is applied: the write path, because of tier durability.** I evaluated a post-ingest reconciliation pass — where `reconcile_codex_spawn_edges` already lives, holding both connections — and rejected it. `session_links` is in the **rebuildable** index tier while hook evidence is in the **durable** source tier, so every reindex reconstructs these rows from scratch. Only a derivation running inside `write_parsed_session_to_archive` — the choke point shared by live incremental ingest and full raw replay — survives a rebuild by construction. A convergence-stage applier would silently lose the marking on the next reindex, which is disqualifying for a reindex-readiness campaign. `source_conn` is threaded in as an optional parameter, mirroring `revision_authority_refuses_write(conn, source_conn, ...)` (`ingest_precedence.py:145`) including its `None` case for index-only harnesses. `ArchiveStore` supplies it via a new `_optional_source_conn()` that degrades to `None` rather than failing a session write. **What "conflict" precisely is.** Scoped to `(src_session_id, link_type)`, **not** to the primary key — because the PK carries `dst_native_id`, keying conflict to it would define the contradiction out of existence. Given child C and link type T: the hook claim is the `parent_thread_id` whose `codex_thread_spawn_edge` payload names C as child; the parser claim is `session.parent_session_provider_id`. Agreement upgrades the single edge to `authoritative-hook-evidence`. Disagreement is a conflict. Hook silence is **not** a conflict — absent evidence is silence, which is why the no-evidence path is provably unchanged. Note the child-side lookup cannot use `list_hook_events(session_native_id=...)`: `codex_state_evidence.py` keys these events by `session_native_id = parent_thread_id`, so the query matches the payload's own `child_thread_id`. **What the durable conflict state looks like.** `TopologyEdgeStatus` gains a member, `AUTHORITY_CONTRADICTED` (`"authority-contradicted"`). The losing edge is retained with that status and `method = 'contradicted-by-hook-evidence'`, its `evidence_json` carrying both parents; the winner is written with `method = 'authoritative-hook-evidence'`. A distinct member rather than reusing `QUARANTINED` is the point, not an accident. Both statuses exclude an edge from composition, but they are different defects and must stay tellable apart forever: a quarantine is a structural cycle-break (the graph SHAPE is wrong), while an authority contradiction is a provenance verdict (the shape is fine; this particular claim was overruled). An operator triaging a live archive needs that distinction, and `method` is an unconstrained `TEXT` column that cannot carry it safely — exactly the hand-written-vocabulary drift this repo warns against. Both members are documented beside each other in `TopologyEdgeStatus`. **The obstacle a new member normally creates, removed rather than accepted.** Eleven exclusion sites across seven modules each hardcoded `'quarantined'`. Adding an exclusion class to that arrangement means finding and updating every one, and any miss silently readmits an excluded edge into lineage. The predicate is now generated: `COMPOSITION_EXCLUDED_TOPOLOGY_STATUSES` is the single definition, rendered by `topology_status_composes_sql()` / `topology_status_excluded_sql()` for SQL and `status_excludes_composition()` for the Python-side filter that has no query to attach to. **Amended claim.** An earlier revision of this body said eight sites and that a future exclusion class is "picked up by every consumer for free". Both were wrong, and I found the first one myself before review by re-running my own sweep with the scope I should have used originally — my search covered `polylogue/storage/**` and missed `devtools/` and `polylogue/operations/`. Cold review then found two more I had still missed. The corrected set is eleven, and the "for free" claim only holds for consumers that read the shared definition — which is now all of them, but was not when the sentence was written. The three sites added in this revision: - `storage/insights/topology/derivation.py:80` — a Python-side `status == "quarantined"` filter. Because a contradicted edge is unresolved *by construction*, **100%** of them were readmitted here. - `insights/transforms.py:77,1791` — `SubagentChildLinkStatus`' four-value allowlist mapped every contradicted edge to `None` ("no link status") rather than to a reason. - `operations/daemon_workload_probe.py:1925-1942` — the `CASE` buckets by raw status, so contradicted edges already had their own bucket; it was simply never read out, so census counts stopped summing to the table. `REPAIRED` is deliberately absent from the excluded set: a repaired edge was *fixed*, so it composes. `4ts.10` anticipated `authoritative-hook-evidence` as a method token only; that is implemented, plus the contradiction token and status member it did not anticipate, because a method alone can neither exclude an edge from composition nor be constrained. **Schema.** The `CHECK` on `session_links.status` is generated from the enum (`nullable_check("status", TopologyEdgeStatus)`), so the new member is a DDL change: `INDEX_SCHEMA_VERSION` 67 → **69** with an `IndexDeltaDeclaration` of **`SEMANTIC_REPARSE`**. Widening the CHECK is inert for existing rows, but the new state is only *produced* by re-deriving edges against the durable hook spool during raw replay — an existing generation cannot fast-forward into it, and its lineage projections would keep composing through parents the hook evidence overrules. `CONSTRAINT_ONLY` would have been the cheap and dishonest call. > **Version-number coordination — resolved.** #4015 merged (squash `ca466345`) taking 68; this PR is rebased onto that master and takes **69**. `lab policy schema-versioning` now reports "Schema evolution policy intact." and the three lifecycle tests that previously failed on the gap are green. **What does NOT change:** lineage composition semantics, prefix-dedup, `branch_point_message_id`/`inheritance` (including the deliberate non-FK), cycle quarantine, and every edge in an archive with no hook evidence. **Surfacing.** A new `hook-authority-topology-conflict` registry check censuses contradictions. Contradictions themselves are reported as observability, not errors — recording them is the mechanism working. The single error condition is a contradicted edge with **no authoritative sibling for the same child**, which would mean inference was demoted by nothing. ## Verification Lane `/realm/worktrees/hook-authority-conflict`, guard-verified; `devtools test` reported `polylogue package → /realm/worktrees/hook-authority-conflict/polylogue/__init__.py`. ``` devtools test tests/unit/storage/test_topology_hook_authority_conflict.py \ tests/unit/maintenance/test_archive_verification.py -> 134 passed in 32.74s devtools test <7 topology/lineage/delegation/correlation suites> \ tests/unit/storage/test_archive_tiers_write.py \ tests/unit/pipeline/test_ingest_batch.py -> 265 passed in 30.63s (pre-existing behaviour unchanged across the generated exclusion predicate) devtools lab policy schema-versioning -> "Schema evolution policy intact." (0 undeclared index schema deltas) devtools verify --quick -> exit 0, zero "out of sync" ``` ### Red twins Each guard was mutated and shown to fail the test that claims it. | Mutation | Result | | --- | --- | | Drop the contradiction branch (hook stops winning) | 3 failed | | Restore `INSERT OR REPLACE` (authority downgradable in place) | 1 failed — `test_reparse_cannot_downgrade_authoritative_evidence` | | Remove the purge exemption (full replace wipes authority) | 1 failed — same test | | Mark edges unconditionally (no-evidence path diverges) | 3 failed — both byte-identical cases | | Two authoritative parents for one child | 1 failed — `test_two_authoritative_parents_for_one_child_trips_the_check` | **Retracted row, and what replaced it.** An earlier revision of this table claimed that dropping `AUTHORITY_CONTRADICTED` from `COMPOSITION_EXCLUDED_TOPOLOGY_STATUSES` produced "1 failed, 6 errors". Cold review could not reproduce it; I re-ran the identical mutation and got **7 passed**, after dumping the generated predicate to confirm the mutation genuinely reached it (`NOT IN ('quarantined')`). The original figure was almost certainly captured mid-edit, before the enum member existed — `1 + 6` equals the file's test count, which is the signature of a collection failure, not a detection. The row is withdrawn. The reviewer's mechanical explanation is correct and is now documented in the code: `_resolve_outbound_session_links`' pre-existing `status IS NULL` gate is the **operative** mechanism. A contradicted edge never acquires `resolved_dst_session_id`, so composition cannot traverse it regardless of the exclusion set; membership in that set is **defense-in-depth** for an edge that resolved *before* acquiring a status (the cycle-quarantine path does exactly that). No test can distinguish its presence from absence today, so no twin should claim otherwise. The genuine pin is `test_contradicted_edge_is_excluded_from_composition`, which asserts the invariant at the layer that enforces it: the contradicted edge stays unresolved and the child's composed parent is the hook's parent. The registry check carries its own red twins, `test_contradiction_without_authoritative_winner_trips_the_check` and the multi-authoritative one above, plus a positive control asserting a properly resolved contradiction reports OK. The third mutation is the one worth noting: it was not a planned twin. `test_reparse_cannot_downgrade_authoritative_evidence` failed on first run with `KeyError`, because the authoritative row was gone rather than downgraded — which is how the unconditional purge was found. The fix mirrors the exemption three lines above it in the same function, where `capture_gap` events are already spared as "archive-generated ingest evidence, not projections owned by whichever parser payload currently wins source precedence." Hook evidence is the same category. ## Gate substitution Per coordinator policy, the plain full `devtools verify` was not run. Checked rather than assumed: this lane's testmon environment digest is `polylogue-a8fac865...` and the graph `lane-init` seeded from the main checkout carries five environments, none matching — a plain verify would have been a `bootstrap (absent)` full run. Notably this is the **same digest** a previous lane computed, so the mismatch is systematic across lanes rather than per-lane. The focused runs above cover every changed module, and `--quick` gates format, lint, strict mypy, layering, schema-versioning, and all generated surfaces. ## Bead disposition This PR closes no bead and mutates no bead record; the carrier below is the typed `self_contained` scope. | Bead | Disposition | Residual | | --- | --- | --- | | `polylogue-hook-authority-conflict-proof` | **partial — mechanism built** | The AC's resolution + anti-overwrite semantics now exist and are tested through the production write path. The bead is an **acceptance** bead: it wants the effect proven against a frozen source or candidate generation with an immutable receipt. No live or candidate run is claimed here. | | `polylogue-foee` (closed) | **AC2 consumer built** | Its topology consumer now exists and prefers authoritative edges. Its "report how many previously-inferred edges are now backed by authoritative evidence" reporting is served by the new registry check's `contradicted_count`/`authoritative_count` evidence. The title-ladder wiring (AC1) and live UUID-title census (AC3) are untouched. | Ref polylogue-hook-authority-conflict-proof, polylogue-foee, polylogue-4ts.10 ## Not in scope - **No live/candidate census run** — the acceptance bead's own requirement, and it needs the reindex window. - **Codex-only.** The mechanism keys on `codex_thread_spawn_edge`; no other origin currently acquires authoritative topology evidence. The guard generalizes, but claiming provider-neutrality would overstate what is wired. - `reconcile_codex_spawn_edges` is untouched by deliberate scope guard; its disposition is later bookkeeping. It remains a useful read-only correlation counter, and its inability to detect same-child contradictions is documented above rather than fixed, since the write path now records that state directly. - No title-ladder work (`polylogue-foee` AC1). <!-- polylogue-pr-scope:v2 { "assigned_beads": [], "dispositions": [], "mutated_beads": [], "scope_digest": "79a7984a9ec80a157c96dc8d28561159c642c15de3793837eff751fa7eac34a1", "scope_kind": "self_contained", "version": 2 } -->
…ype (#4028) ## Summary Two `test_durable_change_train.py` tests have been failing on master in whole-module runs since long before tonight, characterized in `polylogue-s5iyt` as an order-dependent flake. The cause is a process-wide tier-prototype cache in `bootstrap.initialize_archive_tier` whose key does not include the DDL, so a test that monkeypatches `ARCHIVE_DDL_BY_TIER` mints a prototype from its synthetic schema and every later test at that version silently receives it. Dropping the poisoned key around the two modules that patch bootstrap's DDL fixes it. Test-only. ## Problem Reproduction, deterministic, 3 node ids, ~1 second: ``` devtools test tests/unit/storage/test_durable_change_train.py \ ::test_maintenance_route_persists_and_proves_a_future_train \ ::test_bootstrap_reconciles_and_persists_interrupted_train_evidence \ ::test_bootstrap_finishes_persisted_applied_train_without_reapplying -p no:randomly -> 2 failed, 1 passed ``` Drop the first test and the other two pass. Both victims fail with `DurableChangeTrainError: actual post-apply bytes do not have admitted fresh-DDL parity`. **Mechanism.** `initialize_archive_tier` caches one materialized prototype database per `(tier, version)` and page-copies it into every later empty connection — that reuse keeps ~0.8s of DDL parsing off thousands of tests. The cache key deliberately excludes the DDL, because in production `ARCHIVE_DDL_BY_TIER` is a constant: one DDL per tier and version, always. A test that monkeypatches the DDL breaks that premise. `test_maintenance_route_persists_and_proves_a_future_train` patches SOURCE to a synthetic `base_items + future_items` schema at version 2 and, being first, records *that* as the prototype for `(source, 2)`. The bootstrap victims patch SOURCE to `base_items + durable_items` at the same version, then build a fresh database — and get the first test's schema by page copy. `monkeypatch` restores the dict; it cannot restore a prototype minted from it. Their admitted fresh-DDL parity proof (built from a synthetic in-memory target) then disagrees with the recovered image, which is exactly what the parity check exists to refuse. Instrumenting the comparison showed only one field diverging (`fresh_vs_admitted=False`, computed `b98a8df2…` vs admitted `5b173b1b…`) through an identical call path in both orders — same code, different bytes, which is the signature of cached state rather than a branch difference. ## Solution A `clear_tier_prototypes` fixture in `tests/conftest.py`, requested via `pytestmark = pytest.mark.usefixtures(...)` by the two modules that patch **bootstrap's own** `ARCHIVE_DDL_BY_TIER` — `test_durable_change_train.py` and `test_archive_maintenance_cli.py`. It drops the SOURCE prototype on both sides of each test, so such a module neither inherits nor exports a poisoned prototype. Two scoping decisions, both forced by measurement rather than taste: - **SOURCE only, not the whole cache.** Clearing every tier is not a free "safer" choice: it makes `test_audit_adoption_receipt_recovers_interrupted_publication_during_bootstrap` fail *on its own*, because a page-copy restore and a fresh `executescript` do not produce byte-identical databases and that test compares an audit image against a canonical recoverable one. Every assignment in the DDL-patching modules targets `ArchiveTier.SOURCE`, so dropping only the poisoned key is both sufficient and non-disruptive. - **`test_workload_artifacts.py` deliberately excluded**, though it also appears in a `setattr.*ARCHIVE_DDL_BY_TIER` grep. Its single patch targets `tests.infra.workload_artifacts.ARCHIVE_DDL_BY_TIER` — a test-infra reference, not bootstrap's — so it never mints a prototype from a synthetic DDL and cannot poison the cache. Adding the marker there was strictly harmful: it broke `test_seeded_archive_corruption_is_refused_by_a_fresh_process`, which relies on the cache. The production cache is untouched. In production its premise holds, and the perf win is the reason it exists. ## Verification ``` # 3-node reproduction, red -> green devtools test <3 node ids> -p no:randomly -> 3 passed in 0.98s (was 2 failed, 1 passed) # whole module, deterministic order devtools test tests/unit/storage/test_durable_change_train.py -p no:randomly -> 103 passed in 11.41s (was 2 failed, 101 passed) # whole module, randomized devtools test tests/unit/storage/test_durable_change_train.py -> 103 passed in 9.51s devtools verify --quick -> exit 0, zero "out of sync" ``` **No failure traded.** Across all three DDL-adjacent modules together, deterministic order: | | result | | --- | --- | | master | **5 failed**, 258 passed | | this branch | **3 failed**, 260 passed | The two durable-change-train failures are fixed; the three remaining (`test_rebuild_index_source_replay_expands_every_execution_selection_to_authority_cohorts[all|only-missing|explicit]`) are **pre-existing on master**, confirmed by running the identical selection on a stashed tree. They are untouched by this change and out of scope here. ## Bisect: what this is not `polylogue-s5iyt` was raised tonight as possibly a new master red introduced by #4015's v68 `CONSTRAINT_ONLY` delta. It is not. Whole-module runs at `7b671755b` (pre-#4015), `70a3ca2ad` (#4015 itself), `f93a8b87c`, and current master HEAD all produce the identical 2 failures. The v68 CHECK widening is not implicated, and the failure long predates it. Two disproved hypotheses, recorded so nobody re-runs them: - **Not the split DDL reference.** The victims patch only `bootstrap` while the polluter patches both `bootstrap` and `migration_runner`. Adding the missing `migration_runner` patch to the victims does **not** fix it. - **Not `sys.modules` leakage.** The polluter's fixed-name `fixture_migrations_maintenance` package does leak into `sys.modules` and survive teardown (verified), and the module's own helper builds unique per-`tmp_path` names — a real inconsistency. But purging those entries between tests does **not** fix it either. Ref polylogue-s5iyt ## Not in scope - The three pre-existing `test_archive_maintenance_cli.py` cohort failures. - The fixed-vs-unique fixture package-name inconsistency in `test_durable_change_train.py` — real, but not the cause, and changing it would be unmotivated churn in this PR. - Making the prototype cache key DDL-aware. That would fix the class in production rather than per test module, but it changes a hot production path for a test-only symptom; worth its own discussion, not this PR. <!-- polylogue-pr-scope:v2 { "assigned_beads": [], "dispositions": [], "mutated_beads": [], "scope_digest": "79a7984a9ec80a157c96dc8d28561159c642c15de3793837eff751fa7eac34a1", "scope_kind": "self_contained", "version": 2 } -->
Summary
Completes the raw-admission chokepoint (
polylogue-1fijp, aggz Invariant 2) by resolving the last three architecturally-distinct creators ofraw_sessionsrows: grouped capture is migrated through the chokepoint under a new typed arm, the copy-forward repair is wrapped as an explicitly-reasoned named exemption, and the live-acquisition paths were re-surveyed and found already routed. Along the way it fixes a real identity bug in the BASELINE arm and closespolylogue-2tfug's replay-ledger gap, both red-first.Problem
The bead's own survey named three remaining creators. Re-verifying each against current source changed the picture:
sources/live/append_ingest.py/batch.py— the note recorded these as incompatible with the chokepoint. They are not, any more: every call already passespost_parse=Trueand resolves thePOST_PARSE_PENDINGarm. No work needed; the note was stale.archive_ingest.pymain path — already routed throughadmit_raw_and_parsed_result, except on itsshared_raw=Truebranch, which issued a barewrite_source_raw_session. That branch is the grouped-JSONL path (a resume-fork chain, a Drive bundle), i.e. the high-traffic case the note was pointing at.storage/repair.pycopy-forward — a hand-assembledINSERT INTO raw_sessions. It reads like the last unmigrated call site, and a future sweep would try to "finish" it.A second census pass over the whole tree, run after the grouped migration landed, found the bead's list was incomplete. Three further classes existed:
write_raw_blob_and_parsed/_result(+ twoArchiveStorefacade methods) — the blob-ref twin ofwrite_raw_and_parsed_result, i.e. the same bareFULL/revision=Nonelimbo write, with zero callers inpolylogue/ortests/.durable_change_train.py×3 — anonymousINSERT INTO raw_sessionsstatements.write_raw_payload/write_raw_blob_ref'spost_parse=Falsebranch — a wrapper arm that writes a bare row without consulting the chokepoint.Two defects surfaced while verifying, both proven red before any fix:
BASELINEarm is the only arm that never forwarded the caller's explicitraw_idtowrite_source_raw_session. A route with its own identity scheme —hermes_profile_raw_id, or the grouped deterministic key — addressed one raw row and silently got another. Correction (cold review): this PR previously described the harm as memberships recorded against a phantom id. That is wrong for this route —replace_raw_membership_censusonly runs undershared_key, which Hermes never had. The real harm is that one Hermes snapshot minted N raw rows for one set of bytes (the duplicate-raw patternpolylogue-sjf6removed for Claude Code) whilehermes_profile_raw_idwas computed and then discarded.polylogue-2tfug: reparsing the raw that is already the accepted head movedsessions.content_hashand leftraw_revision_heads.accepted_content_hashbehind.validate_raw_replay_application_receiptrequires the two to agree, so a formal replay audit would report a legitimate parser correction as ledger inconsistency.Solution
Grouped capture →
RawAdmissionArm.SHARED_GROUPED.admit_raw_and_parsed_result'sshared_rawbranch now resolves a named arm instead of writing its own row. The persisted row is byte-for-byte what the bypass produced (native_idNULL, no revision envelope, source.db'srevision_kinddefault) — a grouped payload's identity is its acquisition coordinate, and which sessions it speaks for lives inraw_session_memberships, so a revision chain has no single subject to be about. This moves the decision, deliberately not the bytes; changing the stored envelope would be a semantic change to source.db and is out of scope for an acquire-side bead.Copy-forward →
insert_reconstructed_raw_row()(source_write.py). This is an architectural exemption, not a deferred migration.admit_raw_observationdecides what a fresh observation means from bytes plus the prior head; a copy-forward has neither — the source is gone and the verdict was already adjudicated by a proven repair plan. Routing it through the chokepoint would resolveBASELINE/assertedagainst the absent prior head and discard theBYTE_PROVENauthority the plan established.ReconstructedRawRowmakes every envelope column a required field, so the no-nullable-limbo invariant holds on this path by construction; what does not apply is the resolution step. It lives insource_write.pyrather than beside the chokepoint becauseraw_admission.py's contract is that it composes writers and issues no SQL of its own —devtools verify layeringcaught the first placement aswriter_module_unmarked_mutation.Dead blob-and-parsed pair → deleted.
write_raw_blob_and_parsed/_resultand their facade methods are removed. Their payload twin is already superseded byadmit_raw_and_parsed_result, and nothing anywhere calls the blob variants. Keeping a dead public entrypoint that bypasses the chokepoint would leave the invariant merely bounded rather than true.durable_change_train×3 →_seed_probe_raw_row(). These are not the copy-forward class, and the evidence is unambiguous: every caller is a_probe_*function writing into atempfile.TemporaryDirectoryarchive deleted before it returns, and each deliberately seeds an unusual row — adetected_providerthat disagrees withorigin, a row carrying aparse_error, a bare row with no envelope — precisely to prove a migrated reader still handles that shape. Routing them throughadmit_raw_observationorinsert_reconstructed_raw_rowwould normalize the row into a well-formed envelope and destroy the condition under test. The named helper therefore keeps the shapes and only names the class, so a census can classify it at a glance.post_parse=Falsebranch → surveyed, documented, not migrated. No live acquisition route reaches it: every production acquisition caller (append_ingest.py,batch.py) passespost_parse=Trueand resolvesPOST_PARSE_PENDING. What remains is fixture seeding —durable_change_train's self-probes andtests/infracorpus builders, which need row shapes admission would normalize away. The docstring now says so and tells a future reader to treat a new production caller as a bypass, not precedent.Resulting census. Every anonymous
INSERT INTO raw_sessionsin the tree is gone. The only three left aresource_write.py's two writer primitives (this tier's declared writer module, which the chokepoint composes) and the one inside the named_seed_probe_raw_rowhelper.Multi-session Hermes snapshots → the grouped arm (cold-review BLOCK, fixed). Honoring the explicit
raw_idinBASELINEexposed a real regression inparse_sources_archive:hermes_profile_raw_idis keyed per snapshot and excludes the session id, so onestate.dbcarries N sessions under one acquisition id.archive_ingestcomputedshared_keyonly whenraw_idwas stillNone, so those payloads took the non-grouped path and were admitted per session asBASELINE; the second session collided with the first's row (raw id is already bound to different acquisition evidence), andwrite_paircatches onlyContentExcisedError, so the whole batch aborted — 3 parsed sessions became 1 raw row and 0 indexed sessions.The fix routes them through
SHARED_GROUPED, which is what a Hermes snapshot actually is:shared_keyis now computed whenever a blob hash exists, and the generic native_id-free id is derived only when the route did not already supply one, so Hermes keeps its snapshot-scoped identity instead of having it overwritten.Chosen over the alternative of dropping
hermes_profile_raw_idfrom theBASELINEarm. That would restore master's behaviour — but master's behaviour is the bug in slower motion: the arm ignored the explicit id and derived a per-session one, minting N raw rows for one set of bytes and leavinghermes_profile_raw_iddead on this route. Routing the snapshot through the arm matching its real shape fixes the abort and makes that identity mean what its docstring says. Scope isparse_sources_archiveonly (import/reprocess/demo); the live daemon Hermes route admits throughPOST_PARSE_PENDINGand never reached this branch.polylogue-2tfugreceipt reissue. Both ordinary write call sites now detect the narrow shape — same raw, same session, changed hash — and reissue a receipt that moves the head. Detection runs beforewrite_parsed_session_to_archiveso both land in its transaction; placing it after leaves the head update uncommitted and silently lost, which is how the first attempt failed. The decision gets its ownApplicationDecision.REPARSE_REAFFIRMATIONrather than borrowingSELECTED_BASELINE's "this raw won a contest" meaning — no contest happened. That widens the generated CHECK onraw_revision_applications.decision, declared as index v68 /CONSTRAINT_ONLY(purely permissive; no stored row changes meaning, no parser semantics), so it fast-forwards rather than forcing a rebuild.Verification
Every command ran in this lane's own worktree with its own venv (checkout guard confirms
polylogue → /realm/worktrees/1fijp-admission-chokepoint).devtools verify --quick— all ten steps ok, includingverify layering ... okandlab policy schema-versioning ... ok(undeclared index schema deltas found: 0, accepting the v68 declaration).devtools test tests/unit/pipeline+ all four Hermes suites + raw-admission — 613 passed.devtools testover repair, browser-capture-origin-repair, revision-application/replay, accepted-head-reparse and archive-tiers — 216 passed.devtools testover the chokepoint, durable-change-train, repair, revision-application/replay, archive-tiers and shared-raw suites, fixed order — 346 passed, 2 failed (the pre-existing pair below).tests/unit/storage— 3 failed, 2680 passed;tests/unit/pipeline tests/unit/maintenance— 3 failed, 1337 passed.Every failure is pre-existing, established by controlled baseline rather than assertion. Reverting
polylogue/andtests/to master in this same worktree and rerunning the same files under fixed order (-p no:randomly) reproduces each set identically. For the two durable-change-train failures this was re-baselined after the probe rewrite specifically to confirm I had not taken ownership of them: master gives2 failed, 100 passed, 1 xfailedon that file, and so does this branch, with the same two node ids. The six aretest_durable_change_train.py::test_bootstrap_reconciles_and_persists_interrupted_train_evidence,::test_bootstrap_finishes_persisted_applied_train_without_reapplying,test_rebuild_paging_content_order.py::test_rebuild_content_order_paging_dedups_first_time_classification_via_content_cache,test_message_owner_scope_backfill.py::test_stale_plan_wrong_backup_and_active_daemon_are_fail_closed,::test_prepared_recovery_rejects_a_nonidentity_assertion_change_after_commit,test_rebuild_parse_apply_split.py::test_rebuild_index_from_source_sync_auto_engages_pipelined_decode.Full
devtools verifydeliberately skipped, under the lane gate policy for bootstrap-predicted runs. This lane's plain verify reportedselection: bootstrap (absent)for environment digestpolylogue-e962f60d05f5…; the attempted run was killed by its own 596s cap partway through a ~2700s bootstrap. That digest now has a row in.cache/testmon/testmondata, but only the partial one that interrupted run left behind, so a fresh full verify is at best incomplete and at worst a second full bootstrap. Per policy, focuseddevtools testplusdevtools verify --quickare this PR's gate and the merge receipt is recorded centrally at head rather than by this lane.Anti-vacuity: the Hermes regression test fails on the pre-fix head with the exact production error and passes after; reverting only the
shared_keyguard reproduces it. The two earlier red commits fail against the pre-fix code with the exact assertions named. The copy-forward path's existing coverage was confirmed by injecting anAssertionErrorinto the new constructor — it fires 24 times intests/unit/storage/test_browser_capture_origin_repair.pyand zero times intest_repair.py, which is why the direct regressions were added. The dead-code deletion is confirmed reachable-by-nobody by grep acrosspolylogue/andtests/, andverify layeringindependently caught the stale entrypoint manifest.Bead disposition matrix
polylogue-1fijpINSERT INTO raw_sessionsremains. The three left aresource_write.py's two writer primitives (composed by the chokepoint), and the one inside the named_seed_probe_raw_rowtemp-archive helper; the copy-forward is the namedinsert_reconstructed_raw_rowexemption; the dead blob-and-parsed bypass pair is deleted. AC(c)/(d) satisfied structurally by arms 4/5 (unchanged).revision_kinddefaultunknown) — the arm names the decision but does not eliminate the limbo. AC(e) (zero new quarantined rows over 72h of live daemon operation) is unattempted and needs live time, not code.polylogue-2tfugtests/unit/storage/test_accepted_head_reparse_receipt.py::test_reparse_of_accepted_head_keeps_head_and_session_content_hash_in_sync(red→green, real write path). AC4 by::test_unchanged_reparse_of_accepted_head_issues_no_new_receipt.devtools/raw_authority_restart_proof.pyhas no coverage for this case.polylogue-omswarchive_ingest.py,append_ingest.py,batch.py). Verified live:tool-results/toolu_*.json→parse_as_session=False, cohort=tool_result_sidecar;subagents/workflows/*/journal.jsonl→cohort=workflow_journal.classify_artifact_pathreturnsNoneforstate_5.sqlite/goals_1.sqlitebecause that class is decided by content (magic bytes), not path — and that refusal already landed under the now-closedpolylogue-hbtj2, with its own--apply-gated reclassify actuator. Reclassifying existing contaminated rows (AC3) remains untouched and is durable-tier work needing operator consent.Every residual outcome above carries an open successor with a durable
relates-toedge:polylogue-1fijp→polylogue-ogrri(grouped-raw NULL revision envelope + AC(e) 72h live observation),polylogue-2tfug→polylogue-n6rkz(raw_authority_restart_proof.pycoverage),polylogue-omsw→polylogue-mcnzt(contaminated-row reclassification; durable-tier, consent-gated).Ref polylogue-1fijp, Ref polylogue-2tfug, Ref polylogue-omsw