Skip to content

SurrealDB Migration - Hybrid Architecture (Desktop-Only) #461

Closed

Description

@malibio

SurrealDB Migration - Hybrid Architecture (Desktop-Only)

Context

Following successful completion of Epic #460 (SurrealDB Feasibility PoC), this epic tracks the migration from Turso to a hybrid database architecture:

  • Desktop: SurrealDB embedded (RocksDB backend)
  • Mobile: Turso (existing implementation)

PoC Findings Summary

Phase 1 Results (Desktop Embedding):

  • ✅ Binary size: 10MB (50% under 20MB threshold)
  • ✅ Startup time: 52ms (90% under 500ms threshold)
  • ✅ SCHEMALESS: 100% working with arbitrary properties
  • ✅ Dot notation queries: Clean and intuitive

Phase 2 Results (Scale & Performance):

  • ✅ 100K nodes: Query in 104ms (90% under threshold)
  • ✅ Deep pagination: 8.3ms (exceptional, no degradation)
  • ✅ Complex queries: 211ms avg (within bounds)

Architect Recommendation: Proceed with Hybrid Migration (85% confidence)

Migration Strategy

Approach: Trait-based abstraction layer enabling parallel implementations without data migration.

Key Principles:

  1. No breaking changes to existing code
  2. Feature-flagged rollout (gradual A/B testing)
  3. Performance monitoring at every stage
  4. Mobile strategy deferred (evaluate in 6 months)

Architecture

trait NodeStore {
    async fn create_node(&self, node: Node) -> Result<Node>;
    async fn query_nodes(&self, filter: NodeFilter) -> Result<Vec<Node>>;
    // ... (complete trait in sub-issues)
}

// Factory pattern for backend selection
let store: Box<dyn NodeStore> = if cfg!(feature = "surrealdb") {
    Box::new(SurrealStore::new(path).await?)
} else {
    Box::new(TursoStore::new(connection).await?)
};

Phases

Phase 1: Abstraction Layer (Week 1-2)

Create trait-based abstraction and wrap existing Turso implementation.

Phase 2: SurrealDB Implementation (Week 2-3)

Implement NodeStore trait for SurrealDB using PoC code as foundation.

Phase 3: Testing & Validation (Week 3-4)

A/B testing framework, performance monitoring, parallel testing.

Phase 4: Gradual Rollout (Week 5-6)

Feature-flagged rollout: 10% → 25% → 50% → 100% (desktop only).

Success Criteria

  • Zero regressions in existing Turso functionality
  • SurrealDB performance meets/exceeds PoC benchmarks
  • A/B testing shows <2% performance delta
  • Desktop users can switch backends without data loss
  • Complete test coverage for both backends

Out of Scope

  • Data migration: Not needed (early development phase)
  • Mobile migration: Deferred for 6 months (Turso remains mobile backend)
  • Schema changes: Using SCHEMALESS mode for dynamic properties

Dependencies

References

