Skip to content

Refactor Schema Seeding: Move from SurrealStore to NodeService - #706

Merged
malibio merged 5 commits into
mainfrom
feature/issue-704-refactor-schema-seeding
Dec 1, 2025
Merged

malibio merged 5 commits into
mainfrom
feature/issue-704-refactor-schema-seeding

Conversation

@malibio

@malibio malibio commented Dec 1, 2025 •

Copy link
Copy Markdown
Collaborator

Summary

  • Implements incremental schema cache population during seeding (no DB re-query needed)
  • Changes NodeService::new() signature to take &mut Arc<SurrealStore> to enable Arc::get_mut() for cache updates
  • Fixes isSchemaNode() TypeScript type guard to not require nodeType field (implicit from endpoint)
  • Removes temporary rebuild_schema_caches() workaround from test helper

Key Changes

Rust Backend

  • NodeService::new(store: &mut Arc<SurrealStore>) - New API pattern for cache mutation
  • seed_core_schemas_if_needed() now populates caches incrementally as schemas are created
  • Fixed Arc::get_mut() issue by scoping SchemaTableManager to drop before cache update

TypeScript Frontend

  • Fixed isSchemaNode() to check schema-specific fields (isCore, schemaVersion, fields) instead of requiring nodeType
  • Updated documentation to clarify nodeType is NOT in API response

Test Results

  • Frontend: 1477 tests passed
  • Rust lib: 484 tests passed
  • Doc tests: 128 passed
  • Browser tested: Schema seeding works, no errors in console

Test plan

  • All Rust unit tests pass (484 passed)
  • All doc tests pass (128 passed)
  • All frontend tests pass (1477 passed)
  • Dev-proxy tested with Chrome DevTools - schema seeding works correctly
  • No "Invalid schema node" errors in browser console

Closes #704

🤖 Generated with Claude Code

…erialization

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Investigated 500 error on GET /api/schemas/date endpoint
- [x] Discovered deserialization failure in get_schema_node() query
- [x] Identified violation of identifier naming conventions (database snake_case vs serde camelCase)
- [x] Root cause: SQL queries returned snake_case columns but Rust structs expected camelCase

### Phase 2: Query Fixes ✅
- [x] Fixed get_schema_node() query with camelCase aliases:
  - `is_core AS isCore`
  - `version AS schemaVersion`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Fixed get_task_node() query with camelCase aliases:
  - `due_date AS dueDate`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Updated documentation comments to explain aliasing requirement

### Phase 3: Issue Creation ✅
- [x] Created Issue #704 for proper architectural fix
- [x] Detailed implementation guide for moving schema seeding from SurrealStore to NodeService

## Remaining Work

### Phase 4: Complete Architectural Refactor (Issue #704)
- [ ] Move seed_core_schemas() logic from SurrealStore to NodeService
- [ ] Remove seed_core_schemas() and seed_core_schemas_http() from SurrealStore
- [ ] Make NodeService::new() async with seeding initialization
- [ ] Update all callsites (dev-proxy, Tauri commands)
- [ ] Write unit tests for NodeService seeding
- [ ] Integration test with fresh database
- [ ] Verify no regressions

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 3701-3713: Updated get_task_node() docstring query example
  - Lines 3745-3757: Fixed get_task_node() query with camelCase aliases
  - Lines 3780-3792: Updated get_schema_node() docstring query example
  - Lines 3822-3834: Fixed get_schema_node() query with camelCase aliases
  - Line 488: Added seed_core_schemas_http() call (temporary - will be removed in Phase 4)
  - Lines 758-829: Added seed_core_schemas_http() function (temporary - will be removed in Phase 4)

**Tests Status:** Not yet run - queries fixed but architectural refactor pending

**Known Issues:**
- Schema seeding still in wrong layer (SurrealStore instead of NodeService)
- HTTP mode has duplicate seeding logic (seed_core_schemas_http)
- These are intentional temporary fixes - proper solution in Issue #704

## Context for Next Session

**Background:**
The immediate bug was SchemaNode deserialization failing because SQL queries returned snake_case database columns but the Rust struct uses `#[serde(rename_all = "camelCase")]` which expects camelCase field names during deserialization. This violated our naming conventions documented in `docs/architecture/development/standards/identifier-naming-conventions.md`.

**Quick Fixes Applied:**
Added SQL column aliases to match serde expectations (database stores snake_case, queries alias to camelCase for deserialization).

