Skip to content

Re-enable NLP Integration for Vector Embeddings #489

Closed

Description

@malibio

Re-enable NLP Integration for Vector Embeddings

Overview

NodeSpace's database-level embedding infrastructure is now complete (Issue #481), but the NLP engine integration remains stubbed out. This issue focuses on reconnecting the embedding services to use the SurrealDB foundation and re-enable semantic search capabilities.

What Are Vector Embeddings?

Vector embeddings are numerical representations of text that capture semantic meaning. For example, "machine learning" and "artificial intelligence" would have similar embeddings because they're semantically related, even though the words are different.

Why NodeSpace Needs Them:

  • Semantic Search: Find related notes by meaning, not just keywords
  • Smart Connections: Automatically suggest related topics and ideas
  • Knowledge Discovery: Surface relevant content you forgot about

How They Work in NodeSpace:

  1. When you edit node content, the database marks the embedding as "stale"
  2. A background processor generates new embeddings using a local AI model (BAAI/bge-small-en-v1.5)
  3. The 384-dimensional vector is stored in SurrealDB alongside the node
  4. Searches use vector similarity (cosine distance) to find semantically related nodes

Current State

What's Already Complete (Issue #481)

The database infrastructure is ready and working:

SurrealDB Methods (in packages/core/src/db/surreal_store.rs):

// Mark embedding as stale when content changes
pub async fn mark_embedding_stale(&self, node_id: &str) -> Result<()>

// Get nodes needing re-embedding (for batch processing)
pub async fn get_nodes_with_stale_embeddings(&self, limit: Option<i64>) -> Result<Vec<Node>>

// Store embedding vector and clear stale flag
pub async fn update_embedding(&self, node_id: &str, embedding: &[u8]) -> Result<()>

// Search by vector similarity (placeholder - needs implementation)
pub fn search_by_embedding(&self, embedding: &[u8], limit: i64) -> Result<Vec<(Node, f64)>>

Schema:

  • embedding_vector field: Stores binary blob (Vec) of f32 values
  • embedding_stale field: Boolean flag tracking when content changes
  • Both fields automatically handle backward compatibility with existing data

What's Stubbed Out (Needs Implementation)

1. Node Embedding Service (packages/core/src/services/embedding_service.rs lines 1-70):

impl NodeEmbeddingService {
    pub fn new(nlp_engine: Arc<EmbeddingService>) -> Self { /* stub */ }
    pub fn embed_container(&self, node: &Node) -> Result<()> { /* stub */ }
    pub fn batch_embed_containers(&self, limit: Option<usize>) -> Result<usize> { /* stub */ }
}

2. Embedding Processor (packages/core/src/services/embedding_processor.rs lines 1-53):

impl EmbeddingProcessor {
    pub fn new(nlp_engine: Arc<EmbeddingService>) -> Result<Self> { /* stub */ }
    pub fn trigger_batch_embed(&self) -> Result<()> { /* stub */ }
}

3. Tauri Commands (packages/desktop-app/src-tauri/src/commands/embeddings.rs):

  • All 10+ commands return stubs with warnings (lines 43-306)
  • Commands like generate_container_embedding, search_containers, sync_embeddings, etc.

Goal

Re-enable the NLP integration layer to connect the database foundation with the embedding generation engine, restoring full semantic search functionality.

Implementation Tasks

Phase 1: Update NodeEmbeddingService

File: packages/core/src/services/embedding_service.rs

