Skip to content

Consolidate extends-chain parent-map resolution onto one edge source - #2933

Merged
mstomar125 merged 5 commits into
mainfrom
issue-2888-extends-chain-consolidation
Sep 28, 2026
Merged

mstomar125 merged 5 commits into
mainfrom
issue-2888-extends-chain-consolidation

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

Closes #2888. Consolidates two of the three duplicated extends-chain walkers the issue identified onto the single edge source NodeService::resolve_type_chain already uses (SqliteStore::get_extends_parent_map), instead of leaving each caller with its own independently-derived view of the same extends edges.

1. load_parent_map (packages/core/src/schema/mod.rs:736)

Previously rebuilt the parent map by calling get_all_schemas() (a heavier query: all schema nodes + a JOIN over every declaration row) and reading each schema's parent back off extends_chain::declared_parent, which parses the declaration row's properties JSON into a SchemaRelationship.

Now delegates directly to node_service.store().get_extends_parent_map() — the same single, cheaper query (SELECT in_node, out_node FROM relationship WHERE relationship_type = 'extends', reading the indexed columns directly rather than parsing JSON) that NodeService::resolve_type_chain, the playbook engine, and query.rs already use.

Why this was safe to consolidate: I traced load_parent_map and get_extends_parent_map back to the same PR (#2739) that introduced both — there was no documented reason for the two different sources, and no other caller of load_parent_map reads anything else off the get_all_schemas() result. The two already had to describe the same edges (an extends row is only ever written by set_schema_declarations with in_node = the declaring schema), so this removes duplication with no intended behavior change. get_extends_parent_map's own doc comment already called this out explicitly: reading in_node/out_node directly "is what the closure queries below walk, so a disagreement between the two would be a bug this avoids having to detect" — i.e. the JSON-parsing path could in principle silently drop a malformed-but-still-structurally-valid declaration row that the column-based query would not.

2. resolve_declared_relationship (packages/core/src/services/node_service/relationship.rs:488)

Previously hand-walked resolve_type_chain itself, calling get_schema_node per scope and SchemaNode::get_relationship(name) (a lookup over that scope's own, un-filtered relationships list) until the first match.

Now delegates to the existing resolve_relationships helper, which performs the identical nearest-first walk via the already-shared flatten_chain_by_name generalization (core#2830/PR#2862).

Behavior change, called out explicitly: resolve_relationships deliberately excludes the extends/extended_by type-system bookkeeping row (see its own doc comment) — SchemaNode::get_relationship did not. Before this change, naming "extends" as a relationship_name to create_relationship would resolve a schema's own extends declaration as if it were a real, creatable relationship, and (nothing else in create_relationship rejects the type-system names) would let a caller create a bogus data-level extends edge between two ordinary node instances. That path was never reachable through any real caller and had no test coverage either way — this closes it rather than preserving it, consistent with resolve_relationships's own stated rationale for the exclusion.

Sub-change 1 vs 2

Both turned out to be small, low-risk, mechanical swaps once traced — no third case emerged where the two paths' behavior needed to diverge for a real reason. Landed together in one PR/commit rather than split, per the issue's own "fine to do them as two commits or complete only the safer one" guidance — here both were equally safe once verified.

Not touched

Per the issue's scope: flatten_chain_by_name/resolve_field_owners/resolve_relationships's own bodies (schema.rs) are untouched — this PR only changes the two callers' chain-resolution setup that the issue named.

Tests

  • New: test_resolve_effective_fields_agrees_with_resolve_field_owners_across_extends_chain (schema/schema_test.rs) — builds a 3-level extends chain and asserts resolve_effective_fields (schema layer) and NodeService::resolve_field_owners (using resolve_type_chain) resolve the identical effective field set and chain order. This is the "single source of truth" regression guard the issue asked for on the field side.
  • New: create_relationship_rejects_the_extends_type_system_name (tests/relationship_extends_chain_test.rs) — pins the type-system-exclusion fix: create_relationship(..., "extends", ...) on a node whose schema genuinely has an extends declaration is now rejected the same way any other undeclared relationship name is.
  • Full existing suite, unchanged: cargo test -p nodespace-core — 1720 lib tests + all integration test binaries (including relationship_extends_chain_test, schema::, services::node_service::, playbook::) — all pass, 0 failed.
  • Pre-push gate (test:all + cargo build --bin nodespaced + full Tauri-seam test:e2e) passed clean on push.
  • bun run quality:fix clean (rustfmt + cargo clippy --all-targets -D warnings -D clippy::unused-async + eslint/tsc/svelte-check), no unrelated formatting diffs.

🤖 Generated with Claude Code

mstomar125 added a commit that referenced this pull request Sep 25, 2026
…test, document tradeoffs

Review on PR #2933 surfaced three findings:

- SchemaNode::get_relationship (models/schema_node.rs) lost its only
  production caller when resolve_declared_relationship was consolidated
  onto resolve_relationships, leaving it reachable only from tests.
  Deleted, and its 5 test call sites in schema_test.rs inlined to the
  equivalent relationships.iter().find(...).

- The new single-source-of-truth regression test only compared sorted
  field names between resolve_effective_fields and resolve_field_owners,
  which can't catch the two resolvers agreeing on names while disagreeing
  on a field's type/protection/required/core_values/etc. Strengthened to
  also compare every field's full serialized form (SchemaField doesn't
  derive PartialEq — it's a nodespace-types wire type used far more
  broadly than this test, so reusing Serialize avoids widening that type
  just for this assertion) and gave Root's test field real attributes
  (required, an enum vocabulary) for the comparison to have something to
  diverge on.

- resolve_declared_relationship's doc comment now spells out the two
  behavioral consequences of delegating to resolve_relationships instead
  of hand-walking with an early exit: every chain scope is now read
  before the nearest match is picked (no more stopping at the first
  declaring scope), and a real DB error from a farther, uninvolved
  ancestor now propagates where it previously wouldn't have been reached.
  Both are accepted rather than incidental — extends chains are shallow
  by construction, and every other single-name lookup through
  resolve_relationships/resolve_field_owners already pays this same cost
  (check_node_completeness, find_duplicate_for) — so this brings
  relationship creation in line with the rest of the codebase rather than
  leaving it as the one outlier with a bespoke early exit.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
mstomar125 added a commit that referenced this pull request Sep 25, 2026
…test, document tradeoffs

Review on PR #2933 surfaced three findings:

- SchemaNode::get_relationship (models/schema_node.rs) lost its only
  production caller when resolve_declared_relationship was consolidated
  onto resolve_relationships, leaving it reachable only from tests.
  Deleted, and its 5 test call sites in schema_test.rs inlined to the
  equivalent relationships.iter().find(...).

- The new single-source-of-truth regression test only compared sorted
  field names between resolve_effective_fields and resolve_field_owners,
  which can't catch the two resolvers agreeing on names while disagreeing
  on a field's type/protection/required/core_values/etc. Strengthened to
  also compare every field's full serialized form (SchemaField doesn't
  derive PartialEq — it's a nodespace-types wire type used far more
  broadly than this test, so reusing Serialize avoids widening that type
  just for this assertion) and gave Root's test field real attributes
  (required, an enum vocabulary) for the comparison to have something to
  diverge on.

- resolve_declared_relationship's doc comment now spells out the two
  behavioral consequences of delegating to resolve_relationships instead
  of hand-walking with an early exit: every chain scope is now read
  before the nearest match is picked (no more stopping at the first
  declaring scope), and a real DB error from a farther, uninvolved
  ancestor now propagates where it previously wouldn't have been reached.
  Both are accepted rather than incidental — extends chains are shallow
  by construction, and every other single-name lookup through
  resolve_relationships/resolve_field_owners already pays this same cost
  (check_node_completeness, find_duplicate_for) — so this brings
  relationship creation in line with the rest of the codebase rather than
  leaving it as the one outlier with a bespoke early exit.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125
mstomar125 force-pushed the issue-2888-extends-chain-consolidation branch from 09eca29 to a7d1d6d Compare September 25, 2026 15:30
mstomar125 and others added 5 commits September 28, 2026 06:51
load_parent_map (schema/mod.rs) rebuilt the schema-extends parent map by
loading and hydrating every schema node via get_all_schemas() and reading
each one's declaration back off declared_parent()'s JSON-parsed
SchemaRelationship, independently of NodeService::resolve_type_chain's
single get_extends_parent_map() query over the same edges read directly
off indexed relationship columns. Two independently-derived views of the
same extends edges, with nothing guarding that they stayed in agreement.
Point load_parent_map at get_extends_parent_map() directly.

resolve_declared_relationship (relationship.rs) hand-walked the extends
chain with its own per-scope get_schema_node + SchemaRelationship::
get_relationship lookups instead of calling the existing
resolve_relationships helper, which already performs the identical
nearest-first chain walk via the shared flatten_chain_by_name
generalization. Delegate to it instead. This also closes a gap the old
hand-walk carried: resolve_relationships excludes the extends/extended_by
type-system bookkeeping row, which SchemaNode::get_relationship did not
— naming "extends" as a relationship_name previously resolved a schema's
own extends declaration as if it were a real relationship a data-level
edge could be created under.

Adds a regression test pinning that resolve_effective_fields (schema
layer) and NodeService::resolve_field_owners agree on the effective
field set for the same extends chain, and a test pinning that
create_relationship now rejects "extends" as a declared relationship
name the way any other undeclared name is rejected.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…test, document tradeoffs

Review on PR #2933 surfaced three findings:

- SchemaNode::get_relationship (models/schema_node.rs) lost its only
  production caller when resolve_declared_relationship was consolidated
  onto resolve_relationships, leaving it reachable only from tests.
  Deleted, and its 5 test call sites in schema_test.rs inlined to the
  equivalent relationships.iter().find(...).

- The new single-source-of-truth regression test only compared sorted
  field names between resolve_effective_fields and resolve_field_owners,
  which can't catch the two resolvers agreeing on names while disagreeing
  on a field's type/protection/required/core_values/etc. Strengthened to
  also compare every field's full serialized form (SchemaField doesn't
  derive PartialEq — it's a nodespace-types wire type used far more
  broadly than this test, so reusing Serialize avoids widening that type
  just for this assertion) and gave Root's test field real attributes
  (required, an enum vocabulary) for the comparison to have something to
  diverge on.

- resolve_declared_relationship's doc comment now spells out the two
  behavioral consequences of delegating to resolve_relationships instead
  of hand-walking with an early exit: every chain scope is now read
  before the nearest match is picked (no more stopping at the first
  declaring scope), and a real DB error from a farther, uninvolved
  ancestor now propagates where it previously wouldn't have been reached.
  Both are accepted rather than incidental — extends chains are shallow
  by construction, and every other single-name lookup through
  resolve_relationships/resolve_field_owners already pays this same cost
  (check_node_completeness, find_duplicate_for) — so this brings
  relationship creation in line with the rest of the codebase rather than
  leaving it as the one outlier with a bespoke early exit.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…kups, cut redundant owners resolve

get_relationship_mut had zero callers after the prior round deleted its
sibling get_relationship — delete it too rather than leaving a structurally
identical piece of dead code three lines below.

schema_test.rs: replace 5 inline .relationships.iter().find(|r| r.name ==
"...") call sites with one test-local find_relationship helper, now that
get_relationship's deletion left them duplicating the same lookup idiom.

relationship.rs: resolve_declared_relationship built resolve_relationships's
owners map and discarded it. create_relationship_in_tx's reverse_cardinality:
One branch then re-derived the same owners map for the same schema_id with a
second, redundant full-chain resolve_relationships call, inside the same open
write transaction. Return the owners map from resolve_declared_relationship
and reuse it instead, halving that transaction's chain resolutions without
reintroducing a short-circuit hand-walk.

