Repository navigation
fix(storage): unify message-native-id normalization to stop FK failures - #3186
Conversation
Problem: the live v42 index rebuild (operation ab5bad1f) died deterministically
with a bare sqlite3.IntegrityError ("FOREIGN KEY constraint failed") in
_write_blocks, ~10 hours in, with zero context on which session caused it.
Root cause: the SQLite-stored `messages.native_id` and the Python-side
identity computation that feeds `blocks.message_id` (via _message_id ->
core.identity_law.message_id) diverged for pathological provider-native ids:
- Whitespace-only ids (e.g. " ") stored truthy under a bare `or None`, but
identity_law's `native_id.strip()` check falls back to the position/variant
component -- two different message ids for the same message.
- identity_law._required_text also strips non-empty ids, but the DB stored
the raw (unstripped) value -- a second, narrower divergence.
- Lone-surrogate ids were substituted to U+FFFD on the DB side (_sqlite_text)
but not on the Python side at all, and duplicate-id detection counted raw
ids, so two distinct raw ids that collapsed to the same substituted form
weren't flagged ambiguous -- either an FK failure or a silent
INSERT-OR-REPLACE row loss, depending on which write happened first.
Solution: add `_stored_message_native_id` (archive_tiers/write.py) as the
single source of truth for message-native-id normalization -- duplicate
suppression, surrogate substitution, then the same strip/empty-to-None rule
identity_law applies. Both the `_write_messages` INSERT and `_message_id`
(consumed by every message_id call site: blocks, web constructs, paste
spans, parent links, session events, active-leaf resolution) now route
through it, so the generated `messages.message_id` column and the Python
computation can never disagree again. `_duplicate_message_native_ids` also
now counts the same normalized form so surrogate-collapsed duplicates are
caught before they collide.
Twin-check: grepped the async storage tree (async_sqlite*.py) for a second
message/block writer -- none exists; the daemon architecture note ("main
process is the sole SQLite writer") holds, so this single-writer fix is
sufficient.
Also wraps the write path so a sqlite3.IntegrityError raised inside
write_parsed_session_to_archive is re-raised (chained, not swallowed) naming
session_id/origin/native_id, and wraps both membership-replay and
byte-proven-replay call sites in backfill_historical_revision_evidence with
the logical_key -- so a future divergence surfaces with enough context to
act on immediately instead of a bare "FOREIGN KEY constraint failed".
Verification:
- devtools test tests/unit/pipeline/test_archive_write.py
tests/property/test_message_identity_normalization.py
tests/unit/sources/test_revision_backfill.py -> 59 passed
- devtools test tests/unit/storage/test_archive_tiers_write.py
tests/property/test_write_path_state_machine.py
tests/unit/storage/test_lineage_normalization.py
tests/unit/storage/test_bulk_fts_prefix_reextract.py
tests/unit/storage/test_bulk_build_lifecycle.py
tests/unit/pipeline/test_resilience.py -> 133 passed
- devtools test tests/unit/daemon/test_convergence_stages.py
tests/unit/daemon/test_fts_readiness_fallback.py
tests/unit/storage/test_repair.py
tests/unit/storage/test_incremental_rebuild_equivalence.py -> 102 passed
- devtools verify --quick -> ok (ruff format/check, mypy --strict, render
all --check all green)
- Anti-vacuity: reverted the _write_messages fix locally and reran the new
property test -- it failed with the exact
"FOREIGN KEY constraint failed writing session_id=...
native_id=' '" signature (proving both the regression test and the new
loud-failure context work), then restored the fix and reconfirmed green.
Unblocks resuming index rebuild operation ab5bad1f from its 31,882-session
checkpoint. Ref polylogue rebuild ab5bad1f.
Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 22 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 (4)
✨ 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 |
|
CodeRabbit is rate-limited on this PR; merging on coordinator review instead (campaign precedent #3174/#3175). Reviewed: single-source normalization helper routed through both the stored column and every Python-side id consumer; loud IntegrityError context on write + both replay call sites; property sweep asserting DB-generated == Python-computed message_id over hostile native ids; anti-vacuity confirmed (revert reproduces the exact live FK signature). 294 focused tests + quick gate green. This unblocks resume of rebuild operation ab5bad1f. |
…ons (#3191) ## 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's `PRIMARY KEY(session_id, position, variant_index)` silently resolves by dropping one row via `INSERT 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`) computed `variant_index_by_id` as `branch_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 to `variant_index=0`, colliding on the same `(position, variant_index)` coordinate their parents correctly diverged on. Concretely, for a fixture shaped like: ``` root -> chain-1 -> chain-2 -> branch-point -> {variant-a, variant-b} (correct: position 4, variant 0/1) | | continuation-a continuation-b (bug: both position 5, variant 0) ``` `_write_messages`' `INSERT OR REPLACE` silently dropped one of `continuation-a`/`continuation-b`, while `_write_blocks` still computed a distinct Python-side `message_id` for 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 resolved `variant_index` instead 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_depths` cycle-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 in `order_key` order (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.py` computes a similarly-shaped per-parent `branch_index`/`variant_index`, but its `position` is a monotonic enumeration index over every node in the conversation mapping (`position = idx - 1`), unique per emitted message *by construction* regardless of `variant_index` — **not vulnerable**. - `claude/ai_parser.py` and `claude/code_parser.py` route their real parse path through this same `normalize_chat_messages()` — they inherit the fix directly; their standalone `variant_index=0` literals are for degenerate single-message cases only. - All other parsers (`codex.py`, `drive.py` [Gemini/AI Studio], `local_agent.py` [gemini-cli], `antigravity.py`, `browser_capture.py`, `hermes_*.py`, `beads.py`) hardcode `variant_index=0` unconditionally — no branching modeled, **not vulnerable** to this shape. **Writer safety net** (`polylogue/storage/sqlite/archive_tiers/write.py`): - `_assert_unique_message_coordinates` computes the exact 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`, used for from-scratch imports — the path that hit this in production) before any row is touched, and the merge-append path right after `position_offset` is 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 ``` devtools test tests/unit/sources/test_claude_web_normalization.py \ tests/unit/pipeline/test_archive_write.py \ tests/property/test_claude_variant_position_uniqueness.py \ tests/property/test_message_identity_normalization.py -> 32 passed mypy --strict (touched files) -> no issues devtools verify --quick -> exit 0 (format, lint, mypy, render-all-check, topology, layering, closure-matrix, schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage, test-infra-currency, test-clock-hygiene, pytest-timeout-overrides, degrade-loudly) ``` Test coverage added, per the four acceptance criteria this fix was scoped against: - **(a) Regression fixture** (`tests/unit/sources/test_claude_web_normalization.py`): the exact 8-message collision shape above, run through the real `claude-ai` provider detection + parse + `write_parsed_session_to_archive` into 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`) asserted `u2`'s `variant_index == 0`; under the corrected inheritance semantics `u2` (the sole child of variant-1 sibling `a-new`) now correctly inherits `variant_index == 1` — updated with an explanatory comment, not silently changed. - **(b) Property test** (`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) asserting `normalize_chat_messages` output 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. - **(c) Writer collision guard** (`tests/unit/pipeline/test_archive_write.py`): two new tests — a hand-built `ParsedSession` with a forced `(position, variant_index)` collision raises a loud `ValueError` naming the session and both colliding native ids (not a bare `sqlite3.IntegrityError`) on both the full-replace and merge-append write paths. - **(d) #3186 identity-law property test** (`tests/property/test_message_identity_normalization.py`, pre-existing, unmodified): still green — confirmed by direct run, both id-law classes (DB-generated `message_id` vs. 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/property` run surfaced 31 failures across files this change never touches (durable-migration schema counts, FTS derived-surface guard table, `Mock` attribute drift in `test_parsing_service.py`, browser-capture/GDPR title-coalesce ordering, retrieval-readiness `KeyError`s, 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 own `devtools 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]> --------- Co-authored-by: Claude <[email protected]>
Summary
Fixes a deterministic
sqlite3.IntegrityError("FOREIGN KEY constraint failed") in_write_blocksthat killed the live v42 index rebuild (operation ab5bad1f) ~10 hours in, with zero context on which session caused it. Unifies message-native-id normalization into a single helper so the SQLite-generatedmessages.message_idcolumn and the Python-side identity computation that feedsblocks.message_idcan never disagree, and wraps the write path so a future divergence surfaces with session/logical-key context instead of a bare "FOREIGN KEY constraint failed".Problem
_write_blockscomputesblocks.message_idvia_message_id()(Python), which the SQLitemessagestable independently re-derives as a generated column (session_id || ':' || COALESCE(native_id, position||'.'||variant_index)). Before this change the two computations disagreed for pathological provider-native ids:" ") stored truthy under_write_messages's bare_sqlite_text(...) or None, butidentity_law.message_local_id'snative_id.strip()check falls back to the position/variant component — two different message ids for the same message, so theblocksinsert referenced amessage_idthemessagestable never stored." msg-1 "):identity_law._required_textstrips the value, but the DB stored it raw/unstripped — a second, narrower divergence._sqlite_text) but not at all on the Python side, and duplicate-id detection counted raw ids, so two distinct raw ids that collapsed onto the same substituted form weren't flagged ambiguous — either an FK failure or a silentINSERT OR REPLACErow loss, depending on write order.Solution
_stored_message_native_id(polylogue/storage/sqlite/archive_tiers/write.py) as the single source of truth: duplicate suppression → surrogate substitution (_sqlite_text) → the same strip/empty-to-Noneruleidentity_lawapplies. Both_write_messages's INSERT and_message_id(consumed by every message-id call site — blocks, web constructs, paste spans, parent links, session events, active-leaf resolution) now route through it._duplicate_message_native_ids/_effective_message_native_idnow operate on the same surrogate-substituted form, so two raw ids that collapse to the same normalized id are correctly treated as ambiguous (both fall back to position/variant) instead of silently colliding.async_sqlite*.py) for a second message/block writer — none exists; the daemon's "main process is the sole SQLite writer" invariant holds, so this single-writer fix is sufficient (no twin to patch).write_parsed_session_to_archive's write transaction so asqlite3.IntegrityErroris re-raised (chained viafrom exc, not swallowed) namingsession_id/origin/native_id. Wrapped bothapply_raw_revision_replayandapply_raw_membership_classificationcall sites inbackfill_historical_revision_evidence(polylogue/sources/revision_backfill.py) with thelogical_key, so this path's failures name what they were replaying.core/identity_law.pysemantics — it remains the canonical law; the storage layer now conforms to it exactly.Verification
devtools test tests/unit/pipeline/test_archive_write.py tests/property/test_message_identity_normalization.py tests/unit/sources/test_revision_backfill.py→ 59 passeddevtools test tests/unit/storage/test_archive_tiers_write.py tests/property/test_write_path_state_machine.py tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_bulk_fts_prefix_reextract.py tests/unit/storage/test_bulk_build_lifecycle.py tests/unit/pipeline/test_resilience.py→ 133 passeddevtools test tests/unit/daemon/test_convergence_stages.py tests/unit/daemon/test_fts_readiness_fallback.py tests/unit/storage/test_repair.py tests/unit/storage/test_incremental_rebuild_equivalence.py→ 102 passeddevtools verify --quick→ ok (ruff format/check, mypy --strict, render all --check, topology/layering/closure-matrix/manifests/ci-workflows/docs — all green)_write_messagesfix locally and reran the new property test — it failed with the exactsqlite3.IntegrityError: FOREIGN KEY constraint failed writing session_id='unknown-export:identity-law-sweep' ... native_id='identity-law-sweep'signature on a whitespace-only native id (native_ids=[' ']), proving both the regression test and the new loud-failure-context wrapper actually exercise the bug; then restored the fix and reconfirmed green.tests/unit/storage/test_no_string_interpolated_sql.pyas a hardcoded-identifier allowlist gate to run explicitly if f-string SQL was touched — that file does not exist in this checkout (searched, no match), and this change adds no SQL-string interpolation (only Python exception-message f-strings), so it is not applicable here.Unblocks resuming index rebuild operation ab5bad1f from its 31,882-session checkpoint.
Ref polylogue rebuild ab5bad1f.