Tasks:

  1. Add SurrealStore dependency to the service:

    pub struct NodeEmbeddingService {
        nlp_engine: Arc<EmbeddingService>,
        store: Arc<SurrealStore>, // ADD THIS
    }
  2. Update constructor to accept SurrealDB store:

    pub fn new(nlp_engine: Arc<EmbeddingService>, store: Arc<SurrealStore>) -> Self {
        Self { nlp_engine, store }
    }
  3. Implement embed_container() method:

    pub async fn embed_container(&self, node: &Node) -> Result<(), NodeServiceError> {
        // 1. Extract text content from node
        let text = &node.content;
    
        // 2. Generate embedding using NLP engine
        let embedding_vec = self.nlp_engine.generate_embedding(text)
            .map_err(|e| NodeServiceError::EmbeddingError(e.to_string()))?;
    
        // 3. Convert f32 vector to binary blob
        let embedding_blob = EmbeddingService::to_blob(&embedding_vec);
    
        // 4. Store in database and clear stale flag
        self.store.update_embedding(&node.id, &embedding_blob).await
            .map_err(|e| NodeServiceError::DatabaseError(e.to_string()))?;
    
        tracing::info!("Generated embedding for node {}", node.id);
        Ok(())
    }
  4. Implement batch_embed_containers() method:

    pub async fn batch_embed_containers(&self, limit: Option<usize>) -> Result<usize, NodeServiceError> {
        // 1. Get stale nodes from database
        let stale_nodes = self.store.get_nodes_with_stale_embeddings(limit.map(|l| l as i64)).await
            .map_err(|e| NodeServiceError::DatabaseError(e.to_string()))?;
    
        if stale_nodes.is_empty() {
            return Ok(0);
        }
    
        // 2. Extract text from all nodes
        let texts: Vec<&str> = stale_nodes.iter().map(|n| n.content.as_str()).collect();
    
        // 3. Generate embeddings in batch (more efficient)
        let embeddings = self.nlp_engine.generate_batch(texts)
            .map_err(|e| NodeServiceError::EmbeddingError(e.to_string()))?;
    
        // 4. Store all embeddings
        let mut success_count = 0;
        for (node, embedding_vec) in stale_nodes.iter().zip(embeddings.iter()) {
            let embedding_blob = EmbeddingService::to_blob(embedding_vec);
            if let Err(e) = self.store.update_embedding(&node.id, &embedding_blob).await {
                tracing::error!("Failed to update embedding for node {}: {}", node.id, e);
            } else {
                success_count += 1;
            }
        }
    
        tracing::info!("Batch embedded {} nodes", success_count);
        Ok(success_count)
    }

Key Points:

  • Use EmbeddingService::to_blob() to convert f32 vectors to binary format
  • Call store.update_embedding() which automatically clears the stale flag
  • Handle errors gracefully - log failures but continue processing other nodes
  • Return success count for monitoring/metrics

Phase 2: Update EmbeddingProcessor

File: packages/core/src/services/embedding_processor.rs

Tasks:

  1. Add SurrealStore dependency:

    pub struct EmbeddingProcessor {
        nlp_engine: Arc<EmbeddingService>,
        store: Arc<SurrealStore>, // ADD THIS
        shutdown_tx: mpsc::Sender<()>,
    }
  2. Update constructor and spawn background task:

    pub fn new(nlp_engine: Arc<EmbeddingService>, store: Arc<SurrealStore>) -> Result<Self, NodeServiceError> {
        let (shutdown_tx, mut shutdown_rx) = mpsc::channel(1);
        let nlp_clone = Arc::clone(&nlp_engine);
        let store_clone = Arc::clone(&store);
    
        // Spawn background task
        tokio::spawn(async move {
            let mut interval = tokio::time::interval(Duration::from_secs(30));
            loop {
                tokio::select! {
                    _ = interval.tick() => {
                        // Process stale embeddings in batches
                        if let Err(e) = Self::process_batch(&nlp_clone, &store_clone).await {
                            tracing::error!("Background embedding processing failed: {}", e);
                        }
                    }
                    _ = shutdown_rx.recv() => {
                        tracing::info!("Embedding processor shutting down");
                        break;
                    }
                }
            }
        });
    
        Ok(Self { nlp_engine, store, shutdown_tx })
    }
  3. Implement batch processing helper:

    async fn process_batch(nlp_engine: &Arc<EmbeddingService>, store: &Arc<SurrealStore>) -> Result<(), NodeServiceError> {
        const BATCH_SIZE: usize = 50;
    
        let stale_nodes = store.get_nodes_with_stale_embeddings(Some(BATCH_SIZE as i64)).await
            .map_err(|e| NodeServiceError::DatabaseError(e.to_string()))?;
    
        if stale_nodes.is_empty() {
            return Ok(());
        }
    
        let texts: Vec<&str> = stale_nodes.iter().map(|n| n.content.as_str()).collect();
        let embeddings = nlp_engine.generate_batch(texts)
            .map_err(|e| NodeServiceError::EmbeddingError(e.to_string()))?;
    
        for (node, embedding_vec) in stale_nodes.iter().zip(embeddings.iter()) {
            let embedding_blob = EmbeddingService::to_blob(embedding_vec);
            if let Err(e) = store.update_embedding(&node.id, &embedding_blob).await {
                tracing::error!("Failed to update embedding for node {}: {}", node.id, e);
            }
        }
    
        tracing::info!("Background processor embedded {} nodes", stale_nodes.len());
        Ok(())
    }
  4. Implement trigger_batch_embed():

    pub async fn trigger_batch_embed(&self) -> Result<(), NodeServiceError> {
        Self::process_batch(&self.nlp_engine, &self.store).await
    }

