Repository navigation
Description
Refactor Schema Seeding: Move from SurrealStore to NodeService
Overview
Schema seeding logic is currently in the wrong architectural layer. SurrealStore (data layer) is seeding domain data (schema nodes), when this responsibility should belong to NodeService (domain/business logic layer). This violates separation of concerns and causes issues in HTTP mode where seeding doesn't happen.
CRITICAL DISCOVERY (Session 2): Moving seeding to NodeService exposes a cache timing issue. Schema caches are built by querying the schema table, but on first launch this happens BEFORE schemas exist. See "Cache Population Strategy" section below.
Problem Statement
Current Architecture (Incorrect):
SurrealStore::new() (embedded RocksDB)
└─ initialize_schema() → Creates core tables (node, schema, mentions, has_child)
└─ seed_core_schemas() → Creates schema nodes (task, text, date, etc.)
└─ Returns SurrealStore instance
SurrealStore::new_http() (HTTP client)
└─ initialize_schema() → Creates core tables
└─ ❌ NO SEEDING → Assumes external process seeded schemas
└─ Returns SurrealStore instance
Issues:
- Data layer (
SurrealStore) knows about domain concepts (core schemas) - HTTP mode doesn't seed schemas, causing 404 errors on fresh databases
- Duplication of seeding logic needed for embedded vs HTTP modes
- Schema seeding coupled to database connection type
- Cache timing issue: Caches built before schemas exist on first launch
Correct Architecture
Target Architecture:
NodeService::new(store: SurrealStore)
└─ Check if schema nodes exist
└─ If fresh database:
├─ Get core schemas from models::core_schemas
├─ For each schema:
│ ├─ Create schema node (via store.create_schema_node_atomic)
│ ├─ Generate spoke table DDL if schema has fields
│ └─ Add to cache (no DB re-query needed!)
└─ Seed complete
└─ Returns NodeService instance
SurrealStore::new() / new_http()
└─ initialize_schema() → Creates ONLY core infrastructure tables
└─ build_schema_caches() → Queries schema table (empty on first launch, populated on subsequent)
└─ Returns SurrealStore instance (no domain knowledge)
Benefits:
- Clean separation: Data layer handles infrastructure, domain layer handles business data
- Works identically for embedded and HTTP modes
- Single source of truth for schema seeding logic
SurrealStorestays focused on data access only- Optimal cache population: incremental on first launch, single query on subsequent launches
Cache Population Strategy (CRITICAL)
The Problem:
SurrealStore maintains caches (types_with_spoke_tables, valid_node_types) to avoid querying the database on every CRUD operation. These are built by querying the schema table. But on first launch:
SurrealStore::new()→build_schema_caches()queries empty schema table → cache = {"schema"} onlyNodeService::new()→ seeds schema records → cache is STALEcreate_node("task")→has_spoke_table("task")returns false → BUG (no spoke record created)
The Solution (Two-Phase Caching):
First Launch (Fresh Database):
NodeService::seed_core_schemas_if_needed() {
for schema in core_schemas {
create_schema_node_atomic(schema);
// ✅ Add to cache immediately (data already in memory)
Arc::get_mut(&mut store)?
.add_to_schema_cache(schema.id, !schema.fields.is_empty());
}
}Subsequent Launches (Existing Database):
SurrealStore::new() {
initialize_schema();
// Queries populated schema table, builds full cache
build_schema_caches(); // Returns {"schema", "task", "text", "date", ...}
}Key Insight: Don't re-query the database after seeding - we already have the schema data in memory!
Documentation: See docs/architecture/data/schema-cache-population.md for complete strategy.
Implementation Steps
Step 1: Add add_to_schema_cache() Method to SurrealStore ✅ DONE
pub(crate) fn add_to_schema_cache(&mut self, type_name: String, has_fields: bool) {
self.valid_node_types.insert(type_name.clone());
if has_fields {
self.types_with_spoke_tables.insert(type_name);
}
}Step 2: Update NodeService Seeding to Populate Cache
In packages/core/src/services/node_service.rs, in the seeding loop:
for schema in &core_schemas {
// Create schema node + spoke table
self.store
.create_schema_node_atomic(node, ddl_statements)
.await?;
// Add to cache immediately (no DB re-query)
Arc::get_mut(&mut self.store)?
.add_to_schema_cache(schema.id.clone(), !schema.fields.is_empty());
}Step 3: Handle Arc Mutability in NodeService::new()
Since we need &mut SurrealStore but have Arc<SurrealStore>, use Arc::get_mut():
pub async fn new(mut store: Arc<SurrealStore<C>>) -> Result<Self> {
// Seeding logic...
// Get mutable reference for cache updates
let store_mut = Arc::get_mut(&mut store)
.ok_or_else(|| NodeServiceError::SerializationError(
"Cannot update cache: store has multiple references".to_string()
))?;
store_mut.add_to_schema_cache(...);
}Step 4: Update Test Helper
Remove the temporary rebuild_schema_caches() workaround once incremental caching is implemented.
Acceptance Criteria
-
seed_core_schemas()removed fromSurrealStore -
seed_core_schemas_http()removed fromSurrealStore - Schema seeding calls removed from
SurrealStore::new()andnew_http() -
NodeService::new()made async and includes seeding logic - Seeding checks if schemas exist before creating (idempotent)
- All 7 core schemas seeded: task, text, date, header, code-block, quote-block, ordered-list
- Spoke tables created for schemas with fields (task table)
- Schema caches populated incrementally during seeding (documented, needs implementation)
- Dev-proxy works with fresh database (no 404 on
/api/schemas/date) - All tests pass (currently 479/484 passing)
- No regression in existing functionality
Current Progress
Completed ✅
- Schema seeding successfully moved to NodeService
- All callsites updated to use async
NodeService::new() - Unit tests written for seeding (fresh database + idempotent)
- 10 SurrealStore tests fixed with temporary cache rebuild approach
- Cache population strategy fully documented
In Progress 🚧
- Incremental cache population (documented, not yet implemented)
- 5 test failures (likely pre-existing task property bugs)
Next Steps
- Implement
add_to_schema_cache()calls in NodeService seeding loop - Remove temporary
rebuild_schema_caches()workaround - Verify all tests pass
- Complete PR review
Resources & References
Documentation
- Cache Strategy:
docs/architecture/data/schema-cache-population.md- Complete two-phase caching design - SurrealStore:
packages/core/src/db/surreal_store.rs- Data access layer - NodeService:
packages/core/src/services/node_service.rs- Domain logic layer
Related Issues
- Issue Consolidate Database Schema Seeding to Backend Service #691 - Consolidated schema seeding into Rust
- Issue Simplify Schema Architecture: Remove SchemaDefinition and SchemaService #692 - Schema simplification and hub-and-spoke architecture
Activity
WIP: Fix SQL query camelCase aliasing for SchemaNode and TaskNode des…
Refactor Schema Seeding: Move from SurrealStore to NodeService (Issue #…
Refactor Schema Seeding: Move from SurrealStore to NodeService (Issue #…
WIP: Document schema cache population strategy (Issue #704)
Implement incremental schema cache population (Issue #704)
Refactor Schema Seeding: Move from SurrealStore to NodeService (#706)
Refactor Schema Seeding: Move from SurrealStore to NodeService (#706)
Refactor Schema Seeding: Move from SurrealStore to NodeService (#706)
Refactor Schema Seeding: Move from SurrealStore to NodeService (#706)