Skip to content

fix(pipeline): stop the one-shot importer duplicating raw rows - #2729

Merged
Sinity merged 1 commit into
masterfrom
fix/nondeterministic-session-identity
Jul 12, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/nondeterministic-session-identity

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner

Summary

The one-shot polylogue import pipeline (pipeline/services/archive_ingest.py) wrote a separate raw_sessions row per split session for grouped Claude Code/Codex/Gemini/Drive JSONL files, differentiated only by native_id even though the underlying acquired bytes were identical. This produced duplicate raw rows for byte-identical content that the live daemon's membership-replay guard later rejected as an "unrelated accepted head".

Problem

Live production evidence (2026-07-12, daemon PID 1932060): the daemon repeatedly failed full ingest of /home/sinity/.claude/projects/-realm-project-sinex/1e5805bd-72d6-4010-b052-b2b4a0e78425.jsonl (and a sibling file) with RuntimeError: "membership replay cannot retire an unrelated accepted head" (archive.py:2255, guard added by rgh2/#2718).

Direct inspection of the live source.db raw_sessions table showed two rows for the identical source_path, byte-identical content, differing only by native_id (one set to a5724e23-..., one NULL) — and therefore by raw_id, since deterministic_raw_session_id hashes native_id into the id.

Root cause traced to pipeline/services/archive_ingest.py's write_pair: for a Claude Code JSONL file whose content splits into multiple sessions (_SessionEmitter._emit_grouped yields the same captured raw bytes for every split session — verified via source read), the one-shot importer calls write_raw_and_parsed_result(session, payload=<whole file>, ..., native_id=session.provider_session_id) once per split session, writing the whole file's bytes multiple times under different native_id-derived raw_ids. The live daemon watcher instead writes one raw per file (write_raw_payload, native_id always NULL) and defers session identity to membership-census classification (raw_session_memberships / raw_revision_heads). The two pipelines therefore disagree on raw identity for the same bytes, and the daemon's membership-replay guard discovers the importer's extra raw as a spurious competing claim on a logical_source_key it already has an accepted head for.

Reproduced structurally against the real production file: its first record is a 1-message carryover of the last message of a separate, real session (a5724e23-...) — a Claude Code resume/fork artifact where the CLI copies one boundary record into the new file before switching session ids. The same pattern recurs three levels deep in this project's history (25cc6e75 -> 1eed506e -> a5724e23 -> 1e5805bd).

Solution

write_pair (pipeline/services/archive_ingest.py) now caches raw_ids by (origin, source_path, source_index, blob_hash) — the raw's own acquired-bytes identity, not any single session's derived identity:

  • The first session sharing a raw commits it via a raw_id computed without native_id (matching the daemon's own scheme).
  • Every further session sharing that same raw indexes against the same raw_id via a new ArchiveStore.write_parsed_for_retained_raw_result — a counts-returning sibling of the existing write_parsed_for_retained_raw (needed because that method only returns a bare (raw_id, session_id) tuple, and write_pair needs .counts/.content_changed for its own bookkeeping).
  • The cache key uses origin_from_provider(session.source_name), not the raw Provider, since origin_from_provider is non-injective (GEMINI and DRIVE both collapse to AISTUDIO_DRIVE) and deterministic_raw_session_id hashes the origin, not the provider.

docs/plans/layering.yaml gained the new public entrypoint in the writer-module inventory (verify layering enforces this).

The archive.py:2255 guard itself is untouched: it must still reject genuinely divergent content. An initial attempt to also soften the guard directly was reverted after discovering it would skip essential raw_session_memberships bookkeeping on early return. The write-path fix alone removes the structural precondition (duplicate raw rows for identical bytes) that let the guard ever see an "unrelated" head for these files.

Verification

devtools test tests/unit/pipeline/test_archive_ingest_shared_raw.py \
  tests/unit/pipeline/test_archive_ingest_commit_batching.py \
  tests/unit/storage/test_revision_replay.py \
  tests/unit/sources/test_live_batch_support.py

-> 91 passed, 6 pre-existing failures in test_live_batch_support.py (verified identical on unmodified master via git stash; unrelated browser-capture route-observability and append crash-injection assertions).

Anti-vacuity: reverted this diff and reran the two new tests in tests/unit/pipeline/test_archive_ingest_shared_raw.py — both failed exactly as predicted (2 raw rows differentiated by native_id instead of 1). The production dependency exercised is write_pair's raw-identity computation in pipeline/services/archive_ingest.py; the mutation that makes the test fail is deleting the shared-raw cache (reverting to one write_raw_and_parsed_result call per split session).

devtools verify --quick

-> all 14 steps ok, exit 0.

Acceptance criteria (polylogue-sjf6)

  1. Deterministic fixture, byte-identical re-acquisition -> same raw_id/logical_source_key: satisfied — test_reingesting_identical_bytes_resolves_to_the_same_raw_id.
  2. The two specific live raw_ids reparse to the same key / second acquisition no longer raises: the write-path fix prevents this class of duplicate-raw creation going forward from either pipeline. The two specific live raw_ids already in the archive predate this fix and are historical data, not re-created by it — I could not, despite extensive reproduction attempts (single/batched acquisition orderings, up to a 3-hop carryover chain), reproduce the exact RuntimeError in a controlled unit test from a single pipeline's behavior; the live crash required the specific cross-pipeline (one-shot import + daemon) duplicate-raw state that this PR prevents recreating. Flagging as a residual open question for the coordinator: whether the two already-affected raw rows on the live host need separate remediation (e.g. raw_revision_rebuild_selection/raw_membership_census compaction) is not addressed here.
  3. Genuinely divergent content still trips the guard: preserved — the guard itself is unmodified, and test_single_session_full_cannot_overwrite_divergent_membership_head (the guard's own regression test) still passes.
  4. Focused tests + devtools verify --quick pass, anti-vacuity stated: satisfied, see above.
  5. Live catch-up completes without the RuntimeError: not independently re-verified against the live host from this PR; the write-path fix removes the mechanism that created the duplicate raws in the first place.

Ref polylogue-sjf6

Problem: the live daemon repeatedly failed full ingest of two Claude
Code JSONL files with RuntimeError "membership replay cannot retire
an unrelated accepted head" (archive.py:2255, guard added by
rgh2/#2718). Live evidence (source.db raw_sessions) showed the SAME
file had two raw_sessions rows for the identical source_path and
byte-identical content, differing only by native_id (one set, one
NULL) and therefore by raw_id, since deterministic_raw_session_id
hashes native_id into the id.

Root cause: pipeline/services/archive_ingest.py's one-shot importer
(`parse_sources_archive` / `write_pair`, the `polylogue import`
"parse" pipeline stage) writes ONE raw_sessions row PER SPLIT SESSION
for a grouped Claude Code/Codex/Gemini/Drive JSONL file whose content
splits into multiple sessions (`_SessionEmitter._emit_grouped` yields
the SAME captured raw bytes for every split session), via
write_raw_and_parsed_result(native_id=session.provider_session_id).
The live daemon watcher instead writes ONE raw per file
(write_raw_payload, native_id always NULL) and defers session
identity to membership-census classification. The two pipelines
therefore computed different raw_ids for identical bytes, and the
daemon's membership-replay guard later discovered the importer's
extra raw as a spurious competing claim on a logical_source_key it
already had an accepted head for.

Reproduced directly against the real production file
(1e5805bd-72d6-4010-b052-b2b4a0e78425.jsonl): its first record is a
1-message carryover of the LAST message of a separate, real session
(a5724e23-...), a structural Claude Code resume/fork artifact -- and
that same carryover pattern recurs three levels deep in this
project's history (25cc6e75 -> 1eed506e -> a5724e23 -> 1e5805bd).

What changed: `write_pair` now caches raw_ids by (origin, source_path,
source_index, blob_hash) -- the raw's own acquired-bytes identity, not
any single session's derived identity. The first session sharing a
raw commits it via a raw_id computed WITHOUT native_id (matching the
daemon's own scheme); every further session sharing that same raw
indexes against the SAME raw_id via the new
`ArchiveStore.write_parsed_for_retained_raw_result` (a counts-returning
sibling of the existing write_parsed_for_retained_raw, needed because
write_parsed_for_retained_raw only returns a bare (raw_id, session_id)
tuple). Byte-identical content therefore now resolves to the same
raw_id and logical_source_key on every ingest, from either pipeline.

The archive.py:2255 guard itself is untouched: it must still reject
genuinely divergent content, and an initial attempt to also soften it
was reverted after discovering it would skip essential
raw_session_memberships bookkeeping on early return -- the write-path
fix alone removes the structural precondition (duplicate raw rows for
identical bytes) that let the guard ever see an "unrelated" head for
these files.

Verification:
- devtools test tests/unit/pipeline/test_archive_ingest_shared_raw.py
  tests/unit/pipeline/test_archive_ingest_commit_batching.py
  tests/unit/storage/test_revision_replay.py
  tests/unit/sources/test_live_batch_support.py -> 91 passed, 6
  pre-existing failures in test_live_batch_support.py (verified
  identical on unmodified master via git stash, unrelated to this
  change: browser-capture route-observability assertions and append
  crash-injection tests).
- Anti-vacuity: reverted this diff and reran the two new tests --
  both failed exactly as predicted (2 raw rows differentiated by
  native_id instead of 1; production dependency exercised is
  write_pair's raw-identity computation in
  pipeline/services/archive_ingest.py).
- devtools verify --quick -> all 14 steps ok, exit 0.

Ref polylogue-sjf6
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 12, 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: 34 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

Run ID: 9c469d1d-a596-4620-9e3e-51347fefe3b0

📥 Commits

Reviewing files that changed from the base of the PR and between 62dc0b0 and 769340c.

📒 Files selected for processing (4)
  • docs/plans/layering.yaml
  • polylogue/pipeline/services/archive_ingest.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • tests/unit/pipeline/test_archive_ingest_shared_raw.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/nondeterministic-session-identity

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.

@Sinity
Sinity merged commit 45766f3 into master Jul 12, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the fix/nondeterministic-session-identity branch July 12, 2026 01:31
Sinity added a commit that referenced this pull request Jul 12, 2026
Beads-only bookkeeping. polylogue-sjf6 closed with honest AC accounting
(root cause merged PR #2729, AC#5 deferred to polylogue-t0dy);
polylogue-b0b closed (PR #2730 merged).

CI blocked repo-wide by account billing lock; GitGuardian passed.
devtools verify --quick passed locally (14/14).

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 27, 2026
…ey (#3326)

## Summary

Fixes a live, recurring `polylogued` failure: `fold_duplicate_alias`
raw-authority repair kept raising `RuntimeError: duplicate strategy did
not reach its typed terminal postcondition` for the same plan hash on
every retry, never converging (observed 7 identical failures over 90
minutes for one plan, 1 for another).

## Problem

`_inspect_duplicate_raw_identity` (`polylogue/storage/repair.py`) proves
a `(stale_raw_id, canonical_raw_id)` pair is an exact pre-/post-#2729
duplicate-fold shape, and looked up the stale raw's accepted-head row
with `SELECT ... FROM raw_revision_heads WHERE accepted_raw_id = ?` —
scoped only by raw id, not by which session/logical source key the
caller actually cares about.

Correlating the two failing plan hashes to live data (read-only, via
`mode=ro` connections against `/realm/db/polylogue`) showed why that's
ambiguous: the same physical raw acquisition (one `raw_id` under the old
native-id-inclusive scheme) is legitimately the accepted head of **four
different sessions simultaneously** — forked/subagent/resumed Claude
Code sessions replay the identical parent JSONL evidence, so each
session's own materialization can independently accept that raw as its
head. `fetchone()` on the unscoped query picked an arbitrary one of
those four sessions. The frontier item classified for session
`896c6b64-...` ended up carrying a strategy witness describing session
`560a3328-...`'s head instead of its own — directly confirmed: the
item's own `index_preconditions.logical_source_key` was `896c6b64-...`
while its `strategy_witness.logical_source_key` was `560a3328-...`.

At apply time this meant the fold repointed the *wrong* session's head
inside the transaction; the re-inspect (also unscoped) then found a
different remaining row still pointing at the stale raw, saw the
canonical now claimed, and returned `"ineligible"` instead of
`"already_repaired"` — tripping the typed postcondition check and
rolling back the whole transaction. Since nothing ever committed, the
same plan hash and error recurred identically on every retry, exactly
matching the 90-minute log pattern.

This is an application-logic bug (a missing scope key), not a design gap
requiring a new terminal status — `"already_repaired"` only needed
disambiguation.

## Solution

- `_inspect_duplicate_raw_identity` (`polylogue/storage/repair.py`) now
takes a required `logical_source_key` parameter and scopes the stale
raw's accepted-head lookup and the `"already_repaired"`
session/superseded-receipt checks to that key. The canonical raw's
head/session checks stay unscoped — "not claimed by anyone yet" is
genuinely global, not per-session.
- The three call sites in `polylogue/storage/raw_reconciler.py`
(`_classify_frontier`, and both `_apply_strategy` inspect calls for
`FOLD_DUPLICATE_ALIAS`) now pass the frontier row's/item's own
`logical_source_key`.
- Added `_seed_duplicate_raw_fanout` and two regression tests in
`tests/unit/storage/test_duplicate_raw_identity_repair.py` reproducing
the exact fan-out shape (one stale raw shared as accepted head by two
sessions, one canonical twin available): one proves classification no
longer cross-contaminates the strategy witness between siblings, the
other proves applying either sibling's plan folds only that sibling and
leaves the other's head/session pointer untouched. Both new tests fail
against the pre-fix code with the *exact* same `"did not reach its typed
terminal postcondition"` RuntimeError observed live (verified by
temporarily reverting the fix and re-running).

Did not perform any live write against `/realm/db/polylogue` — all
live-archive reads used explicit `mode=ro` URI connections; the fix
ships in code for the daemon to pick up on its next deploy.

## Verification

- `devtools test
tests/unit/storage/test_duplicate_raw_identity_repair.py` → 9 passed (2
new tests confirmed to fail against pre-fix code).
- `devtools test tests/unit/storage/test_repair.py
tests/unit/storage/test_quarantined_accepted_raw_repair.py
tests/unit/storage/test_browser_capture_origin_repair.py
tests/unit/storage/test_raw_authority_ledger.py
tests/unit/storage/test_quarantine_repair_budget.py
tests/unit/devtools/test_raw_authority_scale_proof.py
tests/unit/devtools/test_raw_authority_restart_proof.py` → 141 passed,
no regressions.
- `mypy --strict polylogue/storage/repair.py
polylogue/storage/raw_reconciler.py` → Success, no issues.
- `ruff check` / `ruff format --check` on all touched files → clean.
- `devtools render all --check` → no drift.
- `devtools verify --quick` ran clean on push (pre-push hook, exit 0).
- Did not run `devtools verify --all` (out of scope for this focused
fix).

Ref polylogue-ihc8

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Sep 21, 2026
The apply half of the raw-authority repair product was removed in #5081,
which left the worse residue: a census that still classified every accepted
head into an "executable" repair plan, named a RawAuthorityActuator for each,
minted operator-judgment assertions, and published durable blockers promising
a remedy no code in the tree could run. `_APPLY_DISPATCHED_ACTUATORS` even
documented itself as mirroring `_apply_raw_authority_plan` and a guard test,
neither of which exists.

Delete the promise rather than re-plumbing it:

- `polylogue/storage/raw_convergence.py` (2,915 lines): the three historical
  incident strategies (quarantined accepted raw, browser-capture origin
  mismatch, duplicate raw identity). They prove cohorts of the pre-2026-09-07
  archive, which the fresh-start ruling does not migrate; the duplicate-raw
  strategy is structurally unprovable post-#2729 because it requires a
  native-id-inclusive raw the current writer never emits.
- `RawAuthorityActuator`, `_EXECUTABLE_STATES`, `_APPLY_DISPATCHED_ACTUATORS`,
  `RawAuthorityFrontierItem.executable`, `executable_plan_count`, the
  strategy-override bridge, and the `safely_rekeyable` / `duplicate_alias` /
  `conflicting_authority_needs_judgment` states.
- The operator-judgment loop (`_record_judgment_candidate`,
  `_apply_judgment_dispositions`) and its `--assertion-id` /
  `--judgment-disposition` CLI, protocol, actuator and spec surface.
- `ReconstructedRawRow` / `insert_reconstructed_raw_row`: the one declared
  exemption from `admit_raw_observation`, whose only caller was the
  browser-origin copy-forward repair.

What survives is a read-only frontier census: every non-current state is an
explicit retryable obligation ordinary acquisition discharges, or a typed
permanent refusal. `raw_authority_blockers` and its readers are untouched.

`raw_convergence.py` was a declared materializer-fingerprint root, so this
moves the derived schema identity and must land before a rebuild starts.
Closure shrinks 558 -> 555 members.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
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