Skip to content

Refactor Schema Seeding: Move from SurrealStore to NodeService #704

Closed

Description

@malibio

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:

  1. Data layer (SurrealStore) knows about domain concepts (core schemas)
  2. HTTP mode doesn't seed schemas, causing 404 errors on fresh databases
  3. Duplication of seeding logic needed for embedded vs HTTP modes
  4. Schema seeding coupled to database connection type
  5. 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:

  1. Clean separation: Data layer handles infrastructure, domain layer handles business data
  2. Works identically for embedded and HTTP modes
  3. Single source of truth for schema seeding logic
  4. SurrealStore stays focused on data access only
  5. 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:

  1. SurrealStore::new() → build_schema_caches() queries empty schema table → cache = {"schema"} only
  2. NodeService::new() → seeds schema records → cache is STALE
  3. create_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 from SurrealStore
  • seed_core_schemas_http() removed from SurrealStore
  • Schema seeding calls removed from SurrealStore::new() and new_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

  1. Implement add_to_schema_cache() calls in NodeService seeding loop
  2. Remove temporary rebuild_schema_caches() workaround
  3. Verify all tests pass
  4. 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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions