Skip to content

Repair branch points invalidated by deferred prefix re-extraction - #5090

Merged
Sinity merged 1 commit into
masterfrom
fix/lineage-three-generation-branch-point-repair
Sep 14, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/lineage-three-generation-branch-point-repair

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

A rebuilt archive's composed content depended on the order sources were
visited: in a three-generation lineage the youngest session silently lost its
entire inherited prefix. This scopes the in-write branch-point repair to the
generation it was written for, and adds an archive-wide dangling-branch-point
census so the condition is measured instead of inferred.

Problem

In a lineage P -> B -> A, if A's edge to B resolves while B is still stored
whole (P not yet written), A's branch_point_message_id binds to a B-owned
message row. When P lands, _reextract_prefix_tail_db deletes exactly those
rows, and nothing re-points A — so A composes to its own tail only.

Executed at the pre-fix head (Codex-origin P=[m0..m3], B=P-prefix+[m4],
A=[m0,m1]+[x2]):

visit order A's envelope
P, B, A ['m0','m1','x2']
A, B, P ['x2']
B, A, P ['x2']

Same inputs, same parser, two different logical archives.

The in-write repair could not see it. _resolve_session_graph computed
impacted_session_ids = {session_id, *resolved_child_ids, *(invalidated_session_ids or set())} — P plus B. A is the source of the
stale edge and is absent, and _repair_stale_prefix_branch_points_db filters
AND l.src_session_id IN (...). invalidated_session_ids is populated only
by identity-claim invalidation, never by re-extraction — so the repair skipped
precisely the case its own docstring describes.

This is reachable at scale: a rebuild visits sources in lexicographic key order
(operations/daemon_ingest.py, min(pending_keys)) — UUID order for
per-session files, uncorrelated with lineage.

Nothing measured it either. repair_stale_prefix_branch_points has exactly one
caller (daemon/lineage_startup.py via daemon/cli.py), so a freshly rebuilt
archive read truncated until the next daemon start;
read_archive_session_envelope returns the truncated list with no flag, and the
workload probe's topology census counted QUARANTINED edges only.

Solution

Both halves:

  1. Repair scope. _reextract_prefix_tail_db now returns the set of other
    sessions whose prefix-sharing edges name one of the inherited-prefix rows it
    is about to delete — collected before the delete — and _resolve_session_graph
    folds them into impacted_session_ids. The existing in-write repair then
    re-points those edges at the composed ancestor message in the same write, so
    every visit order converges on the same archive.

  2. Readiness census. New count_dangling_prefix_branch_points(conn) returns
    (edge_count, session_count) for composing prefix-sharing edges whose branch
    point names a message row that no longer exists. The predicate itself is
    factored into dangling_prefix_branch_point_sql() and shared with
    _repair_stale_prefix_branch_points_db, so the measured condition and the
    repaired condition cannot drift apart. The workload probe's
    topology_quarantine_state now reports dangling_branch_point_count and
    dangling_branch_point_session_count (REPORT_VERSION 21 → 22, documented
    in docs/internals.md).

Verification

devtools test tests/unit/storage/test_lineage_normalization.py
  -> PASSED exit=0 (receipt 20260914T161447Z-focused-test-3014571-29bd2bd9)
devtools test tests/unit/storage/test_lineage_normalization.py tests/integration/test_daemon_convergence_evidence.py
devtools test tests/unit/operations/test_daemon_workload_probe.py
devtools verify --quick

New tests:

  • test_three_generation_lineage_composes_identically_in_every_visit_order
    writes P/B/A in all six orders and asserts A composes to ['m0','m1','x2']
    and the census reads (0, 0) in each.
  • test_dangling_branch_point_census_counts_edges_and_sessions asserts the
    census sees a hand-corrupted edge as (1, 1), that the session then reads
    ['x2'], and that it returns to (0, 0) after the archive-wide repair.

Anti-vacuity (verified by reverting). Dropping the
reextract_invalidated_ids contribution to impacted_session_ids turns the two
grandparent-last orderings red:

FAILED tests/unit/storage/test_lineage_normalization.py::test_three_generation_lineage_composes_identically_in_every_visit_order[...]
E       AssertionError: assert ['x2'] == ['m0', 'm1', 'x2']
E         At index 0 diff: 'x2' != 'm0'
============== 2 failed, 41 passed ==============

For the census, a check that ignored the branch point's existence — or scoped
itself to one session — reports (0, 0) for the corrupted state the second test
builds.

Derived schema closure

polylogue/storage/sqlite/archive_tiers/write.py is IN the derived schema
closure
(devtools schema closure → IN). This edit moves the derived schema
identity: the archive must reconverge, this must land before a fresh rebuild
starts, never during one
, and it invalidates the seeded fixture cache.

The other touched files are outside the closure:
polylogue/operations/daemon_workload_probe.py → out,
tests/unit/storage/test_lineage_normalization.py → out.

Residuals

  • Existing archives still carry whatever damage a prior ingest order created.
    repair_stale_prefix_branch_points fixes it, but it still has exactly one
    caller (daemon startup lineage readiness) — no convergence stage calls it. The
    census now makes the remaining damage visible; wiring the archive-wide repair
    into convergence is separate work.
  • read_archive_session_envelope still returns a truncated transcript with no
    completeness flag; only get_messages_with_lineage_completeness reports
    dangling_branch_point. Unchanged here.
  • The repair maps a stale suffix to the parent's composed transcript; genuinely
    ambiguous suffixes stay unrepaired and now show up in the census rather than
    being silent.
  • No full rebuild was executed against this change; the ordering evidence is the
    executed unit reproduction above.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

In a lineage P -> B -> A, if A's edge to B resolved while B was still
stored whole, A's branch_point_message_id bound to a B-owned message row.
Writing P re-extracted B and deleted exactly those rows, and nothing
re-pointed A, so A composed to its own tail only. The in-write repair
missed it because impacted_session_ids never contained the source of the
stale edge: A is neither the written session, a resolved child, nor an
identity-claim invalidation. A rebuild visits sources in lexicographic
key order, so the resulting archive content depended on ingest order.

_reextract_prefix_tail_db now returns the sessions whose prefix-sharing
edges name the inherited-prefix rows it is about to delete, and
_resolve_session_graph folds them into the repair scope.

Adds count_dangling_prefix_branch_points and reports it from the workload
probe's topology census (REPORT_VERSION 22) so a rebuilt archive that
reads short is measured rather than inferred; the predicate is shared
with the repair so the two cannot drift.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 40 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: bbf20199-9192-4fa4-a34e-1ebc60212032

📥 Commits

Reviewing files that changed from the base of the PR and between 06d73a3 and 4055873.

📒 Files selected for processing (4)
  • docs/internals.md
  • polylogue/operations/daemon_workload_probe.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/storage/test_lineage_normalization.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.

@Sinity
Sinity merged commit 0527186 into master Sep 14, 2026
3 checks passed
@Sinity
Sinity deleted the fix/lineage-three-generation-branch-point-repair branch September 14, 2026 16:34
Sinity added a commit that referenced this pull request Sep 14, 2026
…5161)

## Summary

The coordination context envelope was a second source of truth for
session topology. It now composes through the one canonical
`session_links`-owned graph engine, and reports its own bound instead of
hiding it.

## Problem

`polylogue-27ezu` decided one `session_links`-owned topology projection.
PR #5007/#5012 landed that spine — `_archive_session_topology` is gone,
and `api`/`cli`/`mcp`/`daemon` all reach
`storage/derived/topology/derivation.py` through
`repository.get_session_topology`. But the census that produced the
bead's `write_scope` missed
`polylogue/coordination/envelope.py::_session_tree_payload`, which is
reachable from the public MCP `context` surface and was still building
its own graph:

- Resolved edges were synthesized from `sessions.parent_session_id` +
`branch_type` — the exact red condition in AC2.
`tests/unit/coordination/test_envelope.py` asserted this as correct: its
fixture carried a single `session_links` row, and the two "resolved
edges" it expected had **no** canonical row behind them at all.
- A private edge mapper flattened an unresolved link's declared
`link_type` to a generic `"unresolved_native"` kind, collapsing
resolvedness into type (AC4 red).
- `cycle_detected=False` was hard-coded, and quarantined/contradicted
edges were invisible (AC5 red).
- `edges[:limit]` truncated silently, and the compact projection trimmed
`nodes[:3]`/`edges[:3]` again — a partial tree was indistinguishable
from a whole one (AC6 red).

Separately, `compose_session_topology` raised `KeyError` when a
composable edge resolved to a parent outside the bounded node scope.

## Solution

- `compose_session_topology` (was `_compose`) is now the public, single
graph classification engine, narrowed to a `TopologyNodeInput`
(`session_id`, `origin`, `title`) so a caller holding raw `sessions`
rows reaches it without constructing a `SessionRecord`.
- A resolved edge whose parent is out of scope is excluded with the
named reason `parent-out-of-scope` instead of crashing or vanishing.
- `_session_tree_payload` uses the parent/root columns for **node
discovery only** and projects every edge from `session_links`. The
target sorts first in discovery so a tight bound can never trim away the
session the tree was requested for.
- `CoordinationSessionTreeEdgePayload` gains `composable` /
`composability_reason`; `CoordinationSessionTreePayload` gains
`conflicting_parent_detected`, `nodes_complete`, `edges_complete`,
`truncated_node_count`, `truncated_edge_count`, `generation_id`. The
compact projection folds its own trim into those fields.
- The fixture now carries the canonical link rows production's
`write_parsed_session_to_archive` mints, so the existing assertions
prove edges come from `session_links`.

Two anti-vacuity tests:
`test_coordination_tree_edges_come_only_from_session_links` deletes the
resolved link rows while leaving `parent_session_id` fully intact — red
for any route that synthesizes from the accelerator columns;
`test_coordination_tree_reports_its_own_truncation` is red if the
completeness fields are dropped or the silent trim returns.

## Verification

```
devtools test tests/unit/coordination/test_envelope.py tests/unit/storage/test_session_topology.py \
  tests/unit/storage/test_topology_edges.py tests/unit/api/test_topology_api.py \
  tests/unit/daemon/test_topology_endpoint.py tests/unit/daemon/test_topology_stack.py \
  tests/unit/mcp/test_envelope_contracts.py tests/unit/storage/test_tree_laws.py \
  tests/unit/pipeline/test_branching.py
```
`devtools test: PASSED exit=0 diagnosis=pytest_passed` — 127 passed.

`devtools verify --quick` → exit 0. `devtools render all --check` → exit
0, no `out of sync` lines. `devtools gate layering` →
`"violations":[],"count":0`.

## Schema closure

`devtools schema closure` reports **`out`** for all four source files
touched (`coordination/envelope.py`, `coordination/payloads.py`,
`storage/derived/topology/derivation.py`,
`storage/derived/topology/__init__.py`). This change does not move the
derived-schema identity and does not invalidate a seeded fixture cache
or an in-flight rebuild.

## Residuals

Not fixed here, reported as remaining `polylogue-27ezu` scope:

- `storage/sqlite/archive_tiers/archive.py::get_session_tree` +
`_root_session_id_for_tree` still walk
`parent_session_id`/`root_session_id` with no `session_links` read.
Public reach: `Polylogue.get_session_tree` (`api/archive.py:7104`), the
sync wrapper (`api/sync/sessions.py:168`), and the MCP resource
`polylogue://session-tree/{conv_id}` (`mcp/server_resources.py:289`).
All four consumers are list-shaped (membership only, no edge traversal),
so this is a scoping rather than an edge-provenance defect — but AC2 is
not met until it reads canonical rows.
- `storage/repository/archive/tree.py`
(`get_root`/`get_children`/`get_parent`/`get_session_tree`) is a third
parent-walk implementation with **zero** callers in production or tests
apart from one incidental `SessionRepository.get_session_tree` call at
`tests/unit/pipeline/test_branching.py:423`. Left in place pending an
explicit retirement decision.
- `derive_session_topology_sync` still describes itself as a test
adapter and has no production callers.
- `read_archive_session_envelope` still returns a truncated transcript
with no completeness flag (#5090's recorded residual). This PR does not
touch that path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
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