Key Points:

  • Background task runs every 30 seconds
  • Processes up to 50 nodes per batch (configurable)
  • Uses tokio::select! for graceful shutdown
  • Logs errors but continues processing

Phase 3: Re-enable Tauri Commands

File: packages/desktop-app/src-tauri/src/commands/embeddings.rs

Tasks:

  1. Update EmbeddingState to include services:

    pub struct EmbeddingState {
        pub service: Arc<NodeEmbeddingService>,
        pub processor: Arc<EmbeddingProcessor>,
        pub store: Arc<SurrealStore>,
    }
  2. Re-enable generate_container_embedding():

    #[tauri::command]
    pub async fn generate_container_embedding(
        state: State<'_, EmbeddingState>,
        container_id: String,
    ) -> Result<(), CommandError> {
        // Get node from database
        let node = state.store.get_node(&container_id).await
            .map_err(|e| CommandError::NotFound(e.to_string()))?;
    
        // Generate embedding
        state.service.embed_container(&node).await
            .map_err(|e| CommandError::ServiceError(e.to_string()))?;
    
        Ok(())
    }
  3. Re-enable sync_embeddings():

    #[tauri::command]
    pub async fn sync_embeddings(state: State<'_, EmbeddingState>) -> Result<usize, CommandError> {
        state.service.batch_embed_containers(None).await
            .map_err(|e| CommandError::ServiceError(e.to_string()))
    }
  4. Re-enable get_stale_container_count():

    #[tauri::command]
    pub async fn get_stale_container_count(
        state: State<'_, EmbeddingState>,
    ) -> Result<usize, CommandError> {
        let stale_nodes = state.store.get_nodes_with_stale_embeddings(None).await
            .map_err(|e| CommandError::DatabaseError(e.to_string()))?;
        Ok(stale_nodes.len())
    }
  5. Implement placeholder for search_containers() (semantic search):

    #[tauri::command]
    pub async fn search_containers(
        state: State<'_, EmbeddingState>,
        params: SearchContainersParams,
    ) -> Result<Vec<Node>, CommandError> {
        // 1. Generate query embedding
        let query_embedding = state.service.nlp_engine.generate_embedding(&params.query)
            .map_err(|e| CommandError::ServiceError(e.to_string()))?;
    
        // 2. Convert to blob
        let query_blob = EmbeddingService::to_blob(&query_embedding);
    
        // 3. Search database (note: SurrealDB implementation pending)
        let limit = params.limit.unwrap_or(20) as i64;
        let results = state.store.search_by_embedding(&query_blob, limit)
            .map_err(|e| CommandError::DatabaseError(e.to_string()))?;
    
        // 4. Filter by threshold if provided
        let threshold = params.threshold.unwrap_or(0.7);
        let filtered: Vec<Node> = results.into_iter()
            .filter(|(_, score)| *score <= threshold as f64)
            .map(|(node, _)| node)
            .collect();
    
        Ok(filtered)
    }

