Repository navigation
Schema Support for Relational Fields - Architecture Design - #707
Conversation
## Summary
Complete architecture design and implementation plan for runtime schema-driven
relationships in NodeSpace. Users can define custom node types with relationships
via NLP/MCP, and NodeSpace automatically generates SurrealDB edge tables.
## Key Design Decisions
- **Runtime schema engine**: NLP → SchemaNodes → DDL generation → SurrealDB
- **Relationships separate from fields**: Clearer separation, easier for NLP
- **Atomic creation**: Schema + edge tables created in single transaction
- **Bidirectional auto-sync**: Reverse relationships auto-added to target schemas
- **Edge table naming**: {source_type}_{relationship_name}_{target_type}
- **Structural relations preserved**: has_child, mentions remain in schema.surql
## Documentation Added
- `docs/architecture/data/schema-relational-fields.md` - Complete architecture
- Runtime schema engine overview
- Composition vs relationship decision tree
- SchemaRelationship struct definition
- Edge table DDL generation strategy
- Atomic transaction patterns
- Bidirectional relationship auto-sync
- Example use cases (Invoice→Customer, Task→Person)
- Migration path from simple record to relation
## GitHub Issue Updated
Issue #703 now contains:
- Finalized design decisions
- 6-phase implementation plan with detailed tasks
- Example JSON schemas with relationships
- Technical notes on data structures and DDL patterns
- Clear acceptance criteria
## Implementation Phases (Documented, Not Implemented)
1. Data Model Extensions (SchemaRelationship struct, schema.surql update)
2. DDL Generation (edge table creation in SchemaTableManager)
3. Schema CRUD API (atomic transactions, validation)
4. Relationship Query API (abstract graph traversal)
5. MCP Handler Integration (expose to NLP)
6. NLP Discovery API (relationship metadata for query generation)
## Test Status
- Frontend: 1477 tests passed
- Rust: 482 tests passed
- No new test failures introduced
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
## Summary Updated architecture documentation based on senior architect review and collaborative discussion. Key refinements: ## Architecture Refinements 1. **Edge-Only Storage** (Decision 1) - 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. **Computed Reverse Relationship Discovery** (Decision 3) - Do NOT mutate target schemas when relationship created - Use query-time discovery via `get_inbound_relationships(node_type)` - Avoids write amplification, OCC conflicts, user confusion 3. **Forward-Looking Schema Changes** (Decision 4) - Schema changes apply to NEW data only - Existing data is grandfathered (null allowed for historical) - Optional backfill for simple types with `retroactive_default` - Consistent with existing field migration behavior 4. **Soft-Delete for Relationship Removal** (Decision 5) - Edge table + data preserved when relationship removed from schema - Schema node is source of truth for what's "active" - Matches existing field behavior (FLEXIBLE tables, no REMOVE FIELD) ## New Documentation - Schema Migration Behavior section documenting existing soft-delete pattern - Detailed migration behavior table for relationships - Breaking changes require decision points (e.g., cardinality changes) - Simplified EdgeField struct (distinct from SchemaField) ## GitHub Issue Updated - Acceptance criteria updated (architecture + migration docs checked) - Implementation phases refined with concrete tasks - Migration behavior table added 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
malibio
left a comment
There was a problem hiding this comment.
Architecture Review: Schema Relational Fields (PR #703)
Summary Assessment
RECOMMENDATION: APPROVE WITH MINOR RECOMMENDATIONS
This is a well-designed architecture that thoughtfully integrates schema-driven relationships into NodeSpace's existing hybrid system. The design demonstrates strong understanding of the codebase patterns and makes sound technical decisions. The documentation is comprehensive and follows established conventions.
Key Strengths
1. Excellent Integration with Existing Architecture
- ✅ Follows hub-spoke pattern: Relationships correctly use edge tables (RELATE) vs Record Links, maintaining clear separation between composition and association
- ✅ Consistent with hybrid approach: Preserves hardcoded structural relations (
has_child,mentions) while enabling user-extensible relationships - ✅ Builds on proven patterns: Extends existing
create_schema_node_atomictransaction pattern rather than inventing new mechanisms - ✅ Aligns with schema-as-node philosophy: Schemas remain regular nodes, relationships are just additional metadata
2. Smart Design Decisions
Decision 1: Edge-Only Storage ⭐
- Excellent rationale: single source of truth, no sync issues
- Bidirectional queries use same edge table (simple and efficient)
- Avoids common pitfall of duplicating relationship data in spoke fields
Decision 3: Computed Reverse Relationships ⭐⭐
- Brilliant solution to write amplification problem
- Prevents OCC conflicts and user confusion
- Query-time discovery is cheaper than mutation cascades
- Suggested caching strategy shows performance awareness
Decision 4: Forward-Looking Schema Changes ⭐
- Perfectly consistent with existing field migration behavior (documented in schema-management-implementation-guide.md)
- Grandfathering approach is pragmatic and user-friendly
- Optional backfill with
retroactive_defaultprovides escape hatch
Decision 5: Soft-Delete for Relationships ⭐
- Matches existing field deletion pattern (FLEXIBLE tables)
- No accidental data loss - always recoverable
- Schema node as source of truth is clean separation of concerns
3. Comprehensive Documentation
- Clear executive summary with key insights
- Detailed rationale for each decision
- Practical examples throughout
- Migration behavior explicitly documented
- Related documents properly cross-referenced
4. Scalability Considerations
- Edge table naming convention prevents collisions
- Proper indexes (in, out, unique) for bidirectional queries
- Performance notes (cache inbound relationships)
- Atomic transactions prevent partial state
Concerns and Issues
CRITICAL (Must Address Before Implementation)
None. The architecture is sound.
MAJOR (Should Address)
1. EdgeField vs SchemaField Distinction
Issue: The EdgeField struct is simplified compared to SchemaField, but the rationale could be clearer.
Questions:
- Why no
protectionlevel for edge fields? (Core vs user edge fields?) - Why no
descriptionfield for documentation? - Should edge fields support nested types (object, array)?
Recommendation: Add a brief section explaining why EdgeField is simpler than SchemaField.
2. Relationship Cardinality Enforcement
Issue: The doc mentions cardinality changes require decision points, but doesn't explain how cardinality is enforced for new relationships.
Questions:
- How do you prevent creating multiple edges when
cardinality: "one"? - Is it application-level validation, or database UNIQUE constraint?
- What happens if you try to create invoice→customer twice with cardinality="one"?
Recommendation: Add section on cardinality enforcement at edge creation time.
MINOR (Nice to Have)
3. Query API Return Types
Phase 4 defines API signatures but doesn't specify return types. Consider adding explicit return types for clarity.
4. Relationship Name Validation
No mention of validation rules for relationship names:
- Valid characters? (alphanumeric, underscores, hyphens?)
- Reserved names? (can't name a relationship "has_child"?)
- Case sensitivity?
5. Validation: Target Schema Existence
Phase 3 mentions "target schema exists if required" but doesn't specify when this validation happens.
6. Edge Table Naming Collision Prevention
Naming convention {source}_{name}_{target} could collide. Document collision handling strategy.
Completeness Assessment
✅ Covered Comprehensively
- Runtime schema engine overview
- DDL generation strategy
- Atomic transaction patterns
- Migration behavior
- Query patterns (forward, reverse, with edge data)
- Integration with existing systems
⚠️ Needs Expansion (Before Phase 1)
- EdgeField simplification rationale (why no protection levels?)
- Cardinality enforcement details (application vs database)
- Relationship name validation rules
- Target schema existence validation timing
- Edge table name collision handling
📝 Future Considerations (Document Later)
- Performance benchmarks
- Relationship query limits/pagination
- Cascading deletes
- Relationship metadata (created by, modified at)
- Circular dependency handling
Integration with Existing Systems
✅ Excellent Alignment
With Node Behavior System: Correctly distinguishes core vs extension relationships
With Schema Management: Follows schema-as-node pattern, consistent protection model
With Hub-Spoke Architecture: Correctly uses RELATE edges for node-to-node relationships
With SurrealDB Schema: Proper DDL patterns with FLEXIBLE tables
No Conflicts Found
Architecture properly extends rather than replaces existing patterns.
Questions for Clarification
- EdgeField Protection: Should edge fields have protection levels?
- Relationship Versioning: Do relationships need version tracking for OCC?
- Cascading Deletes: When target schema deleted, what happens to relationships referencing it?
- Circular Dependencies: Are circular relationships allowed? (A→B, B→A)
- Relationship Query Limits: Should
get_related_nodes()have default LIMIT? Pagination strategy?
Implementation Risks
| Risk Level | Phase | Notes |
|---|---|---|
| LOW ✅ | Phase 1 (Data Model) | Straightforward struct additions |
| LOW ✅ | Phase 2 (DDL Generation) | Extends proven pattern |
| MEDIUM |
Phase 3 (Atomic Transactions) | Complex transaction - test with large schemas |
| MEDIUM |
Phase 5 (NLP Discovery) | Caching strategy needs careful design |
| LOW ✅ | Phase 6 (MCP Handlers) | Simple API exposure |
Final Verdict
APPROVE: This architecture is ready for implementation with minor documentation enhancements.
Required Before Phase 1 Implementation
- Add EdgeField rationale section
- Document cardinality enforcement strategy
- Specify relationship name validation rules
- Clarify edge table collision handling
- Detail inbound relationship caching strategy
Recommended Enhancements (Can be added during implementation)
- Add query API return type specifications
- Document target schema validation timing
- Specify relationship versioning strategy (if needed)
- Define cascading delete behavior
Next Steps
- Update Architecture Doc: Address the 5 required items above
- Review Updated Doc: Quick review by senior architect
- Proceed to Phase 1: Begin
SchemaRelationshipstruct implementation - Add Performance Tests: Include in Phase 2
Overall Assessment: This is high-quality architectural work that demonstrates deep understanding of the codebase and thoughtful design. The few gaps identified are minor and easily addressed. The architecture is sound, scalable, and ready for implementation once the documentation is enhanced per the recommendations above.
🤖 Review conducted by Senior Architect Agent
## Summary Added the 5 required sections identified in architect review to complete the architecture documentation before implementation begins. ## Sections Added ### 1. EdgeField Simplification Rationale - Explained why EdgeField is simpler than SchemaField - No protection levels (all user-defined) - No nested types (primitives only) - No enum extension (simpler lifecycle) - Tightly coupled to relationship lifecycle ### 2. Cardinality Enforcement Strategy - Application-level validation for cardinality="one" - Database-level UNIQUE index on (in, out) prevents duplicates - Check existing edges before creating new ones - Clear error messages for violations ### 3. Relationship Name Validation Rules - Pattern: ^[a-zA-Z][a-zA-Z0-9_-]*$ (start with letter) - Reserved names: has_child, mentions, node, data - Validation during schema node validation (SchemaNodeBehavior) - Case-sensitive storage ### 4. Target Schema Validation Timing - Schema creation: Lenient (allow forward references) - Relationship creation: Strict (validate target schema + node exists) - Four-step validation: source exists, schema exists, target exists, type matches ### 5. Inbound Relationship Caching Strategy - HashMap cache: target_type → Vec<InboundRelationship> - Event-driven invalidation (schema change flag) - Time-based refresh (max 60s stale) - Performance: <1µs cache hit, 50-200ms refresh ## Edge Table Name Collision Handling - Detailed collision scenarios and resolution - Triplet (source, name, target) ensures uniqueness by design - Validation prevents accidental collision ## Status All 5 required items from architect review addressed. Architecture ready for implementation. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
* Document architecture for schema relational fields (closes #703) ## Summary Complete architecture design and implementation plan for runtime schema-driven relationships in NodeSpace. Users can define custom node types with relationships via NLP/MCP, and NodeSpace automatically generates SurrealDB edge tables. ## Key Design Decisions - **Runtime schema engine**: NLP → SchemaNodes → DDL generation → SurrealDB - **Relationships separate from fields**: Clearer separation, easier for NLP - **Atomic creation**: Schema + edge tables created in single transaction - **Bidirectional auto-sync**: Reverse relationships auto-added to target schemas - **Edge table naming**: {source_type}_{relationship_name}_{target_type} - **Structural relations preserved**: has_child, mentions remain in schema.surql ## Documentation Added - `docs/architecture/data/schema-relational-fields.md` - Complete architecture - Runtime schema engine overview - Composition vs relationship decision tree - SchemaRelationship struct definition - Edge table DDL generation strategy - Atomic transaction patterns - Bidirectional relationship auto-sync - Example use cases (Invoice→Customer, Task→Person) - Migration path from simple record to relation ## GitHub Issue Updated Issue #703 now contains: - Finalized design decisions - 6-phase implementation plan with detailed tasks - Example JSON schemas with relationships - Technical notes on data structures and DDL patterns - Clear acceptance criteria ## Implementation Phases (Documented, Not Implemented) 1. Data Model Extensions (SchemaRelationship struct, schema.surql update) 2. DDL Generation (edge table creation in SchemaTableManager) 3. Schema CRUD API (atomic transactions, validation) 4. Relationship Query API (abstract graph traversal) 5. MCP Handler Integration (expose to NLP) 6. NLP Discovery API (relationship metadata for query generation) ## Test Status - Frontend: 1477 tests passed - Rust: 482 tests passed - No new test failures introduced 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Refine schema relational fields architecture based on review ## Summary Updated architecture documentation based on senior architect review and collaborative discussion. Key refinements: ## Architecture Refinements 1. **Edge-Only Storage** (Decision 1) - 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. **Computed Reverse Relationship Discovery** (Decision 3) - Do NOT mutate target schemas when relationship created - Use query-time discovery via `get_inbound_relationships(node_type)` - Avoids write amplification, OCC conflicts, user confusion 3. **Forward-Looking Schema Changes** (Decision 4) - Schema changes apply to NEW data only - Existing data is grandfathered (null allowed for historical) - Optional backfill for simple types with `retroactive_default` - Consistent with existing field migration behavior 4. **Soft-Delete for Relationship Removal** (Decision 5) - Edge table + data preserved when relationship removed from schema - Schema node is source of truth for what's "active" - Matches existing field behavior (FLEXIBLE tables, no REMOVE FIELD) ## New Documentation - Schema Migration Behavior section documenting existing soft-delete pattern - Detailed migration behavior table for relationships - Breaking changes require decision points (e.g., cardinality changes) - Simplified EdgeField struct (distinct from SchemaField) ## GitHub Issue Updated - Acceptance criteria updated (architecture + migration docs checked) - Implementation phases refined with concrete tasks - Migration behavior table added 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Address architect review feedback - add implementation details ## Summary Added the 5 required sections identified in architect review to complete the architecture documentation before implementation begins. ## Sections Added ### 1. EdgeField Simplification Rationale - Explained why EdgeField is simpler than SchemaField - No protection levels (all user-defined) - No nested types (primitives only) - No enum extension (simpler lifecycle) - Tightly coupled to relationship lifecycle ### 2. Cardinality Enforcement Strategy - Application-level validation for cardinality="one" - Database-level UNIQUE index on (in, out) prevents duplicates - Check existing edges before creating new ones - Clear error messages for violations ### 3. Relationship Name Validation Rules - Pattern: ^[a-zA-Z][a-zA-Z0-9_-]*$ (start with letter) - Reserved names: has_child, mentions, node, data - Validation during schema node validation (SchemaNodeBehavior) - Case-sensitive storage ### 4. Target Schema Validation Timing - Schema creation: Lenient (allow forward references) - Relationship creation: Strict (validate target schema + node exists) - Four-step validation: source exists, schema exists, target exists, type matches ### 5. Inbound Relationship Caching Strategy - HashMap cache: target_type → Vec<InboundRelationship> - Event-driven invalidation (schema change flag) - Time-based refresh (max 60s stale) - Performance: <1µs cache hit, 50-200ms refresh ## Edge Table Name Collision Handling - Detailed collision scenarios and resolution - Triplet (source, name, target) ensures uniqueness by design - Validation prevents accidental collision ## Status All 5 required items from architect review addressed. Architecture ready for implementation. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
* Document architecture for schema relational fields (closes #703) ## Summary Complete architecture design and implementation plan for runtime schema-driven relationships in NodeSpace. Users can define custom node types with relationships via NLP/MCP, and NodeSpace automatically generates SurrealDB edge tables. ## Key Design Decisions - **Runtime schema engine**: NLP → SchemaNodes → DDL generation → SurrealDB - **Relationships separate from fields**: Clearer separation, easier for NLP - **Atomic creation**: Schema + edge tables created in single transaction - **Bidirectional auto-sync**: Reverse relationships auto-added to target schemas - **Edge table naming**: {source_type}_{relationship_name}_{target_type} - **Structural relations preserved**: has_child, mentions remain in schema.surql ## Documentation Added - `docs/architecture/data/schema-relational-fields.md` - Complete architecture - Runtime schema engine overview - Composition vs relationship decision tree - SchemaRelationship struct definition - Edge table DDL generation strategy - Atomic transaction patterns - Bidirectional relationship auto-sync - Example use cases (Invoice→Customer, Task→Person) - Migration path from simple record to relation ## GitHub Issue Updated Issue #703 now contains: - Finalized design decisions - 6-phase implementation plan with detailed tasks - Example JSON schemas with relationships - Technical notes on data structures and DDL patterns - Clear acceptance criteria ## Implementation Phases (Documented, Not Implemented) 1. Data Model Extensions (SchemaRelationship struct, schema.surql update) 2. DDL Generation (edge table creation in SchemaTableManager) 3. Schema CRUD API (atomic transactions, validation) 4. Relationship Query API (abstract graph traversal) 5. MCP Handler Integration (expose to NLP) 6. NLP Discovery API (relationship metadata for query generation) ## Test Status - Frontend: 1477 tests passed - Rust: 482 tests passed - No new test failures introduced 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Refine schema relational fields architecture based on review ## Summary Updated architecture documentation based on senior architect review and collaborative discussion. Key refinements: ## Architecture Refinements 1. **Edge-Only Storage** (Decision 1) - 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. **Computed Reverse Relationship Discovery** (Decision 3) - Do NOT mutate target schemas when relationship created - Use query-time discovery via `get_inbound_relationships(node_type)` - Avoids write amplification, OCC conflicts, user confusion 3. **Forward-Looking Schema Changes** (Decision 4) - Schema changes apply to NEW data only - Existing data is grandfathered (null allowed for historical) - Optional backfill for simple types with `retroactive_default` - Consistent with existing field migration behavior 4. **Soft-Delete for Relationship Removal** (Decision 5) - Edge table + data preserved when relationship removed from schema - Schema node is source of truth for what's "active" - Matches existing field behavior (FLEXIBLE tables, no REMOVE FIELD) ## New Documentation - Schema Migration Behavior section documenting existing soft-delete pattern - Detailed migration behavior table for relationships - Breaking changes require decision points (e.g., cardinality changes) - Simplified EdgeField struct (distinct from SchemaField) ## GitHub Issue Updated - Acceptance criteria updated (architecture + migration docs checked) - Implementation phases refined with concrete tasks - Migration behavior table added 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Address architect review feedback - add implementation details ## Summary Added the 5 required sections identified in architect review to complete the architecture documentation before implementation begins. ## Sections Added ### 1. EdgeField Simplification Rationale - Explained why EdgeField is simpler than SchemaField - No protection levels (all user-defined) - No nested types (primitives only) - No enum extension (simpler lifecycle) - Tightly coupled to relationship lifecycle ### 2. Cardinality Enforcement Strategy - Application-level validation for cardinality="one" - Database-level UNIQUE index on (in, out) prevents duplicates - Check existing edges before creating new ones - Clear error messages for violations ### 3. Relationship Name Validation Rules - Pattern: ^[a-zA-Z][a-zA-Z0-9_-]*$ (start with letter) - Reserved names: has_child, mentions, node, data - Validation during schema node validation (SchemaNodeBehavior) - Case-sensitive storage ### 4. Target Schema Validation Timing - Schema creation: Lenient (allow forward references) - Relationship creation: Strict (validate target schema + node exists) - Four-step validation: source exists, schema exists, target exists, type matches ### 5. Inbound Relationship Caching Strategy - HashMap cache: target_type → Vec<InboundRelationship> - Event-driven invalidation (schema change flag) - Time-based refresh (max 60s stale) - Performance: <1µs cache hit, 50-200ms refresh ## Edge Table Name Collision Handling - Detailed collision scenarios and resolution - Triplet (source, name, target) ensures uniqueness by design - Validation prevents accidental collision ## Status All 5 required items from architect review addressed. Architecture ready for implementation. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Claude <[email protected]>
Closes #703