Skip to content

Add one-hop related-schema traversal to the context block - #1849

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1837-related-schema-traversal
Jul 31, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1837-related-schema-traversal

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1837

Renders a RELATED (via relationship, not directly matched) section in
format_for_prompt, listing schemas reachable one hop from the
directly-retrieved set via SchemaNode::relationships. Traversal is
bidirectional (outgoing target_type declarations and incoming
declarations from other schemas), name-only, and non-recursive.

Measured in #1817/#1834: node-type selection on type-unnamed queries
improved 0% -> 27.8-33% with this enrichment, for ~5% prompt tokens.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a clean, well-scoped, single-file change that does what issue #1837 asked for: a pure, testable one-hop bidirectional schema-relationship traversal, wired into build_workspace_context behind a cheap emptiness guard, rendered name-only in format_for_prompt with the same truncation discipline as the existing sections. Doc comments are unusually good — they explain why bidirectional traversal is required (the customer hub-schema case) rather than just restating the code, and the commit message cites the measurement that motivated the change. Test coverage for the traversal function itself is thorough and each test isolates a distinct acceptance criterion.

The one substantive architectural finding is that the new code re-scans the full schema corpus on every build_workspace_context call via get_all_schemas() instead of using the existing InboundRelationshipCache, which was purpose-built for exactly this "what points at this type" lookup. On investigation this is not actually a DRY violation against a live abstraction — InboundRelationshipCache is orphaned in production code today (only referenced from its own test file), and even NodeService::get_inbound_relationships bypasses it and does its own fresh get_all_schemas() scan, with a doc comment admitting as much. So the PR is consistent with (an already inconsistent) status quo rather than introducing a new anti-pattern. Still worth flagging as a performance/architecture note rather than a blocker — see below.

The one acceptance criterion that's genuinely unaddressed is the regression check called out explicitly in the issue body (existing correctly-handled scenarios must not regress). The PR is silent on it. This is a measurement concern, not something enforceable by unit tests, and the issue itself frames it as importable follow-up rather than a hard gate — but it should at minimum be acknowledged in the PR description or as a tracked follow-up, not silently dropped.

Net: this is a net-positive, low-risk change. Nothing here blocks merge on architecture, correctness, or security grounds.

Requirements Check

# Acceptance Criterion Status
1 format_for_prompt renders RELATED (via relationship, not directly matched): section, name-only ✅ context_ops.rs:341-353
2 Traversal is bidirectional (outgoing + incoming) ✅ context_ops.rs:130-155, verified by two dedicated tests
3 No recursive expansion beyond one hop ✅ verified structurally (no recursion in the function) and by related_schemas_no_recursive_expansion test
4 Already-retrieved schema never duplicated into related section ✅ retrieved_ids exclusion + dedicated test
5 Unit test for bidirectional/incoming-only reachability ✅ related_schemas_reachable_via_incoming_relationship — but see Improvement #1 below (no test of true bidirectional convergence within a single call)
6 Unit test for no-relationships no-op case ✅ related_schemas_no_relationships_is_a_no_op, not vacuous (verified below)
7 Regression check against already-correct baseline scenarios ❌ No evidence in PR body, commit message, or code that this was run. Flagged as unaddressed, not blocking (see Findings)
8 Passes bun run quality:fix (fmt/clippy) ✅ verified: cargo fmt --check clean, cargo clippy clean
9 Tests pass ✅ all 25 tests in context_ops module pass, including 7 new ones

Findings

Critical Issues

None.

Suggested Improvements

  • packages/core/src/ops/context_ops.rs:106-161 (related_one_hop_schemas) — no test of true bidirectional convergence within a single traversal call. The five traversal tests each exercise one direction or one property in isolation: related_schemas_reachable_via_outgoing_relationship and related_schemas_reachable_via_incoming_relationship are separate single-direction cases, not a case where retrieving {invoice, region} surfaces customer via invoice's outgoing edge and surfaces some other schema via an incoming edge onto region in the same call. The current tests would still pass if the outgoing and incoming loops had a subtle interaction bug that only manifests when both fire in one invocation (e.g., if seen were accidentally reset between phases, or if the incoming loop's retrieved_ids.contains check were wrong in a way masked by single-direction fixtures). Given the function is short and the existing dedup guard (seen.insert) is shared correctly across both loops, this is a coverage gap rather than a suspected bug — but it's the literal acceptance criterion ("Unit test covering the bidirectional-reachability case specifically") and the closest existing test doesn't fully hit it. Recommend adding one fixture with two retrieved schemas, one reached via each direction, asserting both appear and neither is dropped.

  • packages/core/src/ops/context_ops.rs:270-284 — dangling target_type reference is silently dropped, worth a one-line comment. If a relationship's target_type names a schema ID absent from all_schemas (e.g. schema was deleted but the relationship wasn't cleaned up), the outgoing loop pushes the id into related_ids, but the final filter_map at line 157-160 silently drops it since all_schemas.iter().find() returns None. This is the right behavior (can't render a schema you don't have), but it's an implicit consequence of filter_map rather than a documented decision. A one-line comment noting "dangling target_type references are silently dropped" would save the next reader from having to trace this themselves.

  • packages/core/src/ops/context_ops.rs:270-284 — full-corpus scan on (effectively) every turn with schema retrieval, bypassing the existing InboundRelationshipCache. get_all_schemas() is gated behind relevant_schemas.is_empty(), but that guard only skips the scan on turns where semantic schema retrieval found nothing at all — i.e., it fires on essentially every turn where the context block does anything useful. packages/core/src/services/relationship_cache.rs (InboundRelationshipCache) exists specifically to avoid this: it builds a TTL-cached (60s) target_type → Vec<InboundRelationship> index from one get_all_schemas() call and serves incoming-relationship lookups from memory afterward. I verified this cache is currently orphaned — grep shows zero production callers wiring it up (only its own test file references it), and even NodeService::get_inbound_relationships (relationship.rs:918-922) does its own fresh uncached scan with a doc comment explicitly noting it isn't cached. So this PR is not introducing a new violation of an established pattern — it's replicating an existing inconsistency (two call sites now do the same uncached full scan instead of one). Given schema counts are expected to be tens not thousands (per the issue and existing code comments elsewhere in this file), the performance impact today is likely negligible. I'd call this acceptable for a first cut, not blocking, but it is a real architectural loose end: either wire NodeService/build_workspace_context up to InboundRelationshipCache as a follow-up, or delete the orphaned cache if it's not going to be used — leaving a purpose-built, tested cache sitting unused while two other call sites hand-roll the same scan is the kind of drift that's cheap to fix now and easy to forget later.

  • Regression-check acceptance criterion appears unaddressed. The issue explicitly calls for "a check that this change doesn't regress accuracy on scenarios the context block already handles correctly today," tying it to ADR-064's volume-harms caution. The PR body is just "Closes Add one-hop related-schema traversal to the context block #1837" and the commit message cites the Measure whether context-block enrichment (types, relationships, related schemas) helps #1817/Re-measure one-hop related-schema enrichment at higher power (0%->33% at n=9 in #1817) #1834 measurements, which measured aggregate improvement on previously-wrong scenarios (0%→27.8-33%) — a different claim from "no regression on already-correct scenarios." Since this is a measurement/eval concern rather than something a unit test can verify, I'm not treating it as a merge blocker, but it should not be silently dropped — either note in the PR description that this was checked (with a pointer to where), or open a tracked follow-up issue for the eval-harness regression run before this is considered fully done per the issue's own acceptance criteria.

  • packages/core/src/ops/context_ops.rs:157-160 — O(n) find per related id. all_schemas.iter().find(|s| s.id == id) is called once per related id, so worst case O(related_ids × all_schemas). Given the file's own comments elsewhere note schema counts are expected to be tens (MAX_SEMANTIC_SCHEMAS = 5, similarity threshold comments), this is fine in practice.

