Skip to content

fix(storage): union messages/blocks across acquisitions, not re-parses - #3413

Merged
Sinity merged 2 commits into
masterfrom
feature/storage/field-path-union-coalesce
Jul 31, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/storage/field-path-union-coalesce

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

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 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. 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 wins silently deletes data a
prior 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:

  • Two different acquisitions of the same logical session (a second export
    download, a later browser capture) are independent partial observations —
    they should union.
  • 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 and defeats the
    point of a reprocess re-run. This is exactly what
    test_provider_usage_model_vanishing_on_reingest_leaves_no_stale_rollup
    pins, and what the 19 browser-capture/native-vs-DOM-fallback precedence
    tests (ingest_precedence.browser_capture_precedence() deciding a fuller
    native 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_rows runs before the full replace's delete, reads
    what's currently stored, and merges it against the freshly-built row
    tuples for messages/blocks — but only fires when there is positive
    proof of a different acquisition
    :
    • 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 caller (write_parsed_session_to_archive) captures
      sessions.raw_id for this session before its own upsert overwrites
      it, and threads both the incoming and prior raw_id down.
    • Union fires only when both raw_ids are known and differ. Equal raw_ids,
      unknown provenance on either side (e.g. ArchiveStore.write_parsed()'s
      direct path used by demo seeding/most unit tests), or
      force_replace=True (an explicit caller precedence decision) all fall
      back to plain replace — unchanged from before this feature.
  • Matched messages/blocks coalesce column-wise (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) — this is what restores dropped
    citation keys; block content_hash is recomputed from the merged fields
    since it feeds citation/evidence matching.
  • A message/block entirely absent from the new acquisition is reinjected
    verbatim (position reassigned only on collision — safe because native_id
    already makes message_id position-independent).
  • A block only merges when block_type matches 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
    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 this
    exercises "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/July
    export 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_id branch (same
    acquisition, corrected message-boundary re-parse) — the retraction must
    survive, not get unioned back.

Deferred scope

Filed as polylogue-u8x7: web_content_constructs/file_edits are sidecar
tables 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_usage aren't unioned either, so a reinjected
message's model rolls up with zero usage. Both need the same
raw_id/force_replace discriminator extended per-table.

Verification

devtools test tests/unit/storage/test_archive_tiers_write.py
  76 passed

devtools test tests/unit/storage/test_archive_tiers_write.py 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/daemon/test_daemon_bulk_rebuild_responsiveness.py \
  tests/unit/devtools/test_pytest_supervisor.py
  309 passed

ruff format --check / ruff check / mypy --strict polylogue/storage/sqlite/archive_tiers/write.py
  clean

devtools render all --check
  OK, no drift

devtools verify --quick (pre-push hook)
  exit 0

One pre-existing failure was investigated and excluded:
test_archive_tiers_api_raw_artifacts_read_source_tier (a clock-freeze gap
in revision_governance.py's _raw_parse_success_state) reproduces
identically against unmodified origin/master, confirmed by temporarily
swapping in the master version of the touched file and re-running the test in
isolation.

Ref polylogue-geop

🤖 Generated with Claude Code

Sinity and others added 2 commits July 31, 2026 05:20
…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]>
@coderabbitai

coderabbitai Bot commented Jul 31, 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: 25 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 Plus

Run ID: 192a7239-e609-4722-9d22-e5ad7b97069e

📥 Commits

Reviewing files that changed from the base of the PR and between a9f2f30 and 77dce3f.

📒 Files selected for processing (2)
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/storage/test_archive_tiers_write.py

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +2332 to +2334
merged_message_rows.append(
tuple(_coalesce_scalar(new_v, old_v) for new_v, old_v in zip(row, existing_row, strict=True))
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@Sinity
Sinity merged commit db6274a into master Jul 31, 2026
3 checks passed
@Sinity
Sinity deleted the feature/storage/field-path-union-coalesce branch July 31, 2026 07:48
Sinity added a commit that referenced this pull request Jul 31, 2026
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
Sinity added a commit that referenced this pull request Aug 1, 2026
…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]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 76.F002 / P1: fixed-already at the checked revision: Cross-acquisition union splices the old and incoming native-message sequences before assigning new positions, so an omitted interior tool message retains its relative transcript position instead of moving after the assistant. See polylogue/storage/sqlite/archive_tiers/write.py:5900.
  • 76.F003 / P1: fixed-already at the checked revision: Blocks are matched using structural keys and merged as ordered sequences, not matched solely by their old positions; dropping an interior code block does not pair the shifted text with that code slot. See polylogue/storage/sqlite/archive_tiers/write.py:5950.
  • 76.F004 / P1: fixed-already at the checked revision: The union captures dependent projections before replacement and restores them after rebuilding incoming rows, including attachment refs, paste spans, file edits and web constructs belonging to carried evidence. See polylogue/storage/sqlite/archive_tiers/write.py:6029.

Only the rows listed above are dispositioned. Held findings remain open.

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