Skip to content

Make check_node_completeness direction-aware for required in-relationships - #2935

Merged
malibio merged 2 commits into
mainfrom
issue-2921-in-direction-completeness
Sep 25, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2921-in-direction-completeness

Conversation

@malibio

@malibio malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator

Closes #2921

Problem

check_node_completeness checked every required relationship with check_relationship_exists(node_id, name) (in_node = node_id AND relationship_type = name). An in-direction declaration is the target's view of a forward edge, which is stored under the forward name (the declaration's reverse_name) with the source as in_node and this node as out_node. The lookup could never match, so a required in relationship was always reported missing.

Fix

  • New SqliteStore::check_inbound_relationship_exists(target_id, rel_type) (out_node = target_id).
  • check_node_completeness branches on relationship.direction: Out keeps the existing lookup by name; In uses the inbound lookup by reverse_name.

Tests

Added to node_completeness_extends_chain_test.rs, using a self-referential supersedes / superseded_by pair:

  • a required in relationship with no edge is reported missing
  • an edge attached from the other side satisfies it on the target, and not on the source

I checked that the satisfied-case test fails without the fix. The pre-push gate passed.

🤖 Generated with Claude Code

…ships (closes #2921)

An in-direction declaration is the target's view of a forward edge stored
under its reverse_name with this node as out_node. The completeness check
looked up an outbound edge by the in-declaration's own name, which is never
stored, so a required in-relationship was permanently reported missing.
Route In declarations through a new inbound existence query instead.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #2935

Review Type: Initial Review

Summary

A small, well-scoped fix for a real bug. For the canonical write spelling, the forward edge (new --supersedes--> old), the new In branch is correct. I checked the author's storage model against create_relationship_in_tx: edges are inserted with in_node = source and relationship_type = <name passed to create_relationship>. A forward-name write therefore lands as out_node = target, type = reverse_name, which is exactly what check_inbound_relationship_exists counts. The regression test fails without the fix. rustfmt is clean (cargo fmt -p nodespace-core -- --check).

The model has one gap: it is not the only way an In declaration's edges get stored. Details are in finding 1. It doesn't block the merge, but this PR is the right place to fix it.

Requirements Check (#2921)

  • ✅ check_node_completeness no longer reports a required in-direction relationship as permanently missing
  • ✅ Regression test: a real edge attached from the other side is reported satisfied on the target and not on the source (required_inbound_relationship_satisfied_from_other_side_reports_complete)
  • ✅ quality:fix: rustfmt check passes on nodespace-core
  • ✅ test:all: the author reports that the pre-push gate (which runs test:all) passed. I did not re-run it.

Code Review Findings

🟡 1. In edges written under the declaration's own name no longer count

📁 packages/core/src/services/node_service/schema.rs:1315-1326, related to packages/core/src/services/node_service/relationship.rs:488 (resolve_declared_relationship)

create_relationship_in_tx finds the declaration with SchemaNode::get_relationship(name), which does not filter by direction. It then stores the edge under the name the caller passed. So create_relationship("old", "superseded_by", "new") is accepted and stores in_node = old, out_node = new, type = "superseded_by". This is a valid way to say "old is superseded by new", and it is reachable from the CLI and the agent's create_relationship tool because rel_ops::create_relationship passes the name through unchanged.

  • Before this PR, the check counted that edge (outbound by name) and missed the forward-spelled edge.
  • After this PR, it counts the forward-spelled edge and misses that one.

Neither version handles both spellings. For callers who wrote via the in name, this change turns a previously satisfied node into an incomplete one.

Suggestion: for In, treat the relationship as satisfied if either query finds an edge: check_inbound_relationship_exists(node_id, reverse_name) or check_relationship_exists(node_id, name). That can be two calls, or one OR query. Add a test that writes via superseded_by from old. The deeper fix is to normalize an in-name write into the forward edge, or reject it, in create_relationship_in_tx. That changes the write path, which #2921's non-goals exclude, so file it as a follow-up.

Principle: correctness and robustness. A read-side check should accept every storage shape the write side can produce.

🟡 2. The inbound count doesn't narrow by source type

📁 packages/core/src/db/sqlite_store/relationships.rs:1571-1586

The Out path is naturally precise. It counts edges from this node, and this node's own schema chain is what makes name meaningful. The In path counts out_node = node AND type = reverse_name from any source. Suppose two schemas declare the same forward name toward this type, for example invoice.billed_to → customer and order.billed_to → customer. Then a customer's required In invoices declaration is satisfied by an order edge. So this is a wider imprecision than the Out path has, not the same one.

rel_ops::get_related_nodes handles this exact case with a descendant-aware source_type filter (resolve_type_chain(n.node_type).contains(source_type)). For an In declaration, target_type names the source type. Consider narrowing by in_node's type (plus its ADR-078 descendants) when target_type is Some. If target_type is None (untyped), counting any source is correct, since no narrowing is possible. If you defer this, add a comment that names the limitation.

Principle: consistency with the existing inbound-narrowing pattern (DRY of intent) and correctness.

🟢 3. The write path's last-edge guard is still Out-only

📁 packages/core/src/services/node_service/relationship.rs:1170, 1374

Now that required In relationships can be satisfied, deleting the last forward supersedes edge silently makes the target incomplete. The removal guard only protects Out declarations. This is correctly out of scope under #2921's non-goals. Consider a follow-up issue so read and write enforcement of required agree.

🟢 4. Nits

  • Nit: 📁 schema.rs:1316,1321: the fully qualified crate::models::schema::RelationshipDirection::… matches relationship.rs, but a local use would read more cleanly.
  • Nit: 📁 relationships.rs:1571: check_inbound_relationship_exists duplicates check_relationship_exists except for the column. The file already takes a column parameter elsewhere (direction == "in_node" at ~1811). One helper that takes the endpoint column would avoid the copy. It's optional at two call sites.
  • Nit: 📁 packages/core/tests/node_completeness_extends_chain_test.rs: the new In tests don't involve the extends chain. A separate node_completeness_direction_test.rs, or a module-level doc note, would keep the file name accurate.
  • Nit: the self-referential fixture can't exercise finding 2, because source and target types are the same. A two-type fixture (for example completeness_customer ← completeness_invoice.billed_to) would cover the common case.

What's good

  • The comment explains why the forward name and out_node are used, not just what the code does.
  • The negative assertion on the source end (new is still missing superseded_by) guards against an over-broad fix.
  • The change is atomic and stays inside the issue's non-goals.

Recommendation

APPROVE (with a strong suggestion to fold in finding 1 before merge). The fix is a clear net improvement: the canonical forward-edge spelling now works where it never did. Finding 1 is a small change (an OR of two existing queries) that keeps the one write spelling the old code handled working, so it's worth doing in this PR. Finding 2 can be a follow-up.

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

…e type

- A required in-relationship is also satisfied by an edge written through
  the in name itself (stored from this node's own end), which the write
  path accepts.
- Inbound forward-name edges only count when the source satisfies the
  declared targetType (itself or an ADR-078 descendant), since another
  schema may declare the same forward name toward this type.
- Import RelationshipDirection instead of fully qualified paths.

Skipped: merging the two existence queries into one column-parameterized
helper (the inbound query now returns source types, so they no longer
duplicate); moving the in-direction tests to their own file (they share the
fixture helpers and the completeness subject).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed (0b45ffa)

✅ 🟡1 — edges written under the in name now count. An edge written through the in name is stored from this node's own end (in_node = node_id, type = name). That edge now satisfies the relationship, and so does a forward edge written from the other side (out_node = node_id, type = reverse_name). Test: required_inbound_relationship_written_through_in_name_reports_complete.

✅ 🟡2 — inbound edges are narrowed by source type. check_inbound_relationship_exists is replaced by get_inbound_relationship_source_types, which returns the distinct source node types. An edge counts only if its source satisfies the declared targetType via type_satisfies, which follows the ADR-078 chain; type_satisfies is now pub(super). An untyped declaration accepts any source. Test: required_inbound_relationship_narrows_by_source_type. In that test, a memo --supersedes--> adr edge does not satisfy the relationship, and an adr_sub --supersedes--> adr edge does.

✅ Nit — local import. RelationshipDirection is imported with use instead of written as a full path.

⏭️ Nit — shared query helper: skipped. The inbound query now returns source types instead of a count, so it no longer duplicates check_relationship_exists.

⏭️ Nit — separate test file: skipped. The new tests reuse the file's fixture helpers and test the same function.

⏭️ 🟢3 — Out-only last-edge removal guard: out of scope. The issue's non-goals exclude write-path required enforcement. Normalizing or rejecting writes made through an in name belongs in the same follow-up.

The pre-push gate passed (test:all, the daemon build and e2e).

@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #2935 (Re-Review)

Review Type: Re-Review. Scope: dca994ab..0b45ffa4 only.

Previous Review Summary: 7 recommendations. 3 addressed (🟡1, 🟡2, the local-use nit). 4 not addressed, each with a reasonable skip (🟢3 is out of scope by the issue's non-goals, and the other three are nits). The new commit introduces no 🔴 or 🟡 issues. It has 2 new 🟢 nits.

Requirements Check (#2921)

  • ✅ A required in relationship is satisfied by a forward edge written from the other side.
  • ✅ New: a required in relationship is also satisfied by an edge written through the in name itself (in_node = node, type = name). This is the shape the pre-PR code handled, so the change no longer regresses callers who write that way.
  • ✅ New: inbound edges are narrowed by source type, following the ADR-078 chain. An untyped declaration accepts any source.
  • ✅ Out behavior is unchanged: it still makes exactly one check_relationship_exists(node_id, name) call.
  • ✅ I ran cargo test -p nodespace-core --test node_completeness_extends_chain_test locally: 6/6 pass.

Verification of prior findings

🟡1 (in-name spelling): addressed correctly. Every declaration now runs the name lookup first. For In, the reverse lookup runs only when that first lookup finds nothing. The in-name lookup doesn't need source-type narrowing: create_relationship_in_tx already validated the target against the declaration's targetType when the edge was written, and a name is unique within a schema chain. So the asymmetry is correct. I also checked that it does not over-match on the other end. For new (the target of an in-name write), the edge has in_node = old and type superseded_by, so neither lookup finds it. That is correct, because new is not superseded.

🟡2 (source-type narrowing): addressed correctly.

  • SQL. SELECT DISTINCT n.node_type FROM node n JOIN relationship r ON r.in_node = n.id WHERE r.out_node = ?1 AND r.relationship_type = ?2 returns the right set. An inner join to node drops an edge whose source node was hard-deleted. That is the right outcome here: a dangling edge shouldn't satisfy a required relationship.
  • type_satisfies becoming pub(super). This is the minimum widening needed. It stays private to the node_service module and reuses the same ADR-078 check the write path uses. That is better than a second copy of the check (DRY).
  • Direction of the check. type_satisfies(source_type, expected) asks whether the source is expected or a descendant of it. That is the right direction for "a source of the declared type".
  • Does the test fail without narrowing? Yes. Without narrowing, the memo1 --supersedes--> old edge produces source_types = ["completeness_in_memo"]. That list is non-empty, so the relationship counts as satisfied and assert_eq!(missing, ["superseded_by"]) fails. The second half (adr_sub) catches the opposite mistake, an exact-match comparison that ignores the chain, because completeness_in_adr_sub != completeness_in_adr. The test covers both ways the narrowing could be wrong.

Nits and 🟢3: skips accepted. Now that the query returns types instead of a count, the shared-helper nit no longer applies. The test-file-name nit is cosmetic. The write-path removal guard is correctly left to a follow-up. Please make sure a follow-up issue actually gets filed for that guard, and for normalizing or rejecting writes made through an in name, so it isn't lost.

Code Review Findings

🟢 1. type_satisfies reloads the whole extends map for each source type

📁 packages/core/src/services/node_service/schema.rs (the for source_type in &source_types loop) calls relationship.rs:558 type_satisfies, which calls resolve_type_chain, which calls get_extends_parent_map().

Each call to type_satisfies for a type that doesn't match exactly runs one full query over the extends edges. The cost is bounded: the query runs only for required In relationships not already satisfied by the in-name lookup, the loop stops at the first match, and the list holds a handful of distinct types at most. Completeness checks are not a hot path, so this is fine as it is. If a caller ever checks completeness in bulk, load the parent map once per check_node_completeness call and resolve chains against it. Principle: YAGNI for now; note it for later.

🟢 2. Errors from type_satisfies skip the query_failed context

📁 schema.rs, at self.type_satisfies(source_type, expected).await?

Both store calls are wrapped by the query_failed closure, so their errors say "Failed to check required relationship ''". An extends-map failure inside type_satisfies propagates bare, as "Failed to load extends edges". It is still a query_failed error, so the caller sees the same error kind and nothing is lost. The message just doesn't name the relationship. Nit.

The closure itself is sound. It captures only &relationship, so it is Copy and can be passed to map_err twice.

What's good

  • The two comments explain why each lookup exists and when each storage shape arises. That is the kind of comment this area needs, since the edge-orientation model is not obvious.
  • The doc comment on get_inbound_relationship_source_types explains why it returns types rather than a count: edges are keyed on relationship_type alone.
  • Each new test targets one failure mode, and the narrowing test checks both the positive and the negative case.

Recommendation

APPROVE. Both 🟡 findings were fixed correctly and each has a test that would catch a regression. The skips are justified, and the new findings are 🟢 only. Merging is the author's call.

@malibio

malibio commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed

⏭️ 🟢1 — the extends map reloads for each source type: skipped. The cost is bounded: it only applies to required in relationships not already satisfied, the loop stops at the first match, and there are only a few distinct types. Completeness checks aren't a hot path. Revisit if completeness is ever checked in bulk.

⏭️ 🟢2 — an error from type_satisfies doesn't name the relationship: skipped. It is already a NodeServiceError::query_failed, so callers see the same error kind; only the message wording differs.

No code changes, so no re-review is needed.

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.

check_node_completeness can never satisfy a required in-direction relationship

1 participant