Skip to content

Schema Support for Relational Fields - Architecture Design - #707

Merged
malibio merged 3 commits into
mainfrom
feature/issue-703-schema-relational-fields
Dec 1, 2025
Merged

malibio merged 3 commits into
mainfrom
feature/issue-703-schema-relational-fields

Conversation

@malibio

@malibio malibio commented Dec 1, 2025

Copy link
Copy Markdown
Collaborator

Closes #703

malibio and others added 2 commits December 1, 2025 10:33
## 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 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.

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_atomic transaction 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_default provides 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 protection level for edge fields? (Core vs user edge fields?)
  • Why no description field 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)

  1. EdgeField simplification rationale (why no protection levels?)
  2. Cardinality enforcement details (application vs database)
  3. Relationship name validation rules
  4. Target schema existence validation timing
  5. Edge table name collision handling

📝 Future Considerations (Document Later)

  1. Performance benchmarks
  2. Relationship query limits/pagination
  3. Cascading deletes
  4. Relationship metadata (created by, modified at)
  5. 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

  1. EdgeField Protection: Should edge fields have protection levels?
  2. Relationship Versioning: Do relationships need version tracking for OCC?
  3. Cascading Deletes: When target schema deleted, what happens to relationships referencing it?
  4. Circular Dependencies: Are circular relationships allowed? (A→B, B→A)
  5. 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

  1. Add EdgeField rationale section
  2. Document cardinality enforcement strategy
  3. Specify relationship name validation rules
  4. Clarify edge table collision handling
  5. Detail inbound relationship caching strategy

Recommended Enhancements (Can be added during implementation)

  1. Add query API return type specifications
  2. Document target schema validation timing
  3. Specify relationship versioning strategy (if needed)
  4. Define cascading delete behavior

Next Steps

  1. Update Architecture Doc: Address the 5 required items above
  2. Review Updated Doc: Quick review by senior architect
  3. Proceed to Phase 1: Begin SchemaRelationship struct implementation
  4. 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]>
@malibio
malibio merged commit 44e0625 into main Dec 1, 2025
@malibio
malibio deleted the feature/issue-703-schema-relational-fields branch December 1, 2025 12:05
malibio added a commit that referenced this pull request Feb 4, 2026
* 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]>
malibio added a commit that referenced this pull request Feb 5, 2026
* 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]>
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.

Schema Support for Relational Fields - Architecture Design

1 participant