Skip to content

feat(topology): materialize session lineage graph (#866) - #1097

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/session-topology-graph
May 16, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/session-topology-graph

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

Summary

Materializes a typed session topology read model over the existing
archive parent edges so reader/search/analytics surfaces can answer
parent/descendant/sibling/first-appearance/unresolved-edge questions
without re-walking parent pointers ad hoc.

Problem

Polylogue stores partial lineage on conversations
(parent_conversation_id, branch_type) and messages
(parent_message_id), but no consumer-facing graph contract exposed
those edges with classification, root membership, cycle handling, or
unresolved-native-parent preservation. get_session_tree in the
repository facade only returned a flat BFS of resolved children, with
no edge taxonomy and no representation for orphans whose provider-native
parent hadn't been ingested yet (#866 acceptance criteria).

Solution

A derived read model, computed on demand from canonical archive tables.
No new DDL: the durable edge data already exists at ingest through
pipeline/prepare_enrichment parent resolution and BranchType
classification. Modules added:

  • polylogue/insights/topology.py — SessionTopology, TopologyNode,
    TopologyEdge, TopologyEdgeKind (frozen pydantic models). Edge
    kind extends BranchType with UNKNOWN (resolved but unclassified)
    and UNRESOLVED_NATIVE (native parent pointer with no matching
    conversation row).
  • polylogue/storage/insights/topology/ — sync + async derivation.
    Ancestry walk is cycle-safe and reports cycle_detected; descendants
    enumerated via BFS through ConversationRecordQuery(parent_id=...).
    Unresolved native edges detected from
    conversations.provider_meta by scanning a small allowlist of
    observed parent-pointer key names (parent_session_id,
    parentSessionId, etc.).
  • polylogue/storage/repository/insight/topology_reads.py — repository
    mixin exposing get_session_topology(conversation_id). Wired into
    ConversationRepository alongside the existing insight read mixins.

Future MCP/CLI/reader surfaces should consume this rather than
re-walking parent pointers; that adaptation work intentionally stays
out of this slice (other agents own those files).

Also fixes a preexisting redundant-expr mypy error in
devtools/evidence_dashboard.py that was blocking the local baseline,
and refreshes the topology projection / docs/topology-status.md for
the new module additions.

Verification

Local commands run:

  • nix develop -c pytest tests/unit/storage/test_session_topology.py -q
    → 6 passed in 16.93s
  • nix develop -c devtools verify --quick
    → total_duration_s: 46.54, exit_code: 0
  • Manual edge-count sanity check on a synthetic 6-conversation corpus
    (root + continuation + fork + subagent + sidechain + orphan with
    provider_meta.parent_session_id):
    • root topology: nodes=5 edges=4 unresolved=0 cycle=False
    • fork topology: nodes=5 edges=4 unresolved=0 cycle=False
      (correctly anchors at root from a deep descendant)
    • orphan topology: nodes=1 edges=1 unresolved=1 cycle=False
      (native pointer preserved as UNRESOLVED_NATIVE edge)

Acceptance criteria status (#866)

  • Missing provider-native parents preserved as unresolved edges
    (read-model side; parsers writing the native ID into provider_meta
    is a parser/ingest concern out of this slice's owned files)
  • Cycles surfaced as SessionTopology.cycle_detected
  • Continuation / sidechain / fork / subagent fixtures covered in
    tests/unit/storage/test_session_topology.py
  • Read model exposes ancestors / descendants / siblings / root
    membership / edge kind
  • Late parent arrival deterministic repair — derivation is
    re-runnable so a late parent insert is reflected on next query, but
    no durable repair pass is wired into the convergence loop yet
  • work_threads migration onto topology — deferred; work_threads
    continues as a derived lineage summary

Ref #866

Adds a derived topology read model over the existing archive parent
edges (conversations.parent_conversation_id + branch_type +
provider_meta native pointers), exposed through a new repository mixin
get_session_topology(conversation_id) -> SessionTopology.

The model classifies edges as continuation/sidechain/fork/subagent and
preserves unresolved native parent pointers (UNRESOLVED_NATIVE) so late
parent arrival can deterministically repair them. Cycles are surfaced
through SessionTopology.cycle_detected rather than silently broken.

Files:
- polylogue/insights/topology.py — typed graph models
- polylogue/storage/insights/topology/ — derivation (sync + async)
- polylogue/storage/repository/insight/topology_reads.py — repo mixin
- tests/unit/storage/test_session_topology.py — synthetic forks/cycles
  + unresolved-native fixtures

Also fixes a preexisting redundant-isinstance mypy error in
devtools/evidence_dashboard.py that was blocking the local baseline,
and refreshes the topology projection / docs/topology-status.md for
the new module additions.

Ref #866
@coderabbitai

coderabbitai Bot commented May 16, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 58 minutes and 26 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c8350d49-db6b-4013-86e1-4b84704fb218

📥 Commits

Reviewing files that changed from the base of the PR and between d9111f0 and aa54856.

📒 Files selected for processing (9)
  • devtools/evidence_dashboard.py
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/insights/topology.py
  • polylogue/storage/insights/topology/__init__.py
  • polylogue/storage/insights/topology/derivation.py
  • polylogue/storage/repository/__init__.py
  • polylogue/storage/repository/insight/topology_reads.py
  • tests/unit/storage/test_session_topology.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/session-topology-graph

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 and usage tips.

@Sinity
Sinity merged commit 1c116a7 into master May 16, 2026
2 checks passed
@Sinity
Sinity deleted the feature/feat/session-topology-graph branch May 16, 2026 16:02

@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: aa54856793

ℹ️ 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 thread polylogue/insights/topology.py Resolved
Comment thread devtools/evidence_dashboard.py Resolved
Sinity added a commit that referenced this pull request May 17, 2026
## Summary

Add a Lineage inspector tab to the web reader plus a new
`GET /api/conversations/{id}/topology` endpoint backed by the
`SessionTopology` read model from #866. Closes #1121. Re-dispatch of
the prior PR #1174 against a fresh `origin/master`.

## Problem

The reader had no way to see a conversation's place in the lineage
graph — parents, sub-agent branches, sidechains, or resumed sessions —
even though #866 (PR #1097) materialized the durable lineage graph as
`SessionTopology` with cycle-safe derivation. #1121 calls for a
read-only lineage view that consumes the existing public read surface
and renders explicit empty / partial / no-lineage states.

## Solution

- **HTTP endpoint** (`polylogue/daemon/http.py`,
  `polylogue/daemon/topology_http.py`):
  `GET /api/conversations/{id}/topology` returns a bounded
  `SessionTopology` envelope:
  - `?limit=` (default 200, hard cap 1000) so the reader never streams
    an unbounded subtree — #1121 AC: lineage rendering is bounded.
  - Edges referencing dropped nodes are filtered so the UI never
    plots a dangling endpoint; `truncated_count` signals the gap.
  - Explicit `readiness` chip (`ok` / `partial` / `empty`),
    `unresolved_edge_count` for provider-native parents that did not
    resolve, and `cycle_detected` for cycle-quarantine flagging.
  - Envelope shape lives in `daemon/topology_http.py` so `http.py`
    stays close to its per-file budget; budget bumped to 1380.
  - 404 with shared error envelope for unknown id; 400 `invalid_limit`
    for out-of-range `?limit=`.

- **Reader UI** (`polylogue/daemon/web_shell.py`,
  `polylogue/daemon/web_shell_lineage.py`): new `Lineage` inspector
  tab rendering the rooted tree as an indented BFS list with edge-kind
  chips (`continuation` / `sidechain` / `fork` / `subagent` /
  `unresolved_native`), the focused conversation highlighted, an
  `Open parent` button, and a `Compare with parent` affordance that
  delegates to the existing compare workspace route from #1124.
  Unresolved native parent IDs surface in a dedicated section.
  Empty / partial / cycle states use the MK3 chip vocabulary
  (`q-canonical` / `q-partial` / `q-unavailable` / `q-unresolved`).
  Lineage CSS+JS extracted to a sibling module matching the
  `BULK_`/`WORKSPACE_`/`PROVENANCE_` split.

- **Tests** (`tests/unit/daemon/test_topology_endpoint.py`): 24 tests
  in three groups:
- pure helpers — `coerce_node_limit` bounds + `build_topology_envelope`
    readiness vocabulary, edge filter, truncation, hard-cap clamp;
  - end-to-end dispatch over a seeded archive (root → child →
    grandchild, sidechain sibling, isolated leaf, missing id) asserting
    BFS-from-descendant anchors at root, empty readiness for the
    isolated leaf, `?limit=` payload clamping, and the hard-cap reject;
  - reader-shell structural smoke pinning the new `data-tab="lineage"`
button, `loadLineage`/`renderInspectorLineage`/`openCompareWithParent`/
    `lineageReadinessChip` JS hooks, the MK3 chip vocabulary, and that
    no `__LINEAGE_JS__` / `__PROVENANCE_JS__` template placeholders
    leaked into the shipped HTML.

Rejected alternatives:

- Returning the unbounded raw `SessionTopology.model_dump()` — would
  fail the #1121 AC that lineage rendering be bounded.
- Adding a lineage rail to the conversation header — kept the
  inspector-tab placement because it lets the lineage tree share space
  with raw and notes without crowding the header chip row that
  #956/#1078 already pinned.
- Mutating lineage in the UI — #1121 explicitly scopes this read-only.

## Verification

```
nix develop -c pytest tests/unit/daemon/test_topology_endpoint.py -q
  → 24 passed in 9.33s

nix develop -c pytest tests/unit/daemon -q
  → 503 passed in 14.92s

nix develop -c pytest tests/unit/daemon tests/unit/storage/test_session_topology.py \
                   tests/unit/architecture/test_topology_invariants.py -q
  → 517 passed in 12.24s

nix develop -c devtools verify --quick
  → exit_code 0 (format, lint, mypy --strict, render-all --check,
    verify-topology, verify-file-budgets, verify-test-ownership,
    verify-cluster-cohesion, manifest gates, verification-impact all green)

git push (pre-push hook runs verify --quick)
  → exit_code 0
```

## Acceptance criteria (#1121)

- [x] Reader displays a lineage rail for any conversation with
  materialized lineage rows — `Lineage` inspector tab consumes the
  topology endpoint.
- [x] Parent chain is navigable; sub-agent branches are listed —
  rooted tree with edge-kind chips; clickable nodes call
  `selectConversation`; sibling branches render under their shared
  parent.
- [x] No-lineage and partial-lineage states are rendered explicitly
  with a readiness chip — `readiness` ∈ `ok` / `partial` / `empty`
  drives the MK3 chip vocabulary.
- [x] Reader does not query lineage tables directly — only the public
  lineage read surface from #866 — endpoint calls
  `poly.repository.get_session_topology`; UI calls the endpoint.
- [x] Tests assert lineage rendering is bounded (does not unbound
  expand the whole graph in one payload) —
  `test_node_limit_is_bounded_and_signals_truncation`,
  `test_node_limit_hard_cap_enforced`,
  `test_node_limit_hard_cap_rejects_unbounded_request`,
  `test_node_limit_clamps_payload_size`.
- [ ] Visual smoke harness (#865) covers a multi-level tree, a leaf
  conversation, and a no-lineage state — deferred to #865's
  Playwright-based screenshot lane; the structural smoke in
  `test_topology_endpoint.py::TestLineageReaderShell` covers the same
  three states at the HTML/JSON contract level.

Ref #866, #859, #1118.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity

Sinity commented Sep 30, 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.

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

@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.

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