Skip to content

Schema Support for Relational Fields - Architecture Design #703

Closed

Description

@malibio

Schema Support for Relational Fields - Implementation

Overview

Implement runtime schema-driven relationships in NodeSpace. Users can define custom node types with relationships via NLP/MCP, and NodeSpace automatically generates SurrealDB edge tables.

Architecture Reference: See docs/architecture/data/schema-relational-fields.md for complete architectural decisions.


Key Design Decisions (Finalized)

1. Edge-Only Storage

  • Relationships stored only in edge tables - no spoke table fields
  • Both directions query the same edge table
  • Single source of truth, no sync issues

2. Relationships Separate from Fields

  • Add relationships array to schema spoke (separate from fields)
  • Edge tables are fundamentally different from spoke fields
  • Clearer for NLP parsing

3. Computed Reverse Relationship Discovery

  • Do NOT mutate target schemas when relationship created
  • Use query-time discovery: get_inbound_relationships(node_type)
  • Avoids write amplification, OCC conflicts, user confusion

4. Forward-Looking Schema Changes (Grandfathering)

  • Schema changes apply to new data only
  • Existing data is grandfathered (null allowed for historical)
  • Optional backfill for simple types (edge fields)
  • Consistent with existing field migration behavior

5. Soft-Delete for Relationship Removal

  • When relationship removed from schema: edge table + data preserved
  • Schema node is source of truth for what's "active"
  • User can recover by re-adding relationship
  • Matches existing field behavior (FLEXIBLE tables)

6. Atomic Schema + Edge Table Creation

  • Extends existing create_schema_node_atomic pattern
  • Single transaction: schema node + spoke + edge tables
  • Already proven to work with DDL in transactions

7. Structural Relations Remain Hardcoded

  • has_child and mentions stay in schema.surql
  • User-defined relationships use new schema-driven approach

Example Schema with Relationships

{
  "id": "invoice",
  "nodeType": "schema",
  "content": "Invoice",
  "fields": [
    {"name": "amount", "type": "number", "required": true},
    {"name": "due_date", "type": "date"}
  ],
  "relationships": [
    {
      "name": "billed_to",
      "targetType": "customer",
      "direction": "out",
      "cardinality": "one",
      "required": true,
      "reverseName": "invoices",
      "reverseCardinality": "many",
      "edgeFields": [
        {"name": "billing_date", "type": "date", "required": true},
        {"name": "payment_terms", "type": "string"}
      ]
    }
  ]
}

Implementation Phases

Phase 1: Data Model Extensions

  • Add SchemaRelationship struct to packages/core/src/models/schema.rs
  • Add EdgeField struct (simpler than SchemaField)
  • Update packages/core/src/db/schema.surql - add relationships field
  • Add serialization/deserialization tests

Phase 2: DDL Generation for Edge Tables

  • Add generate_relationship_ddl_statements() to SchemaTableManager
  • Implement edge table name computation: {source}_{name}_{target}
  • Generate edge field DDL with IF NOT EXISTS
  • Generate bidirectional indexes (in, out, unique)
  • Add tests for edge table DDL generation

Phase 3: Schema CRUD API

  • Extend create_schema_node_atomic to include edge table DDL
  • Extend update_schema_node_atomic for relationship changes
  • Add relationship validation (target schema exists if required)
  • Add tests for schema CRUD with relationships

Phase 4: Relationship CRUD API

  • Add create_relationship(source_id, relationship_name, target_id, edge_data)
  • Add delete_relationship(source_id, relationship_name, target_id)
  • Add get_related_nodes(node_id, relationship_name, direction)
  • Add tests for relationship CRUD

Phase 5: NLP Discovery API

  • Add get_schema_with_relationships(schema_id) helper
  • Add get_inbound_relationships(node_type) computed lookup
  • Cache relationship metadata for fast NLP access
  • Add documentation for NLP integration

Phase 6: MCP Handler Integration

  • Extend MCP schema handlers to support relationships
  • Add relationship CRUD handlers
  • Add integration tests

Migration Behavior (Documented)

