Repository navigation
fix(storage): union messages/blocks across acquisitions, not re-parses - #3413
Conversation
…eplacing
Problem: newer provider exports are not supersets of older ones. Measured
on chatgpt (polylogue-geop): a 2026-07 export of the same conversations as
a 2026-04 export dropped the entire tool/system role layer (24,914 tool
messages, 20,384 code blocks) and, within citation records both exports
still carried, dropped keys one level deeper (start_idx/end_idx/
matched_text/refs/safe_urls/error/status/style) while keeping identical
record counts and byte-identical message text. A full-session re-ingest
previously did DELETE FROM messages WHERE session_id=? followed by a
blind re-insert, so a poorer re-acquisition silently deleted content a
richer prior acquisition had already supplied.
Solution: `_union_with_existing_rows` in
polylogue/storage/sqlite/archive_tiers/write.py runs before the full
replace's delete, reading what's currently stored for the session and
merging it against the freshly-built row tuples:
- messages/blocks matched by native_id / (message_id, position): scalar
columns coalesce (new value wins when present, else the stored value
survives), mirroring the existing sessions.title-style
COALESCE(excluded.x, table.x) upsert pattern.
- blocks.tool_input (the one non-scalar column) gets a recursive
field-path JSON union (`_merge_json_value`), which is what actually
restores the dropped citation keys; block content_hash is recomputed
from the merged fields since it feeds citation/evidence matching.
- A message or block entirely absent from the new acquisition is
reinjected verbatim rather than deleted, with its position reassigned
only on collision (native_id already makes message_id
position-independent).
- A block match additionally requires the same block_type at that
position -- a re-parse that reorders/replaces what occupies a slot is
a different block, not a partial observation of the old one (block
identity is content-addressed, not position -- svfj already excludes
tool_id/position from the evidence hash for the same reason).
- Whole-message reinjection is skipped for a session that is itself the
resolved parent of a prefix-sharing lineage child: the child's stored
branch_point_message_id is load-bearing, and resurrecting a message a
parent's own re-ingest intentionally dropped would fabricate a prefix
the operator's correction just removed. Field-path union within
still-present messages/blocks is unaffected by this guard.
Deliberately deferred (tracked as polylogue-u8x7): web_content_constructs
and file_edits are sidecar tables populated only from the current
acquisition's parsed domain objects, so a reinjected message's citation/
edit sidecar rows are not restored; session_events/session_model_usage
are not unioned either, so a reinjected message's model rolls up with
zero usage. Both are structurally the same "read before delete, merge,
skip for lineage parents" pattern, just not yet applied to those tables.
Two pre-existing tests encoded the old delete-and-replace assumption and
are updated to match the new, deliberately-changed contract:
test_provider_usage_model_vanishing_on_reingest_preserves_message_with_zero_usage_rollup
(renamed from ..._leaves_no_stale_rollup) now asserts the reinjected
message survives with a zero-usage skeleton row instead of being purged.
Verification:
devtools test tests/unit/storage/test_archive_tiers_write.py
75 passed
devtools test tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_archive_tiers_write.py
108 passed
ruff format --check / ruff check / mypy polylogue/storage/sqlite/archive_tiers/write.py
clean
devtools render all --check
OK, no drift
Ref polylogue-geop
Co-Authored-By: Claude <[email protected]>
Problem: the previous commit applied field-path union unconditionally to
every full-session replace. Review caught that this conflates two
structurally different causes of a full replace:
- Two DIFFERENT acquisitions of the same logical session (a second
export download, a later browser capture) are independent partial
observations -- they should union (the measured chatgpt case).
- A RE-PARSE of the SAME acquisition (unchanged raw bytes, a parser
bugfix or corrected message-boundary logic) is a better reading of the
same evidence and must be able to RETRACT a value the old parse got
wrong -- unioning here makes every historical mis-parse immortal.
Unconditional union broke this in two concrete, measured ways once run
against the wider suite (`devtools verify --seed-testmon --skip-slow`):
`test_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rollup`
(a same-acquisition re-parse retracting a wrong model attribution) and 19
browser-capture/native-vs-DOM-fallback precedence tests across
test_ingest_batch.py, test_archive_tiers_archive.py, test_browser_capture.py,
etc. -- all of which encode a caller-decided supersession (`force_replace`)
that union would have silently partially undone.
Solution: `_union_with_existing_rows` now requires positive proof of a
different acquisition before it unions anything:
- `raw_id` is content-addressed (SHA-256 of the acquired bytes,
`pipeline/services/acquisition_records.py`) and is carried forward
unchanged by a `reprocess` (parse-only) re-run of the same raw file
(confirmed via `pipeline/ingest_support.py`'s stage table and the parse
backlog in `pipeline/services/planning_runtime.py`, which loads the
existing `RawSessionRecord` rather than recomputing an id). The daemon's
real full-replace caller (`pipeline/services/ingest_batch/_core.py`)
always threads a real `raw_id` through.
- The caller (`write_parsed_session_to_archive`) now captures
`sessions.raw_id` for this session_id BEFORE its own upsert overwrites
it, and threads both the incoming and prior raw_id down into
`_union_with_existing_rows`. Querying after the upsert would always see
the write's own value and could never detect a difference -- this was
the first bug found while implementing the gate.
- Union only fires when both raw_ids are known and differ. Equal raw_ids
(same acquisition re-parsed), unknown provenance on either side (e.g.
`ArchiveStore.write_parsed()`'s direct path used by demo seeding and
most unit tests -- no positive evidence of a different acquisition), or
`force_replace=True` (the caller already made its own authoritative
precedence call, e.g. `ingest_precedence.browser_capture_precedence()`
deciding a fuller native capture supersedes a weaker DOM-fallback one)
all fall back to plain replace, unchanged from before this feature.
Test changes:
- `test_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rollup`
is restored to its original, unmodified assertions (neither write passes
a raw_id, so this exercises the "unknown provenance -> replace" branch,
which is the correct outcome for a same-acquisition correction).
- `test_reingest_with_poorer_export_unions_fields_instead_of_deleting_them`
now passes two DIFFERENT raw_ids (matching the real April/July export
scenario) and documents why that's what makes it the union path.
- New `test_reingest_with_same_raw_id_replaces_instead_of_unioning`
explicitly exercises the `existing_raw_id == raw_id` branch (not just
the "no raw_id supplied" fallback), simulating a real `reprocess`
parser-bugfix re-run.
Verification:
devtools test tests/unit/storage/test_archive_tiers_write.py
76 passed
devtools test tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_prepared_session_rows.py tests/unit/storage/test_archive_tiers_archive.py tests/unit/storage/test_bulk_fts_prefix_reextract.py tests/unit/storage/test_fts_bloat_invariants.py tests/unit/sources/test_browser_capture.py tests/unit/storage/test_fts_identity_ledger.py tests/unit/storage/test_embedding_rebuild_survival.py tests/unit/pipeline/test_ingest_batch.py tests/unit/sources/test_chatgpt_normalization_survivors.py tests/unit/storage/test_archive_tiers_write.py
567 passed, 1 failed (test_archive_tiers_api_raw_artifacts_read_source_tier,
reproduced identically against unmodified origin/master -- pre-existing
clock-freeze gap in revision_governance.py, unrelated to this change)
devtools test tests/unit/daemon/test_daemon_bulk_rebuild_responsiveness.py tests/unit/devtools/test_pytest_supervisor.py tests/unit/cli/test_terminal_snapshots.py tests/unit/devtools/test_render_quality_reference.py
29 passed, 2 failed (docs-content and live-CLI-snapshot tests that do
not import archive_tiers/write.py at all -- pre-existing/environment)
ruff format --check / ruff check / mypy --strict polylogue/storage/sqlite/archive_tiers/write.py
clean
devtools render all --check
OK, no drift
Ref polylogue-geop
Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 25 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 Plus Run ID: 📒 Files selected for processing (2)
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 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 77dce3fdb1
ℹ️ 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".
| merged_message_rows.append( | ||
| tuple(_coalesce_scalar(new_v, old_v) for new_v, old_v in zip(row, existing_row, strict=True)) | ||
| ) |
There was a problem hiding this comment.
Recompute message metadata after restoring blocks
When an incoming message remains but drops a tool-use, thinking, or paste block, this scalar merge keeps the incoming non-null zero flags and incoming content_hash; the later block loop then restores the old block. _refresh_session_counts() consequently derives counts from flags that contradict the stored blocks, and the message hash no longer describes its stored content. Recompute block-derived message fields and the message content hash from the final unioned block set.
Useful? React with 👍 / 👎.
Independent verification pass on the ChatGPT-export union bead: traced the already-merged fix (write_parsed_session_to_archive's raw_id- discriminated _union_with_existing_rows, #3413) end to end, cross-checked it against the live archive (Oct-2025/April-2026 chatgpt cohorts resolve correctly today), and confirmed both AC clauses hold with the regression test the AC asked for already in place. An attempted redundant top-level fix (a content-blind "refuse the whole write" guard) was reverted after it broke the same-acquisition retraction test that #3413's raw_id discriminator exists to protect -- see the closing note for detail. Residual sidecar/usage-rollup union scope stays tracked in the already- filed follow-up polylogue-u8x7. Ref polylogue-geop
…eld-path union (#3524) ## Summary Closes a gap flagged in PR #3413's review: field-path union can reconcile/reinject a message or block that a newer acquisition dropped, but its attachment/paste-span/file-edit/citation metadata still silently vanished because those four projection tables are rebuilt solely from the incoming `ParsedSession`, never from the union's reconciled rows. ## Problem `attachment_refs`, `paste_spans`, `file_edits`, and `web_content_constructs` are rebuilt from the incoming `ParsedSession`'s domain objects on every full replace. A reinjected message surviving the field-path union (`_union_with_existing_rows`) was not enough — its sidecar evidence rows were still lost unless captured before the replace's DELETE cascade and restored after the incoming rebuild. ## Solution - `_union_with_existing_rows` now returns a `_ProjectionCarryForward` (pre-delete captured rows + a block_id remap + surviving message ids) alongside the unioned rows. - `_capture_session_projection_rows` snapshots the four tables before delete; `_restore_captured_projection_rows` re-inserts any row whose owning message survived and whose slot the rebuild didn't reclaim, remapping `block_id` through position shifts. - `_splice_merge_keys` preserves a reinjected message/block's relative transcript order (naive append would silently reorder the conversation). - `_block_structural_keys` matches blocks by content-addressed identity (`tool_id`, else Nth-occurrence-of-type) instead of raw position, since a dropped non-trailing block shifts its siblings. - `_message_content_hash_from_rows` recomputes a merged message's stored hash/flags from its final reconciled block set. **Bug found and fixed while landing this** (not present in the original diff as committed, since it was never run to completion): the attachment-projection restore ran *after* `_write_attachments`' own stale-attachment ref-count sweep. An attachment whose `attachment_refs` row had already been cascade-deleted by the replace, but not yet restored, had its `ref_count` computed as 0 and its `attachments` row swept outright — the later restore then failed its FK to `attachments(attachment_id)`. Fixed by excluding attachment ids projection carry-forward is about to restore from the sweep's `refresh_attachment_ids` set. This work was found sitting as an uncommitted dirty diff in a stale agent worktree whose own prior commits (the field-path-union feature itself) had already landed via PR #3413's squash-merge. ## Verification - `devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_index_generation.py tests/unit/storage/test_attachment_first_class_ids.py` → 115 passed. - `devtools verify --quick` → 19 steps, exit 0. Ref polylogue-geop Co-Authored-By: Claude <[email protected]> Co-authored-by: Claude <[email protected]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Full-session re-ingest previously did
DELETE FROM messages WHERE session_id=?followed by a blind re-insert. A field-path union coalesce now runs ahead of
that delete, but only when there is positive evidence this write is a
genuinely different raw acquisition of the same logical session — not a
same-acquisition re-parse.
Problem
Measured on chatgpt (
polylogue-geop): a 2026-07 export of the sameconversations as a 2026-04 export dropped the entire tool/system role layer
(24,914 tool messages, 20,384 code blocks) and, within citation records both
exports still carried, dropped keys one level deeper
(
start_idx/end_idx/matched_text/refs/safe_urls/error/status/style)while keeping identical record counts and byte-identical message text. Field
walk over 44,171 common messages: 291,774 field observations agreed, 2,479
"conflicts" were strict key-subsetting (never a real disagreement), 453,956
were April-only, zero were July-only.
Latest winssilently deletes data aprior acquisition already supplied.
A first pass at the fix applied field-path union unconditionally to every
full-session replace. Review caught that this conflates two structurally
different causes of a full replace, confirmed by running the wider suite
(
devtools verify --seed-testmon --skip-slow), which broke ~19 tests:download, a later browser capture) are independent partial observations —
they should union.
bugfix or corrected message-boundary logic) is a better reading of the same
evidence and must be able to retract a value the old parse got wrong —
unioning here makes every historical mis-parse immortal and defeats the
point of a
reprocessre-run. This is exactly whattest_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rolluppins, and what the 19 browser-capture/native-vs-DOM-fallback precedence
tests (
ingest_precedence.browser_capture_precedence()deciding a fullernative capture supersedes a weaker DOM-fallback one, via
force_replace)encode as a caller-decided supersession.
Solution
polylogue/storage/sqlite/archive_tiers/write.py:_union_with_existing_rowsruns before the full replace's delete, readswhat's currently stored, and merges it against the freshly-built row
tuples for
messages/blocks— but only fires when there is positiveproof of a different acquisition:
raw_idis content-addressed (SHA-256 of the acquired bytes,pipeline/services/acquisition_records.py) and is carried forwardunchanged by a
reprocess(parse-only) re-run of the same raw file(confirmed via
pipeline/ingest_support.py's stage table and the parsebacklog in
pipeline/services/planning_runtime.py, which loads theexisting
RawSessionRecordrather than recomputing an id).write_parsed_session_to_archive) capturessessions.raw_idfor this session before its own upsert overwritesit, and threads both the incoming and prior raw_id down.
unknown provenance on either side (e.g.
ArchiveStore.write_parsed()'sdirect path used by demo seeding/most unit tests), or
force_replace=True(an explicit caller precedence decision) all fallback to plain replace — unchanged from before this feature.
else the stored value survives — mirroring the existing
sessions.title-styleCOALESCE(excluded.x, table.x)upsert pattern).blocks.tool_input(the one non-scalar column) gets a recursivefield-path JSON union (
_merge_json_value) — this is what restores droppedcitation keys; block
content_hashis recomputed from the merged fieldssince it feeds citation/evidence matching.
verbatim (position reassigned only on collision — safe because
native_idalready makes
message_idposition-independent).block_typematches at that position — are-parse that reorders/replaces what occupies a slot is a different block,
not a partial observation of the old one (block identity is
content-addressed, not position —
svfjalready excludestool_id/position from the evidence hash for the same reason).resolved parent of a prefix-sharing lineage child — the child's stored
branch_point_message_idis load-bearing, and resurrecting a message aparent's own re-ingest intentionally dropped would fabricate a prefix the
correction just removed.
What each test now covers
test_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rollup(unchanged from before this PR): neither write passes a
raw_id, so thisexercises "unknown provenance → replace" — a same-acquisition correction
retracting a stale model attribution.
test_reingest_with_poorer_export_unions_fields_instead_of_deleting_them(new): passes two different
raw_ids (matching the real April/Julyexport scenario) — pins the union path, asserting a dropped tool-role
message and narrowed citation keys are both restored.
test_reingest_with_same_raw_id_replaces_instead_of_unioning(new):explicitly exercises the
existing_raw_id == raw_idbranch (sameacquisition, corrected message-boundary re-parse) — the retraction must
survive, not get unioned back.
Deferred scope
Filed as
polylogue-u8x7:web_content_constructs/file_editsare sidecartables populated only from the current acquisition's parsed domain objects,
so a reinjected message's citation/edit sidecar rows aren't restored yet;
session_events/session_model_usagearen't unioned either, so a reinjectedmessage's model rolls up with zero usage. Both need the same
raw_id/force_replacediscriminator extended per-table.Verification
One pre-existing failure was investigated and excluded:
test_archive_tiers_api_raw_artifacts_read_source_tier(a clock-freeze gapin
revision_governance.py's_raw_parse_success_state) reproducesidentically against unmodified
origin/master, confirmed by temporarilyswapping in the master version of the touched file and re-running the test in
isolation.
Ref polylogue-geop
🤖 Generated with Claude Code