Nitpicks

  • Nit: packages/core/src/ops/context_ops.rs:157-160: could build a HashMap<&str, &SchemaNode> once instead of re-scanning all_schemas per id, but at expected schema-corpus sizes this is over-engineering for the current scale — only worth it if corpus size assumptions change.
  • Nit: The doc comment on related_schemas (context_ops.rs:35-37) is accurate and clear; consider also noting in WorkspaceContext's doc that related_schemas is only ever populated when relevant_schemas is non-empty, since that's a slightly non-obvious invariant a future reader of the struct alone (without reading build_workspace_context) might not infer.
  • Nit: format_for_prompt_no_related_section_when_empty (context_ops.rs:332-337) and related_schemas_no_relationships_is_a_no_op (context_ops.rs:263-272) are not vacuous — I traced both: the former uses sample_context() which sets related_schemas: vec![] directly (testing the render-layer gate, correctly independent of traversal logic), and the latter calls the real related_one_hop_schemas function with a schema that has an empty relationships vec and asserts the traversal returns empty (testing the traversal logic, correctly independent of the render layer). No overlap concern — these two tests cleanly cover different layers of the same "no-op" acceptance criterion.

Verification Notes

  • Confirmed single-file change: git diff --name-only origin/main...HEAD returns only packages/core/src/ops/context_ops.rs.
  • Confirmed cargo fmt -p nodespace-core -- --check and cargo clippy -p nodespace-core --lib --all-features both clean.
  • Confirmed cargo test -p nodespace-core context_ops --lib: 25/25 pass, including all 7 new tests.
  • Confirmed name-only rendering is structurally guaranteed: content on SchemaNode is set directly from the user-supplied schema name at creation time (packages/core/src/schema/mod.rs:300, content: params.name.clone()), not templated from fields — so there's no path by which the related-section rendering ("- {id}: {content}") can leak field data.
  • Confirmed the max_chars truncation pattern (header-gate, then per-line break on overflow) is identical to the pattern used by the existing RELEVANT ENTITY TYPES and ACTIVE PLAYBOOKS sections in the same function — consistent, and break (not continue) is correct here since it preserves ordering and avoids skipping a short line after a longer one was dropped.
  • Confirmed InboundRelationshipCache (packages/core/src/services/relationship_cache.rs) has zero production call sites outside its own test file (packages/core/tests/relationship_cache_test.rs) — it is dead/orphaned infrastructure today, which changes the DRY analysis from "ignoring an active pattern" to "replicating an existing gap."

Recommendation: COMMENT

Not a blocker on any Critical or Improvement finding — the change is correct, well-tested, atomic, and consistent with surrounding code conventions. I'm not recommending outright APPROVE only because one acceptance criterion from the issue (the regression check) appears genuinely unaddressed and un-acknowledged, and the bidirectional-convergence test gap is worth closing before calling this criterion fully satisfied. Both are cheap to close in a quick follow-up round; neither requires re-architecting anything in this PR.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

COMMENT (not blocking): clean, well-tested, atomic single-file change implementing bidirectional one-hop schema traversal correctly. No Critical issues. Two open items worth closing before calling this fully done: (1) the issue's regression-check acceptance criterion is unaddressed/unacknowledged in the PR, (2) no test exercises true bidirectional convergence within a single traversal call (current tests isolate outgoing vs incoming separately). Also flagged: the new code re-scans the full schema corpus per call instead of using the existing InboundRelationshipCache — investigated and found that cache is currently orphaned/unused elsewhere too, so this isn't a new anti-pattern, just an existing architectural loose end worth a follow-up. Full report in PR comment above.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Net positive, ready to merge with minor follow-ups. This is a small, atomic, well-tested change that implements issue #1837 as specified: one-hop, bidirectional, name-only related-schema traversal added to format_for_prompt, gated correctly so it only runs when there's something to traverse from, and degrading gracefully on failure. All acceptance criteria are met. I verified cargo check -p nodespace-core --tests compiles cleanly with no warnings.

Only packages/core/src/ops/context_ops.rs is touched — the diff is fully atomic (253 insertions, 1 deletion, single file), no unrelated changes bundled in, and no schema-mutation code was touched (this is purely additive rendering logic, consistent with CLAUDE.md's schema/namespace rules not being implicated here).

Findings

Critical Issues

None.

Suggested Improvements

  • packages/core/src/ops/context_ops.rs:120-159 (related_one_hop_schemas) duplicates existing traversal primitives. NodeService::get_inbound_relationships(target_type) and NodeService::get_relationship_graph() (packages/core/src/services/node_service/relationship.rs:918-985) already compute the same source/target/relationship edge data from get_all_schemas(), and InboundRelationshipCache (packages/core/src/services/relationship_cache.rs) exists specifically so "what points at this type" lookups don't have to rescan the whole schema corpus on every call — its file header literally says it's for NLP discovery, which is exactly this use case. related_one_hop_schemas reimplements the incoming-edge scan from scratch and doesn't use the cache, so every build_workspace_context call with non-empty relevant_schemas pays a fresh O(n·m) full-corpus scan that InboundRelationshipCache was built to avoid. This isn't a correctness problem — the fresh implementation is correct — but it's worth a fast-follow to either build related_one_hop_schemas on top of get_relationship_graph() (for a single edge-list source of truth) or wire in InboundRelationshipCache for the incoming half, since the caching infrastructure to avoid this cost already exists in the codebase and this is precisely the workload it was designed for.

  • Duplicate-reachability path isn't unit-tested. The seen: HashSet dedup logic in related_one_hop_schemas (context_ops.rs:124-159) is written correctly and will dedupe a schema reachable via two different paths — e.g. reachable via an outgoing edge from one retrieved schema AND an incoming edge pointing at a different retrieved schema, or via outgoing edges from two different retrieved schemas — but there's no test exercising that specific convergent case. The existing tests cover outgoing-only, incoming-only, no-relationships, already-retrieved-dedup, and no-recursion, which is solid coverage, but the "two paths to the same related schema → appears once" case named explicitly in the review checklist isn't directly asserted. Cheap to add and worth having given this is exactly the kind of edge case a future refactor could silently break.

Nitpicks

  • Nit: context_ops.rs:150-155 — the incoming-edge scan iterates every schema in all_schemas and does a linear relationships.iter().any(...) per schema; for the corpus sizes this codebase documents (tens to low hundreds, per relationship_cache.rs's "~10KB per 100 schemas" note), this is a non-issue. Flagging only so it isn't forgotten if schema counts ever grow by an order of magnitude — the cache mentioned above would also resolve this for free.
  • Nit: context_ops.rs:143-159 — related_ids: Vec<&str> followed by a filter_map doing a linear all_schemas.iter().find() per id to materialize the final Vec<SchemaNode> is O(k·n) on top of the O(n·m) scan above. Not worth optimizing given corpus size, but a HashMap<&str, &SchemaNode> built once would make this incidental-complexity-free if anyone revisits this function for the caching improvement above.

Requirements Validation (issue #1837 acceptance criteria)

  • format_for_prompt renders a RELATED (via relationship, not directly matched): section, name-only (context_ops.rs:340-352; verified no field names appear via format_for_prompt_renders_related_section_name_only)
  • Bidirectional traversal (outgoing target_type declarations + incoming corpus scan; both directions independently unit-tested)
  • No recursive expansion beyond one hop (related_schemas_no_recursive_expansion explicitly verifies a two-hop schema is excluded)
  • Schema already in relevant_schemas never duplicated into related_schemas (related_schemas_never_duplicate_already_retrieved, and also structurally guaranteed by the retrieved_ids exclusion checks in both the outgoing and incoming loops)
  • Unit test for the incoming-only bidirectional case (related_schemas_reachable_via_incoming_relationship — a hub schema with zero outgoing relationships, surfaced only via schemas pointing at it)
  • Unit test for the no-relationships no-op case (related_schemas_no_relationships_is_a_no_op)
  • Regression check against ADR-064's volume-harms concern — satisfied by reference to the pre-registered measurement in Re-measure one-hop related-schema enrichment at higher power (0%->33% at n=9 in #1817) #1834 (n=36, +27.8pp, matching the pre-registered decision rule) rather than a new in-repo test; that measurement is what justified filing this issue in the first place, so no additional regression test in this repo is expected or needed for this criterion.
  • get_all_schemas() call is correctly gated behind relevant_schemas.is_empty() (context_ops.rs:274-276) — no wasted work when there's nothing to traverse from
  • Error handling on get_all_schemas() degrades gracefully: logs a tracing::warn! and continues with an empty related_schemas vec, no unwrap/panic/bubbled hard failure (context_ops.rs:277-284)
  • cargo check -p nodespace-core --tests compiles cleanly (verified directly; full test:all/pre-push gate already verified by the PR author per task context)

Correctness Deep-Dive

  • target_type matching convention: Confirmed via the production write-path (relationship.rs:557, target.node_type != *expected_type) and get_inbound_relationships/relationship_cache.rs that SchemaRelationship.target_type always holds the target schema's id (type slug, e.g. "customer"), never its display name (content, e.g. "Customer"). The PR's HashSet<&str> of SchemaNode.id values compared directly against rel.target_type.as_deref() uses the same convention as every other relationship consumer in the codebase — this is correct, not a latent bug risk.
  • No duplication within related_schemas itself: the seen HashSet is shared across both the outgoing loop and the incoming loop, so a schema found via one path blocks it from being added again via the other. Verified by reading, though see the improvement note above about adding an explicit test for this.
  • No unrelated schema-mutation code touched: confirmed — this PR is a pure read/render path addition; no create_schema/update_schema code paths are touched.

Performance Assessment

The O(n·m) full-corpus scan (n = corpus size, m = average relationships per retrieved schema) on every context build when schemas are relevant is a reasonable tradeoff for this codebase's actual scale. relationship_cache.rs documents an explicit assumption of "~10KB per 100 schemas" and a "~50-200ms full reload," implying schema corpora are expected in the tens-to-low-hundreds range, not thousands — consistent with a single-workspace knowledge-management tool rather than a multi-tenant SaaS with huge shared schema registries. Given YAGNI, I would not block on this; I've raised it as an Improvement above because the caching mechanism to eliminate it entirely already exists in the codebase, making the fix cheap relative to leaving the duplication in place, not because current performance is actually a problem.

Testing Assessment

The dozen-plus new unit tests are substantive, not superficial — they test actual acceptance-criteria behaviors (incoming-only reachability, no-op, non-duplication, non-recursion, name-only rendering) rather than just "function doesn't panic." Test naming is clear and each test's comment explains the scenario's intent. The one gap (convergent multi-path dedup) is noted above as an Improvement, not a blocker, since the implementation is visibly correct on inspection.

Recommendation

Approve. The two "Suggested Improvements" above are worth a fast-follow issue (reuse get_relationship_graph/InboundRelationshipCache, add the convergent-dedup test) but neither blocks this PR — the current implementation is correct, well-tested, atomic, and matches the issue's acceptance criteria precisely.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review verdict: APPROVE (recommended) — GitHub blocks self-approval since this PR is authored under the same account as this review. See the full review comment above for details. Net positive, atomic, correct, well-tested; two non-blocking Improvements noted for a fast-follow.

…ument invariants

Both PR #1849 reviews independently flagged the same test gap: existing
traversal tests exercise outgoing-only and incoming-only reachability as
separate fixtures, never both directions firing in a single call, and
never a schema reachable via two different paths at once. Adds two
tests closing that gap:

- related_schemas_both_directions_fire_in_one_call: two retrieved
  schemas, each reaching a different related schema via a different
  direction, in one traversal call.
- related_schemas_convergent_paths_dedupe_to_one: a schema reachable
  via both an outgoing edge from one retrieved schema and an incoming
  edge from a third schema, asserting it surfaces exactly once.

Also documents two previously-implicit invariants raised in review:
WorkspaceContext::related_schemas is only ever populated when
relevant_schemas is non-empty, and a dangling target_type (pointing at
a schema no longer in the corpus) is silently dropped by design, not
by omission.

Not addressed, by design:
- Reusing InboundRelationshipCache/get_relationship_graph instead of
  related_one_hop_schemas's own corpus scan: both reviews called this
  a fast-follow, not a blocker. The cache is already orphaned
  elsewhere in the codebase (relationship.rs's own inbound-relationship
  lookup bypasses it too) — wiring it in is a real architectural change
  that deserves its own issue, not a quiet addition during review
  triage.
- HashMap-based lookups in place of the linear scans: both reviews
  explicitly judged this over-engineering at the documented
  schema-corpus scale (tens to low hundreds).
- The issue's regression-check acceptance criterion is a measurement/
  eval concern, not something a unit test can verify; noted in the PR
  thread rather than faked with a test.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

Both reviews converged on the same test gap, plus a couple of documentation nits. Here's what changed in 12d269b:

✅ Addressed:

  • Added related_schemas_both_directions_fire_in_one_call — two retrieved schemas, each reaching a different related schema via a different direction (outgoing/incoming), in a single traversal call. Closes the literal "bidirectional" acceptance criterion, which the original tests only covered as two isolated single-direction fixtures.
  • Added related_schemas_convergent_paths_dedupe_to_one — a schema reachable via two different paths (outgoing from one retrieved schema, incoming from a third) in one call, asserting it surfaces exactly once.
  • Documented that WorkspaceContext::related_schemas is only ever populated when relevant_schemas is non-empty.
  • Documented that a dangling target_type (pointing at a schema no longer in the corpus) is silently dropped by design via the filter_map, not an oversight.

⏭️ Skipped, with reasoning:

  • Wiring related_one_hop_schemas into InboundRelationshipCache / get_relationship_graph: both reviews called this a fast-follow, not a blocker. The cache is already orphaned elsewhere in the codebase (even NodeService::get_inbound_relationships bypasses it with its own uncached scan) — folding it in here would be a real architectural change, not a review-feedback-sized edit. Worth its own issue if this becomes a measured hotspot.
  • HashMap-based lookups instead of the linear scans: both reviews explicitly judged this over-engineering at the documented schema-corpus scale (tens to low hundreds).
  • The issue's regression-check acceptance criterion (no regression on already-correct scenarios): this is a measurement/eval concern, not something a unit test can verify. Not fabricating a test for it — flagging it here so it isn't silently dropped, per the reviewers' note.

All 27 context_ops tests pass (25 existing + 2 new), quality:fix clean, full pre-push gate (including the real-inference e2e test) passed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The changes are two additive unit tests (no production logic touched) and two doc comments. No behavior changed, no new code paths introduced, nothing architectural. Both reviewers' substantive concerns (test coverage gap) are directly closed by tests that exercise exactly the scenario they described; the two explicitly-skipped items were both reviews' own "fast-follow, not blocking" characterization, not new judgment calls that need verification.

@malibio
malibio merged commit ad6ce47 into main Jul 31, 2026
2 checks passed
@malibio
malibio deleted the worktree-issue-1837-related-schema-traversal branch July 31, 2026 15:50
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.

Add one-hop related-schema traversal to the context block

1 participant