NodeSpace uses a forward-looking, soft-delete migration pattern for both fields and relationships:

Change Historical Data New Data
Add relationship N/A Must provide if required
Remove relationship Edges preserved (soft-delete) Can't create new
Set required: true Null allowed (grandfathered) Must provide
Add edge field Null for historical Required if marked
Remove edge field Data preserved Not stored

Breaking changes require decision points (e.g., cardinality change from many→one).


Acceptance Criteria

  • Architecture documented in docs/architecture/data/schema-relational-fields.md
  • Migration behavior documented (consistent with existing field pattern)
  • SchemaRelationship and EdgeField structs defined and tested
  • Schema spoke table supports relationships array
  • Edge table DDL generation working with tests
  • Atomic schema + relationship creation working
  • Relationship CRUD API working
  • NLP discovery API working
  • MCP handlers support relationship CRUD

Technical Notes

Edge Table Naming: {source_type}_{relationship_name}_{target_type}

Query Patterns:

-- Forward: invoice -> customer
SELECT ->billed_to->customer.* FROM invoice:INV-001;

-- Reverse: customer -> invoices  
SELECT <-billed_to<-invoice.* FROM customer:acme;

-- With edge properties
SELECT in, out, billing_date FROM invoice_billed_to_customer
WHERE billing_date > time::now() - 30d;

Dependencies

Definition of Done

  • All acceptance criteria met
  • All tests passing
  • Architecture documentation complete
  • MCP handlers functional
  • NLP can discover and query relationships