Note: The search_by_embedding() method in SurrealStore is currently a placeholder. Full vector search implementation will be addressed in a follow-up issue (see Issue #107).

Phase 4: Update Service Initialization

File: packages/desktop-app/src-tauri/src/lib.rs (or equivalent app setup)

Tasks:

  1. Initialize NLP engine and services during app startup:

    // Initialize NLP engine
    let embedding_config = EmbeddingConfig::default();
    let mut nlp_engine = EmbeddingService::new(embedding_config)?;
    nlp_engine.initialize()?;
    let nlp_engine = Arc::new(nlp_engine);
    
    // Initialize SurrealDB store
    let store = Arc::new(SurrealStore::new(db_path).await?);
    
    // Initialize embedding service
    let embedding_service = Arc::new(NodeEmbeddingService::new(
        Arc::clone(&nlp_engine),
        Arc::clone(&store),
    ));
    
    // Initialize background processor
    let embedding_processor = Arc::new(EmbeddingProcessor::new(
        Arc::clone(&nlp_engine),
        Arc::clone(&store),
    )?);
    
    // Create Tauri state
    let embedding_state = EmbeddingState {
        service: embedding_service,
        processor: embedding_processor,
        store,
    };
  2. Register the state with Tauri:

    tauri::Builder::default()
        .manage(embedding_state)
        .invoke_handler(tauri::generate_handler![
            generate_container_embedding,
            search_containers,
            sync_embeddings,
            get_stale_container_count,
            // ... other commands
        ])
        .run(tauri::generate_context!())?;

Acceptance Criteria

  • NodeEmbeddingService accepts Arc<SurrealStore> in constructor
  • embed_container() generates embeddings and calls update_embedding()
  • batch_embed_containers() processes multiple nodes efficiently using generate_batch()
  • EmbeddingProcessor spawns background task that processes stale nodes every 30 seconds
  • Background processor uses get_nodes_with_stale_embeddings() to find work
  • Tauri commands no longer return stub warnings
  • generate_container_embedding command works end-to-end
  • sync_embeddings command processes all stale nodes
  • get_stale_container_count returns accurate count
  • Services are initialized correctly during app startup
  • All existing unit tests pass
  • New integration tests verify embedding generation and storage

Testing Requirements

Unit Tests

File: packages/core/src/services/embedding_service.rs (add tests section)

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::SurrealStore;
    use crate::models::Node;
    use std::path::PathBuf;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_embed_container() {
        // Setup temporary database
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let store = Arc::new(SurrealStore::new(db_path).await.unwrap());

        // Setup NLP engine (stub mode for tests)
        let config = EmbeddingConfig::default();
        let mut nlp_engine = EmbeddingService::new(config).unwrap();
        nlp_engine.initialize().unwrap();
        let nlp_engine = Arc::new(nlp_engine);

        // Create service
        let service = NodeEmbeddingService::new(nlp_engine, Arc::clone(&store));

        // Create test node
        let node = Node {
            id: "test-node".to_string(),
            node_type: "text".to_string(),
            content: "This is test content for embedding".to_string(),
            // ... other fields
        };

        // Store node first
        store.create_node(&node).await.unwrap();

        // Generate embedding
        service.embed_container(&node).await.unwrap();

        // Verify embedding was stored
        let retrieved = store.get_node("test-node").await.unwrap();
        assert!(retrieved.embedding_vector.is_some());
        assert!(!retrieved.embedding_stale); // Should be cleared
    }

    #[tokio::test]
    async fn test_batch_embed_containers() {
        // Similar setup as above
        // Create multiple nodes marked as stale
        // Call batch_embed_containers()
        // Verify all embeddings were generated
        // Verify stale flags were cleared
    }
}

Integration Tests

File: packages/core/src/tests/integration/embedding_integration.test.rs (create new file)

#[tokio::test]
async fn test_embedding_workflow() {
    // 1. Create node
    // 2. Update content (marks stale)
    // 3. Trigger embedding generation
    // 4. Verify embedding stored
    // 5. Verify stale flag cleared
}

#[tokio::test]
async fn test_background_processor() {
    // 1. Create multiple stale nodes
    // 2. Start processor
    // 3. Wait for background task to run
    // 4. Verify nodes were processed
}

Manual Testing Checklist

  • Start application - no errors in logs
  • Create a text node - embedding marked as stale
  • Call sync_embeddings - embedding generated successfully
  • Check database - embedding_vector populated, embedding_stale = false
  • Call get_stale_container_count - returns 0 after sync
  • Update node content - embedding marked as stale again
  • Wait 30+ seconds - background processor generates new embedding
  • Check logs - background processor logs successful processing

Estimated Effort

6-8 hours for a junior engineer with Rust experience:

  • Phase 1: 2-3 hours (service implementation)
  • Phase 2: 2 hours (background processor)
  • Phase 3: 1-2 hours (Tauri commands)
  • Phase 4: 1 hour (initialization and integration)
  • Testing: 1-2 hours (unit + integration tests)

Note: If unfamiliar with async Rust or Tauri, add 2-4 hours for learning and debugging.

Dependencies

Prerequisite:

Blocks:

Related Issues

Resources / File Locations

Key Files to Modify

  1. NodeEmbeddingService: packages/core/src/services/embedding_service.rs

    • Current: Lines 1-70 (stubbed)
    • Pattern: Existing NLP integration in packages/nlp-engine/src/embedding.rs
  2. EmbeddingProcessor: packages/core/src/services/embedding_processor.rs

    • Current: Lines 1-53 (stubbed)
    • Pattern: Background tasks with tokio::spawn and select!
  3. Tauri Commands: packages/desktop-app/src-tauri/src/commands/embeddings.rs

    • Current: Lines 43-306 (all stubbed)
    • Pattern: Other working Tauri commands in same directory
  4. App Initialization: packages/desktop-app/src-tauri/src/lib.rs

    • Add service initialization during startup
    • Register Tauri state