Activity

  1. malibio commented on Nov 11, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline

    Test Results (Before Implementation):

    • ✅ 753 passing tests (728 passed + 25 skipped)
    • ⏭️ 26 tests skipped (in-memory mode, require database persistence)
    • ⏱️ Test duration: ~20s (fast unit tests with Happy-DOM)

    Test breakdown:

    • Happy-DOM unit tests: 728 tests passing
    • Skipped tests: 26 (database persistence required)
    • No failures detected

    Status: Proceeding with Epic #461 implementation (SurrealDB Migration - Hybrid Architecture)

  2. self-assigned this
    on Nov 11, 2025
  3. malibio commented on Nov 11, 2025

    @malibio
    CollaboratorAuthor

    Epic #461 Implementation Plan - Senior Architect Analysis

    Executive Summary

    After thorough architectural review, recommend implementing PHASE 1 ONLY for this epic:

    ✅ SCOPE FOR EPIC #461 (Phase 1):

    ❌ DEFER TO FUTURE EPICS:

    Why Phase 1 Only?

    Risk Mitigation (Critical):

    • Refactoring database layer = HIGH RISK of regressions
    • Need to validate abstraction introduces ZERO breaking changes first
    • Escape hatch: Can revert if problems arise (no SurrealDB complexity yet)

    Incremental Validation:

    Architecture Design

    NodeStore Trait (24 methods):

    • Core CRUD: 4 methods (create, get, update, delete)
    • Querying: 4 methods (query, get_children, search, etc.)
    • Hierarchy: 2 methods (move, reorder)
    • Mentions: 5 methods (create, delete, get mentions)
    • Schema: 2 methods (get, update schema)
    • Embeddings: 3 methods (vector search operations)
    • Batch/Transaction: 2 methods (performance optimization)
    • Lifecycle: 2 methods (connection management)

    Abstraction Layer Location:

    NodeService (business logic)
        ↓ 
    NodeStore Trait ← NEW ABSTRACTION
        ↓
    TursoStore (wraps DatabaseService)
        ↓
    DatabaseService (unchanged)
    

    Implementation Strategy

    3-Step Refactoring Process:

    1. Extract SQL to DatabaseService - Move raw SQL from NodeService → new DatabaseService methods
    2. Implement TursoStore - Thin wrapper delegating to DatabaseService
    3. Refactor NodeService - Use Arc<dyn NodeStore> instead of direct DatabaseService

    Branch Strategy: Single branch (feature/issue-461-phase1-abstraction-layer)

    • Incremental commits (one method extraction per commit)
    • Run bun run test:all after EACH commit
    • ZERO new test failures required

    Success Criteria

    • ✅ All existing tests pass (100% requirement)
    • ✅ Performance overhead <5% (benchmark validated)
    • ✅ Complete API coverage (all NodeService operations)
    • ✅ Comprehensive documentation

    Timeline

    2 weeks (14 days):

    • Week 1: Trait definition + SQL extraction
    • Week 2: TursoStore implementation + NodeService refactoring + testing

    Risk Assessment

    Confidence Level: 95% - Proven refactoring pattern with clear validation
    Risk Level: LOW - Minimal complexity, easily reversible with feature flag

    Next Steps

    Proceeding with Phase 1 implementation. Full architectural details available in senior architect analysis.

  4. added 2 commits that reference this issue on Nov 11, 2025
  5. malibio commented on Nov 11, 2025

    @malibio
    CollaboratorAuthor

    Architectural Decision: No Feature Flags for Backend Selection

    Based on review feedback and project phase, we've simplified the migration approach by removing feature flag complexity.

    Decision

    No --features surrealdb flag. Instead:

    • Phase 1: TursoStore via trait abstraction
    • Phase 2: Direct replacement with SurrealStore
    • Safety net: git revert for rollback

    Rationale

    1. Early Development Phase

      • Limited production users
      • Acceptable to use git for rollback
      • Faster iteration without feature flag maintenance
    2. Simpler Implementation

      • No conditional compilation (#[cfg(feature = "surrealdb")])
      • Single code path to test and maintain
      • Trait abstraction already provides clean switching (change one line)
    3. Cleaner Rollback

      • git revert takes <1 hour (vs maintaining dual backends)
      • No risk of feature flag state bugs
      • If SurrealDB fundamentally fails, we need to fix it, not toggle it

    Updated Rollback Plans

    Phase 1 Rollback (Abstraction Layer):

    git revert <commit-range>  # Undo trait abstraction
    # Return to direct DatabaseService usage
    # Recovery time: <1 hour

    Phase 2 Rollback (SurrealDB Implementation):

    git revert <commit-range>  # Undo SurrealStore
    # Return to TursoStore
    # Recovery time: <1 hour

    What This Means for Implementation

    Phase 1 (Current):

    • Define NodeStore trait with 22 methods
    • Implement TursoStore wrapper
    • Refactor NodeService to use trait
    • No feature flags added

    Phase 2 (Future):

    • Implement SurrealStore with same 22 methods
    • Change one line: TursoStore::new() → SurrealStore::new()
    • Test with SurrealDB backend
    • No feature flags needed

    Documentation Updated

    All planning docs reflect this decision:

    • ✅ node-store-abstraction.md - No transaction method (deferred to Phase 2)
    • ✅ surrealdb-migration-roadmap.md - Feature flags removed, git revert rollback
    • ✅ surrealdb-migration-guide.md - Updated method count (22 methods)

    See PR #467 for complete changes.

  6. 5 remaining items

  7. malibio commented on Nov 12, 2025

    @malibio
    CollaboratorAuthor

    Phases 1-3 complete and merged. Phase 4 (gradual rollout) closed as unnecessary for pre-production software. Next: Issue #467 will remove abstraction layer and switch directly to SurrealDB.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions