Repository navigation
feat(storage): raw-identity evidence packets and duplicate-raw repair - #2877
Conversation
Problem polylogue-lkrc.3: after the byte-proven browser-capture rekey actuator (polylogue-lkrc.2, PR #2850) repairs the safe cohort, four current ChatGPT sessions remain with an unknown-export accepted head that cannot be safely rekeyed -- two diverge from a semantic canonical head at different content hashes, one has a superseded_equivalent membership row blocking the null-membership precondition, and one has production reparse hash drift against an incompatible canonical byte head. The existing actuator already fails closed for all four (proven by test_byte_proven_browser_rekey_fails_closed_for_observed_conflicts), but only surfaces a terse ineligibility reason string -- no structured evidence survives the rejection for an operator to adjudicate, and nothing records that the conflict exists once the inspection call returns. Solution Add inspect_browser_canonical_authority_conflicts(config, raw_ids): read-only, re-runs the byte-proven-rekey actuator's exact eligibility proof per raw id, and for every ineligible raw builds an enriched evidence packet (competing head content hash/frontier kind/decision, blocking membership row, and -- when both sides are single-session byte-frontier raws -- the first diverging message index) instead of the terse reason string. A raw the actuator can already repair is reported resolved, not returned as a conflict. Add record_browser_canonical_authority_conflict_blockers(config, raw_ids): the separate, explicit step the design requires -- it never picks an authority itself. Each conflict becomes one durable AssertionKind.BLOCKER candidate assertion in user.db (durable, irreplaceable tier), keyed by a deterministic id over the raw id and its evidence digest so re-running after new evidence creates a new row instead of overwriting, and unchanged re-runs are idempotent. Mirrors upsert_pathology_findings_as_assertions (#2383): written through upsert_assertion's author_kind="detector" chokepoint, so it is always forced to status=candidate with inject:false -- it can never self-promote to an authoritative, context-injectable claim. Neither function mutates raw/blob/head/application/membership state or authorizes a repair for the four conflicts; resolving them under an explicit operator policy remains separately scoped follow-up work. Verification devtools test tests/unit/storage/test_browser_capture_origin_repair.py -k "conflict or record_conflict" -> 11 passed (6 new + the 5 pre-existing conflict-matrix cases the new evidence builder reads underneath) devtools verify --quick -> exit_code 0 (15/15 steps, including verify degrade-loudly after adding a logger.warning to the new best-effort message-diff except-handler) mypy polylogue/storage/repair.py tests/unit/storage/test_browser_capture_origin_repair.py -> no issues Anti-vacuity: test_inspect_conflicts_semantic_hash_divergence_evidence mutates raw_revision_heads.accepted_content_hash to a distinct value and asserts the returned competing_content_hash reflects exactly that mutation; reverting the fix (dropping the direct raw_revision_heads query and returning only the terse reason) makes the assertion on item.competing_content_hash fail with AttributeError/None. Not run: live archive census/promotion of any real blocker (explicitly deferred to the operator per the cluster's live-archive-safety constraint). Ref polylogue-lkrc.3 Ref polylogue-lkrc Ref polylogue-lkrc.2 Co-Authored-By: Claude <[email protected]>
Problem polylogue-t0dy: PR #2729 aligned the one-shot importer and the live daemon watcher on one deterministic raw-id scheme (no native_id) so new ingests of a grouped/split-session Claude Code/Codex resume-fork file converge on one raw row instead of duplicating. It explicitly did not retroactively repair raw pairs that already duplicated under the OLD, native_id-inclusive scheme before that fix landed: the accepted head/session pointer stays bound to the stale raw, and its post-fix, correctly-keyed twin sits orphaned, so every later daemon catch-up pass over that file hits "RuntimeError: membership replay cannot retire an unrelated accepted head" (archive.py:2255) indefinitely. Two live production files are known-affected; the design explicitly called for a typed actuator using the existing revision-application machinery rather than a hand-written raw UPDATE. Solution Add repair_duplicate_raw_identity(config, pairs, apply=, receipt_path=, proof_digest=): the same dry-run/apply/CAS/receipt shape as every other actuator in this file. For each (stale_raw_id, canonical_raw_id) pair, _inspect_duplicate_raw_identity proves: both raws are byte-identical (origin/source_path/source_index/blob_hash/blob_size, plus an actual BlobStore read verifying the retained bytes match the declared digest/size); each raw id equals the deterministic id its own recorded fields (and native_id shape) predict via deterministic_raw_session_id -- native_id-inclusive for stale, native_id=NULL for canonical; the stale raw is the CURRENT accepted head and session pointer; and the canonical raw is a genuinely dangling duplicate, not itself referenced by any head or session. _apply_duplicate_raw_identity_repair reuses record_revision_application_sync (not a hand-written raw_revision_heads UPDATE, per the design note) twice: a SELECTED_BASELINE receipt for the canonical raw performs the head CAS -- session_id/content_hash/frontier_kind/frontier are unchanged from the current head since the two raws are byte-identical, so this is exactly the existing "equivalent-content" acceptance path, only accepted_raw_id repoints -- then a SUPERSEDED receipt on the stale raw records the loss of authority for audit. The stale raw's own row is never mutated or deleted. Verification devtools test tests/unit/storage/test_duplicate_raw_identity_repair.py -> 10 passed (dry-run proof, apply + exact before/after row diff, idempotent reapply, 4-way ineligible-shape matrix, duplicate/ malformed-id rejection, stale-digest rejection, missing-receipt-path rejection) devtools verify --quick -> exit_code 0 (15/15 steps) mypy polylogue/storage/repair.py tests/unit/storage/test_duplicate_raw_identity_repair.py -> no issues Anti-vacuity: test_apply_repoints_head_and_session_preserving_stale_raw asserts raw_revision_heads.accepted_raw_id and sessions.raw_id both equal canonical_raw_id after apply, that the stale raw's own raw_sessions row is byte-for-byte unchanged, and that the stale raw gained a 'superseded' application receipt naming canonical_raw_id; reverting _apply_duplicate_raw_identity_repair to a no-op makes the head/session assertions fail with the pre-repair (stale) raw id. test_fails_closed_for_ineligible_shapes mutates four different witness fields (competing accepted head, wrong accepted raw, content divergence, matching native_id schemes) and asserts apply raises before any write. Not run: live archive census/repair of the two known-affected production files (explicitly reserved for the operator, not this implementation lane -- the cluster's live-archive-safety constraint). Ref polylogue-t0dy Co-Authored-By: Claude <[email protected]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 45 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (5)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
Problem: adversarial review of PR #2877 found two majors and a minor (polylogue-hleq). (1) repair_duplicate_raw_identity's apply-mode receipt was a single unlocked receipt_path.write_text() call issued after the index transaction committed, gated only by a TOCTOU-racy `receipt_path.exists()` check -- two concurrent --apply invocations could both pass the check before either wrote. (2) the byte-frontier competing-head branch in _browser_canonical_authority_conflict_witness re-read the competing raw mid-function on an independent point-in-time read, without re-proving it against the same snapshot the base eligibility proof used. (3, minor) record_browser_canonical_authority_ conflict_blockers mutates user.db (durable, irreplaceable) with no apply flag/proof-digest gate/receipt, unlike every other actuator in this file's established pattern. What changed: - repair_duplicate_raw_identity now locks one receipt inode via the same flock(LOCK_EX|LOCK_NB) + O_NOFOLLOW + fsync(file, then parent) contract as the existing quarantined-raw-repair receipt (_lock_quarantined_raw_repair_receipt), with the same planned/applied two-phase JSONL shape, torn-terminal crash recovery, and CAS revalidation against the durably-written planned record. A second concurrent --apply against the same receipt path now fails closed with "already locked" instead of racing into the transaction. - inspect_browser_canonical_authority_conflicts now wraps the base eligibility proof and the witness's own re-reads of raw_revision_heads/raw_session_memberships/raw_revision_applications in one BEGIN DEFERRED/COMMIT read transaction per raw id, so both see one consistent snapshot instead of two independent point-in-time reads. Read-only (nothing to roll back); COMMIT just releases the read lock. - record_browser_canonical_authority_conflict_blockers: investigated and judged genuinely exempt from the apply/proof-digest/receipt ceremony -- it writes exactly one candidate/non-injected assertion through upsert_assertion's single write chokepoint (mirrors upsert_pathology_findings_as_assertions), which already refuses to resurrect a judged-terminal row back to candidate. Documented that reasoning in the function's docstring and hardened it further: added an explicit read_assertion_envelope/existing.status guard so a re-run over unchanged evidence never touches a row an operator has already judged (accepted/rejected/deferred/superseded), matching the same terminal-judgment protection this file's other candidate writers already have. - NIT (not blocking, addressed for completeness): wired all three functions into `polylogue ops maintenance` as browser-canonical-authority-conflicts (read-only by default, --record persists blockers) and duplicate-raw-identity (dry-run/--apply with the same --proof-digest/--receipt contract as the sibling quarantined-accepted-raws/browser-capture-origin- mismatches commands), mirroring the existing actuator CLI pattern. Tests: 3 new receipt-locking/crash-recovery/symlink tests in test_duplicate_raw_identity_repair.py; 1 new byte-frontier message- divergence-evidence test and 1 new judged-row-protection test in test_browser_capture_origin_repair.py; 4 new CLI adapter tests in test_archive_maintenance_cli.py (read-only default, --record plumbing, dry-run bounds, malformed --pair, missing receipt/proof). Verification: devtools test tests/unit/storage/test_duplicate_raw_identity_repair.py \ tests/unit/storage/test_browser_capture_origin_repair.py -> 15 pre-existing failures (test_browser_capture_origin_copy_forward_ mutations_fail_closed[*], already documented in PR #2877 and reproduced identically on a clean checkout), 127 passed (was 126 before this PR's fix -- the new judged-row-protection test). devtools test tests/unit/cli/test_archive_maintenance_cli.py -k \ "browser_canonical_authority_conflicts or duplicate_raw_identity_cli" -> 3 passed devtools test tests/unit/cli/test_archive_maintenance_cli.py (full file) -> 5 pre-existing failures (backup/migrate-tier, embedding-orphan- reconcile x2, assertion-export x2), reproduced identically with this PR's changes stashed out -- confirmed unrelated flakiness, not caused by this diff. mypy polylogue/storage/repair.py polylogue/cli/commands/maintenance.py \ tests/unit/storage/test_browser_capture_origin_repair.py \ tests/unit/storage/test_duplicate_raw_identity_repair.py \ tests/unit/cli/test_archive_maintenance_cli.py -> Success: no issues found in 5 source files devtools verify --quick -> exit_code 0, all 15 steps green Ref polylogue-hleq Ref polylogue-t0dy Ref polylogue-lkrc.3 Co-Authored-By: Claude <[email protected]>
## Summary Closes three small pieces of independent-reviewer-flagged residual debt from Wave 1's merged clusters (excision #2875, raw-identity #2877, sinex evidence mode #2873). Done directly, without a separate implementer/reviewer Workflow round, per operator instruction. ## Problem Each item is a real gap an independent adversarial reviewer found in an already-merged PR: - **polylogue-re4a**: the excision-bypass regression test routed through the pre-existing small-payload gate, never touching the new streaming blob-ref gate it claimed to prove. - **polylogue-iwth**: (1) the operator-judgment-guard test asserted only fields that are deterministically identical whether or not the guard fires, so it would pass even with the guard removed; (2) `repair_duplicate_raw_identity`'s apply path skipped `RebuildLease`, unlike its sibling actuators. - **polylogue-ihwv**: sinex_mode's own fix was independently re-verified correct (existing targeted tests green); two residual nits: `material_adapter.py` silently dropped unrecognized blocks without declaring a fidelity gap, and `ObligationStatus.PUBLISHING` was declared but never written. ## Solution - `tests/unit/sources/test_live_batch_support.py`: patch `_STREAMING_FULL_INGEST_BYTES` down to 1 (existing pattern in this file) so the excised/normal fixtures route through the blob-ref write path. Verified as a genuine anti-vacuity check with an in-memory `mock.patch` on `is_blob_hash_excised` (not a file edit to the production gate — the auto-mode classifier correctly blocked that as a security-weakening action). - `tests/unit/storage/test_browser_capture_origin_repair.py` + `polylogue/storage/repair.py`: added an `updated_at_ms`-unchanged assertion — the one field `upsert_assertion`'s `ON CONFLICT` always moves regardless of the guard, so it's the only observable proof the guard short-circuited before writing. Verified as a genuine negative control with an in-memory mock (side_effect returning `None` only for the guard's own read, real behavior otherwise) — bypassing the guard moves `updated_at_ms` as predicted. Wrapped `repair_duplicate_raw_identity`'s apply block in `RebuildLease(archive_root)`. - `polylogue/sinex/material_adapter.py` + test: `session_material_from_session` now emits a `FidelityGapInput(gap_kind="dropped_block")` per dropped block. Extended the existing fixture's assertions (it already had a `"not-a-real-block-type"` block commented "must be dropped, not raise"). - `polylogue/sinex/obligations.py` + `service.py` + test: added `mark_publishing()`, a pre-attempt transition distinct from `mark_attempt` (no attempt_count/receipt outcome yet). `PublicationService._attempt` now durably marks the obligation `PUBLISHING` immediately before the transport call, in its own short transaction, so a crash mid-attempt is now observably distinguishable from a never-tried `pending` row — consistent with `pending()`/`lag()` already including `PUBLISHING` in their filters. ## Verification - `devtools test tests/unit/sources/test_live_batch_support.py -k test_full_ingest_skips_durably_excised_content_without_aborting_batch` — 1 passed - `devtools test tests/unit/storage/test_browser_capture_origin_repair.py -k test_record_conflict_blockers_never_clobbers_an_operator_judged_row` — 1 passed - `devtools test tests/unit/storage/test_duplicate_raw_identity_repair.py` — 13 passed - `devtools test tests/unit/sinex/` — 25 passed - `devtools verify --quick` — exit 0, all 16 steps green Ref polylogue-re4a. Ref polylogue-iwth. Ref polylogue-ihwv.
Problem: rebasing feature/refactor/sqlite-leak-sweep-and-staleness-unify onto origin/master (which gained #2875/#2876/#2877 since this branch was cut) produced conflicts in the generated topology-target.yaml and topology-status.md artifacts. Both sides had regenerated these independently from source, so a manual merge would desync them from the actual module graph. What changed: resolved the conflicts with a placeholder (--ours), then ran `devtools render topology-projection && devtools render topology-status` to regenerate both files from the post-rebase source tree, matching this repo's documented policy for generated-surface conflicts. Verification: `devtools render all --check` reports no "out of sync" lines (all surfaces sync OK).
…enter decomposition (#2900) ## Summary Implements the Architecture cluster (polylogue-1r9c + a7xr features/bugs): a source-grounded hotspot map for Polylogue's largest execution control centers with a first coherent extraction slice landed against it, plus six real bugs/features from the a7xr substrate-consolidation set. ## Problem Production Python grew from ~255k to ~281k lines while the largest execution hubs (storage tier, API facade, daemon HTTP, write tier, storage repair) kept expanding faster than the codebase average, with no committed map of their call boundaries, ownership seams, or a prioritized decomposition sequence. Alongside that, a cluster of real substrate bugs and abstraction-audit findings (sqlite connection leaks, a converger/repair staleness disagreement, dead abstractions with zero production consumers, a hard-coded write-effects choke point) had accumulated as separately tracked beads. ## Solution **polylogue-1r9c** (`docs/architecture-hotspots.md`, new): maps all eight named control centers with file:line evidence, call-boundary/ownership-seam analysis, and a prioritized extraction sequence with explicit non-goals. Lands one coherent slice: `session_annotations_write.py` extracts the self-contained session tag/work-event/phase CRUD contract out of `storage/sqlite/archive_tiers/write.py` (4,595 → 4,210 lines, −8.4%), with `write.py` re-exporting the same public names unchanged (no duplicate execution path). Files seven durable child beads for the remaining seven control centers (`polylogue-redt`, `-u5dw`, `-1vzf`, `-gikp`, `-kchb`, `-avmq`, `-w9di`), each with an explicit non-goal. The layering-policy fix this required also corrected a pre-existing, now-exposed imprecision in `archive_tiers/archive.py`'s `raw-revision-authority` twin-write contract (a coarse tier-attribution artifact, not a behavior change). **polylogue-0aj** (write-effects registry, slice 1 of 2): `archive/write_effects.py`'s hard-coded FTS-repair/cache-invalidation branches become a declared `WriteEffect` registry (name, phase, should_run, failure_policy) that the choke point walks generically — behavior-identical for the three existing effects, with the phase/failure-policy declarations now explicit for future consumers (embedding scheduling, SSE announce) to register against. **polylogue-yp0** (daemon event bus, partial — honestly not fully closed): lands the typed in-process pub/sub core (`daemon/event_bus.py`, 5 event types, full failure-isolation test coverage) but not a live producer/consumer wiring — that's sequenced as follow-up (`polylogue-14t7`) per the bead's own design note, since touching a live daemon polling loop needs its own focused pass against the lock/starvation invariants `polylogue-9e5.7` mapped. **polylogue-c9y** (package-topology doctrine): `docs/architecture.md`'s placement rules become an 8-question decision procedure with worked examples, plus the insights-vs-analytics vocabulary rule recorded ahead of `analytics/` landing. `core/` absorbs the former top-level `errors.py`/ `protocols.py`/`types.py` (165 import sites updated, zero behavior change). **Prior-session work on this branch** (a7xr.1/.2/.10/.13/.14/.17, all committed before this PR turn but included here): sqlite connection-leak sweep across ~9 sites, unified `session_profile_stale_predicate` between converger and repair, killed the zero-consumer FTS5/Hybrid search-provider lane, deleted the api/contracts shadow-adapter layer, collapsed the one-operation operations-contract framework to concrete Import models, and added an import-resolution drift gate for operation/artifact catalog `code_refs`. **Discovered, filed, not fixed in this PR** (out of scope for this cluster, flagged rather than silently absorbed): `polylogue-0puw` (a stale `blob_publication_reservations` row survives an ingest batch that should drain it — confirmed pre-existing, reproduces with `write_effects.py` reverted), `polylogue-g99u` (`'codex' is not a valid Origin` ValueError in two facade contract tests — confirmed unrelated to the write-tier extraction, the extracted code never touches origin/provider resolution), and `polylogue-ihp0` (`test_fresh_user_tier_has_no_legacy_overlay_tables` asserts a stale exact table-set literal that migrations 007/008 — both merged well before this branch's own base commit — already invalidated; confirmed pre-existing via `git merge-base --is-ancestor`, unrelated to the `session_annotations_write.py` extraction which the dedicated write-tier suite proves behavior-identical, 63/63). **Rebase onto current `origin/master`** (post-review): this branch was 3 commits behind `origin/master` (missing #2875/#2876/#2877) when first opened, with GitHub reporting `mergeable: CONFLICTING`. Rebased cleanly; resolved a trivial resolve-both import-block conflict in `polylogue/api/archive.py` (this branch's `protocols.py`→`core/protocols.py` move landed on the same import line master's Hermes-delivery-correlation import touched) and regenerated the two generated-artifact conflicts (`docs/plans/topology-target.yaml`, `docs/topology-status.md`) via `devtools render topology-projection && devtools render topology-status` rather than merging them by hand. Also closed a self-consistency gap in `polylogue-a7xr.10`'s own acceptance criteria: its FTS5/Hybrid provider kill decision requires `polylogue-mhx.3` to record that it now owns lane construction now that the shared `SearchProvider` abstraction is gone — that note was missing and has been appended. ## Verification - `devtools verify --quick` green end to end (ruff format/check, `mypy --strict`, `render all --check` with zero "out of sync"/"unindexed" findings, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/ test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly all pass) — run repeatedly across the session, last clean at HEAD. - `devtools test tests/unit/archive/test_write_effects.py tests/unit/archive/test_write_gateway.py` — 12 passed (new registry tests + full existing gateway suite). - `devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_archive_tiers_self_verify.py` — 64 passed (full behavioral parity for the write-tier extraction). - `devtools test tests/unit/storage/test_revision_replay.py` — 16 passed (covers `apply_raw_membership_classification`, the entrypoint whose layering contract was corrected). - `devtools test tests/unit/daemon/test_event_bus.py` — 10 passed (event bus pub/sub core, failure isolation, immutability). - `devtools render topology-projection && devtools render topology-status` regenerated for every new module (`session_annotations_write.py`, `daemon/event_bus.py`). - Three pre-existing, unrelated test failures found and filed as follow-ups rather than silently ignored (`polylogue-0puw`, `polylogue-g99u`, `polylogue-ihp0`) — all confirmed to reproduce independent of this PR's changes (`ihp0` additionally confirmed via `git merge-base --is-ancestor` to predate this branch's base commit). - Post-rebase re-verification: `devtools verify --quick` green again (39.76s, 15/15 steps); `devtools test` across the branch's new/touched test files (`test_write_effects.py`, `test_event_bus.py`, `test_session_profile_staleness_predicate.py`, `test_sqlite_connection_hygiene.py`, `test_code_refs_resolve.py`) — 232 passed; `tests/unit/storage/test_archive_tiers_write.py` — 63 passed (write-tier extraction behavioral parity, re-confirmed post-rebase). ## Not run Full `devtools verify --all` / broad directory test sweeps (per repo policy — testmon-affected/focused selection is the default, not blanket directory runs). Per-PR CI is disabled repo-wide (billing-locked). --------- Co-authored-by: Claude <[email protected]>
Summary
Two additive, read-mostly repair-substrate capabilities for the raw-identity
repair cluster (polylogue-lkrc, polylogue-lkrc.2, polylogue-lkrc.3,
polylogue-yla8, polylogue-yla8.6, polylogue-t0dy, polylogue-57rp,
polylogue-5k5l.1), plus a follow-up commit closing an adversarial-review
hold (polylogue-hleq):
reviewable blocker for the four browser-capture sessions whose canonical
ChatGPT authority genuinely conflicts (not just fails a precondition) and
cannot be safely rekeyed by the existing narrow actuator.
the two known live production raw pairs still stuck under the pre-fix(pipeline): stop the one-shot importer duplicating raw rows #2729
duplicate-raw scheme, using the existing revision-application machinery
rather than a hand-written
raw_revision_headsUPDATE.Everything else in the assigned cluster (lkrc, lkrc.2, yla8, yla8.6, 57rp,
5k5l.1) was investigated and found either already resolved by prior merged
PRs in this campaign, or blocked on live-archive execution that this PR
deliberately does not perform (see bead-by-bead notes below and in bead
comments).
Problem
lkrc.3:
repair_byte_proven_browser_capture_null_native_ids(merged inPR #2850) already correctly refuses to rekey four browser-capture sessions
whose unknown-export accepted head cannot be safely repointed: two diverge
from a semantic canonical head at different content hashes, one has a
superseded_equivalentmembership row blocking the null-membershipprecondition, and one has production reparse hash drift against an
incompatible canonical byte head
(
test_byte_proven_browser_rekey_fails_closed_for_observed_conflicts,already green). But the rejection path only returns a terse
ineligible_reasonstring — the competing-authority evidence(
_inspect_browser_capture_origin_mismatch's internal state) is computed andthen discarded on every early-return branch, so nothing survives for an
operator to adjudicate, and nothing records that the conflict exists once the
inspection call returns (AC1/AC4 of lkrc.3).
t0dy: PR #2729 aligned the one-shot importer and the live daemon watcher
on one deterministic raw-id scheme (
native_id=NULL) so new ingests of agrouped/split-session Claude Code/Codex resume-fork file converge on one raw
row. It explicitly did not retroactively repair raw pairs that already
duplicated under the OLD, native_id-inclusive scheme before that fix landed —
the accepted head stays bound to the stale raw, its post-fix twin sits
orphaned, and every later daemon catch-up pass over that file hits
RuntimeError: membership replay cannot retire an unrelated accepted head(
archive.py:2255) indefinitely. Two live production files areknown-affected (bead notes name the exact raw ids). t0dy's own design note is
explicit that this needs a typed actuator using the existing
revision-application machinery, not a hand-written raw UPDATE.
Solution
polylogue/storage/repair.py(all additive, no existing functiontouched):
inspect_browser_canonical_authority_conflicts(config, raw_ids)— read-only,re-runs the byte-proven-rekey actuator's exact eligibility proof per raw id.
A raw that comes back eligible/already_repaired is not a conflict (counted
in
resolved_count, not returned). A raw that stays ineligible gets aBrowserCanonicalAuthorityConflictWitness: competing head contenthash/frontier kind/decision (queried directly against
raw_revision_heads/raw_revision_applications, since the underlying inspector discards this onreject), any blocking membership row (queried without a
logical_source_keyfilter, matching the actuator's own broader
COUNT(*)precondition), and —when both sides are single-session byte-frontier raws — the first diverging
message index via
session_revision_projection.record_browser_canonical_authority_conflict_blockers(config, raw_ids)—the separate, explicit persistence step. Each conflict becomes one
AssertionKind.BLOCKERcandidate assertion inuser.db(durable,irreplaceable tier), deterministic id over
(raw_id, evidence_digest)sore-running after new evidence creates a new row rather than overwriting,
unchanged re-runs idempotent. Written through
upsert_assertion'sauthor_kind="detector"chokepoint (mirrorsupsert_pathology_findings_as_assertions, feat(insights): mine agent-workflow failure-mode pathologies #2383) — always forced tostatus=candidate/inject:false, can never self-promote to anauthoritative claim. Neither function authorizes a repair; resolving the
four conflicts under an explicit operator policy is separately scoped
follow-up (matches lkrc.3 AC2: "no automatic overwrite based on partial
equality").
repair_duplicate_raw_identity(config, pairs, apply=, receipt_path=, proof_digest=)— the same dry-run/apply/CAS/receipt shape as every otheractuator in this file.
_inspect_duplicate_raw_identityproves per pair:both raws byte-identical (
origin/source_path/source_index/blob_hash/blob_size, plus an actualBlobStoreread verifying retainedbytes match the declared digest/size); each raw id equals the deterministic
id its own fields (and
native_idshape) predict viadeterministic_raw_session_id; the stale raw is the current acceptedhead/session pointer; the canonical raw is a genuinely dangling duplicate
(not itself referenced by any head or session).
_apply_duplicate_raw_identity_repairreuses
record_revision_application_synctwice — aSELECTED_BASELINEreceipt for the canonical raw performs the head CAS (session_id/
content_hash/frontier_kind/frontier are unchanged since the raws are
byte-identical, so this is exactly the existing "equivalent-content"
acceptance path, only
accepted_raw_idrepoints), then aSUPERSEDEDreceipt on the stale raw records the loss of authority. The stale raw's own
row is never mutated or deleted.
Tests:
tests/unit/storage/test_browser_capture_origin_repair.py(+6tests reusing the existing fixture matrix) and new
tests/unit/storage/test_duplicate_raw_identity_repair.py(10 tests: dry-runproof, apply + exact before/after row diff, idempotent reapply, 4-way
ineligible-shape matrix, duplicate/malformed-id rejection, stale-digest
rejection, missing-receipt-path rejection).
Bead-by-bead disposition
AC3's "if a repair is authorized" is explicitly not exercised — no repair
is authorized here).
for the code portion of t0dy's design. The live one-time census/apply
against the two named production files is explicitly reserved for the
operator per this cluster's live-archive-safety constraint (t0dy's own AC5
requires a verified backup + stopped daemon, which this session does not
perform).
master: the four"adversarial loop iteration 5" proof gaps named in its notes (capture_mode
binding,
blob_ref.source_pathbinding,native_idbinding,restore_canonical_headfield coverage) are already present in_browser_origin_source_envelope_is_exacton currentmaster(landed viaPRs fix(storage): copy forward legacy browser NULL identities (#2843) #2843/fix(storage): admit proven legacy semantic heads #2847/fix(storage): accept generated active index paths #2848/fix(storage): rekey proven browser captures #2850, all merged after the note was written). AC1
(new captures acquire correct origin) is already covered by
test_streaming_sized_browser_capture_json_uses_native_payload_detection.Remaining scope (AC4's dynamic live census reaching zero, or — after this
PR — an explicit durable blocking state for the four) is live-execution-only.
purely the parent-run stopped-daemon dry proof/apply/postflight, which is
live-execution-only and out of this PR's scope.
already-merged children (yla8.10 closed with live postflight evidence;
yla8.6's own notes record a completed live repair). No further code gap
identified beyond what's already merged; final closure is a live-postflight
confirmation, reserved for the operator.
848,460-byte/SHA reproduction) and AC5 (live re-capture convergence)
inherently require either embedding real recovered production bytes in a
repo fixture or a live capture — correctly left deferred, not fabricated.
AC4 (replay-debt counts) was investigated; extending it safely would need a
materially deeper read of
_raw_materialization_candidate_ids's WHEREclause than this session's remaining budget allowed, so it is left as
explicitly deferred rather than guessed at.
acquisition) is complete per its notes (PR fix(browser): authenticate ChatGPT interpreter asset fetches #2712, live-proven); the one
remaining item it names is explicitly owned by 57rp, not 5k5l.1.
Review response (polylogue-hleq)
An adversarial review found two majors and a minor, held pending fixes. All
three are addressed in the follow-up commit on this branch:
repair_duplicate_raw_identity'sapply-mode receipt was a single unlocked
receipt_path.write_text()callissued after the index transaction committed, gated only by a TOCTOU-racy
receipt_path.exists()check — two concurrent--applyinvocations couldboth pass the check before either wrote. Fixed: it now locks one
receipt inode via the exact same
flock(LOCK_EX|LOCK_NB)+O_NOFOLLOW+fsync(file, then parent dir)contract this codebase already uses for the quarantined-raw-repair receipt
(
_lock_quarantined_raw_repair_receipt), with the identicalplanned→applied two-phase JSONL shape and torn-terminal crash recovery. A
second concurrent
--applyagainst the same receipt path now fails closedwith
RuntimeError: operator repair receipt is already locked by another applyinstead of racing into the transaction. New tests: concurrent-applylock contention, crash-before-terminal-append resume, symlink receipt path
rejection.
elif competing_frontier_kind == "byte" and competing_raw_id != raw_idbranch in
_browser_canonical_authority_conflict_witnessre-read thecompeting raw mid-function on an independent point-in-time SQLite read,
without re-proving it against the same snapshot the base eligibility proof
(
base.reason) used. Fixed:inspect_browser_canonical_authority_conflictsnow wraps the base proof and the witness's own re-reads of
raw_revision_heads/raw_session_memberships/raw_revision_applicationsin one
BEGIN DEFERRED/COMMITread transaction per raw id, so both seeone consistent snapshot instead of two independent reads. This is
read-only isolation, not the apply-time CAS/receipt ceremony — nothing is
mutated, so
COMMITjust releases the read lock. New test exercises thepreviously-untested byte-frontier message-divergence-evidence branch
directly.
record_browser_canonical_authority_conflict_blockershas noapply flag/proof-digest/receipt: investigated and judged genuinely
exempt from this file's actuator ceremony, not a gap to close with more
machinery. That ceremony exists because the other actuators repoint
authoritative identity state (
raw_revision_heads,sessions) where anerror is expensive to detect and reverse. This function never touches
authoritative state — it writes exactly one
candidate/non-injected/private assertion through
upsert_assertion's single write chokepoint(mirrors
upsert_pathology_findings_as_assertions, feat(insights): mine agent-workflow failure-mode pathologies #2383), which alreadyrefuses to resurrect a judged-terminal row back to candidate on a later
automated write. Documented this reasoning directly in the function's
docstring, and hardened it further: added an explicit
read_assertion_envelope/existing.statusguard so a re-run overunchanged evidence never touches a row an operator has already judged
(accepted/rejected/deferred/superseded) — the same terminal-judgment
protection this file's other candidate writers already have. New test
proves a judged row's status and value survive a re-run untouched.
functions are now reachable from
polylogue ops maintenance:browser-canonical-authority-conflicts(read-only by default,--recordpersists blockers) and
duplicate-raw-identity(dry-run/--applywiththe same
--proof-digest/--receiptcontract as the siblingquarantined-accepted-raws/browser-capture-origin-mismatchescommands),mirroring the existing actuator CLI pattern exactly. 4 new CLI adapter
tests.
Verification
Not run: the full non-integration suite (
devtools verify --all) or the livearchive.
Anti-vacuity
test_inspect_conflicts_semantic_hash_divergence_evidencemutatesraw_revision_heads.accepted_content_hashto a distinct value and assertsthe returned
competing_content_hashreflects exactly that mutation;reverting to the original terse-reason-only inspector makes the assertion
fail with
AttributeError/None.test_apply_repoints_head_and_session_preserving_stale_rawassertsraw_revision_heads.accepted_raw_idandsessions.raw_idboth equalcanonical_raw_idafter apply, the stale raw's ownraw_sessionsrow isbyte-for-byte unchanged, and the stale raw gained a
supersededreceiptnaming
canonical_raw_id; reverting_apply_duplicate_raw_identity_repairto a no-op makes the head/session assertions fail with the pre-repair
(stale) raw id.
test_fails_closed_for_ineligible_shapesmutates four different witnessfields (competing accepted head, wrong accepted raw, content divergence,
matching native_id schemes) and asserts apply raises before any write.
test_apply_serializes_one_receipt_inode_against_a_concurrent_applyholds the real receipt-lock flock open (as a genuinely concurrent apply
would) and proves a second
repair_duplicate_raw_identity(apply=True, ...)call refuses and never mutates the accepted head; deleting the flock
acquisition from the receipt lock (regressing to the old bare
receipt_path.exists()TOCTOU check) makes this test fail.test_record_conflict_blockers_never_clobbers_an_operator_judged_rowjudges a blocker candidate via
judge_assertion_candidate(decision="accept"),then re-runs the detector over identical evidence and asserts the judged
row's status and value are byte-identical; deleting the
read_assertion_envelope/existing.statusguard makes this test fail(the judged row's value would silently be overwritten back to the
detector's regenerated evidence payload).
Live-archive safety
No repair actuator in this PR was run against the live archive at
/realm/db/polylogue(or any host archive) — every dry-run and apply call inthis PR's tests targets an isolated
tmp_pathfixture archive. The daemonwas not touched.
Ref polylogue-lkrc
Ref polylogue-lkrc.2
Ref polylogue-lkrc.3
Ref polylogue-t0dy
Ref polylogue-yla8
Ref polylogue-yla8.6
Ref polylogue-57rp
Ref polylogue-5k5l.1
Ref polylogue-hleq
Co-Authored-By: Claude [email protected]