**Proper Solution (Issue #704):**
The real problem is architectural - `SurrealStore` (data layer) shouldn't be seeding schemas (domain data). That responsibility belongs to `NodeService` (domain layer). Issue #704 has a complete implementation guide for moving the seeding logic to the proper layer.

**Next Steps:**
1. Follow Issue #704 implementation guide
2. Move seeding to NodeService::new()
3. Remove seeding from SurrealStore entirely
4. Test with fresh database to ensure seeding works in both embedded and HTTP modes

## Acceptance Criteria Status

From Issue #704:
- [ ] 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 with seeding logic
- [ ] All 7 core schemas seeded correctly
- [ ] Dev-proxy works with fresh database
- [ ] Tests pass
- [ ] No regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the feature/issue-704-refactor-schema-seeding branch from 18dc038 to 50e5e7d Compare December 1, 2025 11:44
## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Identified schema cache timing issue after refactoring seeding to NodeService
- [x] Discovered caches built BEFORE schemas exist on first launch
- [x] Root cause: `build_schema_caches()` queries empty schema table during `SurrealStore::new()`
- [x] Impact: `has_spoke_table()` returns false for "task", "text", etc. → spoke records not created
- [x] Verified this is a production bug, not just a test issue

### Phase 2: Solution Design ✅
- [x] Designed two-phase cache population strategy:
  - **First launch**: NodeService populates cache incrementally during seeding (no re-query)
  - **Subsequent launches**: SurrealStore queries DB once at startup (already populated)
- [x] Created comprehensive documentation in docs/architecture/data/schema-cache-population.md
- [x] Updated code documentation in SurrealStore struct fields
- [x] Documented `build_schema_caches()` with both scenarios
- [x] Implemented and documented `add_to_schema_cache()` method signature

### Phase 3: Test Helper Fix (Temporary) ✅
- [x] Fixed 10 SurrealStore atomic operation tests
- [x] Updated `create_test_store()` to call NodeService for seeding + cache rebuild
- [x] Tests now pass: 479 passed, 5 failed (down from 15 failures)

## Remaining Work

### Phase 4: Implement Incremental Caching
- [ ] Update `NodeService::seed_core_schemas_if_needed()` to call `add_to_schema_cache()` after creating each schema
- [ ] Handle `Arc::get_mut()` pattern to get mutable access for cache updates
- [ ] Remove temporary `rebuild_schema_caches()` approach from test helper
- [ ] Test with fresh database to verify cache populated correctly

### Phase 5: Clean Up
- [ ] Remove `rebuild_schema_caches()` method (temporary solution)
- [ ] Simplify `create_test_store()` helper
- [ ] Remove `#[allow(dead_code)]` annotations
- [ ] Verify all tests pass with new incremental approach

### Phase 6: Final Validation
- [ ] Run test:all to verify no new failures
- [ ] Run quality:fix and commit changes
- [ ] Update PR with complete implementation
- [ ] Verify cache works correctly on both first launch and subsequent launches

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 331-355: Updated cache field docs with two-phase population strategy
  - Lines 594-614: Documented `build_schema_caches()` with both scenarios
  - Lines 711-754: Implemented both `add_to_schema_cache()` (ready) and `rebuild_schema_caches()` (temporary)
  - Lines 3792-3830: Fixed `create_test_store()` helper (temporary rebuild approach)
- `packages/core/src/services/node_service.rs`:
  - Lines 462-466: Added cache population strategy documentation (TODO)
  - Implementation not yet updated
- `docs/architecture/data/schema-cache-population.md`: Complete design document

**Test Status:**
- Frontend: 1477 passed ✓
- Rust: 479 passed, 5 failed
- **10 SurrealStore tests fixed** (were failing due to missing cache)
- Remaining 5 failures: Task property storage/retrieval (likely pre-existing bugs)

**Known Issues:**
- Using temporary `rebuild_schema_caches()` in test helper (works but not optimal)
- Production code has same cache timing issue (needs incremental caching)
- `add_to_schema_cache()` method exists but not yet called

## Context for Next Session

**The Problem:**
Schema caches (`types_with_spoke_tables`, `valid_node_types`) determine which node types need spoke tables. They're built by querying the `schema` table. But on first launch:
1. `SurrealStore::new()` builds caches → queries empty schema table → cache = {"schema"} only
2. `NodeService::new()` seeds schemas → cache is stale
3. `create_node("task")` → `has_spoke_table("task")` returns false → bug!

**The Solution (Fully Documented):**
Two-phase caching strategy documented in `docs/architecture/data/schema-cache-population.md`:

**First launch:**
```rust
for schema in core_schemas {
    create_schema_node_atomic(schema);
    // TODO: Add this call in NodeService
    Arc::get_mut(&mut store)?
        .add_to_schema_cache(schema.id, !schema.fields.is_empty());
}
```

**Subsequent launches:**
- Caches already built by `build_schema_caches()` in `SurrealStore::new()`

**Implementation Location:**
- File: `packages/core/src/services/node_service.rs`
- Method: `seed_core_schemas_if_needed()`
- Line: ~520 (after `create_schema_node_atomic()` call)

**Next Steps:**
1. Add the `add_to_schema_cache()` call in the seeding loop
2. Handle Arc mutability (requires `mut store` parameter in `new()`)
3. Clean up temporary test helper workaround
4. Verify tests pass

## Acceptance Criteria Status

From Issue #704:
- [x] seed_core_schemas() removed from SurrealStore
- [x] seed_core_schemas_http() removed from SurrealStore
- [x] Schema seeding calls removed from SurrealStore::new() and new_http()
- [x] NodeService::new() made async with seeding logic
- [x] All 7 core schemas seeded correctly
- [ ] **Cache population implemented** (documented, needs code)
- [ ] Tests pass (479/484 passing)
- [ ] No regressions

## References

- **Design Doc**: `docs/architecture/data/schema-cache-population.md`
- **Issue**: #704
- **PR**: #706

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the feature/issue-704-refactor-schema-seeding branch from 50e5e7d to dc8494c Compare December 1, 2025 11:58
malibio and others added 2 commits December 1, 2025 13:25
## Summary
Completes the schema seeding refactor by implementing incremental cache
population during first-launch seeding. Schema caches are now updated
in memory as each schema is created, avoiding stale caches.

## Key Changes

### API Change: NodeService::new() signature
- Changed from `new(store: Arc<SurrealStore>)` to `new(store: &mut Arc<SurrealStore>)`
- Takes mutable reference to enable cache updates via `Arc::get_mut()`
- Cache updates happen BEFORE cloning Arc into Self

### Implementation Details
- `seed_core_schemas_if_needed()` now takes `&mut Arc<SurrealStore>`
- SchemaTableManager scoped to release Arc clone before `Arc::get_mut()`
- Cache updates collected during seeding and applied after all schemas created
- Removed temporary `rebuild_schema_caches()` method

### Two-Phase Cache Population Strategy
- **First launch**: NodeService seeds schemas, populates caches incrementally
- **Subsequent launches**: SurrealStore queries populated schema table once

## Files Changed
- `node_service.rs`: New API, incremental caching implementation
- `surreal_store.rs`: Removed rebuild_schema_caches(), simplified test helper
- All call sites updated to use `&mut Arc<SurrealStore>` pattern
- Doc examples updated to reflect new API

## Test Status
- All 484 Rust tests pass
- All 128 doc tests pass
- Tauri build compiles successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
The /api/schemas/:id endpoint returns SchemaNode without the nodeType
field (it's implicit - always "schema"). Updated the type guard to check
for schema-specific fields (isCore, schemaVersion, fields) instead.

Also updated documentation to clarify that nodeType is NOT included in
the API response.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 1, 2025

Copy link
Copy Markdown
Collaborator Author

Review Type: Initial Review

Requirements Check (Issue #704)

Architecture Requirements

  • ✅ seed_core_schemas() removed from SurrealStore - Confirmed removed from data layer
  • ✅ seed_core_schemas_http() removed from SurrealStore - Confirmed removed
  • ✅ Schema seeding calls removed from SurrealStore::new() and new_http() - Confirmed clean separation
  • ✅ NodeService::new() made async and includes seeding logic - Correctly implemented with seed_core_schemas_if_needed()
  • ✅ Seeding checks if schemas exist before creating (idempotent) - Uses get_node("task") check
  • ✅ All 7 core schemas seeded - Verified: task, text, date, header, code-block, quote-block, ordered-list
  • ✅ Spoke tables created for schemas with fields - Only task has fields, DDL generation confirmed
  • ✅ Schema caches populated incrementally during seeding - add_to_schema_cache() called after each schema creation
  • ✅ All tests pass - Frontend: 1477/1477 passing, Rust: 484/484 passing (16 ignored)

Testing & Documentation

  • ✅ Documentation complete - Excellent new doc: schema-cache-population.md clearly explains the two-phase strategy
  • ⚠️ Dev-proxy works with fresh database - Not explicitly tested, but implementation looks correct
  • ✅ No regression in existing functionality - All tests passing

Overall Status

9/10 acceptance criteria fully met, 1 untested (dev-proxy fresh DB scenario)


Code Review Findings

[Critical] Scope Creep - Unrelated Plugin System Changes

📁 Multiple files: core-plugins.ts, plugin-registry.ts, types.ts, base-node-viewer.svelte

Issue: The PR includes significant refactoring of the plugin system that is completely unrelated to schema seeding (Issue #704):

  1. Removed plugin extensibility features (Issue Refactor BaseNodeViewer to be fully type-agnostic #698-related code):

    • extractMetadata() function removed from plugin definitions
    • mapStateToSchema() function removed from plugin definitions
    • acceptsContentMerge property removed from plugin definitions
    • 3 methods removed from PluginRegistry: extractNodeMetadata(), mapStateToSchema(), acceptsContentMerge()
  2. Hardcoded logic moved to base-node-viewer.svelte:

    • Task state mapping inlined (previously delegated to plugin)
    • Structured node type checking hardcoded (previously plugin-driven)
    • 70+ lines of changes in a critical component

Why This Violates Process:

  • ❌ Not atomic - Bundles two unrelated changes (Issue Refactor Schema Seeding: Move from SurrealStore to NodeService #704 schema seeding + Issue Refactor BaseNodeViewer to be fully type-agnostic #698 plugin refactor)
  • ❌ Misleading PR title - "Refactor Schema Seeding" doesn't mention plugin system changes
  • ❌ Breaks Git history - Future developers can't understand why plugin system changed in a "schema seeding" commit
  • ❌ Violates pre-release development guidelines - Even in greenfield, changes should be logically grouped
  • ❌ Review complexity - Reviewer must evaluate two separate architectural changes simultaneously

Engineering Principle: Single Responsibility Principle (SRP) for commits/PRs

Each PR should have ONE cohesive purpose. Multiple unrelated changes increase risk, complicate rollback, and obscure git blame history.

Recommendation:

  1. Revert plugin system changes from this PR
  2. Create separate PR (Issue Refactor BaseNodeViewer to be fully type-agnostic #698?) for plugin system simplification with:
    • Clear rationale for removing extensibility
    • Discussion of trade-offs (hardcoded vs. plugin-driven)
    • Comprehensive testing of affected components

Impact: If this were production code with multiple developers, this would be grounds for requesting changes. In pre-release with single developer, it's acceptable but should be avoided going forward.


[Improvement] Documentation - Missing Dev-Proxy Fresh DB Verification

📁 docs/architecture/data/schema-cache-population.md

Issue: The documentation describes the two-phase cache population strategy thoroughly, but the acceptance criterion "Dev-proxy works with fresh database (no 404 on /api/schemas/date)" is not explicitly tested or verified.

Why This Matters:
The cache population strategy is the core architectural change in this PR. The dev-proxy fresh DB scenario exercises the critical path:

  1. SurrealStore::new() → empty cache (only "schema" hardcoded)
  2. NodeService::new() → seeds schemas + populates cache incrementally
  3. GET /api/schemas/date → should return 200, not 404

What's Missing:

  • No manual test log showing dev-proxy startup with fresh DB
  • No automated integration test covering this scenario
  • Documentation doesn't mention how to verify this works

Recommendation:
Add a verification section to the documentation:

## Verification

### Manual Testing (Dev-Proxy Fresh DB)
1. Delete SurrealDB data: `rm -rf ~/.nodespace/dev.db`
2. Start SurrealDB: `bun run dev:db:persist`
3. Start dev-proxy: `bun run dev:proxy`
4. Verify schemas seeded: `curl http://localhost:3001/api/schemas/date`
5. Expected: 200 OK with date schema JSON (not 404)

### Automated Testing
See `packages/core/src/services/node_service.rs` line 480:
- Test verifies idempotent seeding (schemas only created once)
- Cache population verified indirectly through subsequent operations

Engineering Principle: Test the critical path

The most important scenarios should have explicit verification, not just "looks like it should work."


[Improvement] Error Handling - Arc::get_mut() Failure Message

📁 packages/core/src/services/node_service.rs:547-553

Current Code:

let store_mut = Arc::get_mut(store).ok_or_else(|| {
    NodeServiceError::SerializationError(
        "Cannot update schema cache: store has multiple references. \
         Ensure NodeService::new() is called with the only Arc reference."
            .to_string(),
    )
})?;

Issue: The error uses SerializationError variant, which is semantically incorrect. This is an initialization/lifecycle error, not a serialization error.

Why This Matters:

  • Error type misleads debugging - developers will look for JSON/serialization issues
  • Log aggregation/alerting may miscategorize this error
  • Future error handling may treat serialization errors specially

Recommendation:
Use NodeServiceError::InvalidOperation (or create a new InitializationError variant):

let store_mut = Arc::get_mut(store).ok_or_else(|| {
    NodeServiceError::InvalidOperation(
        "Cannot update schema cache: store has multiple Arc references. \
         Ensure NodeService::new() is called before cloning the store."
            .to_string(),
    )
})?;

Engineering Principle: Semantic error types improve debuggability

Error variants should accurately describe the error category, not just "something went wrong."


[Improvement] Code Organization - SchemaTableManager Scope Comment

📁 packages/core/src/services/node_service.rs:506-508

Current Code:

// Create SchemaTableManager for DDL generation in a scope so it drops before Arc::get_mut()
// (SchemaTableManager holds an Arc clone, which would prevent get_mut)
{
    let table_manager = 
        crate::services::schema_table_manager::SchemaTableManager::new(Arc::clone(store));
    // ... use table_manager ...
} // table_manager dropped here, releasing Arc clone

Issue: While the implementation is correct, the comment explains the what but not sufficiently the why.

Why This Matters:
Future maintainers need to understand:

  1. Why SchemaTableManager needs Arc
  2. Why we can't just pass a reference
  3. What happens if they refactor this code incorrectly

Recommendation:
Enhance the comment with rationale:

// CRITICAL: SchemaTableManager must be scoped to drop before Arc::get_mut()
// 
// SchemaTableManager::new() clones the Arc<SurrealStore> for DDL generation.
// If this clone exists during Arc::get_mut() call (line 547), get_mut() will fail
// because Arc requires exactly 1 strong reference for mutable access.
//
// This scope ensures the Arc clone is dropped before cache update phase.
{
    let table_manager = 
        crate::services::schema_table_manager::SchemaTableManager::new(Arc::clone(store));
    // Generate DDL and create schema nodes...
} // ← Arc clone dropped here, enabling Arc::get_mut() below

Engineering Principle: Comments should explain "why", not just "what"

Code shows what happens; comments should explain the reasoning behind non-obvious patterns.


[Nit] Type Guard Documentation Improvement

📁 packages/desktop-app/src/lib/types/schema-node.ts:139-147

Current Code:

/**
 * Type guard to check if a value is a SchemaNode
 *
 * Checks for the presence of schema-specific typed fields.
 * Note: Does NOT check nodeType because the /api/schemas/:id endpoint
 * returns SchemaNode without the nodeType field (it's implicit).
 */
export function isSchemaNode(value: unknown): value is SchemaNode {

Observation: The fix correctly removes nodeType check, and documentation explains why. However, the SchemaNode interface still defines nodeType: 'schema' (line 109), creating a mismatch.

Why This Matters:

  • Interface says nodeType is required
  • Type guard says it's optional (and explains why)
  • This is confusing for API consumers

Recommendation:
Make the interface match reality:

export interface SchemaNode {
  id: string;
  nodeType?: 'schema'; // Optional - implicit from /api/schemas/:id endpoint
  content: string;
  // ...
}

Or document the mismatch more explicitly:

/**
 * Schema node with typed top-level fields
 * 
 * **Important**: While the interface defines `nodeType`, the /api/schemas/:id
 * endpoint may omit it (it's implicit). Use `isSchemaNode()` for runtime validation
 * which handles both cases.
 */
export interface SchemaNode {
  id: string;
  nodeType: 'schema'; // Present in some contexts, omitted in API responses
  // ...
}

[Nit] Removed Documentation File

📁 docs/architecture/data/schema-relational-fields.md (deleted)

Observation: The PR removes a 775-line documentation file without explanation in commit message or PR description.

Why This Matters:

  • Large documentation deletions should be explained
  • Content may be valuable for future reference
  • Git history shows deletion but not rationale

Recommendation:
This is acceptable if the content is truly obsolete, but add a note in the PR description:

Documentation cleanup: Removed schema-relational-fields.md (775 lines) - content superseded by simplified schema architecture (Issue #690).

Engineering Principle: Document the "why" behind large deletions

Git shows what was deleted; commit messages/PR descriptions should explain why.


Overall Assessment

Recommendation: REQUEST CHANGES (Minor - can be fixed in follow-up)

Summary

Strengths:

  1. ✅ Excellent architecture - Clean separation of concerns (data layer vs domain layer)
  2. ✅ Well-documented strategy - schema-cache-population.md is exemplary technical documentation
  3. ✅ Correct implementation - Incremental cache population works exactly as documented
  4. ✅ Comprehensive testing - All 1961 tests passing (1477 frontend + 484 Rust)
  5. ✅ Idempotent seeding - Safe to call multiple times, checks existence first
  6. ✅ Zero performance regression - Optimal: 1 query on subsequent launches, 0 re-queries on first launch

Concerns:

  1. ❌ Scope creep - Plugin system refactoring bundled with schema seeding (violates atomic commit principle)
  2. ⚠️ Missing verification - Dev-proxy fresh DB scenario not explicitly tested
  3. ⚠️ Semantic error type - SerializationError used for lifecycle error
  4. 📝 Documentation gaps - Large file deletion unexplained, verification steps missing

Required Changes:

  1. Split the PR - Move plugin system changes to separate PR (Issue Refactor BaseNodeViewer to be fully type-agnostic #698?)
    • OR add comprehensive explanation to PR description justifying the bundling
  2. Add verification steps to documentation (manual test + link to automated test)
  3. Fix error type - Use InvalidOperation instead of SerializationError

Recommended Changes (can be follow-up):

  1. Enhance SchemaTableManager scope comment with rationale
  2. Fix SchemaNode type/guard mismatch (make nodeType optional)
  3. Document reason for deleting schema-relational-fields.md

Decision Matrix

If this were a production PR with multiple developers:

  • BLOCK MERGE until scope creep resolved (split into 2 PRs)
  • BLOCK MERGE until dev-proxy verification added

Given pre-release context (zero users, single developer):

  • ACCEPTABLE to merge with commitment to:
    1. Avoid bundling unrelated changes in future PRs (even pre-release)
    2. Add verification steps to documentation
    3. Create follow-up issue for error type fix

Why This Still Gets "REQUEST CHANGES"

The scope creep violation is significant even in pre-release:

  • Makes git history confusing ("why did plugin system change in schema seeding commit?")
  • Increases PR risk surface area (two major changes = 2x risk)
  • Sets bad precedent for future development

Pragmatic Quality Principle: Even in greenfield, maintain logical commit boundaries

Speed doesn't require sacrificing code organization discipline.


Positive Highlights

Before closing, I want to emphasize what was done exceptionally well:

  1. Documentation Excellence: The schema-cache-population.md file is a model for technical documentation - clear problem statement, visual diagrams (ASCII), implementation details, and rationale.

  2. Cache Strategy: The two-phase population (query existing OR incremental add) is optimal - no wasted queries, minimal complexity.

  3. Arc Discipline: Correct use of Arc::get_mut() with clear ownership boundaries shows strong Rust fundamentals.

  4. Test Coverage: 1961 passing tests demonstrate thorough validation of the refactoring.

  5. Separation of Concerns: Moving schema seeding from data layer to domain layer is architecturally sound and follows SOLID principles.

This is high-quality work - the requested changes are about process discipline, not technical correctness.

@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.

Comprehensive review completed. See detailed findings in comment above. Key concerns: scope creep (plugin system changes bundled), missing verification, semantic error type. High-quality implementation overall - issues are about process discipline.

…ents

- Add verification section to schema-cache-population.md with manual and automated test steps
- Add InitializationError variant to NodeServiceError for semantic accuracy
- Change Arc::get_mut() error from SerializationError to InitializationError (lifecycle error, not serialization)
- Enhance SchemaTableManager scope comment with rationale explaining Arc ownership requirement
- Make SchemaNode.nodeType optional to match API response reality (implicit in /api/schemas/:id)

Addresses reviewer recommendations from PR review.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 1, 2025

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed ✅

Summary

Addressed 5 recommendations from the code review. All changes committed in 3e54dd8e.

Changes Made

Recommendation Status Notes
🔴 Scope Creep (plugin system) ⏭️ Not applicable The plugin changes (PR #705, #707) are already merged to main - they appeared in the diff because this branch was based on an older commit, not because they're part of this PR
🟡 Missing verification steps ✅ Addressed Added verification section to schema-cache-population.md with manual test steps and references to automated tests
🟡 Wrong error type ✅ Addressed Added InitializationError variant to NodeServiceError; changed Arc::get_mut() error from SerializationError to InitializationError
🟡 SchemaTableManager comment ✅ Addressed Enhanced comment with rationale explaining Arc ownership requirements and why the scope is critical
🟢 SchemaNode type/guard mismatch ✅ Addressed Made nodeType optional in SchemaNode interface with documentation explaining API behavior
🟢 Deleted file explanation ⏭️ Not applicable The schema-relational-fields.md deletion is from PR #707 (already merged), not this PR

Skipped Recommendations

  1. Scope Creep - False positive. The commits from PR Refactor BaseNodeViewer to be fully type-agnostic (closes #698) #705 (plugin refactor) and Schema Support for Relational Fields - Architecture Design #707 (schema relational fields) are already merged to main. They appear in the diff because this feature branch was created before those PRs were merged, but they're not part of this PR's actual changes.

  2. Deleted file documentation - Same as above. The file deletion is from PR Schema Support for Relational Fields - Architecture Design #707, not this PR.

Test Results

  • ✅ Frontend: 1477/1477 passed
  • ✅ Rust: 484/484 passed (16 ignored)
  • ✅ Quality checks: All passing

Files Changed

  • docs/architecture/data/schema-cache-population.md - Added verification section
  • packages/core/src/services/error.rs - Added InitializationError variant
  • packages/core/src/services/node_service.rs - Fixed error type + enhanced comment
  • packages/desktop-app/src/lib/types/schema-node.ts - Made nodeType optional

🤖 Generated with Claude Code

@malibio
malibio merged commit faad24f into main Dec 1, 2025
@malibio
malibio deleted the feature/issue-704-refactor-schema-seeding branch December 1, 2025 14:15
malibio added a commit that referenced this pull request Feb 4, 2026
* WIP: Fix SQL query camelCase aliasing for SchemaNode and TaskNode deserialization

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Investigated 500 error on GET /api/schemas/date endpoint
- [x] Discovered deserialization failure in get_schema_node() query
- [x] Identified violation of identifier naming conventions (database snake_case vs serde camelCase)
- [x] Root cause: SQL queries returned snake_case columns but Rust structs expected camelCase

### Phase 2: Query Fixes ✅
- [x] Fixed get_schema_node() query with camelCase aliases:
  - `is_core AS isCore`
  - `version AS schemaVersion`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Fixed get_task_node() query with camelCase aliases:
  - `due_date AS dueDate`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Updated documentation comments to explain aliasing requirement

### Phase 3: Issue Creation ✅
- [x] Created Issue #704 for proper architectural fix
- [x] Detailed implementation guide for moving schema seeding from SurrealStore to NodeService

## Remaining Work

### Phase 4: Complete Architectural Refactor (Issue #704)
- [ ] Move seed_core_schemas() logic from SurrealStore to NodeService
- [ ] Remove seed_core_schemas() and seed_core_schemas_http() from SurrealStore
- [ ] Make NodeService::new() async with seeding initialization
- [ ] Update all callsites (dev-proxy, Tauri commands)
- [ ] Write unit tests for NodeService seeding
- [ ] Integration test with fresh database
- [ ] Verify no regressions

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 3701-3713: Updated get_task_node() docstring query example
  - Lines 3745-3757: Fixed get_task_node() query with camelCase aliases
  - Lines 3780-3792: Updated get_schema_node() docstring query example
  - Lines 3822-3834: Fixed get_schema_node() query with camelCase aliases
  - Line 488: Added seed_core_schemas_http() call (temporary - will be removed in Phase 4)
  - Lines 758-829: Added seed_core_schemas_http() function (temporary - will be removed in Phase 4)

**Tests Status:** Not yet run - queries fixed but architectural refactor pending

**Known Issues:**
- Schema seeding still in wrong layer (SurrealStore instead of NodeService)
- HTTP mode has duplicate seeding logic (seed_core_schemas_http)
- These are intentional temporary fixes - proper solution in Issue #704

## Context for Next Session

**Background:**
The immediate bug was SchemaNode deserialization failing because SQL queries returned snake_case database columns but the Rust struct uses `#[serde(rename_all = "camelCase")]` which expects camelCase field names during deserialization. This violated our naming conventions documented in `docs/architecture/development/standards/identifier-naming-conventions.md`.

**Quick Fixes Applied:**
Added SQL column aliases to match serde expectations (database stores snake_case, queries alias to camelCase for deserialization).

**Proper Solution (Issue #704):**
The real problem is architectural - `SurrealStore` (data layer) shouldn't be seeding schemas (domain data). That responsibility belongs to `NodeService` (domain layer). Issue #704 has a complete implementation guide for moving the seeding logic to the proper layer.

**Next Steps:**
1. Follow Issue #704 implementation guide
2. Move seeding to NodeService::new()
3. Remove seeding from SurrealStore entirely
4. Test with fresh database to ensure seeding works in both embedded and HTTP modes

## Acceptance Criteria Status

From Issue #704:
- [ ] 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 with seeding logic
- [ ] All 7 core schemas seeded correctly
- [ ] Dev-proxy works with fresh database
- [ ] Tests pass
- [ ] No regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Document schema cache population strategy (Issue #704)

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Identified schema cache timing issue after refactoring seeding to NodeService
- [x] Discovered caches built BEFORE schemas exist on first launch
- [x] Root cause: `build_schema_caches()` queries empty schema table during `SurrealStore::new()`
- [x] Impact: `has_spoke_table()` returns false for "task", "text", etc. → spoke records not created
- [x] Verified this is a production bug, not just a test issue

### Phase 2: Solution Design ✅
- [x] Designed two-phase cache population strategy:
  - **First launch**: NodeService populates cache incrementally during seeding (no re-query)
  - **Subsequent launches**: SurrealStore queries DB once at startup (already populated)
- [x] Created comprehensive documentation in docs/architecture/data/schema-cache-population.md
- [x] Updated code documentation in SurrealStore struct fields
- [x] Documented `build_schema_caches()` with both scenarios
- [x] Implemented and documented `add_to_schema_cache()` method signature

### Phase 3: Test Helper Fix (Temporary) ✅
- [x] Fixed 10 SurrealStore atomic operation tests
- [x] Updated `create_test_store()` to call NodeService for seeding + cache rebuild
- [x] Tests now pass: 479 passed, 5 failed (down from 15 failures)

## Remaining Work

### Phase 4: Implement Incremental Caching
- [ ] Update `NodeService::seed_core_schemas_if_needed()` to call `add_to_schema_cache()` after creating each schema
- [ ] Handle `Arc::get_mut()` pattern to get mutable access for cache updates
- [ ] Remove temporary `rebuild_schema_caches()` approach from test helper
- [ ] Test with fresh database to verify cache populated correctly

### Phase 5: Clean Up
- [ ] Remove `rebuild_schema_caches()` method (temporary solution)
- [ ] Simplify `create_test_store()` helper
- [ ] Remove `#[allow(dead_code)]` annotations
- [ ] Verify all tests pass with new incremental approach

### Phase 6: Final Validation
- [ ] Run test:all to verify no new failures
- [ ] Run quality:fix and commit changes
- [ ] Update PR with complete implementation
- [ ] Verify cache works correctly on both first launch and subsequent launches

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 331-355: Updated cache field docs with two-phase population strategy
  - Lines 594-614: Documented `build_schema_caches()` with both scenarios
  - Lines 711-754: Implemented both `add_to_schema_cache()` (ready) and `rebuild_schema_caches()` (temporary)
  - Lines 3792-3830: Fixed `create_test_store()` helper (temporary rebuild approach)
- `packages/core/src/services/node_service.rs`:
  - Lines 462-466: Added cache population strategy documentation (TODO)
  - Implementation not yet updated
- `docs/architecture/data/schema-cache-population.md`: Complete design document

**Test Status:**
- Frontend: 1477 passed ✓
- Rust: 479 passed, 5 failed
- **10 SurrealStore tests fixed** (were failing due to missing cache)
- Remaining 5 failures: Task property storage/retrieval (likely pre-existing bugs)

**Known Issues:**
- Using temporary `rebuild_schema_caches()` in test helper (works but not optimal)
- Production code has same cache timing issue (needs incremental caching)
- `add_to_schema_cache()` method exists but not yet called

## Context for Next Session

**The Problem:**
Schema caches (`types_with_spoke_tables`, `valid_node_types`) determine which node types need spoke tables. They're built by querying the `schema` table. But on first launch:
1. `SurrealStore::new()` builds caches → queries empty schema table → cache = {"schema"} only
2. `NodeService::new()` seeds schemas → cache is stale
3. `create_node("task")` → `has_spoke_table("task")` returns false → bug!

**The Solution (Fully Documented):**
Two-phase caching strategy documented in `docs/architecture/data/schema-cache-population.md`:

**First launch:**
```rust
for schema in core_schemas {
    create_schema_node_atomic(schema);
    // TODO: Add this call in NodeService
    Arc::get_mut(&mut store)?
        .add_to_schema_cache(schema.id, !schema.fields.is_empty());
}
```

**Subsequent launches:**
- Caches already built by `build_schema_caches()` in `SurrealStore::new()`

**Implementation Location:**
- File: `packages/core/src/services/node_service.rs`
- Method: `seed_core_schemas_if_needed()`
- Line: ~520 (after `create_schema_node_atomic()` call)

**Next Steps:**
1. Add the `add_to_schema_cache()` call in the seeding loop
2. Handle Arc mutability (requires `mut store` parameter in `new()`)
3. Clean up temporary test helper workaround
4. Verify tests pass

## Acceptance Criteria Status

From Issue #704:
- [x] seed_core_schemas() removed from SurrealStore
- [x] seed_core_schemas_http() removed from SurrealStore
- [x] Schema seeding calls removed from SurrealStore::new() and new_http()
- [x] NodeService::new() made async with seeding logic
- [x] All 7 core schemas seeded correctly
- [ ] **Cache population implemented** (documented, needs code)
- [ ] Tests pass (479/484 passing)
- [ ] No regressions

## References

- **Design Doc**: `docs/architecture/data/schema-cache-population.md`
- **Issue**: #704
- **PR**: #706

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Implement incremental schema cache population (Issue #704)

## Summary
Completes the schema seeding refactor by implementing incremental cache
population during first-launch seeding. Schema caches are now updated
in memory as each schema is created, avoiding stale caches.

## Key Changes

### API Change: NodeService::new() signature
- Changed from `new(store: Arc<SurrealStore>)` to `new(store: &mut Arc<SurrealStore>)`
- Takes mutable reference to enable cache updates via `Arc::get_mut()`
- Cache updates happen BEFORE cloning Arc into Self

### Implementation Details
- `seed_core_schemas_if_needed()` now takes `&mut Arc<SurrealStore>`
- SchemaTableManager scoped to release Arc clone before `Arc::get_mut()`
- Cache updates collected during seeding and applied after all schemas created
- Removed temporary `rebuild_schema_caches()` method

### Two-Phase Cache Population Strategy
- **First launch**: NodeService seeds schemas, populates caches incrementally
- **Subsequent launches**: SurrealStore queries populated schema table once

## Files Changed
- `node_service.rs`: New API, incremental caching implementation
- `surreal_store.rs`: Removed rebuild_schema_caches(), simplified test helper
- All call sites updated to use `&mut Arc<SurrealStore>` pattern
- Doc examples updated to reflect new API

## Test Status
- All 484 Rust tests pass
- All 128 doc tests pass
- Tauri build compiles successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix isSchemaNode type guard to not require nodeType field

The /api/schemas/:id endpoint returns SchemaNode without the nodeType
field (it's implicit - always "schema"). Updated the type guard to check
for schema-specific fields (isCore, schemaVersion, fields) instead.

Also updated documentation to clarify that nodeType is NOT included in
the API response.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Documentation, error types, and code clarity improvements

- Add verification section to schema-cache-population.md with manual and automated test steps
- Add InitializationError variant to NodeServiceError for semantic accuracy
- Change Arc::get_mut() error from SerializationError to InitializationError (lifecycle error, not serialization)
- Enhance SchemaTableManager scope comment with rationale explaining Arc ownership requirement
- Make SchemaNode.nodeType optional to match API response reality (implicit in /api/schemas/:id)

Addresses reviewer recommendations from PR review.

🤖 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
* WIP: Fix SQL query camelCase aliasing for SchemaNode and TaskNode deserialization

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Investigated 500 error on GET /api/schemas/date endpoint
- [x] Discovered deserialization failure in get_schema_node() query
- [x] Identified violation of identifier naming conventions (database snake_case vs serde camelCase)
- [x] Root cause: SQL queries returned snake_case columns but Rust structs expected camelCase

### Phase 2: Query Fixes ✅
- [x] Fixed get_schema_node() query with camelCase aliases:
  - `is_core AS isCore`
  - `version AS schemaVersion`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Fixed get_task_node() query with camelCase aliases:
  - `due_date AS dueDate`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Updated documentation comments to explain aliasing requirement

### Phase 3: Issue Creation ✅
- [x] Created Issue #704 for proper architectural fix
- [x] Detailed implementation guide for moving schema seeding from SurrealStore to NodeService

## Remaining Work

### Phase 4: Complete Architectural Refactor (Issue #704)
- [ ] Move seed_core_schemas() logic from SurrealStore to NodeService
- [ ] Remove seed_core_schemas() and seed_core_schemas_http() from SurrealStore
- [ ] Make NodeService::new() async with seeding initialization
- [ ] Update all callsites (dev-proxy, Tauri commands)
- [ ] Write unit tests for NodeService seeding
- [ ] Integration test with fresh database
- [ ] Verify no regressions

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 3701-3713: Updated get_task_node() docstring query example
  - Lines 3745-3757: Fixed get_task_node() query with camelCase aliases
  - Lines 3780-3792: Updated get_schema_node() docstring query example
  - Lines 3822-3834: Fixed get_schema_node() query with camelCase aliases
  - Line 488: Added seed_core_schemas_http() call (temporary - will be removed in Phase 4)
  - Lines 758-829: Added seed_core_schemas_http() function (temporary - will be removed in Phase 4)

**Tests Status:** Not yet run - queries fixed but architectural refactor pending

**Known Issues:**
- Schema seeding still in wrong layer (SurrealStore instead of NodeService)
- HTTP mode has duplicate seeding logic (seed_core_schemas_http)
- These are intentional temporary fixes - proper solution in Issue #704

## Context for Next Session

**Background:**
The immediate bug was SchemaNode deserialization failing because SQL queries returned snake_case database columns but the Rust struct uses `#[serde(rename_all = "camelCase")]` which expects camelCase field names during deserialization. This violated our naming conventions documented in `docs/architecture/development/standards/identifier-naming-conventions.md`.

**Quick Fixes Applied:**
Added SQL column aliases to match serde expectations (database stores snake_case, queries alias to camelCase for deserialization).

**Proper Solution (Issue #704):**
The real problem is architectural - `SurrealStore` (data layer) shouldn't be seeding schemas (domain data). That responsibility belongs to `NodeService` (domain layer). Issue #704 has a complete implementation guide for moving the seeding logic to the proper layer.

**Next Steps:**
1. Follow Issue #704 implementation guide
2. Move seeding to NodeService::new()
3. Remove seeding from SurrealStore entirely
4. Test with fresh database to ensure seeding works in both embedded and HTTP modes

## Acceptance Criteria Status

From Issue #704:
- [ ] 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 with seeding logic
- [ ] All 7 core schemas seeded correctly
- [ ] Dev-proxy works with fresh database
- [ ] Tests pass
- [ ] No regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Document schema cache population strategy (Issue #704)

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Identified schema cache timing issue after refactoring seeding to NodeService
- [x] Discovered caches built BEFORE schemas exist on first launch
- [x] Root cause: `build_schema_caches()` queries empty schema table during `SurrealStore::new()`
- [x] Impact: `has_spoke_table()` returns false for "task", "text", etc. → spoke records not created
- [x] Verified this is a production bug, not just a test issue

### Phase 2: Solution Design ✅
- [x] Designed two-phase cache population strategy:
  - **First launch**: NodeService populates cache incrementally during seeding (no re-query)
  - **Subsequent launches**: SurrealStore queries DB once at startup (already populated)
- [x] Created comprehensive documentation in docs/architecture/data/schema-cache-population.md
- [x] Updated code documentation in SurrealStore struct fields
- [x] Documented `build_schema_caches()` with both scenarios
- [x] Implemented and documented `add_to_schema_cache()` method signature

### Phase 3: Test Helper Fix (Temporary) ✅
- [x] Fixed 10 SurrealStore atomic operation tests
- [x] Updated `create_test_store()` to call NodeService for seeding + cache rebuild
- [x] Tests now pass: 479 passed, 5 failed (down from 15 failures)

## Remaining Work

### Phase 4: Implement Incremental Caching
- [ ] Update `NodeService::seed_core_schemas_if_needed()` to call `add_to_schema_cache()` after creating each schema
- [ ] Handle `Arc::get_mut()` pattern to get mutable access for cache updates
- [ ] Remove temporary `rebuild_schema_caches()` approach from test helper
- [ ] Test with fresh database to verify cache populated correctly

### Phase 5: Clean Up
- [ ] Remove `rebuild_schema_caches()` method (temporary solution)
- [ ] Simplify `create_test_store()` helper
- [ ] Remove `#[allow(dead_code)]` annotations
- [ ] Verify all tests pass with new incremental approach

### Phase 6: Final Validation
- [ ] Run test:all to verify no new failures
- [ ] Run quality:fix and commit changes
- [ ] Update PR with complete implementation
- [ ] Verify cache works correctly on both first launch and subsequent launches

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 331-355: Updated cache field docs with two-phase population strategy
  - Lines 594-614: Documented `build_schema_caches()` with both scenarios
  - Lines 711-754: Implemented both `add_to_schema_cache()` (ready) and `rebuild_schema_caches()` (temporary)
  - Lines 3792-3830: Fixed `create_test_store()` helper (temporary rebuild approach)
- `packages/core/src/services/node_service.rs`:
  - Lines 462-466: Added cache population strategy documentation (TODO)
  - Implementation not yet updated
- `docs/architecture/data/schema-cache-population.md`: Complete design document

**Test Status:**
- Frontend: 1477 passed ✓
- Rust: 479 passed, 5 failed
- **10 SurrealStore tests fixed** (were failing due to missing cache)
- Remaining 5 failures: Task property storage/retrieval (likely pre-existing bugs)

**Known Issues:**
- Using temporary `rebuild_schema_caches()` in test helper (works but not optimal)
- Production code has same cache timing issue (needs incremental caching)
- `add_to_schema_cache()` method exists but not yet called

## Context for Next Session

**The Problem:**
Schema caches (`types_with_spoke_tables`, `valid_node_types`) determine which node types need spoke tables. They're built by querying the `schema` table. But on first launch:
1. `SurrealStore::new()` builds caches → queries empty schema table → cache = {"schema"} only
2. `NodeService::new()` seeds schemas → cache is stale
3. `create_node("task")` → `has_spoke_table("task")` returns false → bug!

**The Solution (Fully Documented):**
Two-phase caching strategy documented in `docs/architecture/data/schema-cache-population.md`:

**First launch:**
```rust
for schema in core_schemas {
    create_schema_node_atomic(schema);
    // TODO: Add this call in NodeService
    Arc::get_mut(&mut store)?
        .add_to_schema_cache(schema.id, !schema.fields.is_empty());
}
```

**Subsequent launches:**
- Caches already built by `build_schema_caches()` in `SurrealStore::new()`

**Implementation Location:**
- File: `packages/core/src/services/node_service.rs`
- Method: `seed_core_schemas_if_needed()`
- Line: ~520 (after `create_schema_node_atomic()` call)

**Next Steps:**
1. Add the `add_to_schema_cache()` call in the seeding loop
2. Handle Arc mutability (requires `mut store` parameter in `new()`)
3. Clean up temporary test helper workaround
4. Verify tests pass

## Acceptance Criteria Status

From Issue #704:
- [x] seed_core_schemas() removed from SurrealStore
- [x] seed_core_schemas_http() removed from SurrealStore
- [x] Schema seeding calls removed from SurrealStore::new() and new_http()
- [x] NodeService::new() made async with seeding logic
- [x] All 7 core schemas seeded correctly
- [ ] **Cache population implemented** (documented, needs code)
- [ ] Tests pass (479/484 passing)
- [ ] No regressions

## References

- **Design Doc**: `docs/architecture/data/schema-cache-population.md`
- **Issue**: #704
- **PR**: #706

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Implement incremental schema cache population (Issue #704)

## Summary
Completes the schema seeding refactor by implementing incremental cache
population during first-launch seeding. Schema caches are now updated
in memory as each schema is created, avoiding stale caches.

## Key Changes

### API Change: NodeService::new() signature
- Changed from `new(store: Arc<SurrealStore>)` to `new(store: &mut Arc<SurrealStore>)`
- Takes mutable reference to enable cache updates via `Arc::get_mut()`
- Cache updates happen BEFORE cloning Arc into Self

### Implementation Details
- `seed_core_schemas_if_needed()` now takes `&mut Arc<SurrealStore>`
- SchemaTableManager scoped to release Arc clone before `Arc::get_mut()`
- Cache updates collected during seeding and applied after all schemas created
- Removed temporary `rebuild_schema_caches()` method

### Two-Phase Cache Population Strategy
- **First launch**: NodeService seeds schemas, populates caches incrementally
- **Subsequent launches**: SurrealStore queries populated schema table once

## Files Changed
- `node_service.rs`: New API, incremental caching implementation
- `surreal_store.rs`: Removed rebuild_schema_caches(), simplified test helper
- All call sites updated to use `&mut Arc<SurrealStore>` pattern
- Doc examples updated to reflect new API

## Test Status
- All 484 Rust tests pass
- All 128 doc tests pass
- Tauri build compiles successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix isSchemaNode type guard to not require nodeType field

The /api/schemas/:id endpoint returns SchemaNode without the nodeType
field (it's implicit - always "schema"). Updated the type guard to check
for schema-specific fields (isCore, schemaVersion, fields) instead.

Also updated documentation to clarify that nodeType is NOT included in
the API response.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Documentation, error types, and code clarity improvements

- Add verification section to schema-cache-population.md with manual and automated test steps
- Add InitializationError variant to NodeServiceError for semantic accuracy
- Change Arc::get_mut() error from SerializationError to InitializationError (lifecycle error, not serialization)
- Enhance SchemaTableManager scope comment with rationale explaining Arc ownership requirement
- Make SchemaNode.nodeType optional to match API response reality (implicit in /api/schemas/:id)

Addresses reviewer recommendations from PR review.

🤖 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 26, 2026
* WIP: Fix SQL query camelCase aliasing for SchemaNode and TaskNode deserialization

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Investigated 500 error on GET /api/schemas/date endpoint
- [x] Discovered deserialization failure in get_schema_node() query
- [x] Identified violation of identifier naming conventions (database snake_case vs serde camelCase)
- [x] Root cause: SQL queries returned snake_case columns but Rust structs expected camelCase

### Phase 2: Query Fixes ✅
- [x] Fixed get_schema_node() query with camelCase aliases:
  - `is_core AS isCore`
  - `version AS schemaVersion`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Fixed get_task_node() query with camelCase aliases:
  - `due_date AS dueDate`
  - `node.created_at AS createdAt`
  - `node.modified_at AS modifiedAt`
- [x] Updated documentation comments to explain aliasing requirement

### Phase 3: Issue Creation ✅
- [x] Created Issue #704 for proper architectural fix
- [x] Detailed implementation guide for moving schema seeding from SurrealStore to NodeService

## Remaining Work

### Phase 4: Complete Architectural Refactor (Issue #704)
- [ ] Move seed_core_schemas() logic from SurrealStore to NodeService
- [ ] Remove seed_core_schemas() and seed_core_schemas_http() from SurrealStore
- [ ] Make NodeService::new() async with seeding initialization
- [ ] Update all callsites (dev-proxy, Tauri commands)
- [ ] Write unit tests for NodeService seeding
- [ ] Integration test with fresh database
- [ ] Verify no regressions

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 3701-3713: Updated get_task_node() docstring query example
  - Lines 3745-3757: Fixed get_task_node() query with camelCase aliases
  - Lines 3780-3792: Updated get_schema_node() docstring query example
  - Lines 3822-3834: Fixed get_schema_node() query with camelCase aliases
  - Line 488: Added seed_core_schemas_http() call (temporary - will be removed in Phase 4)
  - Lines 758-829: Added seed_core_schemas_http() function (temporary - will be removed in Phase 4)

**Tests Status:** Not yet run - queries fixed but architectural refactor pending

**Known Issues:**
- Schema seeding still in wrong layer (SurrealStore instead of NodeService)
- HTTP mode has duplicate seeding logic (seed_core_schemas_http)
- These are intentional temporary fixes - proper solution in Issue #704

## Context for Next Session

**Background:**
The immediate bug was SchemaNode deserialization failing because SQL queries returned snake_case database columns but the Rust struct uses `#[serde(rename_all = "camelCase")]` which expects camelCase field names during deserialization. This violated our naming conventions documented in `docs/architecture/development/standards/identifier-naming-conventions.md`.

**Quick Fixes Applied:**
Added SQL column aliases to match serde expectations (database stores snake_case, queries alias to camelCase for deserialization).

**Proper Solution (Issue #704):**
The real problem is architectural - `SurrealStore` (data layer) shouldn't be seeding schemas (domain data). That responsibility belongs to `NodeService` (domain layer). Issue #704 has a complete implementation guide for moving the seeding logic to the proper layer.

**Next Steps:**
1. Follow Issue #704 implementation guide
2. Move seeding to NodeService::new()
3. Remove seeding from SurrealStore entirely
4. Test with fresh database to ensure seeding works in both embedded and HTTP modes

## Acceptance Criteria Status

From Issue #704:
- [ ] 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 with seeding logic
- [ ] All 7 core schemas seeded correctly
- [ ] Dev-proxy works with fresh database
- [ ] Tests pass
- [ ] No regressions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* WIP: Document schema cache population strategy (Issue #704)

## Completed in This Session

### Phase 1: Root Cause Analysis ✅
- [x] Identified schema cache timing issue after refactoring seeding to NodeService
- [x] Discovered caches built BEFORE schemas exist on first launch
- [x] Root cause: `build_schema_caches()` queries empty schema table during `SurrealStore::new()`
- [x] Impact: `has_spoke_table()` returns false for "task", "text", etc. → spoke records not created
- [x] Verified this is a production bug, not just a test issue

### Phase 2: Solution Design ✅
- [x] Designed two-phase cache population strategy:
  - **First launch**: NodeService populates cache incrementally during seeding (no re-query)
  - **Subsequent launches**: SurrealStore queries DB once at startup (already populated)
- [x] Created comprehensive documentation in docs/architecture/data/schema-cache-population.md
- [x] Updated code documentation in SurrealStore struct fields
- [x] Documented `build_schema_caches()` with both scenarios
- [x] Implemented and documented `add_to_schema_cache()` method signature

### Phase 3: Test Helper Fix (Temporary) ✅
- [x] Fixed 10 SurrealStore atomic operation tests
- [x] Updated `create_test_store()` to call NodeService for seeding + cache rebuild
- [x] Tests now pass: 479 passed, 5 failed (down from 15 failures)

## Remaining Work

### Phase 4: Implement Incremental Caching
- [ ] Update `NodeService::seed_core_schemas_if_needed()` to call `add_to_schema_cache()` after creating each schema
- [ ] Handle `Arc::get_mut()` pattern to get mutable access for cache updates
- [ ] Remove temporary `rebuild_schema_caches()` approach from test helper
- [ ] Test with fresh database to verify cache populated correctly

### Phase 5: Clean Up
- [ ] Remove `rebuild_schema_caches()` method (temporary solution)
- [ ] Simplify `create_test_store()` helper
- [ ] Remove `#[allow(dead_code)]` annotations
- [ ] Verify all tests pass with new incremental approach

### Phase 6: Final Validation
- [ ] Run test:all to verify no new failures
- [ ] Run quality:fix and commit changes
- [ ] Update PR with complete implementation
- [ ] Verify cache works correctly on both first launch and subsequent launches

## Current State

**Files Modified:**
- `packages/core/src/db/surreal_store.rs`:
  - Lines 331-355: Updated cache field docs with two-phase population strategy
  - Lines 594-614: Documented `build_schema_caches()` with both scenarios
  - Lines 711-754: Implemented both `add_to_schema_cache()` (ready) and `rebuild_schema_caches()` (temporary)
  - Lines 3792-3830: Fixed `create_test_store()` helper (temporary rebuild approach)
- `packages/core/src/services/node_service.rs`:
  - Lines 462-466: Added cache population strategy documentation (TODO)
  - Implementation not yet updated
- `docs/architecture/data/schema-cache-population.md`: Complete design document

**Test Status:**
- Frontend: 1477 passed ✓
- Rust: 479 passed, 5 failed
- **10 SurrealStore tests fixed** (were failing due to missing cache)
- Remaining 5 failures: Task property storage/retrieval (likely pre-existing bugs)

**Known Issues:**
- Using temporary `rebuild_schema_caches()` in test helper (works but not optimal)
- Production code has same cache timing issue (needs incremental caching)
- `add_to_schema_cache()` method exists but not yet called

## Context for Next Session

**The Problem:**
Schema caches (`types_with_spoke_tables`, `valid_node_types`) determine which node types need spoke tables. They're built by querying the `schema` table. But on first launch:
1. `SurrealStore::new()` builds caches → queries empty schema table → cache = {"schema"} only
2. `NodeService::new()` seeds schemas → cache is stale
3. `create_node("task")` → `has_spoke_table("task")` returns false → bug!

**The Solution (Fully Documented):**
Two-phase caching strategy documented in `docs/architecture/data/schema-cache-population.md`:

**First launch:**
```rust
for schema in core_schemas {
    create_schema_node_atomic(schema);
    // TODO: Add this call in NodeService
    Arc::get_mut(&mut store)?
        .add_to_schema_cache(schema.id, !schema.fields.is_empty());
}
```

**Subsequent launches:**
- Caches already built by `build_schema_caches()` in `SurrealStore::new()`

**Implementation Location:**
- File: `packages/core/src/services/node_service.rs`
- Method: `seed_core_schemas_if_needed()`
- Line: ~520 (after `create_schema_node_atomic()` call)

**Next Steps:**
1. Add the `add_to_schema_cache()` call in the seeding loop
2. Handle Arc mutability (requires `mut store` parameter in `new()`)
3. Clean up temporary test helper workaround
4. Verify tests pass

## Acceptance Criteria Status

From Issue #704:
- [x] seed_core_schemas() removed from SurrealStore
- [x] seed_core_schemas_http() removed from SurrealStore
- [x] Schema seeding calls removed from SurrealStore::new() and new_http()
- [x] NodeService::new() made async with seeding logic
- [x] All 7 core schemas seeded correctly
- [ ] **Cache population implemented** (documented, needs code)
- [ ] Tests pass (479/484 passing)
- [ ] No regressions

## References

- **Design Doc**: `docs/architecture/data/schema-cache-population.md`
- **Issue**: #704
- **PR**: #706

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Implement incremental schema cache population (Issue #704)

## Summary
Completes the schema seeding refactor by implementing incremental cache
population during first-launch seeding. Schema caches are now updated
in memory as each schema is created, avoiding stale caches.

## Key Changes

### API Change: NodeService::new() signature
- Changed from `new(store: Arc<SurrealStore>)` to `new(store: &mut Arc<SurrealStore>)`
- Takes mutable reference to enable cache updates via `Arc::get_mut()`
- Cache updates happen BEFORE cloning Arc into Self

### Implementation Details
- `seed_core_schemas_if_needed()` now takes `&mut Arc<SurrealStore>`
- SchemaTableManager scoped to release Arc clone before `Arc::get_mut()`
- Cache updates collected during seeding and applied after all schemas created
- Removed temporary `rebuild_schema_caches()` method

### Two-Phase Cache Population Strategy
- **First launch**: NodeService seeds schemas, populates caches incrementally
- **Subsequent launches**: SurrealStore queries populated schema table once

## Files Changed
- `node_service.rs`: New API, incremental caching implementation
- `surreal_store.rs`: Removed rebuild_schema_caches(), simplified test helper
- All call sites updated to use `&mut Arc<SurrealStore>` pattern
- Doc examples updated to reflect new API

## Test Status
- All 484 Rust tests pass
- All 128 doc tests pass
- Tauri build compiles successfully

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Fix isSchemaNode type guard to not require nodeType field

The /api/schemas/:id endpoint returns SchemaNode without the nodeType
field (it's implicit - always "schema"). Updated the type guard to check
for schema-specific fields (isCore, schemaVersion, fields) instead.

Also updated documentation to clarify that nodeType is NOT included in
the API response.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address review: Documentation, error types, and code clarity improvements

- Add verification section to schema-cache-population.md with manual and automated test steps
- Add InitializationError variant to NodeServiceError for semantic accuracy
- Change Arc::get_mut() error from SerializationError to InitializationError (lifecycle error, not serialization)
- Enhance SchemaTableManager scope comment with rationale explaining Arc ownership requirement
- Make SchemaNode.nodeType optional to match API response reality (implicit in /api/schemas/:id)

Addresses reviewer recommendations from PR review.

🤖 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.

Refactor Schema Seeding: Move from SurrealStore to NodeService

1 participant