Activity

  1. malibio commented on Dec 1, 2025

    @malibio
    CollaboratorAuthor

    Test baseline established:

    • Frontend: 728 tests passed
    • Rust: (running, will update when complete)

    Starting architecture design work for schema relational fields support.

  2. self-assigned this
    on Dec 1, 2025
  3. malibio commented on Dec 1, 2025

    @malibio
    CollaboratorAuthor

    Implementation Guide - Schema Relational Fields

    Based on our discussion, here is the complete implementation plan for adding runtime schema-driven relationships to NodeSpace.

    Architecture Overview

    Goal: Enable users to define custom node types with relationships via NLP/MCP. NodeSpace automatically generates SurrealDB edge tables and provides schema-driven query capabilities.

    Key Principles:

    • Runtime schema engine (no compile-time code generation)
    • Atomic schema + relationship DDL generation
    • Abstract graph traversal using relationship metadata
    • NLP-driven schema discovery and query generation

    Phase 1: Data Model Extensions

    1.1 Add SchemaRelationship Struct

    File: packages/core/src/models/schema.rs

    Add new struct alongside SchemaField:

    /// Definition of a relationship between node types
    #[derive(Debug, Clone, Serialize, Deserialize)]
    #[serde(rename_all = "camelCase")]
    pub struct SchemaRelationship {
        /// Relationship name (e.g., "billed_to", "assigned_to")
        pub name: String,
        
        /// Target node type (e.g., "customer", "person")
        pub target_type: String,
        
        /// Direction: "out" (this->target) or "in" (target->this)
        pub direction: String,
        
        /// Cardinality: "one" or "many"
        pub cardinality: String,
        
        /// Whether this relationship is required
        #[serde(skip_serializing_if = "Option::is_none")]
        pub required: Option<bool>,
        
        /// Reverse relationship name on target type
        #[serde(skip_serializing_if = "Option::is_none")]
        pub reverse_name: Option<String>,
        
        /// Reverse cardinality
        #[serde(skip_serializing_if = "Option::is_none")]
        pub reverse_cardinality: Option<String>,
        
        /// Generated edge table name (auto-computed)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub edge_table: Option<String>,
        
        /// Whether this is auto-generated from reverse relationship
        #[serde(skip_serializing_if = "Option::is_none")]
        pub auto_generated: Option<bool>,
        
        /// Link to source relationship (for reverse relationships)
        #[serde(skip_serializing_if = "Option::is_none")]
        pub reverse_of: Option<String>,
        
        /// Fields stored on the edge itself
        #[serde(skip_serializing_if = "Option::is_none")]
        pub edge_fields: Option<Vec<SchemaField>>,
        
        /// Human-readable description
        #[serde(skip_serializing_if = "Option::is_none")]
        pub description: Option<String>,
    }

    1.2 Update Schema Spoke Table DDL

    File: packages/core/src/db/schema.surql

    Add relationships field to schema table:

    -- Schema spoke: Type definitions (STRUCTURAL - not derived from schema nodes)
    DEFINE TABLE IF NOT EXISTS schema SCHEMALESS;
    DEFINE FIELD IF NOT EXISTS node ON TABLE schema TYPE option<record>;
    
    -- Core schema fields
    DEFINE FIELD IF NOT EXISTS is_core ON TABLE schema TYPE bool DEFAULT false;
    DEFINE FIELD IF NOT EXISTS version ON TABLE schema TYPE int DEFAULT 1;
    DEFINE FIELD IF NOT EXISTS description ON TABLE schema TYPE string DEFAULT "";
    
    -- Fields array
    DEFINE FIELD IF NOT EXISTS fields ON TABLE schema FLEXIBLE TYPE option<array> DEFAULT [];
    
    -- NEW: Relationships array
    DEFINE FIELD IF NOT EXISTS relationships ON TABLE schema FLEXIBLE TYPE option<array> DEFAULT [];

    1.3 Add Tests for SchemaRelationship Serialization

    File: packages/core/src/models/schema.rs (test module)

    #[test]
    fn test_schema_relationship_serialization() {
        let relationship = SchemaRelationship {
            name: "billed_to".to_string(),
            target_type: "customer".to_string(),
            direction: "out".to_string(),
            cardinality: "one".to_string(),
            required: Some(true),
            reverse_name: Some("invoices".to_string()),
            reverse_cardinality: Some("many".to_string()),
            edge_table: Some("invoice_billed_to_customer".to_string()),
            auto_generated: None,
            reverse_of: None,
            edge_fields: Some(vec\![
                SchemaField {
                    name: "billing_date".to_string(),
                    field_type: "date".to_string(),
                    // ... rest of field definition
                }
            ]),
            description: Some("Links invoice to customer".to_string()),
        };
    
        let json = serde_json::to_value(&relationship).unwrap();
        
        assert_eq\!(json["name"], "billed_to");
        assert_eq\!(json["targetType"], "customer");
        assert_eq\!(json["direction"], "out");
        assert_eq\!(json["cardinality"], "one");
        assert_eq\!(json["required"], true);
    }

    Phase 2: DDL Generation for Edge Tables

    2.1 Add Edge Table DDL Generation Method

    File: packages/core/src/services/schema_table_manager.rs

    Add new method:

    impl<C> SchemaTableManager<C>
    where
        C: surrealdb::Connection,
    {
        /// Generate DDL statements for relationship edge tables
        ///
        /// Creates SurrealDB RELATION tables with proper IN/OUT constraints,
        /// edge fields, and bidirectional indexes.
        pub fn generate_relationship_ddl_statements(
            &self,
            source_type: &str,
            relationships: &[SchemaRelationship],
        ) -> Result<Vec<String>, NodeServiceError> {
            let mut statements = Vec::new();
            
            for rel in relationships {
                // Skip auto-generated reverse relationships (handled by source)
                if rel.auto_generated.unwrap_or(false) {
                    continue;
                }
                
                // Compute edge table name
                let edge_table = rel.edge_table
                    .clone()
                    .unwrap_or_else(|| self.compute_edge_table_name(source_type, rel));
                
                // Validate edge table name
                if \!edge_table.chars().all(|c| c.is_alphanumeric() || c == '_') {
                    return Err(NodeServiceError::invalid_update(format\!(
                        "Invalid edge table name '{}'", edge_table
                    )));
                }
                
                // 1. Define edge table with IN/OUT constraints
                let (in_type, out_type) = match rel.direction.as_str() {
                    "out" => (source_type, rel.target_type.as_str()),
                    "in" => (rel.target_type.as_str(), source_type),
                    _ => return Err(NodeServiceError::invalid_update(
                        format\!("Invalid direction '{}', must be 'in' or 'out'", rel.direction)
                    )),
                };
                
                statements.push(format\!(
                    "DEFINE TABLE IF NOT EXISTS {} SCHEMAFULL TYPE RELATION IN {} OUT {};",
                    edge_table, in_type, out_type
                ));
                
                // 2. Core edge fields (always present)
                statements.push(format\!(
                    "DEFINE FIELD IF NOT EXISTS created_at ON TABLE {} TYPE datetime DEFAULT time::now();",
                    edge_table
                ));
                
                statements.push(format\!(
                    "DEFINE FIELD IF NOT EXISTS version ON TABLE {} TYPE int DEFAULT 1;",
                    edge_table
                ));
                
                // 3. User-defined edge fields
                if let Some(ref edge_fields) = rel.edge_fields {
                    for field in edge_fields {
                        self.generate_field_ddl(&edge_table, field, None, &mut statements)?;
                    }
                }
                
                // 4. Core indexes for bidirectional queries
                statements.push(format\!(
                    "DEFINE INDEX IF NOT EXISTS idx_{}_in ON TABLE {} COLUMNS in;",
                    edge_table, edge_table
                ));
                
                statements.push(format\!(
                    "DEFINE INDEX IF NOT EXISTS idx_{}_out ON TABLE {} COLUMNS out;",
                    edge_table, edge_table
                ));
                
                // 5. Unique constraint (prevent duplicate edges)
                statements.push(format\!(
                    "DEFINE INDEX IF NOT EXISTS idx_{}_unique ON TABLE {} COLUMNS in, out UNIQUE;",
                    edge_table, edge_table
                ));
            }
            
            Ok(statements)
        }
        
        /// Compute edge table name from relationship definition
        fn compute_edge_table_name(&self, source_type: &str, rel: &SchemaRelationship) -> String {
            format\!("{}_{}_{}",
  4. added a commit that references this issue on Dec 1, 2025
    cbb55c2
  5. reopened this on Dec 1, 2025
  6. malibio commented on Dec 1, 2025

    @malibio
    CollaboratorAuthor

    Architecture phase complete and merged in PR #707.

    Reopening issue to track implementation of the 6 phases documented in the architecture.

    Next: Begin Phase 1 (Data Model Extensions) when ready.

  7. malibio commented on Dec 1, 2025

    @malibio
    CollaboratorAuthor

    Test baseline: Frontend 1477 passed (74 files), Rust 482 passed (16 ignored). Starting Phase 1 implementation.

  8. added 6 commits that reference this issue on Dec 1, 2025
    7321810
    0afc6b4
    4ac483e
    705f5fa
    3de13d3
    b2b2d4e
  9. malibio commented on Dec 1, 2025

    @malibio
    CollaboratorAuthor

    Phases 5-6 Complete! 🎉

    Phase 5: NLP Discovery API ✅

    • Added relationships field to SchemaNode struct
    • Added get_all_schemas() method to SurrealStore and NodeService
    • Created InboundRelationshipCache with time-based (60s TTL) and event-driven invalidation
    • Added get_inbound_relationships() for reverse relationship discovery
    • Added get_relationship_graph() for complete model visualization
    • Added get_schema_with_relationships() convenience method

    Phase 6: MCP Handler Integration ✅

    Created relationships.rs handler module with 6 new MCP tools:

    • create_relationship - Create edges between nodes
    • delete_relationship - Remove relationship edges
    • get_related_nodes - Query connected nodes (supports direction: 'out'/'in')
    • get_relationship_graph - Get complete relationship graph summary
    • get_inbound_relationships - Discover reverse relationships by target type
    • get_all_schemas - Get all schema definitions with relationships

    Test Results

    • All 521 tests passing ✅
    • Quality checks (clippy, rustfmt, svelte-check) passing ✅

    Commit

    b2b2d4e - Phase 5-6 Complete: NLP Discovery API and MCP Handler Integration

  10. added 6 commits that reference this issue on Feb 4, 2026
    018643f
    206262b
    d818eea
    8507027
    6bf1dc2
    0284033
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions