Repository navigation
fix(storage): carry forward evidence-dependent projections through field-path union - #3524
Conversation
…eld-path union Problem: PR #3413 review flagged that attachment_refs/paste_spans/ file_edits/web_content_constructs are rebuilt SOLELY from the incoming ParsedSession's domain objects on every full replace, never from the field-path union's reconciled/reinjected row tuples. A reinjected message's transcript row surviving the union was not enough -- its attachment, paste-span, file-edit, and citation metadata still silently vanished unless that metadata was captured before the replace's DELETE and re-inserted after the incoming rebuild. What changed: - _union_with_existing_rows now returns a _ProjectionCarryForward (captured pre-delete projection rows + a block_id remap + the set of message ids that survived reconciliation) alongside the unioned message/block rows. - Two new helpers close the four gaps: _capture_session_projection_rows snapshots attachment_refs/attachment_native_ids/paste_spans/file_edits/ web_content_constructs before the delete cascade; _restore_captured_projection_rows re-inserts any row whose owning message survived the merge and whose slot the incoming rebuild didn't reclaim, remapping block_id references through the reconciliation's position shifts. - _splice_merge_keys preserves a reinjected message/block's RELATIVE transcript order (naive append would silently reorder the conversation, worse than dropping it since it's invisible). - _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 trailing siblings' positions and raw-position matching would corrupt the shifted survivor. - _message_content_hash_from_rows recomputes a merged message's stored hash/flags from its final (possibly reconciled) block set, so they don't keep describing content that no longer matches what's stored. Found sitting as an uncommitted dirty diff in a stale agent worktree whose own prior commits (this file's field-path-union feature itself) had already landed via PR #3413's squash-merge; this follow-up had not been tested or committed. Discovered and fixed one real bug while landing it: the attachment-projection restore ran AFTER _write_attachments' own stale-attachment ref-count sweep, so an attachment whose attachment_refs row was cascade-deleted by the replace and not yet restored got 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 that projection carry-forward is about to restore from the sweep's refresh_attachment_ids set. 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 (80 + 35, with attachment_first_class_ids folded into the second run). devtools verify --quick -> 19 steps, exit 0. Ref polylogue-geop Co-Authored-By: Claude <[email protected]>
|
Warning Review limit reached
Next review available in: 21 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: 4f7c3b7369
ℹ️ 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".
| row_list[has_tool_use_idx] = ( | ||
| 1 if any(b[b_idx["block_type"]] == BlockType.TOOL_USE.value for b in final_blocks) else 0 | ||
| ) | ||
| row_list[has_thinking_idx] = ( | ||
| 1 if any(b[b_idx["block_type"]] == BlockType.THINKING.value for b in final_blocks) else 0 | ||
| ) |
There was a problem hiding this comment.
Recompute paste flags when restoring paste spans
When a newer acquisition retains a message but omits its previously observed paste_spans, the restoration code re-inserts those spans, while this recomputation updates only has_tool_use and has_thinking. The message therefore keeps the incoming has_paste = 0, and _refresh_session_counts records paste_count = 0, so paste-filtered queries exclude a message that has stored paste evidence. Recompute has_paste and paste_boundary from the final carried-forward spans as well.
Useful? React with 👍 / 👎.
|
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 Restore the corpus, progress receipt, hash and incremental-work verification contracts behind six historical findings. Attachment ingestion keeps native authored turns, lineage and durable bytes through ordinary parsing and retained replay. ## Problem Executable corpus generators supplied arbitrary transcript bytes; Attach projected native transcripts into a lossy single-turn envelope. Nested progress tests could steal the managed run ledger. The restored-content hash fixture expected unequal hashes for equal content. The incremental law allowed archive-wide refreshes through relaxed budgets and incomplete SQL measurement. The original findings remain linked in polylogue-kx9vb: [F003](#3889 (comment)), [F004](#3889 (comment)), [F048](#3956 (comment)), [F081](#3524 (comment)), [F088](#3842 (comment)), [F089](#3890 (comment)). ## Solution - Generate provider-valid native acquisitions/appends/replacements, and require actual retained admission and convergence evidence before advancing reference operations. - Keep native provider records in the existing capture envelope, delegate to ordinary Codex/ChatGPT/Claude parsers, and merge durable attachment evidence. Guard native/envelope identity and witnessed idless ownership. Preserve native ordering, semantic fields, selected leaf and fork lineage on replay. - Bind the loaded progress plugin's destinations to its session, isolate nested hook tests and verify the real outer ledger. - Compare final semantic message fields and exact ordered blocks before equal production hashes; changed content is a separate negative control. - Measure actual SQLite statements and VM work. Require zero archive-wide derived writes and fixed-component work stable at sizes 2/8/32. Sixty-two populated write/reset/DROP mutants and an archive-wide read negative control exercise ordinary SQL owners, including quoted/qualified targets, conflict modifiers and SQL comments. Comment-looking bytes inside quoted tokens are preserved. Raw SQLite FTS shadow traces remain measurable VM evidence. ## Verification Final candidate: `2e44e4fb4c11b0c2f8d2385262efb31f4164e549`, tree `d901f0d94508e92d9e7f7355dedaa54404ec1527`, including master `ca80dade13d9bf51a4c4eed9fd1cb04be8b4751c`. ```sh agentctl job start polylogue pytest_focused --workspace /realm/worktrees/polylogue-verification-p1 -- tests/unit/storage/test_rebuild_complexity.py -q agentctl job start polylogue verify_quick --workspace /realm/worktrees/polylogue-verification-p1 ``` - Job 5435: **69 passed in 2088.51s**, exit 0, receipt `20261001T065605Z-focused-test-11546-a3be8b3e`, on the clean unchanged candidate. Selected/setup/call/teardown/terminal sets are exactly equal (69 each). All 62 populated mutants, strict baseline, unrelated-growth read control, scoped/literal controls and the actual FTS shadow VM witness passed. - Job 5436: **all 12 gates passed**, exit 0, receipt `20261001T065607Z-quick-11633-8fcbd248`, on the clean candidate. Earlier complete verification is reused only where its files and production dependencies remain unchanged: ```sh agentctl job start polylogue pytest_focused --workspace /realm/worktrees/polylogue-verification-p1 -- tests/infra/test_corpus_program.py tests/infra/test_timeout_policy.py tests/unit/devtools/test_pytest_progress_plugin.py tests/unit/storage/test_rebuild_complexity.py tests/unit/storage/test_archive_tiers_write.py tests/unit/sources/test_browser_capture.py tests/unit/maintenance/test_browser_spool_restoration.py -q agentctl job start polylogue pytest_focused --workspace /realm/worktrees/polylogue-verification-p1 -- tests/unit/sources/test_browser_capture.py tests/unit/maintenance/test_browser_spool_restoration.py -q ``` Job 5403: **345 passed in 1932.86s**, exit 0, receipt `20261001T050040Z-focused-test-3975611-05cd7b7f`, on clean `18c25b2e467ba108b30fefff09e99a1819db6bc6`. Selected/setup/call/teardown/terminal sets are exactly equal (345 each), including the loaded outer plugin receipt. Its corpus, timeout, plugin and archive writer/hash scope is unchanged. Its earlier SQL measurement is superseded by job 5435. Job 5418: **105 passed in 50.55s**, exit 0, receipt `20261001T055219Z-focused-test-4080362-18b92b28`, on clean integrated `f2af9adf78a83a87e7ea2b2e0fc85f9743db1210`. The five event/selection sets contain exactly the same 105 nodes. These parser/spool files and production dependencies remain unchanged. The master integration changed daemon/read consumers; this complete two-module selection covered them. All 19 owned files outside the SQL counter and complexity test are byte-identical to that reviewed head. This does not claim that all 345 tests ran on the final candidate. The independent full-diff review found SQL comment spellings that bypassed the global-write classifier. The correction covers all sibling header positions and protects quoted identifiers/literals. Job 5423 then reported **67 passed and 1 failed in 2305.49s**; its unchanged-tree retry also failed. The scoped fixture incorrectly required one trace although SQLite repeats trigger traces and opening an archive performs other-tier bootstrap writes. The correction asserts real changed rows and every relevant index trace. An actual FTS diagnostic also exposed dropped shadow VM attribution; the final counter keeps raw trace evidence separate from normalized classification, and its new populated regression observes real positive FTS shadow VM work. The original diagnostic reported 156 passed and 3 failed, including an actual 120-second timeout during progressing 32-session work. Explicit timeout 0 now uses managed progress/cancellation; the timeout was not raised and the comparison corpus was not reduced. Earlier complete-selection failures and unchanged-tree diagnoses remain recorded in the task. Job 5401 failed the identifier extraction typing gate (11 gates passed), corrected before 5403/5404; job 5400 was cancelled before collection. A passing retry of the transient accepted-await failure does not establish its runtime cause. ## Self-review Author full-diff review on clean 2e44e4f/tree d901f0d against master ca80dad. All 21 owned paths and connected call paths were reread in this context. The final cumulative two-path correction was reviewed as new code; no remaining concrete code finding. Full SQL job 5435 passed 69 tests in 2088.51 seconds on this clean unchanged head, receipt 20261001T065605Z-focused-test-11546-a3be8b3e; selected/setup/call/teardown/terminal sets are exactly equal (69 each). Final quick 5436 passed all 12, receipt 20261001T065607Z-quick-11633-8fcbd248. Independent whole 21 review at f2af remains valid for 19 unchanged blobs; final cumulative correction review and exact receipt readback are clean on the same immutable head. Earlier original 156 passed/3 failed and 120-second timeout and all subsequent diagnostics remain visible. In particular, 5423 failed with 67 passed/1 failed (same unchanged-tree retry), caused by invalid single-trace fixture expectation; FTS shadow diagnostic also exposed dropped actual VM work. Both corrected in 2e. 1. ✓ Siblings and owners. Both corpus generators construct native-valid Acquire/Append/Replace. Native identity is checked before merge in all three native provider routes (definition+3 call sites). The SQL census covers all five derived surfaces, all actual action/FTS/delegation scoped owners, and supported target quote/qualification/conflict/comment forms. Genuine comments are stripped once for write classification; raw SQLite trace annotations remain VM evidence. No new source exclusion or detector owner was introduced. 2. ✓ The fix itself. Re-read every owned hunk as new code. Source-revision reuse prefers exact source/path/wire evidence, then independently retained equal-wire evidence. Idless attachments require explicit retained ordinal plus actual parsed role/text, then the existing private owner coordinate. Target normalization protects quoted tokens and preserves scoped predicate checks. Real FTS shadow VM work remains measured; the recorder control allows actual trigger trace repetition and asserts every index event retains the declared literal. 3. ✓ Memory and limits. Native arrays are streamed record by record into a constant-size digest/root-shape placeholder. Synthetic fixture helpers materialize only their generated transcript. Identifier-token matches cover at most a two-part target, not archive rows. No new acceptance cap; explicit timeout(0) delegates the progressing 32-session seed to managed cancellation instead of increasing its 120-second cutoff. 4. ✓ Cost per unit. The selected component stays one at archive sizes 2, 8 and 32. Real SQLite VM progress and trace callbacks measure work. Global writes must be exactly zero; fixed-component VM work cannot grow with unrelated rows. No statement budget or multiplier. The archive-wide read mutant tests the second law independently. 5. ✓ Interruption. Acquisition/parsing backends close in finally. Reference operations advance only after acquired/parsed/converged evidence. Restart and cold retained replay are exercised. The loaded progress plugin restores prior active session/environment/ledger in its existing sessionfinish finally. 6. ✓ Ordering and races. Acquired bytes and path key source revisions. Native mapping insertion order is preserved in attachment wire serialization; record order remains fingerprint-sensitive. Selected composed leaf is independently asserted as child-tail before comparing all semantic fields. Managed checks bind clean frozen heads; final quick 5436 binds clean 2e44e4f, and full affected SQL job 5435 passed on that same head. 7. ✓ Failure classification. Actual AcquireResult errors, ParseResult failures and failed/pending FileState produce typed corpus refusals. Native/envelope identity disagreement refuses before evidence composition. Missing/conflicting ordinal witness refuses. No broad SQLite/OSError exclusion handler was added. 8. ✓ Silent outcomes. Known skipped duplicate admission requires retained byte proof. Failed parsing or pending daemon stages cannot mark Converge applied. The retained job 5403 receipt proves 345 selected/call/terminal nodes on 18c, including the outer plugin events; the plugin scope is unchanged. Quick alone proves no behavior. 9. ✓ Cleanup on failure. Existing backend finally cleanup survives new refusal paths. Nested hook tests use a fresh module and monkeypatch restoration; the real loaded outer plugin keeps its own ledger. All archives/probes remain isolated synthetic scratch, with no live service mutation. 10. ✓ Identity and keys. Native provider IDs remain unchanged; no ordinal-based provider ID fabrication. All three native session branches refuse identity conflicts. Equal actual semantic fields and exact ordered blocks are asserted before equal production hashes, with changed-content negative control. No reverse Origin-to-Provider lookup or product hash change. 11. ✓ Lossless transforms. Ordinary native parsers own message fields/topology. Capture raw records and durable attachment descriptors replay through the same parser/writer. Exact stored row/position/hash oracles cover web providers; composed child transcript normalizes only physical ownership and contextual leaf while asserting actual selected leaf identity. Source field-choice rules are checked at both modern/legacy fork carriers. 12. ✓ Degenerate inputs. Tests cover empty/unsupported Codex arrays, malformed bytes/JSONL, foreign IDs, missing/negative/outside/role/text ordinal witnesses, same-byte duplicate coordinates and A→B→A source revisions. Timeout policy rejects booleans, negatives, nonfinite values and nonnumbers; zero remains explicit cancellation semantics. 13. ✓ Consumers. Model, stream summary, ordinary native parser, attachment fixture helper, docs and ownership census agree. Existing envelope remains the retained format; no Codex page UI support claimed. Synthetic single-turn/original_payload_b64 predecessor and relaxed SQL budgets are removed. Coordinated browser compact retirement is preserved for its separate owner. 14. ✓ Tests and stubs. Real acquisition/parsing and daemon convergence run; public ingestion fixtures enable the required resident derivation capability while a negative test preserves its refusal. SQL mutants execute once on populated production-opened relations and prove actual changed rows/index contents before the law rejects them. All five INSERT conflict modes use fresh rowids to ensure IGNORE is nonvacuous. Loaded plugin surrounds real nested pytest. 15. ✓ Trust boundaries. Native identity guards precede attachment/events merge. Public fixtures contain neutral synthetic content only; private analyses, run receipts and databases are untracked. Refusal text avoids native session IDs. No paid provider or operator archive calls. 16. ✓ Devtools selection. The seven-file receipt 5403 binds 345 selected/call/terminal nodes to clean 18c; final parser/spool receipt 5418 binds 105 nodes to clean f2af. Only their unchanged scopes are reused. Cumulative SQL corrections passed complete module 5435 on 2e (69 nodes, identical selected/report/terminal sets). Final quick 5436 passed all 12 gates including closure. No zero-test or corpus fallback. The prior 5401 failure remains visible; 5400 cancelled before collection, not reported as tests run. 17. ✓ Index/ops evolution. Model code lies in the computed derived closure; stream/parser do not. No manual identity bump or derived migration. Post-master old private archive correctly refused SchemaSkew rather than weakening validation. Earlier clean 18c fixtures passed 345 tests; the strict baseline completed in 220.009 seconds. Current corrected SQL job 5435 passed 69 tests. No timeout increase or weakened law. 18. N/A Embeddings durability. No embeddings DDL/version/vector replacement/deletion. New archives are synthetic fixture roots using existing initialization. 19. N/A Durable enum checks. No durable DDL or vocabulary changes. Existing durable-enum-checks gate remains required. 20. ✓ Writer authority. Public facade fixtures use existing daemon_serving_archive with session_derivation capability; direct mutation is isolated declared fixture/replay setup only. No new live write bypass or authority. 21. ✓ Durable mutation authority. Source retains native records and attachment bytes; index derives parsed ownership from that evidence. Neither an ephemeral parsed overlay nor a rebuilt index row becomes durable authority. Generic: 1. ✓ Assigned criteria. Six original findings have actual production-route regressions; prior 5403/5404 passed on 18c, final browser consumers 5418/5419 passed on f2af, and quick 5436 passed on 2e. Corrected full SQL 5435 passed 69 tests; final independent correction readback is clean. Original identities and inherited failures are retained; no unrelated Bead closes. 2. ✓ Every site. Sibling searches covered both generators, three native merge routes, loaded plugin event/selection/summary/worker writers, all five SQL surfaces and the actual scoped SQL builders. New target census covers four quote forms, main/temp qualification, case folding and all five INSERT/UPDATE conflict modes; quoted DELETE/DROP/control variants share its owner. 3. ✓ Complete changes. Connected model/stream/parser/caller/docs/census/tests are changed together; deleted single-turn/opaque payload and relaxed-budget predecessors have no new callers. No dual format/identity authority added. 4. ✓ Visible failures. Typed acquire/parse/native identity/ownership refusals reach their actual caller. Pending stages do not imply completion. Original 120-second timeout and transient accepted-await failure stay visible; green fixture checks do not claim an unproved runtime cause fix. 5. ✓ Anti-vacuity. Empty generated Append was observed to fail actual native-ID oracle in job 5167. Rich/restored hashes require independently equal final fields+ordered blocks; changed text differs. All 62 actual populated once-per-pass write/reset/DROP mutants must be rejected, plus actual unrelated-growth read negative control. All 62 passed precursor 5423; final 5435 reproved them with raw FTS accounting restored. Its dedicated populated FTS control requires positive observed shadow VM work, without inventing a numeric budget or attributing data_version PRAGMA work to derived tables. Removing native raw records, identity guard, fork carrier or ownership coordinate breaks exact retained/replay assertions. 6. ✓ Public boundary. Read all 21 owned paths; only synthetic fixtures tracked. Private receipts/probes/archives excluded. Publication will give exact commands/run IDs, not transcript/private analysis content. ## Residuals Verification covers the named selections, not the full corpus or operator archive. The operation.await lifecycle defect remains with its separate source foundation owner; this change makes no runtime cause claim. The operator disabled further hosted Codex requests; the full 21-file independent review at f2af is retained, and its final two-file correction readback is clean at 2e. Publication requires required statuses and resolution of all six existing review threads.
|
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
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, andweb_content_constructsare rebuilt from the incomingParsedSession'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_rowsnow returns a_ProjectionCarryForward(pre-delete captured rows + a block_id remap + surviving message ids) alongside the unioned rows._capture_session_projection_rowssnapshots the four tables before delete;_restore_captured_projection_rowsre-inserts any row whose owning message survived and whose slot the rebuild didn't reclaim, remappingblock_idthrough position shifts._splice_merge_keyspreserves a reinjected message/block's relative transcript order (naive append would silently reorder the conversation)._block_structural_keysmatches 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_rowsrecomputes 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 whoseattachment_refsrow had already been cascade-deleted by the replace, but not yet restored, had itsref_countcomputed as 0 and itsattachmentsrow swept outright — the later restore then failed its FK toattachments(attachment_id). Fixed by excluding attachment ids projection carry-forward is about to restore from the sweep'srefresh_attachment_idsset.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]