Repository navigation
fix(lineage): never strand an inheriting child; drop lineage depth caps - #5685
Conversation
A parent full replace that dropped a message some child had pinned as its branch point left that child composing to its bare tail, and a convergence debt row asked a daemon stage to re-derive the child later from its raw. The child's inherited prefix is evidence from the child's own bytes, so the writer now keeps it whole in the same write: before the replace it records what each direct prefix-sharing child inherits (parent-owned rows copied to TEMP tables), and after graph resolution a child whose branch point no longer resolves gets that prefix materialized into its own rows and stops inheriting (spawned-fresh, still linked). Descendants anchored in those rows follow them. A child whose branch point still resolves keeps inheriting the parent's current prefix, so in-place edits still propagate. Child source_message_id references nulled by the parent's delete are restored. The stranded-branch-point debt producer is deleted; the recompose stage keeps only the identity-contradiction loss, without its 64 MiB replay cap. Lineage walks also stopped at depth 64 (sync reader) or 1024 (writer, async reader, compact lineage), truncating valid chains although the visited set already guarantees termination. The caps, the depth_limit truncation reason and LINEAGE_ITERATIVE_DEPTH_LIMIT are removed; the sync plan is iterative. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
|
You have reached your Codex usage limits for security reviews. Please try again later. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dc42a38dc3
ℹ️ 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".
…refixes A parent replace that drops the last reference to an attachment sweeps the attachment row before the child's copied ref needs it; the guard now snapshots and restores those rows and refreshes their counts. A child with no stored tail gets its last materialized message as active leaf. Child source references are remapped when they still name the captured id, which is the state a bulk rebuild leaves with foreign keys off. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f891fde3ac
ℹ️ 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".
…hored refs The guard captured only a rewritten session's direct children. A deeper descendant that branched inside an intermediate session's inherited prefix, at a row the rewritten session owns, was stranded while its parent stayed composable; the capture now includes every edge anchored in the rewritten session's rows and settles shallower sessions first. Copied prefix rows keep their source (position, variant) coordinates when they fit below the child's own rows, so sibling variants stay one turn and position-based boundaries keep meaning; otherwise they are renumbered densely per source turn. Subagent edges dispatched from a copied tool call follow the block to the child (the delete nulls them), and the child's delegation facts are refreshed. A re-anchored child's own references into the relocated rows follow the re-anchor. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 475f7bb30d
ℹ️ 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".
…ries A materialized prefix spanning several ancestors copies rows the rewritten session never owned. Their attachment counts are now refreshed and the child's references into them remapped, not only the rewritten session's. When the tail must shift to fit the copy, its compaction boundaries shift too. A dispatch pointer resolves to the copy on the dispatcher's own lineage rather than any materialized sibling's. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0648090b4b
ℹ️ 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 ownership is now judged by the message's session, not its id text (a native id can extend another session's). Descendants at any depth whose branch point lies in a materialized copy's plan follow it. A re-anchored prefix maps unchanged rows in order across inserted rows, and dispatch pointers follow re-anchored blocks. The dispatcher lineage walk follows composing edges only. When the tail shifts, only boundaries over the tail move. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 137e505172
ℹ️ 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".
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013Vn4qhKjhyaVBG4aPiqNW4
…refs A compaction range that starts in the inherited prefix but ends in the tail shifted its endpoints together, so the tail-side endpoint stayed on the row it no longer addressed; each endpoint now shifts independently against the tail-start cut. A generated `message:<old_id>` attachment producer reference also stayed pointed at the pre-materialization row; it is now re-rooted onto the copy while a parser-supplied provider reference is left untouched. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4025a75a45
ℹ️ 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".
…dants Reanchoring matches an inherited row by its own surviving id before content signature, so a removed duplicate never takes the surviving row. Descendants that compose through a materialized copy remap their own source-message references, and dispatch pointers into a copied block of a still-live ancestor follow the copy. Compaction boundary endpoints shift independently in one statement, and materialization evidence is set on an object even when the edge held the default array. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1d2c0a6ffe
ℹ️ 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".
…riant # Conflicts: # docs/plans/derived-sweep-census.yaml
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 01c0285123
ℹ️ 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".
Materialization records an identity scope on the child's edge: the inherited message count and, per content identity, which prefix copies took content IDs. A replay of the child stays spawned-fresh and reproduces every stored ID from that scope -- tail identities computed over the tail alone, prefix copies native unless recorded -- and carries the scope forward (polylogue-5gg3u). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 43cc5cd7a9
ℹ️ 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".
The identity scope now records the copied prefix's content-identity sequence, so a replay finds the copied messages even after a message is prepended; positions are renumbered as materialization renumbered them, with compaction boundaries following; the scoped view wraps the parsed sequence so a disk-backed session stays streamed; and a materialized edge is never re-bound by its parser-asserted branch point. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9578f69823
ℹ️ 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".
…ve IDs A scoped replay places rows gained before the copied prefix below it and the tail above both, and a row outside the prefix that repeats a native ID a copied prefix row keeps takes a content ID instead of colliding. LineageCompleteness no longer documents a depth limit. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c1c235b287
ℹ️ 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".
…s appends Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: aa410c5971
ℹ️ 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".
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6f9214de59
ℹ️ 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".
…e linearly Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6724937bb9
ℹ️ 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".
…pies Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
There was a problem hiding this comment.
💡 Codex Review
polylogue/polylogue/storage/sqlite/queries/message_query_reads.py
Lines 184 to 186 in 48ce0d1
Fresh evidence beyond the full-message and synchronous-envelope fixes is get_messages_paginated(..., limit=1) for a 50,000-session chain whose children branch at their parents' final messages. _lineage_segments scans the growing segment tuple to find each branch owner and rebuilds that tuple here at every level, so even a one-row page performs roughly 1.25 billion segment visits/copies before issuing its bounded fetch; use the indexed mutable segment plan already adopted by the synchronous path. This file is in the derived-identity closure, so the fix must land before a rebuild starts.
Review-guide: v1
AGENTS.md reference: AGENTS.md:L105-L108
ℹ️ 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".
…segments, uncapped writer walk Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
…riant # Conflicts: # polylogue/storage/sqlite/archive_tiers/write.py
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…riant # Conflicts: # polylogue/storage/sqlite/archive_tiers/write.py
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…5799) ## Summary Prefix materialization now leaves no derived fact of a copied or moved row describing its former coordinates or owner (polylogue-ednjz, part 1 of 2): - stored message hashes equal what a replay computes; - copied tool uses pair with their results; - every message reference follows the copy its session composes; - dispatch pointers pick the call the dispatcher actually saw; - boundary coordinates and per-segment positions survive replay. ## Problem `_materialize_inherited_prefix` rewrites stored rows outside the parse that produced them. The Codex findings on #5685 grouped into this bead: - **Hashes.** Copied rows got a synthetic hash, and shifted tail rows kept hashes of their old positions, so the first unchanged replay rewrote them (`mwcAc`, `m5g9X`). - **Tool outcomes.** A copied tool use kept `no_result` although its result is in the child's own tail (`mwcAh`). - **References.** - A descendant's reference into a deleted row was nulled by the foreign key before a copy existed (`m2Jqk`). - `boundary_message_id` kept naming a vanished row (`m5g9i`). - A tail message's parent across the prefix boundary was never resolved (`m5Es0`). - **Dispatch.** - A reused generated block id was taken for the dispatched call (`mwcAn`). - Delegation facts were refreshed for the copy owner instead of the resolved dispatcher (`m2Jqd`). - **Edges and coordinates.** - The guard kept an arbitrary edge of a child with two prefix-sharing edges (`m2Jqg`). - A boundary on a renumbered inherited position was shifted instead of mapped (`m5g9S`). - Scoped replay keyed prefix positions by position alone, collapsing rows that materialization had kept apart by source session (`m5g9n`). ## Solution - **Message hash from stored columns.** New storage-only `messages.fields_digest` (the message's own fields: text, role, model, ...). `content_hash` = frame(identity, coordinates, `fields_digest`, block parts). `_message_row_hash` computes it from a parse or from stored rows, so `_rehash_session_messages` gives copied and shifted rows exactly the replay's hash. The field-path merge paths use the stored digest too, and no longer drop the message text. - **Outcomes.** After the copy, `_reconcile_tool_use_outcomes` re-pairs the child's tool uses, then its messages are rehashed. - **References.** The guard captures every message-reference column into a TEMP table: - `source_message_id` on events, usage and policies; - `session_events.boundary_message_id`; - `messages.parent_message_id`. It covers the children's references into any inherited row and every other session's references into rows this write deletes. `_restore_message_refs` points each at the copy its own lineage holds, else a re-anchored row, else the surviving old row. The writer now resolves a tail message's parent through the inherited-id map. - **Dispatch.** A captured pointer first follows the copy its resolved dispatcher's lineage holds. Otherwise the old block survives only if it is the same call by its evidence (type, tool id, name, input). The resolved dispatcher's delegation facts are refreshed on every restore. - **Edges.** The guard follows the edge readers compose (`ORDER BY link_type, dst_origin, dst_native_id`). Materialization flips every prefix-sharing edge of the child, since it now owns its whole transcript. - **Coordinates.** - A boundary endpoint on a tail row moves with the tail; one on an inherited position follows the copied row (first or last copy for start or end); a gap above the tail start moves with it. - The identity scope records the renumbered prefix positions as runs, and scoped replay applies them per row. Schema classification: additive-derived (a nullable `messages.fields_digest` column). The message-hash formula changes, so the derived identity moves. `write.py` is in the closure: this must land before the fresh rebuild. ## Verification - `agentctl … verify_quick` on the branch: Success (job 2222). - `agentctl … pytest_focused -- tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_compact_lineage.py tests/unit/storage/test_branch_point_witness.py` (job 2223): everything passes except the 3 provider-usage tests that fail identically on master (polylogue-ezvw3). - New regression tests, one per finding: `test_materialized_rows_carry_the_hash_a_replay_computes`, `test_materialization_hashes_match_the_first_replay`, `test_a_copied_tool_use_pairs_with_the_result_in_the_child_tail`, `test_the_tail_stays_connected_to_the_copied_prefix`, `test_a_compaction_boundary_on_the_prefix_follows_its_copied_rows`, `test_a_boundary_message_id_follows_the_copied_row`, `test_an_uncaptured_descendant_reference_to_a_deleted_row_follows_the_copy`, `test_a_reused_block_id_is_not_taken_for_the_dispatched_call`, `test_a_dispatch_pointer_follows_the_copy_its_dispatcher_composes`, `test_a_guard_follows_the_edge_readers_compose`, `test_a_scoped_replay_keeps_per_segment_prefix_positions`. The existing boundary tests (`test_renumbered_tail_moves_its_compaction_boundary`, `test_prefix_compaction_boundary_stays_on_the_copied_rows`) still pass under the new endpoint rule. ## Self-review I read the complete diff line by line against each finding. What I checked: - **Hash equivalence.** Stored block parts equal parsed block parts: the writer stores exactly the `_json_dumps` input, semantic type, language and `_sqlite_text` values the parse hashes. The tool-use and hash tests confirm replay equality empirically. A row lacking `fields_digest` (test fixtures inserting rows by SQL) falls back to a digest of its stored columns without text, the same narrowing the removed from-rows functions had. - **Reference restoration.** - It is idempotent: a row is updated only while it still holds NULL or the old id, and only to an existing row. - A plain-text boundary id is matched by the old id. - An unrecoverable reference stays NULL, as before. - Lineage-owner lookups are memoized per (session, old id). - **Endpoint rule.** A tail row takes precedence over an inherited source position, which matches both existing boundary tests. NULL endpoints stay NULL. - **Flipping every prefix-sharing edge.** Correct for a materialized child, since any remaining composing edge would put a second prefix in front of its copy. Future writes already force spawned-fresh through the identity scope. - **Dispatch order.** The lineage copy is preferred over an in-place survivor, because the dispatcher composes the copy. The evidence comparison is used only when no copy exists. - **Residual risks.** - `m2Jqd`: dispatch actions are owned-block scoped, so after materialization a dispatcher that does not own the copied call still has an edge-only delegation row. Refreshing it is correct, but no current column differs, so no test can distinguish the change. It is kept because the row must track the restored pointer. - `m5Esr` (settlement holds the composed signature lists, `sources` and `plan` in Python for a whale child) is not in this PR. It is the second part of polylogue-ednjz, which stays open. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
## Summary Settlement of a parent rewrite no longer holds any child's inherited prefix in Python (polylogue-ednjz, part 2 of 2; Codex finding `m5Esr` on #5685). The guard, the reanchor matching, the materialization plan and the before/after comparison stream through connection-private TEMP tables. ## Problem `_capture_inherited_prefixes` built each inheriting child's composed signature list and kept its inherited ids and signatures as Python tuples, for every child at once. `_settle_inherited_prefixes` composed each child again into a list. `_materialize_inherited_prefix` built full `sources` and `plan` lists and a remap dict. A whale parent with several forks multiplies a prefix larger than the writer's memory. All of this runs inside the parent's replacement transaction, so an OOM rolls back and the same revision fails again on every retry. ## Solution - `_iter_composed_rows` streams `(message_id, signature, owner)` segment by segment, with `_composed_db_signatures`' composition rules; `_disk_composed_db_signatures` now builds on it. - The guard writes each child's pre-write composed transcript into TEMP `before (child, ordinal, message_id, signature, owner)` and keeps only the child-to-parent map in Python. Reference capture and the rewritten-owned id set are SQL over it. - Settlement streams each child's post-write composition into TEMP `now`: - `_reanchor_inherited_rows` matches lost rows forward by signature with indexed queries; - re-anchors and copies go to TEMP `reanchors` and `copies`; - `_composition_matches_before` compares the composition with `before` in lockstep. - `_materialize_inherited_prefix` builds TEMP `sources` (snapshot or live rows) and `placed` (`_plan_prefix_positions`: the same keep-or-renumber rule, in SQL). Each plan row is decided one at a time against TEMP `taken` natives and `occurrences`. The identity scope's digests stream. - `_restore_message_refs`, `_restore_dispatch_refs` and `_copy_in_lineage` look up copies and re-anchors in the TEMP tables. `_session_message_ids`, `_inherited_entries`, `_reanchored_ids`, `_prefix_positions` and `_materialized_owner_in_lineage` are removed. Schema classification: no DDL; `write.py` is in the derived-identity closure, so this lands before the rebuild. Identities, positions, hashes and the recorded scope are unchanged for the same inputs. ## Verification - `agentctl … verify_quick`: Success (job 2329). - `agentctl … pytest_focused -- tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_branch_point_witness.py tests/unit/daemon/test_convergence_debt.py tests/unit/storage/test_archive_tiers_write.py` (job 2335): everything passes except the 3 provider-usage tests that fail on master (polylogue-ezvw3). That includes every existing materialization, reanchor, dispatch, scope and deep-chain test and the part-1 regressions. - New `test_settlement_streams_inherited_prefixes_through_the_guard_tables` materializes three children of one parent while `_composed_db_signatures` (the list builder) raises inside capture and settlement. ## Self-review I read the full diff line by line against the replaced list-based code. What I checked: - **Inherited rows.** They are the composed rows the child does not own (`owner <> child`), the same predicate as the removed `_inherited_entries`, and they precede the child's own rows, so `before` ordinals number the prefix from 0. - **Row sources.** A snapshotted row is read from the snapshot and any other row from the live table. A missing row still raises by name. - **Placement.** `_plan_prefix_positions` reproduces `_prefix_positions`: unique `(position, variant)`, non-decreasing in order and below the child's minimum means kept; otherwise it is a dense `(session, position)` slot by first appearance. - **Identity decisions.** - A native is kept only if `INSERT OR IGNORE` into `taken` inserts it. - A content copy takes the identity's next occurrence (the child's max+1, then +1 per copy). - The per-identity prefix ordinal counts every identity-bearing row. - `copy_bases` and the key and tail digests use `_identity_sequence_digest`'s framing. - **Reanchor matching.** It keeps the removed function's semantics (surviving ids need no entry; lost ids match forward by signature among rows no pre-write id holds). It returns `None` when a lost row has no match, which the caller treats as "materialize". Previously an unmatched row made the `all(...)` check fail; the outcome is the same. - **Cursors.** They are iterated while writing only to other tables, and every per-child TEMP table is dropped before the next child. - **Residual risks.** - The recorded identity scope is still one JSON value holding the content-copy ordinals and a one-byte kind per prefix row. It is persisted state, and replay reads it whole. - `_repair_stale_prefix_branch_points_db` and `_extract_prefix_tail`, outside settlement, still compose into lists on the same parent write. They are pre-existing, and polylogue-fg2ar tracks them. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Resolve the rebase onto the lineage depth-cap removal (#5685), keeping only the seed-free lineage pagination. Recover the archive root from the innermost generations marker, drop the unused whole-tuple expected_tier parameter, fix the status dependency map (the spine is not a presence key), relocate anchors by matching own physical rows across the whole neighbourhood instead of a second composer, and name the test modules by behaviour. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg
#5790) ## Summary Lands the real fixes from the worker-5 pass over storage Codex review debt (beads `polylogue-1tyq5.98`, `.99`, `.100`, 75 findings). 28 findings are fixed here with production-route regressions. 13 were already fixed on master, 8 are stale, 2 are refuted and 24 were not reached. Every kept fix was re-checked against current master. None of the cited or touched storage files changed on master after the salvage base `ab28700c1b`, and the later master merge touched none of this PR's files. ## Problem Each defect below was confirmed on master by a regression test that fails against master's production code (revert-proof job 2488): - **Archive location and tuples.** A root named `.index-generations` resolved to its parent. Local ops/embeddings tiers refused a durable symlink farm. The tuple manifest loader normalized unknown, missing and coerced fields before recomputing the seal, and it admitted a sealed obsolete schema fingerprint. An inactive destination could be a symlink or hard link to a foreign database, which SQLite then initialized; this happened both through bootstrap and through embedding preparation. A forged destination generation passed when the caller gave no hint. A replaced `audit.db` escaped the authority digest. Neither new directory entry was fsynced. Any root that merely contained `.archive-tuples` was refused. - **Readiness.** With a zero denominator the result was `UNMEASURED` even when blocking evidence loss had been measured. - **Block anchors.** Relocation followed NULL-inheritance edges. A private 512-node composer hid blocks that production reads expose. It also bound one SQL variable per transcript message, returned the first sibling match instead of `ambiguous`, and skipped same-session drift when the anchored message had vanished. - **Profiles and status.** `selected_part_facts` reported `valid` while ordinary inspection reported `stale` under pending demand. A session missing only its latency sibling was never rediscovered. Sync hydration dropped `direction`/`producer_ref`. A shared dependency superset zeroed `run_count` on archives that lacked `session_events`. - **Lineage and topology.** A compact-lineage page with `node_limit=1` could not advance past the seed. `siblings()` listed a child once per evidence edge. An unrelated component's cycle or conflict flagged a healthy topology. - **Markers, embeddings and FTS.** One accepted-marker convergence sweep delivered one batch and stopped. Reordered request options changed the recipe hash, and non-float32 recipes produced usable-looking contracts. A failing owned `COMMIT` in FTS repair ran outside rollback protection and left the transaction open. ## Solution - `archive_identity.py`: the innermost generations marker owns the path. Symlink-farm admission counts only the source, user and audit tiers. - `archive_tuple_location.py`: exact manifest key and type validation before the seal. Schema fingerprints must equal the running writer's. The final tier entry must be absent or an unshared regular file (`lstat`, `st_nlink == 1`). The destination generation must equal the manifest's. The live location is re-resolved and the audit identity rechecked. Both new directory entries are fsynced. Only `.archive-tuples/tuple-<id>` marks a candidate path. The unused whole-tuple `expected_tier` is removed; single-tier writers keep it on `validate_inactive_destination`. - `archive_readiness.py`: positive blocking counts are evaluated before the zero-denominator return. - `block_anchor.py`: the private composer and its cap are deleted. Relocation walks every prefix-sharing and spawned-fresh neighbour once and collects the distinct own physical rows that match the hash. Each query binds two values. More than one match is `ambiguous`. Same-session drift is checked before lineage, even when the message is gone. - `derivation.py`: required-page discovery includes sessions missing a latency sibling. Selected facts use the demand-aware classifier. - `rebuild.py`: the sync loader selects and hydrates the attachment provenance columns. The `input_binding.py` exclusion reasons are updated to match. - `status.py`: each run projection declares exactly the relations its own body reads. - `compact.py`: the seed rides every page outside the `node_limit` budget. - `topology.py`, `topology/derivation.py`: siblings are deduplicated as nodes, while evidence edges stay on `edges`. Cycle and conflict flags come from the returned edges. - `marker_domain.py`: `required_page` returns the head as its continuation, and it ends the sweep when the head has not moved (held or failed). One pass drains every committed batch without looping on or overtaking a held head. - `embeddings/identity.py`: request options are sorted and duplicate keys refused; only float32 output is accepted. Production recipes carry no options, so no stored recipe hash or vector address moves. - `fts_lifecycle.py`: the owned `COMMIT` moves inside the rollback guard. ## Derived-identity closure This PR is identity-moving: it must land before the fresh rebuild, never mid-run. It touches 12 members of the committed closure baseline (`docs/plans/schema-closure-baseline.json`, unchanged; the `schema-closure` gate passed): `polylogue/analysis/topology.py`, `polylogue/storage/archive_identity.py`, `polylogue/storage/archive_readiness.py`, `polylogue/storage/archive_tuple_location.py`, `polylogue/storage/derived/lineage/compact.py`, `polylogue/storage/derived/session/{derivation,input_binding,rebuild,status}.py`, `polylogue/storage/derived/topology/derivation.py`, `polylogue/storage/embeddings/identity.py`, `polylogue/storage/fts/fts_lifecycle.py`. Not in the closure: `polylogue/storage/block_anchor.py`, `polylogue/storage/derived/session/marker_domain.py`. ## Verification All checks ran as AgentCTL jobs on this worktree; nothing ran in-process. - `agentctl job start polylogue verify_quick --workspace /realm/worktrees/salvage-w5` returned job **2686** on head `2136284cf0`: `verify: PASSED exit=0` (all gates, including `schema-closure`, `layering` and `mypy`). - `agentctl job start polylogue pytest_focused --workspace /realm/worktrees/salvage-w5 -- <36 test modules covering every changed module and its consumers>` returned job **2687** on `2136284cf0`: 855 passed, 3 failed, 1 error. The 3 failures and the error are `test_archive_readiness::test_pinned_materialization_readiness_degrades_like_its_path_twin`, `test_read_view_operations::test_lineage_and_topology_use_the_pinned_graph_engines`, `test_session_partition_convergence::test_the_partition_input_columns_are_projected_or_declared_excluded`, and a descriptor-leak teardown error in `test_event_order_permutations_converge_to_the_same_relation`. All four fail identically on master `1beb2e516a` (job **2643**) and are untouched by this PR. - Revert proof: the new regression tests ran on a master checkout (`1beb2e516a`, production code unchanged) in job **2488**: `38 failed in 273.95s`, which is every named regression. The rebuilt deep-anchor test then ran alone in job **2685** and failed on the assertion (`message_id not found in the named session or its lineage neighborhood`) in 10.6 s. On this branch it passes (job **2684**, 22 passed). - Hosted: `ci/circleci: quick-gate` and `stacked-review-threads` gate the merge. ## Self-review - **Sibling sites.** The final-entry link check sits in `validate_inactive_destination`, the one gate that bootstrap, embedding preparation and whole-tuple validation all call. The `COMMIT`-outside-`try` pattern also occurs in `fts_invariant_snapshot_sync`, but that closes a read-only snapshot transaction whose `COMMIT` cannot lose writes, so it is left as it is. The FTS derivation writers (`fts/derivation.py`) already commit inside their guard. The status dependency map was re-derived for all three run projections from the tables their SQL actually reads. - **Cancellation, shutdown and loops.** The marker page loop cannot spin. The kernel rejects a continuation it has already visited, and `required_page` returns no keys and no cursor once the head stops moving. The anchor neighbourhood walk visits each session once through a `visited` set, and it terminates on cycles. - **Unbounded reads.** The anchor walk is now bounded by the lineage component rather than by an arbitrary 512-node cap, which had produced wrong `missing` answers. Each step is one indexed edge query and one two-bind hash query. Removing the per-transcript `IN` list removes the only unbounded bind list. - **Fail-open fallbacks.** The manifest loader no longer defaults a missing `state` to inactive. Readiness no longer lets a zero denominator mask measured loss. Anchors refuse on ambiguity and never pick the first match. - **Compatibility shims.** There are none. The removed `expected_tier` parameter had no caller, and mypy (`verify_quick`) proves none remains. The `float16` case was removed from `test_embedding_request_identity.py` because that element type is now refused. - **Removed symbols still referenced.** `_MAX_LINEAGE_SEARCH_NODES`, `_prefix_edge`, `_composed_message_ids` and `_hash_matches_in_composed_session` have no remaining references in code, tests or monkeypatch targets (grep, plus the mypy gate). - **Tests on the production route.** The regressions drive `initialize_archive_database`, `prepare_inactive_embedding_generation`, `ArchiveTupleAllocator.load`, `resolve_block_anchor` over `write_parsed_session_to_archive` data, `converge()` over a real derivation registry, `load_sync_batch` + `hydrate_sessions`, `session_insight_status_sync`, and `repair_message_fts_index_sync` with a real SQLite authorizer denying the first `COMMIT`. The 520-deep anchor test asserts that the cited session's `read_archive_session_envelope` really contains the block. Every named test fails on master (job 2488). ## Per-finding dispositions | key | disposition | evidence | test | |---|---|---|---| | 98.01 | fixed | archive_identity innermost marker | A::test_generation_root_uses_the_final_index_shape | | 98.02 | fixed | farm admission over durable tiers | A::test_durable_symlink_farm_allows_local_disposable_tiers | | 98.03 | fixed-already | archive_readiness.py:798,1167 `attach_readonly_database` | — | | 98.04 | fixed | blockers before zero denominator | A::test_zero_denominator_does_not_erase_measured_evidence_loss | | 98.05 | fixed-already | archive_readiness.py:1886 `attach_readonly_database` | — | | 98.06 | fixed | exact manifest shape before seal | A::test_tuple_loader_rejects_unsealed_manifest_shape_changes | | 98.07 | fixed | fingerprints equal running writer | A::test_tuple_loader_rejects_a_sealed_obsolete_schema | | 98.08 | fixed | unshared regular final entry | A::test_inactive_writer_refuses_foreign_final_file_links | | 98.09 | fixed | generation bound to manifest | A::test_destination_generation_must_match_its_manifest_without_a_caller_hint | | 98.10 | fixed | live re-resolve + audit identity | A::test_tuple_writer_rechecks_audit_identity_after_allocation | | 98.11 | fixed | whole-tuple `expected_tier` removed (no caller; mypy) | — (removed parameter) | | 98.12 | fixed | fsync archive root and tuples root | A::test_allocation_fsyncs_both_new_directory_entries | | 98.13 | fixed | typed `tuple-<id>` child required | A::test_reserved_name_alone_is_not_an_inactive_tuple | | 98.14 | not reached | — | — | | 98.15 | fixed-already | blob_gc.py:235,258 catch SchemaSkewError | — | | 98.16 | fixed-already | blob_gc.py:438-444 fsync marker + dir | — | | 98.17 | fixed-already | blob_gc.py:497 64-hex check | — | | 98.18 | refuted | pre-reset index as GC authority is forbidden legacy authority | — | | 98.19 | not reached | — | — | | 98.20 | fixed-already | blob_gc.py:1352-1355 marker only when `not dry_run` | — | | 98.21–98.24 | not reached | — | — | | 98.25 | stale | `_write_jsonl_rows` removed in e20f6f5 (#5680) | — | | 99.01, 99.02 | stale | writer removed in e20f6f5 (#5680) | — | | 99.03 | fixed-already | blob_integrity.py:1262 subtracts unowned | — | | 99.04 | stale | no generation-scoped projection remains | — | | 99.05–99.07 | not reached | — | — | | 99.08 | fixed | only classified inheritance edges | L::test_anchor_does_not_relocate_through_an_unclassified_edge | | 99.09 | fixed | private capped composer deleted | L::test_anchor_relocation_reaches_an_ancestor_beyond_the_former_search_cap | | 99.10 | fixed | two binds per lookup | L::test_anchor_hash_lookup_does_not_bind_every_transcript_message | | 99.11 | fixed | drift before lineage for a vanished message | L::test_anchor_relocates_locally_after_its_original_message_disappears | | 99.12 | fixed | all distinct matches before uniqueness | L::test_anchor_refuses_two_distinct_sibling_hash_matches | | 99.13 | not reached | — | — | | 99.14 | fixed-already | iterative walk landed in df70214 (#5685); worker rewrite dropped | — | | 99.15 | fixed | seed outside page budget | test_compact_lineage.py::test_one_node_pages_advance_past_the_seed | | 99.16–99.18 | not reached | — | — | | 99.19 | stale | plan-no-progress path gone | — | | 99.20, 99.21 | not reached | — | — | | 99.22 | fixed | demand-aware selected facts | P::test_selected_profile_facts_do_not_certify_pending_demand | | 99.23 | fixed | latency sibling in discovery | P::test_required_profile_page_recovers_a_missing_latency_sibling | | 99.24, 99.25 | not reached | — | — | | 100.01 | not reached | — | — | | 100.02 | fixed | head as continuation; stop on unmoved head | test_accepted_marker_consumer.py::test_one_convergence_sweep_delivers_every_accepted_marker_batch | | 100.03 | stale | per-session marker-set cursor gone | — | | 100.04 | fixed-already | `applied_sequence` + `expected_prior_sequence` in BEGIN IMMEDIATE | — | | 100.05 | fixed | provenance through sync loader | P::test_sync_hydration_preserves_stored_attachment_provenance | | 100.06, 100.07 | fixed-already | rebuild retires absent families; revision-matched acks | — | | 100.08 | stale | thread-row stamping gone | — | | 100.09 | refuted | retaining removed fields is a forbidden compatibility path | — | | 100.10 | fixed | per-projection dependencies | P::test_status_counts_runs_without_unrelated_product_tables | | 100.11 | fixed | siblings deduplicated as nodes | L::test_topology_siblings_are_nodes_not_duplicate_evidence_rows | | 100.12 | fixed | flags from returned edges | L::test_topology_fault_flags_are_scoped_to_the_returned_component | | 100.13–100.15 | not reached | — | — | | 100.16 | fixed-already | generations.py:759 contract before child | — | | 100.17 | fixed | options sorted, duplicates refused | C::test_equal_provider_requests_have_equal_recipe_identities | | 100.18 | fixed | float32 only | C::test_embedding_recipe_refuses_unimplemented_output_encodings | | 100.19–100.21 | not reached | — | — | | 100.22 | fixed | shared final-entry check via embedding preparation | A::test_embedding_preparation_rejects_a_foreign_final_symlink | | 100.23 | fixed | COMMIT inside rollback guard | C::test_fts_owned_commit_failure_rolls_back_and_allows_retry | | 100.24 | fixed-already | index_generation.py:892,949 restore predecessor | — | | 100.25 | stale | `commit_candidate_membership` removed in 0b1e99d (#5336) | — | A = `tests/unit/storage/test_archive_location_admission.py`, L = `test_block_anchor_lineage_and_topology.py`, P = `test_profile_selection_and_hydration.py`, C = `test_embedding_recipe_and_fts_commit.py`. Counts: `.98` 11 fixed / 6 fixed-already / 1 stale / 1 refuted / 6 not reached. `.99` 8 / 2 / 4 / 0 / 11. `.100` 9 / 5 / 3 / 1 / 7. ## Residuals - 24 findings are not reached and remain open on their beads. - The link check on the final entry is a pre-open `lstat`. A process that swaps the entry between the check and SQLite's open is outside the single-writer contract. - The anchor neighbourhood walk costs grow with the size of the lineage component; the walk is not capped, because a cap produced wrong answers. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
Problem
Solution
_capture_inherited_prefixesand_settle_inherited_prefixes: before the replace, record each child's inherited IDs and snapshot the parent-owned rows. After it, keep inheriting only when every pre-write inherited row still composes; otherwise_materialize_inherited_prefixcopies the prefix into the child, flips the edge tospawned-freshand remaps references and descendants.session_identity_scopes(session_id PK, ON DELETE CASCADE), independent of any edge. It records:_scoped_identitiesreproduces stored IDs on replay. The prefix is found by key. Rows after it keep their numbering and appends go past the copies. Rows materialization never saw get fresh occurrences. An unmatched or ambiguous prefix, or a duplicate inserted inside the tail, raisesInheritedPrefixMaterializationError._SegmentList, shared by the envelope planner and the disk signatures: one list cut at each branch point with an index and a running total;_composed_db_signaturesand the async reader: in-place cut and extend, caching only the requested session;_CompositionShape: persistent_Segmentnodes with running totals;_would_create_cycle: a visited set instead of a 1024-step budget;_refresh_session_projection: iterative.LINEAGE_ITERATIVE_DEPTH_LIMIT, thedepth_limittruncation reason, and_CYCLE_WALK_BUDGET.Schema classification: additive-derived. It adds the
session_identity_scopestable and moves the derived identity.write.py,message_query_reads.py,compact.pyandstorage/runtime/*are in the derived-identity closure, so this must land before a fresh rebuild starts.Verification
agentctl job start … verify_quickon bfa6d7b (master merged): Success (job 1936).agentctl job start … pytest_focused -- tests/unit/storage/test_lineage_normalization.py tests/unit/storage/test_compact_lineage.py tests/unit/storage/test_topology_cycle_quarantine_live.py tests/unit/storage/test_topology_deep_lineage.py tests/unit/mcp/test_lineage_completeness_payload.py tests/unit/storage/test_archive_tiers_ddl.py(job 1946): everything passes except 3 tests that fail identically on master (polylogue-ezvw3: the provider-usage and late-parent tests).tests/unit/devtools/test_lineage_validation.pyfails 21 of 21 on master with the sameSchemaSkewError(job 1929, polylogue-cp3z5). The facade contract miss is polylogue-bn8gg. Neither is from this change.Self-review
I read the complete diff of every round against the review threads, and read the final round line by line. What I checked:
InheritedPrefixMaterializationErroris typed and permanent. It fires only when stable evidence cannot place stored IDs: an ambiguous or unmatched prefix, or a duplicate inside a changed tail. An ordinary edit elsewhere in the tail is not refused.len(walk_path) - 2 == walk_budget).Residuals
🤖 Generated with Claude Code
https://claude.ai/code/session_015pdKaZWyGe6Ngvsz468dzg