Skip to content

Make target_type optional on SchemaRelationship and add node completeness check - #890

Merged
malibio merged 2 commits into
mainfrom
feature/issue-888-optional-target-type-and-completeness
Feb 19, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-888-optional-target-type-and-completeness

Conversation

@malibio

@malibio malibio commented Feb 19, 2026

Copy link
Copy Markdown
Collaborator

Closes #888

…de_completeness (closes #888)

## Part 1: Optional target_type

- `SchemaRelationship.target_type`: `String` → `Option<String>`
  - None = untyped relationship accepting any target node type
  - Serializes with `skip_serializing_if = "Option::is_none"` so existing schemas are backward-compatible
- `compute_edge_table_name`: `{source}_{name}` when None, `{source}_{name}_{target}` when Some
- `node_service.rs`: skip type check in `create_relationship` when target_type is None
- `schema_table_manager.rs`: skip `validate_type_name` when target_type is None (both occurrences)
- `relationship_cache.rs`: untyped relationships stored under "*" sentinel; `get_inbound_relationships` merges wildcard entries into every lookup
- `schema_node.rs`: `get_relationships_to` includes untyped (None) relationships
- `node_service.rs`: updated `get_inbound_relationships` and `get_relationship_graph` for Option<String>
- `relationships.rs`: `RelationshipEdge.target_type` → `Option<String>` (skipped when None in JSON)
- `surreal_store.rs`: fixed SurrealDB deserialization bug — `get_all_schemas` and `get_schema_node` now
  use raw JSON path (→ `SchemaNode::from_node` via serde_json) instead of SurrealDB native struct
  deserializer which cannot handle absent Option<String> fields in nested JSON blobs

## Part 2: check_node_completeness

- `node_service.rs`: added `check_node_completeness(&self, node_id) → CompletenessResult`
  - Reads node's schema, checks each `required: true` relationship has at least one edge
  - Read-only introspection — does NOT block node creation or updates
- `relationships.rs`: added `handle_check_node_completeness` MCP handler
- `tools.rs`: added `check_node_completeness` tool (Tier 2 / Discoverable, category: Relationships)

## Tests

- 10+ new unit/integration tests across schema.rs, relationships_handler_test.rs,
  relationship_cache_test.rs, and schema_table_manager_test.rs
- All 1200+ existing tests continue to pass

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

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

malibio commented Feb 19, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This PR addresses a real architectural gap: untyped relationships were impossible to express, and the required field on SchemaRelationship was declared but never consumed. Both gaps are now closed. The implementation correctly propagates Option<String> through the entire stack — model, validation, table management, cache, and the MCP layer — and adds a new check_node_completeness introspection tool. The deserialization fix in surreal_store.rs is the most significant engineering decision and is well-motivated.

Overall this is a net improvement and all acceptance criteria from issue #888 are satisfied. A few issues warrant attention before merge.


Findings

Suggested Improvements

[Improvement] CompletenessResult is missing #[serde(rename_all = \"camelCase\")] — wire format is inconsistent with the rest of the MCP layer

File: packages/core/src/services/node_service.rs, line 6092

The struct serializes with snake_case field names (node_id, is_complete, missing_relationships), but every other MCP output type in this codebase uses camelCase (nodeId, isComplete, missingRelationships). The doc comment in the handler (relationships.rs line 465) even shows the expected camelCase format:

{
  "nodeId": "invoice-001",
  "isComplete": false,
  "missingRelationships": ["billed_to"]
}

But the actual output will be:

{
  "node_id": "invoice-001",
  "is_complete": false,
  "missing_relationships": ["billed_to"]
}

The test test_completeness_result_complete_camel_case at line 441 asserts json[\"node_id\"] and json[\"is_complete\"] — confirming the test was written for snake_case, not camelCase. The test name says "camel_case" but tests the opposite. This is a wire contract bug that will confuse any MCP client consuming this tool.

Fix: add #[serde(rename_all = \"camelCase\")] to CompletenessResult and update the assertions in the test to match (json[\"nodeId\"], json[\"isComplete\"], json[\"missingRelationships\"]).


[Improvement] N+1 query pattern in check_node_completeness — one DB round-trip per required relationship

File: packages/core/src/services/node_service.rs, lines 6046–6080

The loop fires a separate SurrealDB query for each relationship where required == Some(true). The issue notes acknowledge this as a known trade-off. For schemas with a modest number of required relationships (1–5) this is fine today. However, a single GROUP BY or IN query can cover all required relationships in one shot:

SELECT relationship_type, count() AS cnt
FROM relationship
WHERE in = $source
  AND relationship_type IN $rel_types
GROUP BY relationship_type

This is not a blocker for greenfield, but worth capturing as a follow-up issue given the function will be called per-node in workflow loops.


[Improvement] get_all_inbound_relationships now exposes the \"*\" sentinel key in its public return value — callers must know to filter it

File: packages/core/src/services/relationship_cache.rs, lines 151–160

get_all_inbound_relationships returns cache.clone() which now includes the \"*\" key for untyped relationships. Any existing or future caller iterating over this map to build a type graph will see \"*\" as if it were a real node type. The method's doc comment does not mention this behavior change.

Two options:

  1. Update the doc comment to document the \"*\" sentinel explicitly.
  2. Filter \"*\" out of the return value and provide a separate get_untyped_inbound_relationships() accessor.

Option 1 is minimal and sufficient for now. The test at relationship_cache_test.rs:822 already asserts all.contains_key(\"*\") which validates the current behavior, but the public contract should be documented.


Nitpicks

Nit: Doc comment on edge_table field still references the old three-part format only

File: packages/core/src/models/schema.rs, line 301

/// If not specified, computed as: `{source_type}_{name}_{target_type}`

This is now incomplete. Should read:

/// If not specified, computed as: `{source_type}_{name}_{target_type}` when `target_type` is set,
/// or `{source_type}_{name}` when `target_type` is `None`.

Nit: serde_json::to_value(result).unwrap() at line 485 of relationships.rs is a panic path in an MCP handler

This mirrors the existing pattern in handle_get_all_schemas at line 446, so it is consistent with the codebase. However, serde_json::to_value on a struct of String and bool fields is infallible in practice, and the existing pattern can be noted as a low-priority cleanup across the whole handler file.


Nit: Test name test_completeness_result_complete_camel_case (line 433) does not accurately describe what it tests

The name implies camelCase serialization validation, but the assertions check snake_case keys. Once the rename_all = \"camelCase\" fix is applied this test name will be accurate — until then it is misleading.


Acceptance Criteria Verification

Criterion Status
target_type: String → Option<String> with skip_serializing_if Done
compute_edge_table_name handles None Done
create_relationship skips type check when None Done
schema_table_manager.rs skips validate_type_name for None (both call sites) Done
relationship_cache.rs stores untyped under \"*\" and merges in lookups Done
check_node_completeness method on NodeService Done
check_node_completeness MCP tool (Tier 2 / Discoverable) Done
MCP handler in relationships.rs Done
Tests: optional target_type (untyped, typed, edge table naming, cache) Done
Tests: completeness (complete, missing, multiple, no schema, round-trip) Done
All 1200+ existing tests continue to pass (per commit message) Claimed done

The one open issue is the wire format mismatch on CompletenessResult (snake_case vs camelCase) which should be fixed before merge to avoid a breaking change on the MCP client contract.

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

Requesting one change before merge: the CompletenessResult struct is missing #[serde(rename_all = "camelCase")], which breaks the MCP wire contract — the output will be snake_case while all other MCP tools emit camelCase and the handler's own doc comment shows camelCase. The test named test_completeness_result_complete_camel_case also needs its assertions updated to match once the attribute is added. See the detailed comment for full review findings.

- Add `#[serde(rename_all = "camelCase")]` to `CompletenessResult` — fixes
  wire contract bug where MCP output was snake_case while all other MCP
  tools emit camelCase and the handler's own doc comment showed camelCase
- Update test assertions in relationships_handler_test.rs to use camelCase
  keys (`nodeId`, `isComplete`, `missingRelationships`) — test name
  `test_completeness_result_complete_camel_case` now accurately describes
  what it tests
- Update `edge_table` doc comment in schema.rs to document both cases:
  three-part name when `target_type` is set, two-part when `None`
- Update `get_all_inbound_relationships` doc comment in relationship_cache.rs
  to document that the returned map may contain the `"*"` sentinel key for
  untyped relationships, so callers are aware without needing a separate API

Skipped (noted for follow-up):
- N+1 query in check_node_completeness: acknowledged trade-off for
  greenfield with modest required-relationship counts; captured as
  potential future optimization
- `serde_json::to_value(...).unwrap()` panic path: consistent with existing
  codebase pattern across handlers; low-priority cleanup across the file

Addresses reviewer recommendations from PR #890 review.

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

malibio commented Feb 19, 2026

Copy link
Copy Markdown
Collaborator Author

Review Recommendations Addressed

All reviewer recommendations have been processed.

✅ Addressed (4 items)

🔴 Critical — Wire format bug fixed
Added #[serde(rename_all = "camelCase")] to CompletenessResult. The MCP output now correctly emits nodeId, isComplete, missingRelationships — consistent with all other MCP tools and the handler's own doc comment.

Test assertions updated
All json["node_id"], json["is_complete"], json["missing_relationships"] assertions in relationships_handler_test.rs updated to camelCase equivalents. The test name test_completeness_result_complete_camel_case now accurately describes what it validates.

Doc fix — edge_table field
Updated the doc comment to cover both cases: three-part name when target_type is set, two-part when None.

Doc fix — get_all_inbound_relationships sentinel key
Updated the doc comment to document that the returned map may include the "*" sentinel key for untyped relationships, so callers are aware without needing a separate API (Option 1 from review).


⏭️ Skipped (2 items)

N+1 query in check_node_completeness
Acknowledged trade-off for greenfield with modest required-relationship counts (1–5). The reviewer also called this "not a blocker." Captured as a potential future optimization if/when workflow loops make this hot.

serde_json::to_value(...).unwrap() panic path
Consistent with existing codebase pattern in handle_get_all_schemas (same file). Low-priority cleanup across the entire handler file — out of scope for this PR.


All 144 Rust tests pass. Quality checks clean.

@malibio
malibio merged commit 3e4e99c into main Feb 19, 2026
@malibio
malibio deleted the feature/issue-888-optional-target-type-and-completeness branch February 19, 2026 13:03
malibio added a commit that referenced this pull request Feb 26, 2026
…ness check (#890)

* Fix: Make target_type optional on SchemaRelationship and add check_node_completeness (closes #888)

## Part 1: Optional target_type

- `SchemaRelationship.target_type`: `String` → `Option<String>`
  - None = untyped relationship accepting any target node type
  - Serializes with `skip_serializing_if = "Option::is_none"` so existing schemas are backward-compatible
- `compute_edge_table_name`: `{source}_{name}` when None, `{source}_{name}_{target}` when Some
- `node_service.rs`: skip type check in `create_relationship` when target_type is None
- `schema_table_manager.rs`: skip `validate_type_name` when target_type is None (both occurrences)
- `relationship_cache.rs`: untyped relationships stored under "*" sentinel; `get_inbound_relationships` merges wildcard entries into every lookup
- `schema_node.rs`: `get_relationships_to` includes untyped (None) relationships
- `node_service.rs`: updated `get_inbound_relationships` and `get_relationship_graph` for Option<String>
- `relationships.rs`: `RelationshipEdge.target_type` → `Option<String>` (skipped when None in JSON)
- `surreal_store.rs`: fixed SurrealDB deserialization bug — `get_all_schemas` and `get_schema_node` now
  use raw JSON path (→ `SchemaNode::from_node` via serde_json) instead of SurrealDB native struct
  deserializer which cannot handle absent Option<String> fields in nested JSON blobs

## Part 2: check_node_completeness

- `node_service.rs`: added `check_node_completeness(&self, node_id) → CompletenessResult`
  - Reads node's schema, checks each `required: true` relationship has at least one edge
  - Read-only introspection — does NOT block node creation or updates
- `relationships.rs`: added `handle_check_node_completeness` MCP handler
- `tools.rs`: added `check_node_completeness` tool (Tier 2 / Discoverable, category: Relationships)

## Tests

- 10+ new unit/integration tests across schema.rs, relationships_handler_test.rs,
  relationship_cache_test.rs, and schema_table_manager_test.rs
- All 1200+ existing tests continue to pass

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

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Address review: Fix CompletenessResult wire format and update docs

- Add `#[serde(rename_all = "camelCase")]` to `CompletenessResult` — fixes
  wire contract bug where MCP output was snake_case while all other MCP
  tools emit camelCase and the handler's own doc comment showed camelCase
- Update test assertions in relationships_handler_test.rs to use camelCase
  keys (`nodeId`, `isComplete`, `missingRelationships`) — test name
  `test_completeness_result_complete_camel_case` now accurately describes
  what it tests
- Update `edge_table` doc comment in schema.rs to document both cases:
  three-part name when `target_type` is set, two-part when `None`
- Update `get_all_inbound_relationships` doc comment in relationship_cache.rs
  to document that the returned map may contain the `"*"` sentinel key for
  untyped relationships, so callers are aware without needing a separate API

Skipped (noted for follow-up):
- N+1 query in check_node_completeness: acknowledged trade-off for
  greenfield with modest required-relationship counts; captured as
  potential future optimization
- `serde_json::to_value(...).unwrap()` panic path: consistent with existing
  codebase pattern across handlers; low-priority cleanup across the file

Addresses reviewer recommendations from PR #890 review.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[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.

Make target_type optional on SchemaRelationship and add node completeness check

1 participant