Reference Implementations

NLP Engine Interface (packages/nlp-engine/src/embedding.rs):

  • EmbeddingService::new(config) - Create service
  • service.initialize() - Load model
  • service.generate_embedding(text) - Single embedding
  • service.generate_batch(texts) - Batch embeddings
  • EmbeddingService::to_blob() - Convert to binary
  • EmbeddingService::from_blob() - Convert from binary

SurrealDB Methods (packages/core/src/db/surreal_store.rs):

  • Lines 1013-1022: update_embedding() - Store vector and clear stale flag
  • Lines 1047-1055: mark_embedding_stale() - Mark for regeneration
  • Lines 1083-1103: get_nodes_with_stale_embeddings() - Query stale nodes
  • Lines 1105-1111: search_by_embedding() - Placeholder for vector search

Error Handling (packages/core/src/services/error.rs):

  • NodeServiceError::EmbeddingError - Wrap NLP errors
  • NodeServiceError::DatabaseError - Wrap DB errors

Architecture Documentation

  • Development Overview: /docs/architecture/development/overview.md
  • Node Behavior System: /docs/architecture/business-logic/node-behavior-system.md
  • Technology Stack: /docs/architecture/core/technology-stack.md

Testing Utilities

  • Temp Directory: Use tempfile::TempDir for test databases
  • Async Tests: Use #[tokio::test] attribute
  • Mock Data: See existing tests in packages/core/src/tests/

Technical Notes

Binary Format

SurrealDB stores embeddings as binary blobs (Vec<u8>). The NLP engine returns Vec<f32>. Use these conversion functions:

// f32 vector -> binary blob
let blob = EmbeddingService::to_blob(&embedding_vec);

// binary blob -> f32 vector
let vec = EmbeddingService::from_blob(&blob);

Error Handling Pattern

Wrap errors appropriately:

nlp_engine.generate_embedding(text)
    .map_err(|e| NodeServiceError::EmbeddingError(e.to_string()))?;

store.update_embedding(id, blob).await
    .map_err(|e| NodeServiceError::DatabaseError(e.to_string()))?;

Batch Processing Strategy

  • Use generate_batch() for better performance (single forward pass through model)
  • Process 50 nodes per batch (configurable)
  • Continue processing even if individual nodes fail
  • Log errors but don't fail entire batch

Background Processor Design

  • Runs every 30 seconds (configurable via Duration::from_secs(30))
  • Graceful shutdown via tokio::select! on channel
  • Call shutdown() to stop background task cleanly

Future Work (Out of Scope)

These are intentionally excluded from this issue:

  1. Vector Search Implementation: The search_by_embedding() method is currently a placeholder returning empty results. SurrealDB doesn't have native vector similarity functions yet. This will be addressed in Issue Semantic search: validation, benchmarks, and documentation #107 using either:

    • SurrealQL custom functions
    • In-memory brute-force cosine similarity
    • External vector search library integration
  2. Performance Optimization: Initial implementation prioritizes correctness over performance. Future optimizations might include:

    • Parallel embedding generation for large batches
    • Smarter batch sizing based on content length
    • Embedding caching strategies
  3. UI Integration: This issue focuses on backend services. Frontend components for triggering searches and displaying results are separate work.

Questions to Ask if Stuck

  1. Can't find where to initialize services?

    • Look for tauri::Builder::default() in main app setup
    • Search for other .manage() calls to see the pattern
  2. Compilation errors with Arc/async?

    • Make sure methods are async fn where needed
    • Use Arc::clone() when passing to async tasks
    • Remember await on async calls
  3. Tests failing with database errors?

    • Use TempDir::new() to create isolated test database
    • Ensure #[tokio::test] for async tests
    • Clean up resources in tests
  4. Background task not running?

    • Check logs for spawn errors
    • Verify shutdown channel isn't closed prematurely
    • Add debug logging inside the task loop
  5. Embeddings not being stored?

    • Verify blob conversion is correct (test with to_blob/from_blob)
    • Check node.id matches database records
    • Look for database errors in logs

Metadata

Metadata

Assignees

Labels

backendenhancementfoundationnlp

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions