Skip to content

Implement SurrealDB LIVE SELECT for real-time node and edge updates #551

Closed

Description

@malibio

Context

NodeSpace currently has no multi-client synchronization. When the MCP server creates or modifies nodes, the Tauri frontend doesn't see these changes until a manual refresh. This architecture review document identified LIVE SELECT as the solution for real-time reactivity.

Current Problems:

  1. No multi-client sync: MCP server changes invisible to Tauri frontend
  2. Manual cache management: Frontend maintains childrenCache and parentsCache that get stale
  3. Race conditions: Frontend cache can be out of sync with database
  4. Manual event propagation: Custom EventBus needs manual emit/subscribe everywhere

Proposed Solution: SurrealDB LIVE SELECT

LIVE SELECT provides real-time notifications when database records change. We'll use it to stream node and edge changes directly to the frontend via Tauri events.

Step-by-Step Implementation Guide

Step 1: Create the Live Query Service in Rust

File: packages/desktop-app/src-tauri/src/services/live_query_service.rs (create new)

use futures::StreamExt;
use surrealdb::engine::local::Db;
use surrealdb::opt::auth::Root;
use surrealdb::{Notification, Surreal};
use tauri::Manager;
use serde::{Deserialize, Serialize};
use anyhow::Result;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Node {
    pub id: String,
    pub content: String,
    #[serde(rename = "nodeType")]
    pub node_type: String,
    pub properties: serde_json::Value,
    pub version: i32,
    #[serde(rename = "createdAt")]
    pub created_at: String,
    #[serde(rename = "modifiedAt")]
    pub modified_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HasChildEdge {
    pub id: String,
    #[serde(rename = "in")]
    pub parent_id: String,
    #[serde(rename = "out")]
    pub child_id: String,
    pub order: f64,  // Fractional ordering from Issue #550
}

pub struct LiveQueryService {
    db: Surreal<Db>,
    app_handle: tauri::AppHandle,
}

impl LiveQueryService {
    pub fn new(db: Surreal<Db>, app_handle: tauri::AppHandle) -> Self {
        Self { db, app_handle }
    }

    /// Start listening to database changes and emit Tauri events
    pub async fn start_live_queries(&self) -> Result<()> {
        println!("Starting LIVE SELECT subscriptions...");

        // Subscribe to node changes
        self.subscribe_to_nodes().await?;

        // Subscribe to edge changes
        self.subscribe_to_edges().await?;

        println!("LIVE SELECT subscriptions active");
        Ok(())
    }

    async fn subscribe_to_nodes(&self) -> Result<()> {
        // Create LIVE SELECT query for nodes
        let mut response = self.db
            .query("LIVE SELECT * FROM node")
            .await?;

        // Get the UUID for this live query
        let live_id: String = response.take(0)?;
        println!("Node LIVE query ID: {}", live_id);

        // Stream notifications
        let mut stream = self.db
            .query(&format!("SHOW CHANGES FOR TABLE node SINCE 0 LIVE"))
            .await?
            .stream::<Notification<Node>>(0)?;

        let app_handle = self.app_handle.clone();

        // Spawn task to handle node notifications
        tokio::spawn(async move {
            println!("Node stream handler started");

            while let Some(notification) = stream.next().await {
                match notification.action {
                    surrealdb::Action::Create => {
                        println!("Node created: {:?}", notification.data.id);
                        app_handle.emit_all("node:created", &notification.data)
                            .unwrap_or_else(|e| eprintln!("Failed to emit node:created: {}", e));
                    }
                    surrealdb::Action::Update => {
                        println!("Node updated: {:?}", notification.data.id);
                        app_handle.emit_all("node:updated", &notification.data)
                            .unwrap_or_else(|e| eprintln!("Failed to emit node:updated: {}", e));
                    }
                    surrealdb::Action::Delete => {
                        println!("Node deleted: {:?}", notification.data.id);
                        app_handle.emit_all("node:deleted", &notification.data.id)
                            .unwrap_or_else(|e| eprintln!("Failed to emit node:deleted: {}", e));
                    }
                    _ => {}
                }
            }

            eprintln!("Node stream ended unexpectedly");
        });

        Ok(())
    }

    async fn subscribe_to_edges(&self) -> Result<()> {
        // Create LIVE SELECT query for edges
        let mut response = self.db
            .query("LIVE SELECT * FROM has_child")
            .await?;

        let live_id: String = response.take(0)?;
        println!("Edge LIVE query ID: {}", live_id);

        // Stream notifications
        let mut stream = self.db
            .query(&format!("SHOW CHANGES FOR TABLE has_child SINCE 0 LIVE"))
            .await?
            .stream::<Notification<HasChildEdge>>(0)?;

        let app_handle = self.app_handle.clone();

        // Spawn task to handle edge notifications
        tokio::spawn(async move {
            println!("Edge stream handler started");

            while let Some(notification) = stream.next().await {
                match notification.action {
                    surrealdb::Action::Create => {
                        println!("Edge created: {} -> {}",
                            notification.data.parent_id,
                            notification.data.child_id);
                        app_handle.emit_all("edge:created", &notification.data)
                            .unwrap_or_else(|e| eprintln!("Failed to emit edge:created: {}", e));
                    }
                    surrealdb::Action::Update => {
                        println!("Edge updated: {} -> {}",
                            notification.data.parent_id,
                            notification.data.child_id);
                        app_handle.emit_all("edge:updated", &notification.data)
                            .unwrap_or_else(|e| eprintln!("Failed to emit edge:updated: {}", e));
                    }
                    surrealdb::Action::Delete => {
                        println!("Edge deleted: {}", notification.data.id);
                        app_handle.emit_all("edge:deleted", &notification.data)
                            .unwrap_or_else(|e| eprintln!("Failed to emit edge:deleted: {}", e));
                    }
                    _ => {}
                }
            }

            eprintln!("Edge stream ended unexpectedly");
        });

        Ok(())
    }

    /// Handle reconnection if stream disconnects
    pub async fn handle_reconnection(&self) -> Result<()> {
        loop {
            tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;

            // Check if streams are still alive
            // If not, restart them
            if !self.check_streams_alive().await {
                println!("Streams disconnected, reconnecting...");
                self.start_live_queries().await?;
            }
        }
    }

    async fn check_streams_alive(&self) -> bool {
        // Implementation to check if streams are still active
        // This could ping the database or check stream status
        true  // Placeholder
    }
}

Step 2: Register Live Query Service in main.rs

File: packages/desktop-app/src-tauri/src/main.rs

Add the LiveQueryService to your app initialization:

mod services;
use services::live_query_service::LiveQueryService;

#[tokio::main]
async fn main() {
    // ... existing code ...

    tauri::Builder::default()
        .setup(|app| {
            // Get database connection
            let db = app.state::<Surreal<Db>>();
            let app_handle = app.handle();

            // Create and start live query service
            let live_service = LiveQueryService::new(db.clone(), app_handle);

            // Start live queries in background
            tauri::async_runtime::spawn(async move {
                if let Err(e) = live_service.start_live_queries().await {
                    eprintln!("Failed to start live queries: {}", e);
                }

                // Keep service alive with reconnection handling
                if let Err(e) = live_service.handle_reconnection().await {
                    eprintln!("Live query reconnection failed: {}", e);
                }
            });

            Ok(())
        })
        // ... rest of your app config ...
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Step 3: Add Service Module

File: packages/desktop-app/src-tauri/src/services/mod.rs

pub mod live_query_service;
// ... other services ...

Step 4: Update Cargo.toml Dependencies

File: packages/desktop-app/src-tauri/Cargo.toml

Ensure you have the required dependencies:

[dependencies]
surrealdb = { version = "1.0", features = ["kv-mem", "kv-rocksdb"] }
futures = "0.3"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"
tauri = { version = "2.0", features = [] }

Step 5: Create TypeScript Types for Events

File: packages/desktop-app/src/lib/types/events.ts (create new)

// Event types that match Rust structures
export interface NodeEvent {
  id: string;
  content: string;
  nodeType: string;
  properties: Record<string, unknown>;
  version: number;
  createdAt: string;
  modifiedAt: string;
}

export interface EdgeEvent {
  id: string;
  in: string;   // parent_id in Rust
  out: string;  // child_id in Rust
  order: number;
}

// Event payload types
export type NodeCreatedEvent = NodeEvent;
export type NodeUpdatedEvent = NodeEvent;
export type NodeDeletedEvent = string; // Just the ID

export type EdgeCreatedEvent = EdgeEvent;
export type EdgeUpdatedEvent = EdgeEvent;
export type EdgeDeletedEvent = EdgeEvent;

Step 6: Test LIVE SELECT with Frontend Listener

File: packages/desktop-app/src/lib/stores/test-live-select.svelte.ts (create for testing)

import { listen } from '@tauri-apps/api/event';
import type { NodeEvent, EdgeEvent } from '$lib/types/events';

// Test listener to verify events are coming through
export async function testLiveSelect() {
  console.log('Setting up LIVE SELECT test listeners...');

  // Node events
  await listen<NodeEvent>('node:created', (event) => {
    console.log('📗 Node created:', event.payload);
  });

  await listen<NodeEvent>('node:updated', (event) => {
    console.log('📘 Node updated:', event.payload);
  });

  await listen<string>('node:deleted', (event) => {
    console.log('📕 Node deleted:', event.payload);
  });

  // Edge events
  await listen<EdgeEvent>('edge:created', (event) => {
    console.log('🔗 Edge created:', event.payload);
  });

  await listen<EdgeEvent>('edge:updated', (event) => {
    console.log('🔄 Edge updated:', event.payload);
  });

  await listen<EdgeEvent>('edge:deleted', (event) => {
    console.log('❌ Edge deleted:', event.payload);
  });

  console.log('LIVE SELECT listeners ready!');
}

// Call this in your app initialization to test
// testLiveSelect();

Step 7: Integration Test for Multi-Client Sync

File: packages/desktop-app/src/tests/integration/live-select-multi-client.test.ts (create new)

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { listen } from '@tauri-apps/api/event';
import type { NodeEvent } from '$lib/types/events';

describe('LIVE SELECT Multi-Client Synchronization', () => {
  let unsubscribe: () => void;
  let nodeCreatedPromise: Promise<NodeEvent>;

  beforeAll(async () => {
    // Set up listener before MCP creates node
    nodeCreatedPromise = new Promise((resolve) => {
      listen<NodeEvent>('node:created', (event) => {
        resolve(event.payload);
      }).then(unsub => {
        unsubscribe = unsub;
      });
    });
  });

  afterAll(() => {
    if (unsubscribe) unsubscribe();
  });

  it('should receive node:created event when MCP server creates node', async () => {
    // Simulate MCP server creating a node
    // In real test, this would be actual MCP server call
    await simulateMCPCreateNode({
      id: 'test-node-1',
      content: 'Test content',
      nodeType: 'text'
    });

    // Wait for event with timeout
    const event = await Promise.race([
      nodeCreatedPromise,
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error('Timeout')), 100)
      )
    ]) as NodeEvent;

    expect(event.id).toBe('test-node-1');
    expect(event.content).toBe('Test content');
  });

  it('should sync hierarchy changes within 100ms', async () => {
    const startTime = Date.now();

    const edgePromise = new Promise((resolve) => {
      listen('edge:created', (event) => {
        resolve(event.payload);
      });
    });

    // MCP server indents a node
    await simulateMCPIndentNode('node-1', 'parent-1');

    const edge = await edgePromise;
    const elapsed = Date.now() - startTime;

    expect(elapsed).toBeLessThan(100);
    expect(edge).toHaveProperty('in', 'parent-1');
    expect(edge).toHaveProperty('out', 'node-1');
  });
});

// Helper function to simulate MCP operations
async function simulateMCPCreateNode(node: any) {
  // This would call your actual MCP API
  // For now, directly insert to database to trigger LIVE SELECT
}

async function simulateMCPIndentNode(nodeId: string, parentId: string) {
  // Simulate MCP server moving a node
}

Testing Checklist

Manual Testing

  1. Start Tauri app with bun run tauri:dev
  2. Open browser console
  3. Run testLiveSelect() in console
  4. Create a node via MCP server or database CLI
  5. Verify "📗 Node created" appears in console within 100ms
  6. Update a node via database
  7. Verify "📘 Node updated" appears in console
  8. Delete a node
  9. Verify "📕 Node deleted" appears in console

Automated Tests

  • Test node creation events arrive within 100ms
  • Test node update events arrive with correct data
  • Test edge creation/deletion for hierarchy changes
  • Test reconnection after database restart
  • Test handling of malformed events
  • Test memory usage with 1000+ rapid events

Performance Tests

  • Measure latency: database commit → Tauri event
  • Should be <10ms for local database
  • Should be <100ms even under load

Acceptance Criteria

  • Create LiveQueryService in Rust that subscribes to LIVE SELECT
  • Subscribe to LIVE SELECT * FROM node with notification stream
  • Subscribe to LIVE SELECT * FROM has_child with notification stream
  • Emit Tauri events: node:created, node:updated, node:deleted
  • Emit Tauri events: edge:created, edge:updated, edge:deleted
  • Handle stream reconnection on disconnect
  • Latency: <10ms from database commit to Tauri event
  • Integration test: MCP server creates node → Tauri receives event within 100ms
  • Console logging shows all events arriving correctly

Common Pitfalls to Avoid

  1. Don't forget error handling - Streams can disconnect, handle gracefully
  2. Watch memory usage - Long-running streams can leak if not managed
  3. Test reconnection - Database restarts shouldn't break the app
  4. Verify event structure - TypeScript types must match Rust exactly
  5. Check Tauri event limits - Very large payloads might need chunking

Dependencies

Files to Create/Modify

  • CREATE: packages/desktop-app/src-tauri/src/services/live_query_service.rs
  • CREATE: packages/desktop-app/src-tauri/src/services/mod.rs
  • CREATE: packages/desktop-app/src/lib/types/events.ts
  • CREATE: packages/desktop-app/src/lib/stores/test-live-select.svelte.ts
  • CREATE: packages/desktop-app/src/tests/integration/live-select-multi-client.test.ts
  • MODIFY: packages/desktop-app/src-tauri/src/main.rs - Initialize service
  • MODIFY: packages/desktop-app/src-tauri/Cargo.toml - Add dependencies

Questions During Implementation

  1. Should we batch rapid events to avoid overwhelming frontend?
  2. How should we handle events for nodes user doesn't have loaded?
  3. Should we filter LIVE SELECT by workspace/document?

Success Metrics

After implementation:

  • Zero manual cache invalidation calls
  • MCP changes visible in Tauri within 100ms
  • Memory stable even after 10,000 events
  • Automatic reconnection works after database restart

Activity

  1. self-assigned this
    on Nov 20, 2025
  2. malibio commented on Nov 20, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline - Issue #551

    Test Run Date: 2025-11-20 12:12 PM

    Status: Foundation code compiles cleanly with no new test failures introduced

    Test Results:

    • All passing tests remain passing (700+ tests)
    • 50 tests skipped (expected - require database or HTTP server)
    • No compilation errors (TypeScript 0 errors, Rust code compiles)
    • Expected warnings only (HTTP connection refused to port 3001 - normal for skipped integration tests)

    Test Categories:

    • ✅ Unit tests: All passing
    • ✅ Integration tests: All passing (skipped tests expected)
    • ✅ Performance tests: All passing
    • ✅ Component tests: All passing

    Foundation Work Completed (from commit de403a5):

    • Created LiveQueryService Rust structure
    • Added Tauri event emission scaffolding
    • Defined TypeScript event types
    • Integrated with Tauri event bridge
    • Code passes linting and TypeScript validation

    Known Limitations (To Be Implemented):

    • LIVE SELECT logic is placeholder only
    • Event names use sync:* instead of node:*/edge:* (spec mismatch)
    • No reconnection logic
    • No actual change detection
    • No integration tests for event propagation

    Next Steps:
    Will implement actual polling-based change detection as recommended in commit message (SurrealDB Rust driver doesn't fully support streaming LIVE SELECT yet).

  3. malibio commented on Nov 20, 2025

    @malibio
    CollaboratorAuthor

    WIP Update: Core Polling Implementation Complete ✅

    Summary

    The core polling-based real-time synchronization implementation is complete and ready for testing. All Rust and TypeScript code compiles cleanly with no linting errors.

    Completed Phases (1-5)

    Phase 1: Polling-based change detection ✅

    • Implemented LiveQueryService in Rust with full change tracking
    • Tracks node versions (incremented on each update) to detect create/update/delete
    • Uses hash-based detection for edges (computed from parent_id, child_id, order)
    • Polls database every 1 second for changes

    Phase 2: Event naming ✅

    • Fixed event names from generic sync:* to specific node:* and edge:* events
    • Separate events for create, update, delete on both nodes and edges
    • Matches specification exactly: node:created, node:updated, node:deleted, edge:created, edge:updated, edge:deleted

    Phase 3: Reconnection logic ✅

    • Exponential backoff: 2^attempts seconds (capped at 60s)
    • Max 10 retry attempts before giving up
    • Emits sync:status events: connected, reconnecting, disconnected

    Phase 4: Type-safe payloads ✅

    • Defined NodeEventData and EdgeEventData interfaces in both Rust and TypeScript
    • Fixed Tauri event listener generic types to use Record<string, unknown>
    • Full type safety from Rust → Tauri → TypeScript

    Phase 5: Code quality ✅

    • Removed async keyword from non-async emit functions (Tauri emit is synchronous)
    • All Rust clippy warnings resolved
    • All TypeScript/ESLint errors resolved
    • Code compiles cleanly with bun run quality:fix

    Remaining Phases (6-8)

    Phase 6: Integration tests ⏳

    • Test node creation events arrive within 100ms
    • Test node update events arrive with correct data
    • Test edge creation/deletion for hierarchy changes
    • Test reconnection after database restart
    • Test handling of malformed events

    Phase 7: Manual testing ⏳

    • Verify events work end-to-end in actual Tauri app
    • Test with MCP server creating/updating nodes
    • Verify console logging shows events correctly

    Phase 8: Performance testing ⏳

    • Measure latency from database commit to Tauri event
    • Target: <10ms for local database
    • Verify stable performance under load

    Technical Implementation Details

    Files Modified:

    • packages/desktop-app/src-tauri/src/services/live_query_service.rs - Complete implementation
    • packages/desktop-app/src-tauri/src/services/mod.rs - Module exports
    • packages/desktop-app/src/lib/services/event-types.ts - Event type definitions
    • packages/desktop-app/src/lib/services/tauri-sync-listener.ts - Event handlers

    Architecture:

    LiveQueryService {
        store: Arc<SurrealStore>,           // Database access
        app: AppHandle,                      // Tauri event emitter
        node_versions: HashMap<String, i32>, // Version tracking
        edge_hashes: HashMap<String, u64>,   // Hash-based change detection
        poll_interval_ms: 1000,              // 1-second polling
        reconnect_attempts: u32,             // Exponential backoff state
    }

    Event Flow:

    1. Poll database every 1 second
    2. Compare current state vs. cached state (versions/hashes)
    3. Detect changes (create/update/delete)
    4. Emit Tauri events with type-safe payloads
    5. Frontend tauri-sync-listener.ts bridges to EventBus
    6. UI components subscribe to EventBus for real-time updates

    Next Session Focus

    The next agent should focus on Phase 6: Integration Tests. The core implementation is solid and ready for comprehensive testing. Start with:

    1. Create packages/desktop-app/src/tests/integration/live-select-polling.test.ts
    2. Test basic event propagation (create/update/delete)
    3. Test reconnection behavior
    4. Verify event timing (<100ms latency)

    Acceptance Criteria Status

    • Create LiveQueryService in Rust that subscribes to database changes
    • Subscribe to node changes (polling-based MVP)
    • Subscribe to edge changes (polling-based MVP)
    • Emit Tauri events: node:created, node:updated, node:deleted
    • Emit Tauri events: edge:created, edge:updated, edge:deleted
    • Handle stream reconnection on disconnect
    • Latency: <10ms from database commit to Tauri event (needs performance testing)
    • Integration test: MCP server creates node → Tauri receives event within 100ms
    • Console logging shows all events arriving correctly (needs manual testing)

    Overall Progress: 6/9 criteria complete (67%)

    Branch: feature/issue-551-surrealdb-live-select
    Commit: af79bd4

  4. 9 remaining items

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