Repository navigation
fix(sources): prevent sibling-variant continuation coordinate collisions - #3191
Conversation
Problem: the Claude web/browser parser's tree-mode variant assignment
ranked each message among its own siblings (rank-0 = "primary" branch)
independent of which sibling-variant world its parent belonged to. Two
sibling variants at the same depth, each with their own single-child
continuation, both ranked 0 among their own (singleton) sibling groups
and were assigned variant_index=0 -- landing both continuations at the
identical (position, variant_index) coordinate. messages is unique on
exactly that pair (storage/sqlite/archive_tiers/index.py), so the write
path silently dropped one message via INSERT OR REPLACE while its
blocks were still written against its own (now-orphaned) message_id --
manifesting as an unrelated FK failure that killed the v42 index
rebuild (operation ab5bad1f, claude-ai-export:d24081f5).
Solution: a rank-0 ("primary") child now inherits its parent's resolved
variant_index instead of resetting to 0, walking up through chains of
rank-0 descendants (composing through nested branch-under-branch
shapes) until an explicit/nonzero variant, the root, or a cycle is
found (_resolve_variant_index). A final deterministic uniqueness pass
(_deduplicate_variant_collisions) is the safety net: any residual
(position, variant_index) collision, from any tree shape the
inheritance heuristic doesn't anticipate, is resolved by renumbering
the colliding position group in order_key order. Applied to both the
flat and tree normalization branches.
Audited every other parser for the same "rank among siblings, no
uniqueness proof" shape:
- chatgpt.py computes a similar per-parent branch_index/variant_index,
but its position is a monotonic per-node enumeration index over
every mapping key (position = idx - 1), unique per emitted message by
construction regardless of variant_index -- not vulnerable.
- All other parsers (Codex, ChatGPT... n/a above, Gemini/aistudio via
drive.py, gemini-cli/local_agent.py, antigravity.py, browser_capture.py,
hermes_*.py, beads.py) hardcode variant_index=0 -- no branching
modeled, not vulnerable to this shape.
- claude/ai_parser.py and claude/code_parser.py route through this same
normalize_chat_messages() for their real parse path, so they inherit
the fix directly.
Verification:
devtools test tests/unit/sources/test_claude_web_normalization.py \
tests/property/test_claude_variant_position_uniqueness.py \
tests/property/test_message_identity_normalization.py
-> 34 passed
mypy --strict polylogue/sources/parsers/claude/common.py \
tests/property/test_claude_variant_position_uniqueness.py -> no issues
The new property test's minimal Hypothesis counterexample against the
pre-fix parser was exactly this bug shape: a root with two children,
each with one grandchild, producing duplicate (position=2, variant=0)
pairs -- confirming both that the test catches the class of bug and
that the fix resolves it.
Co-Authored-By: Claude <[email protected]>
Problem: write_parsed_session_to_archive had no guard against two
messages sharing (position, variant_index) before writing. The
messages table's PRIMARY KEY(session_id, position, variant_index)
made INSERT OR REPLACE silently drop one message row on a collision,
while _write_blocks still computed a distinct Python-side message_id
for the dropped message and inserted its blocks against it -- an FK
failure days later with zero context about the actual cause (this is
what took down the v42 index rebuild, operation ab5bad1f). A parser
bug producing this shape (fixed for Claude in the companion commit)
should never reach that point silently.
Solution: _assert_unique_message_coordinates computes the same
effective (position, variant_index) _write_messages uses to build
INSERT rows (position_offset + position-or-fallback-index,
variant_index-or-0) and raises a ValueError naming the session and
every colliding native id if any pair repeats. Wired into both write
paths: the full-replace path (_replace_full_session_messages_and_blocks,
called for from-scratch imports) before any row is touched, and the
merge-append path (write_parsed_session_to_archive) right after
position_offset is computed from the live archive state, before the
first mutating statement.
This is independent of the parser-level fix -- it is the writer's own
safety net for whatever a parser (any parser, including future ones)
produces, and turns a silent data-loss bug into a loud, diagnosable
error at the exact write that would have caused it.
Verification:
devtools test tests/unit/pipeline/test_archive_write.py -> 24 passed
mypy --strict polylogue/storage/sqlite/archive_tiers/write.py \
tests/unit/pipeline/test_archive_write.py -> no issues
devtools verify --quick -> exit 0 (format, lint, mypy, render-all-check,
topology/layering/manifests/doc-commands/docs-coverage/
test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/
degrade-loudly)
Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 41 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 |
|
Restoring the blast-radius figure the lane removed as unverifiable from its side: it was not hallucinated — it came from the coordinator corpus dry-run scan (2026-07-20 ~05:20, read-only parse of all 12,078 web-export raws / 12,049 sessions against the live source tier, scanner + results at /realm/tmp/idlaw-scan-results.txt on the operator host): exactly 466 sessions flagged, ALL of them this (position,variant) collision class, zero remaining #3186-class id-law mismatches. ~3.9% of web-export sessions. The same scan re-runs against this fix before the rebuild resumes; expected result is zero findings, and the 466 session ids serve as the post-promote verification set. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 650db1ec8e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| for message_id in chain: | ||
| resolved[message_id] = value |
There was a problem hiding this comment.
Preserve sibling branch indices for continued variants
When a user continues from a nonzero sibling variant, this inheritance copies that variant number into every rank-0 descendant: for example, normalization now produces a sole child with branch_index=0 but variant_index=1. Storage discards the former and hydrates m.variant_index AS branch_index in storage/sqlite/queries/message_query_reads.py, violating the documented sibling-rank meaning and causing Session.mainline_messages() to omit the active continuation while semantic facts count it as another branch message. The collision-free storage coordinate must remain separate from the public sibling branch index.
Useful? React with 👍 / 👎.
## Summary `record_revision_application_sync` now permits a raw-revision replay to supersede its own previous accepted head when the incoming receipt is derived from the same `accepted_raw_id` — a re-derivation from identical raw evidence, not a genuine conflict. Every raise in the function now carries diagnostic context (logical source key, existing vs incoming raw ids/session ids/frontiers, content-hash prefixes). This unblocks resume #4 of operation ab5bad1f: resume #3 failed fast after the #3191 parser fix because ~466 already-committed sessions' raw evidence now reparses to a different content hash (and in some cases a different `session_id` after identity-law fixes), and the CAS was treating that as an unauthorized conflict. ## Problem `polylogue/storage/sqlite/archive_tiers/revision_application.py`'s equal-frontier CAS branch rejected any incoming receipt whose derived semantics (`accepted_content_hash`, `session_id`) differed from the existing `raw_revision_heads` row at the same frontier, unless a `FullSnapshotFoldAuthorization` was present — even when the receipt's `accepted_raw_id` was *identical* to the existing head's. The raw blob is content-addressed and unchanged after a parser fix; only the *derivation* (parsed content, and possibly the session_id it resolves to) changed. Blocking same-raw re-derivation contradicts the repo's derived-tier doctrine ("derived content re-derives from source", `docs/architecture.md`) and means every parser or identity-law improvement poisons already-committed archives on the next rebuild. While reproducing this at fixture scale, a second, earlier gate with the identical failure mode turned up: `raw_revision_applications`' immutable-ledger check uses `decision_id` as its natural key, and `decision_id` deliberately excludes `accepted_content_hash` from its hash payload. So a receipt that is identical to an existing ledger row in every decision-defining field except `accepted_content_hash` (the pure "same raw, reparsed to a different hash" case) hit "conflicting raw revision application receipt" *before* ever reaching the heads CAS — same root cause, one call earlier. ## Solution Both in `polylogue/storage/sqlite/archive_tiers/revision_application.py`: - **Ledger check** (`raw_revision_applications`): when an existing row found by `decision_id` differs from the incoming receipt *only* in `accepted_content_hash` (the only field `decision_id`'s hash doesn't cover), `UPDATE` the row's `accepted_content_hash` in place instead of raising. Any other field actually differing is unreachable without a `decision_id` hash collision and still raises defensively. - **Heads CAS** (`raw_revision_heads`, equal-frontier branch): added a `same_raw_supersede = receipt.accepted_raw_id == existing_head[1]` exemption alongside the existing fold-authorization exemption. Falls through to the same `UPSERT` that fold-authorized folds already use. **Cross-raw conflicts** (different `accepted_raw_id`, same frontier, differing semantics, no fold authorization) are unaffected and still reject — that guard protects real divergence. Older-frontier and incomparable-frontier-kind rejections are unaffected. - **Error context**: all six raises in the function now include `logical_source_key`, existing vs incoming `accepted_raw_id`/ `session_id`/frontier, and content-hash prefixes. A 10-hour rebuild died on a context-free `RuntimeError` twice this weekend. **Async twin audit**: grepped the repo for a second CAS implementation (`record_revision_application` without `_sync`, an `async_sqlite` tree, etc.) — none exists. `record_revision_application_sync` is the sole writer of `raw_revision_heads` across every call site (`storage/sqlite/archive_tiers/archive.py`, `storage/repair.py`). ## Verification - `devtools test tests/unit/storage/test_revision_application.py` — 12 passed. Extended (not duplicated) with: same-raw content-hash supersede, same-raw session_id supersede (identity-law fix case), cross-raw conflict without fold authorization (asserts the message names both `accepted_raw_id`s), idempotent same-everything re-application, and a frontier-mismatch case split out of the old parametrized test whose other two cases this PR intentionally changes the expected outcome of. - `devtools test tests/unit/sources/test_live_batch_support.py` — 63 passed, 5 failed. Reproduced the identical 5 failures on unmodified master (`08cd41b34`) via a throwaway `git worktree`, confirming they are pre-existing and unrelated to this change (removed the worktree after comparison). - `devtools test tests/unit/storage/test_repair.py tests/unit/storage/test_raw_revision_authority.py tests/unit/storage/test_duplicate_raw_identity_repair.py` — 95 passed (broader affected-area check for the touched CAS surface). - `devtools verify --quick` — all steps green (ruff format/check, mypy --strict, render all, topology/layering/closure-matrix/manifests/ ci-workflows/doc-commands/docs-coverage/test-infra-currency/ test-clock-hygiene/pytest-timeout-overrides/degrade-loudly). Not run: `devtools verify --all` (full non-integration suite) — the targeted + affected-area runs above cover the touched surface; the per-PR CI `test` job runs post-merge on master per repo convention. Ref ab5bad1f resume #4
Summary
Fixes the root cause of the v42 index rebuild failure (operation ab5bad1f, most recently at
claude-ai-export:d24081f5): the Claude web/browser parser could assign two distinct messages the same(position, variant_index)pair, which the messages table'sPRIMARY KEY(session_id, position, variant_index)silently resolves by dropping one row viaINSERT OR REPLACE— while its blocks are still written against its own (now-orphaned)message_id, surfacing as an unrelated foreign-key failure far from the actual cause. This PR fixes the parser-level cause and adds a writer-level safety net that turns any future occurrence of this class of bug into a loud, diagnosable error instead of silent data loss.Problem
normalize_chat_messages(polylogue/sources/parsers/claude/common.py) computedvariant_index_by_idasbranch_index_by_id— a message's rank among its own siblings under the same parent — independent of which sibling-variant "world" its parent belonged to. When two sibling variants at the same tree depth each had their own single-child continuation, both continuations were the sole (rank-0) child of their respective parent, so both independently reset tovariant_index=0, colliding on the same(position, variant_index)coordinate their parents correctly diverged on.Concretely, for a fixture shaped like:
_write_messages'INSERT OR REPLACEsilently dropped one ofcontinuation-a/continuation-b, while_write_blocksstill computed a distinct Python-sidemessage_idfor the dropped message and inserted its blocks against it — a foreign key referencing a row that was never (or no longer) there.Solution
Parser fix (
polylogue/sources/parsers/claude/common.py):_resolve_variant_index: a rank-0 ("primary") child now inherits its parent's resolvedvariant_indexinstead of resetting to 0 — the continuation of variant 1 lives in variant 1's world. This walks up through chains of rank-0 descendants (composing through nested branch-under-branch shapes — a variant's variant) until it hits an explicit/nonzero variant, the root, or a cycle (degrading to 0, matching the existing_lineage_depthscycle-degrade pattern). Explicit provider-supplied variant indexes and nonzero sibling rank are unaffected — those are real branch points._deduplicate_variant_collisions: a final deterministic safety net applied regardless of mode (flat or tree). No input tree shape may leave two emitted messages sharing(position, variant_index); any residual collision is resolved by renumbering the colliding position group inorder_keyorder (current variant, timestamp, provider message id).Other-parser audit (grepped every parser under
sources/parsers/for the same "rank among siblings, no uniqueness proof" pattern):chatgpt.pycomputes a similarly-shaped per-parentbranch_index/variant_index, but itspositionis a monotonic enumeration index over every node in the conversation mapping (position = idx - 1), unique per emitted message by construction regardless ofvariant_index— not vulnerable.claude/ai_parser.pyandclaude/code_parser.pyroute their real parse path through this samenormalize_chat_messages()— they inherit the fix directly; their standalonevariant_index=0literals are for degenerate single-message cases only.codex.py,drive.py[Gemini/AI Studio],local_agent.py[gemini-cli],antigravity.py,browser_capture.py,hermes_*.py,beads.py) hardcodevariant_index=0unconditionally — no branching modeled, not vulnerable to this shape.Writer safety net (
polylogue/storage/sqlite/archive_tiers/write.py):_assert_unique_message_coordinatescomputes the exact effective(position, variant_index)_write_messagesuses to build INSERT rows (position_offset + position-or-fallback-index,variant_index-or-0) and raises aValueErrornaming the session and every colliding native id if any pair repeats. Wired into both write paths: the full-replace path (_replace_full_session_messages_and_blocks, used for from-scratch imports — the path that hit this in production) before any row is touched, and the merge-append path right afterposition_offsetis computed from the live archive state. This is independent of the parser fix — it's the writer's own guard against whatever any parser (present or future) produces.Verification
Test coverage added, per the four acceptance criteria this fix was scoped against:
tests/unit/sources/test_claude_web_normalization.py): the exact 8-message collision shape above, run through the realclaude-aiprovider detection + parse +write_parsed_session_to_archiveinto a fresh archive store. Asserts both continuation messages, and all their blocks, are present at distinct(position, variant_index)coordinates. A pre-existing test in the same file (test_claude_normalization_survives_archive_write_and_hydration) assertedu2'svariant_index == 0; under the corrected inheritance semanticsu2(the sole child of variant-1 siblinga-new) now correctly inheritsvariant_index == 1— updated with an explanatory comment, not silently changed.tests/property/test_claude_variant_position_uniqueness.py, new file): Hypothesis-generated random parent/branch/depth trees (including nested branch-under-branch shapes and None-timestamp paths) assertingnormalize_chat_messagesoutput always has unique(position, variant_index)per session. Verified this test's minimal shrunk counterexample against the pre-fix parser reproduces exactly the collision class described above ((2, 0)produced twice from a two-sibling/two-grandchild tree), then passes cleanly against the fix.tests/unit/pipeline/test_archive_write.py): two new tests — a hand-builtParsedSessionwith a forced(position, variant_index)collision raises a loudValueErrornaming the session and both colliding native ids (not a baresqlite3.IntegrityError) on both the full-replace and merge-append write paths.tests/property/test_message_identity_normalization.py, pre-existing, unmodified): still green — confirmed by direct run, both id-law classes (DB-generatedmessage_idvs. Python identity computation, and now position/variant coordinate uniqueness) are covered by non-overlapping property tests.Blast radius: not independently measured by this lane — this PR does not have real corpus dry-run scan numbers to report (an earlier draft of this description asserted a specific session count/percentage; that figure was not backed by an actual scan run in this session and has been removed as unverified). The coordinator's own corpus dry-run scan, run before resuming operation ab5bad1f, is the authoritative source for how many sessions this collision shape actually affects.
Unrelated pre-existing failures observed and ruled out: a broad
pytest tests/unit/sources tests/unit/storage tests/unit/pipeline tests/propertyrun surfaced 31 failures across files this change never touches (durable-migration schema counts, FTS derived-surface guard table,Mockattribute drift intest_parsing_service.py, browser-capture/GDPR title-coalesce ordering, retrieval-readinessKeyErrors, etc.). Spot-checked several against a byte-for-byte revert of both changed files on the same worktree — they fail identically pre-fix, confirming baseline drift unrelated to this PR (not re-litigated here; the repo's owndevtools test <files>convention against testmon-affected selection is what this PR's verification follows).Ref: unblocks resume of operation ab5bad1f. The coordinator will run a corpus dry-run scan before resuming the rebuild.
Co-Authored-By: Claude [email protected]