The broader tradeoff (always resolving every scope rather than stopping at
the nearest match) stays as documented: extends chains are shallow by
construction, a short-circuit-then-fallback variant would reintroduce the
duplicated per-scope walk this PR exists to remove, and the only real
production extends declaration (the built-in linear methodology) is a single
level deep.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The pre-push gate's check-code-references ratchet caught this: a
core#NNNN citation in a code comment, against CLAUDE.md's "describe
the behavior/constraint directly" rule. Describe the deletion/fold-in
directly instead of citing the issue.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ionship's new return shape

PR #2937 (merged to main after this branch's base) added
enforce_cardinality_after_merge_in_tx, which calls
resolve_declared_relationship expecting its old SchemaRelationship-only
return. Rebasing surfaces the resulting compile break from this PR's
own signature change (now returns the owners map alongside the match).

Its reverse branch had the identical redundant-resolve pattern already
fixed elsewhere in this file: it discarded resolve_declared_relationship's
owners map, then immediately re-derived the same map for the same
source.node_type via a second full-chain resolve_relationships call.
Reuse the owners map from the tuple instead, for the same reason as the
create_relationship_in_tx fix this mirrors.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@mstomar125
mstomar125 force-pushed the issue-2888-extends-chain-consolidation branch from a7d1d6d to 88b9469 Compare September 28, 2026 05:00
@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic Code Review — PR #2933 (issue #2888)

Review Type: Re-Review (rebase resolution onto origin/main 0bc01e2d, head 88b9469f)

Previous Review Summary:

  • Earlier rounds' recommendations (delete orphaned get_relationship_mut, dedupe test lookups, cut redundant owners resolve, drop issue-number reference in doc) are all present in the rebased diff.
  • New issues found: 0

Rebase-resolution checks

  1. declared_owners keying after the in→forward rewrite — correct.
    📁 packages/core/src/services/node_service/relationship.rs:1126-1131, 1210, 1230-1250, 1355-1365
    forward_endpoints rebinds source_id/relationship_name at the top of write_relationship_in_tx, before source is loaded; schema_id = &source.node_type is therefore the forward source's type, and resolve_declared_relationship(schema_id, relationship_name) is called with exactly the pair the old second resolve_relationships(schema_id) + owners.get(relationship_name) used. Neither binding is shadowed between the match and the reverse_cardinality: One branch. The owners map returned is the untouched resolve_relationships owners map (same chain, same nearest-first or_insert), so the reuse is behaviour-identical — it just drops one redundant full-chain resolve inside the open write tx. The enforce_cardinality_after_merge_in_tx reverse branch (:1652-1676) does the same with source.node_type/relationship_type — also identical.

  2. Weekend behaviour — no regressions found.

  3. load_parent_map → get_extends_parent_map() — equivalent.
    📁 packages/core/src/schema/mod.rs:1034-1042
    The extends declaration row is the extends relationship row between two schema nodes, so SELECT in_node, out_node WHERE relationship_type='extends' describes the same map declared_parent derived by hydrating every schema. Its only callers are the extends-cycle check (:1091) and resolve_effective_fields (:1254); the delete-refusal path doesn't use it, and no caller overlays a pending edge (the PendingSchema overlay at :457 works on chains, not this map) — the removed doc paragraph describing a pending parameter was already stale.

  4. Deleted SchemaNode::get_relationship/_mut — no callers on main (grep of packages/ clean). No duplicated work on main: the three resolve_declared_relationship callers are all in this file and all adapted.

  5. schema_chain_blindness_guard_test — passes; no stale/unlisted allowlist entries.

Verification run (in the worktree)

  • cargo test -p nodespace-core --test relationship_in_name_normalization_test --test relationship_extends_chain_test --test schema_chain_blindness_guard_test --test rel_ops_forward_name_extends_chain_test --test node_completeness_extends_chain_test — all pass (18/7/6/4/2).
  • cargo test -p nodespace-core --lib -- schema:: relationship — 322 passed (includes Refuse deleting an extended or core schema (closes #2889) #3095's delete-refusal tests in schema_test.rs).

Code Review Findings

None at 🔴/🟡/🟢 confidence worth blocking or nit-picking on.

Recommendation: APPROVE (posted as a comment — self-authored PR)

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Pragmatic Code Review — PR #2933 (issue #2888)

Review Type: Re-Review (rebase resolution onto origin/main 0bc01e2d, head 88b9469f)

Previous Review Summary:

  • Earlier rounds' recommendations (delete orphaned get_relationship_mut, dedupe test lookups, cut redundant owners resolve, drop issue-number reference in doc) are all present in the rebased diff.
  • New issues found: 0

Rebase-resolution checks

  1. declared_owners keying after the in→forward rewrite — correct.
    📁 packages/core/src/services/node_service/relationship.rs:1126-1131, 1210, 1230-1250, 1355-1365
    forward_endpoints rebinds source_id/relationship_name at the top of write_relationship_in_tx, before source is loaded; schema_id = &source.node_type is therefore the forward source's type, and resolve_declared_relationship(schema_id, relationship_name) is called with exactly the pair the old second resolve_relationships(schema_id) + owners.get(relationship_name) used. Neither binding is shadowed between the match and the reverse_cardinality: One branch. The owners map returned is the untouched resolve_relationships owners map (same chain, same nearest-first or_insert), so the reuse is behaviour-identical — it just drops one redundant full-chain resolve inside the open write tx. The enforce_cardinality_after_merge_in_tx reverse branch (:1652-1676) does the same with source.node_type/relationship_type — also identical.

  2. Weekend behaviour — no regressions found.

    • In-direction normalization (#2951): the match (&forward_name, resolved) guard and its "inbound view of …" error are preserved verbatim; only the tuple is threaded through.
    • resolve_relationships filters is_type_system_relationship, so a rewritten extended_by → extends now hits the mismatch error rather than resolving; unreachable anyway because the forward source is a schema and is refused just above ("typed relationships between schemas are declarations").
    • Stored-edge labels (#3176), last-inbound-edge protection, delete refusal (#3095, now in assert_schema_deletable at the store layer): none touch the changed lines.
  3. load_parent_map → get_extends_parent_map() — equivalent.
    📁 packages/core/src/schema/mod.rs:1034-1042
    The extends declaration row is the extends relationship row between two schema nodes, so SELECT in_node, out_node WHERE relationship_type='extends' describes the same map declared_parent derived by hydrating every schema. Its only callers are the extends-cycle check (:1091) and resolve_effective_fields (:1254); the delete-refusal path doesn't use it, and no caller overlays a pending edge (the PendingSchema overlay at :457 works on chains, not this map) — the removed doc paragraph describing a pending parameter was already stale.

  4. Deleted SchemaNode::get_relationship/_mut — no callers on main (grep of packages/ clean). No duplicated work on main: the three resolve_declared_relationship callers are all in this file and all adapted.

  5. schema_chain_blindness_guard_test — passes; no stale/unlisted allowlist entries.

Verification run (in the worktree)

  • cargo test -p nodespace-core --test relationship_in_name_normalization_test --test relationship_extends_chain_test --test schema_chain_blindness_guard_test --test rel_ops_forward_name_extends_chain_test --test node_completeness_extends_chain_test — all pass (18/7/6/4/2).
  • cargo test -p nodespace-core --lib -- schema:: relationship — 322 passed (includes #3095's delete-refusal tests in schema_test.rs).

Code Review Findings

None at 🔴/🟡/🟢 confidence worth blocking or nit-picking on.

Recommendation: APPROVE (posted as a comment — self-authored PR)

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address-review summary (post-rebase round)

Rebased onto main 0bc01e2d and force-pushed as 88b9469f.

Rebase resolution: one textual conflict, in write_relationship_in_tx (relationship.rs). Main's in-direction normalization now wraps resolve_declared_relationship in a match (&forward_name, resolved). I kept that match unchanged and made it operate on this PR's (SchemaRelationship, owners) tuple, so the reverse_cardinality: One branch still reuses declared_owners without a second chain resolve. After the forward rewrite, relationship_name and schema_id are already the forward name and the forward source's type, so the owners map is keyed correctly. The other 4 commits applied cleanly.

Dropped as redundant: nothing. Main still had load_parent_map on get_all_schemas() + declared_parent, and the hand-walked resolve_declared_relationship. No weekend commit duplicated this PR's work, and nothing on main calls the deleted SchemaNode::get_relationship or get_relationship_mut.

Review: APPROVE, 0 findings. Nothing to address.

Tests: cargo build -p nodespace-core is clean. cargo test -p nodespace-core --lib: 1898 passed. Integration tests all pass, including schema_chain_blindness_guard_test, merge_nodes_test, relationship_extends_chain_test, node_completeness_extends_chain_test, relationship_in_name_normalization_test, rel_ops_forward_name_extends_chain_test and the playbook and methodology tests. bun run quality:fix is clean.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED. The review had no findings, so no code changed in this round.

🤖 Generated with Claude Code

@mstomar125
mstomar125 merged commit 650a5c3 into main Sep 28, 2026
@mstomar125
mstomar125 deleted the issue-2888-extends-chain-consolidation branch September 28, 2026 05:16
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.

Three hand-rolled extends-chain walkers over two different edge sources — drift risk, not a single source of truth

1 participant