Skip to content

Implement Gradual Rollout System for SurrealDB Backend #466

Closed

Description

@malibio

Implement Gradual Rollout System for SurrealDB Backend

Parent Epic: #461 (SurrealDB Migration)
Phase: 4 - Gradual Rollout
Estimated Time: 2-3 days
Depends On: #465 (A/B Testing Framework)

Objective

Create a feature-flagged gradual rollout system that enables controlled migration from Turso to SurrealDB desktop backend with real-time monitoring and rollback capability.

Implementation

1. Rollout Configuration

File: packages/desktop-app/src-tauri/src/datastore/rollout_config.rs

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RolloutConfig {
    /// Percentage of users on SurrealDB (0-100)
    pub surrealdb_percentage: u8,
    
    /// Feature flag name
    pub feature_flag: String,
    
    /// Monitoring enabled
    pub monitoring_enabled: bool,
    
    /// Automatic rollback on errors
    pub auto_rollback: bool,
    
    /// Error rate threshold for rollback (%)
    pub rollback_error_threshold: f64,
}

impl RolloutConfig {
    pub fn stage_1() -> Self {
        Self {
            surrealdb_percentage: 10,
            feature_flag: "surrealdb_backend".to_string(),
            monitoring_enabled: true,
            auto_rollback: true,
            rollback_error_threshold: 5.0,
        }
    }
    
    pub fn stage_2() -> Self {
        Self { surrealdb_percentage: 25, ..Self::stage_1() }
    }
    
    pub fn stage_3() -> Self {
        Self { surrealdb_percentage: 50, ..Self::stage_1() }
    }
    
    pub fn stage_4() -> Self {
        Self { surrealdb_percentage: 100, ..Self::stage_1() }
    }
}

2. User Allocation Logic

File: packages/desktop-app/src-tauri/src/datastore/rollout.rs

use anyhow::Result;
use std::sync::Arc;
use crate::datastore::{NodeStore, factory::create_store};

pub struct RolloutManager {
    config: RolloutConfig,
    user_id: String,
}

impl RolloutManager {
    pub async fn new(config: RolloutConfig, user_id: String) -> Result<Self> {
        Ok(Self { config, user_id })
    }
    
    pub async fn get_backend(&self) -> Result<Arc<dyn NodeStore>> {
        // Deterministic user allocation based on user_id hash
        let hash = self.hash_user_id(&self.user_id);
        let allocation = hash % 100;
        
        if allocation < self.config.surrealdb_percentage {
            // User allocated to SurrealDB
            log::info!("User {} allocated to SurrealDB ({}%)", 
                self.user_id, self.config.surrealdb_percentage);
            create_store(&DatabaseConfig::surrealdb()).await
        } else {
            // User remains on Turso
            log::info!("User {} remains on Turso", self.user_id);
            create_store(&DatabaseConfig::turso()).await
        }
    }
    
    fn hash_user_id(&self, user_id: &str) -> u8 {
        // Stable hash function for user allocation
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        
        let mut hasher = DefaultHasher::new();
        user_id.hash(&mut hasher);
        (hasher.finish() % 100) as u8
    }
}

3. Monitoring & Rollback

File: packages/desktop-app/src-tauri/src/datastore/rollout_monitor.rs

pub struct RolloutMonitor {
    config: RolloutConfig,
    error_tracker: ErrorTracker,
}

impl RolloutMonitor {
    pub fn new(config: RolloutConfig) -> Self {
        Self {
            config,
            error_tracker: ErrorTracker::new(),
        }
    }
    
    pub fn record_operation(&mut self, backend: BackendType, result: Result<()>) {
        match result {
            Ok(_) => self.error_tracker.record_success(backend),
            Err(e) => {
                self.error_tracker.record_error(backend, e);
                
                // Check if rollback needed
                if self.should_rollback() {
                    self.trigger_rollback();
                }
            }
        }
    }
    
    fn should_rollback(&self) -> bool {
        if !self.config.auto_rollback {
            return false;
        }
        
        let error_rate = self.error_tracker.get_error_rate(BackendType::SurrealDB);
        error_rate > self.config.rollback_error_threshold
    }
    
    fn trigger_rollback(&mut self) {
        log::error!("Error threshold exceeded, triggering rollback to Turso");
        // Set config to 0% SurrealDB
        // Alert administrators
        // Switch all users back to Turso
    }
}

4. CLI Commands for Rollout Control

File: scripts/rollout-control.ts

import { Command } from 'commander';

const program = new Command();

program
  .command('set-stage <stage>')
  .description('Set rollout stage (1-4)')
  .action(async (stage) => {
    // Update rollout config
    // 1 = 10%, 2 = 25%, 3 = 50%, 4 = 100%
  });

program
  .command('get-status')
  .description('Get current rollout status')
  .action(async () => {
    // Display current percentage, error rates, user allocation
  });

program
  .command('rollback')
  .description('Emergency rollback to Turso')
  .action(async () => {
    // Force all users back to Turso
  });

program.parse();

Acceptance Criteria

  • Rollout configuration system implemented
  • User allocation logic working (deterministic hash-based)
  • Monitoring system tracking errors and performance
  • Automatic rollback triggers on error threshold
  • CLI commands for rollout control
  • Gradual rollout stages configurable (10% → 25% → 50% → 100%)
  • Real-time monitoring dashboard (optional)
  • Manual rollback capability
  • User allocation persists across sessions

Testing

Unit Tests

  • User allocation is deterministic (same user_id → same backend)
  • Percentage allocation works correctly (10% → ~10 users in SurrealDB)
  • Rollback triggers at correct error threshold
  • Config stages properly defined

Integration Tests

  • Rollout manager creates correct backend for user
  • Monitoring records errors accurately
  • Automatic rollback works when threshold exceeded
  • Manual rollback via CLI works

Rollout Stages (Production)

Stage 1: 10% (Week 5)

  • Duration: 3 days
  • Monitor: Error rates, performance metrics
  • Success criteria: <2% error rate, <5% performance delta
  • Rollback if: Error rate >5% OR performance delta >10%

Stage 2: 25% (Week 5)

  • Duration: 3 days
  • Same monitoring and criteria
  • Confidence level should be high before proceeding

Stage 3: 50% (Week 6)

  • Duration: 4 days
  • Majority of users on SurrealDB
  • Final validation before 100%

Stage 4: 100% (Week 6)

  • Full migration complete
  • Turso code remains as fallback
  • Feature flag kept for emergency rollback

Monitoring Metrics

  • Error rates per backend
  • Operation latency (p50, p95, p99)
  • Throughput (operations/sec)
  • User allocation distribution
  • Rollback events (count, timestamps)
  • Performance delta vs baseline

Rollback Plan

Triggers:

  • Error rate >5% on SurrealDB
  • Performance degradation >200% vs Turso
  • Critical bug discovered
  • User complaints exceeding threshold

Procedure:

  1. CLI command: bun run rollout:rollback
  2. Set surrealdb_percentage to 0%
  3. All users immediately switch to Turso
  4. Investigate root cause
  5. Fix issues
  6. Restart rollout from Stage 1

Success Criteria

  • 100% of desktop users successfully migrated to SurrealDB
  • Zero data loss during migration
  • Error rates within normal bounds (<2%)
  • Performance meets/exceeds Turso baseline
  • Rollback capability tested and working

Dependencies

References

Activity

  1. malibio commented on Nov 12, 2025

    @malibio
    CollaboratorAuthor

    Closing as Won't Do

    This issue was planned for a production gradual rollout scenario with existing users. However, NodeSpace is still in development with no production users yet.

    The right approach:

    • Epic SurrealDB Migration - Hybrid Architecture (Desktop-Only) #461 Phases 1-3 are complete (trait abstraction, SurrealDB implementation, A/B testing framework)
    • Simply use feature flags in development: --features surrealdb to test SurrealDB backend
    • When ready for production, just choose one backend and go live with it
    • No need for percentage-based user allocation when there are no users

    What was completed:
    ✅ NodeStore trait abstraction
    ✅ Both Turso and SurrealDB implementations
    ✅ A/B testing framework for validation
    ✅ Feature flags for switching backends

    Next steps:

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions