Skip to content

Implement SurrealDB Vector Similarity Search for Semantic Node Discovery #495

Closed

Description

@malibio

Context

NodeSpace has completed a major architecture evolution toward a unified SurrealDB-only backend. As part of this evolution, the vector embedding infrastructure is now 100% functional:

  • ✅ Embedding Generation: NLP engine integration generates 384-dimensional embeddings
  • ✅ Storage: Embeddings stored as binary blobs in embedding_vector field
  • ✅ Staleness Tracking: Database-level embedding_stale flag with automatic marking
  • ✅ Background Processing: EmbeddingProcessor task processes stale nodes every 30 seconds
  • ✅ Tauri Commands: Frontend commands ready for search integration

The final missing piece is vector similarity search - implementing search_by_embedding() in SurrealStore to enable semantic discovery of related nodes.

Why Vector Search Matters

Vector search enables semantic similarity rather than just keyword matching. When a user searches for "machine learning projects", they should also find nodes about "neural networks", "deep learning", "AI models" - concepts that are semantically related but don't share exact keywords.

Use Cases:

  1. Smart @mentions: When typing @, suggest semantically related nodes
  2. Related Notes Discovery: "Show me notes related to this topic"
  3. Content Clustering: Group similar notes/tasks automatically
  4. Smart Backlinks: Find notes that should reference each other but don't yet

Goal

Implement SurrealDB-native vector similarity search in the search_by_embedding() method to enable semantic node discovery with cosine similarity ranking.

Current State

✅ Working Embedding Infrastructure

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

  • Model: BAAI/bge-small-en-v1.5 (384 dimensions)
  • Generates f32 vector embeddings
  • Supports batch processing

NodeEmbeddingService (packages/core/src/services/embedding_service.rs):

  • embed_container() - Generate and store embeddings
  • batch_embed_containers() - Batch processing
  • Converts embeddings to binary blobs via EmbeddingService::to_blob()

Database Schema (SurrealDB):

DEFINE FIELD embedding_vector ON nodes TYPE option<bytes>;
DEFINE FIELD embedding_stale ON nodes TYPE bool DEFAULT true;

Tauri Command (packages/desktop-app/src-tauri/src/commands/embeddings.rs, line 151):

#[tauri::command]
pub async fn search_containers(
    _state: State<'_, EmbeddingState>,
    params: SearchContainersParams,
) -> Result<Vec<Node>, CommandError> {
    // Currently returns empty Vec - needs implementation
    tracing::warn!("Semantic search temporarily disabled");
    Ok(Vec::new())
}

❌ Missing: Vector Search Implementation

File: packages/core/src/db/surreal_store.rs (lines 1362-1368)

pub fn search_by_embedding(&self, _embedding: &[u8], _limit: i64) -> Result<Vec<(Node, f64)>> {
    // SurrealDB doesn't have built-in vector similarity functions yet
    // This is a placeholder implementation that needs to be enhanced
    // For now, return empty results with a warning
    tracing::warn!("Vector similarity search not yet implemented for SurrealDB");
    Ok(Vec::new())
}

What's Needed: Replace stub with working implementation using SurrealDB's vector::similarity::cosine() function.

SurrealDB Vector Functions

SurrealDB 2.x provides native vector similarity functions for semantic search:

Available Functions

Cosine Similarity (Primary - Best for Semantic Search):

vector::similarity::cosine(array1, array2) -> number
  • Range: 0.0 (orthogonal) to 1.0 (identical)
  • Usage: Higher score = more similar
  • Best For: Text embeddings, semantic similarity
  • Example: vector::similarity::cosine([10, 50, 200], [400, 100, 20]) returns 0.1525

Distance Functions (Alternative Approaches):

vector::distance::euclidean(array1, array2) -> number
vector::distance::manhattan(array1, array2) -> number
vector::distance::cosine(array1, array2) -> number  // 1 - cosine_similarity
  • Usage: Lower distance = more similar
  • Note: Cosine similarity preferred for embeddings

Query Pattern

SELECT
    id,
    content,
    node_type,
    vector::similarity::cosine(embedding_vector, $query_vector) AS similarity
FROM nodes
WHERE embedding_vector != NONE
  AND vector::similarity::cosine(embedding_vector, $query_vector) > $threshold
ORDER BY similarity DESC
LIMIT $limit;

Implementation Tasks

Task 1: Convert Binary Blob to f32 Array

Location: packages/core/src/db/surreal_store.rs, search_by_embedding() method

The embedding_vector field stores embeddings as binary blobs (Vec<u8>), but SurrealDB's vector::similarity::cosine() requires Vec<f32>.

Required Conversion Function:

/// Convert binary blob embedding to f32 array for SurrealDB vector functions
///
/// Embeddings are stored as Vec<u8> (bytes), but SurrealDB vector functions
/// require Vec<f32>. This performs the conversion.
///
/// # Arguments
/// * `blob` - Binary embedding data (384 dimensions * 4 bytes = 1536 bytes)
///
/// # Returns
/// Vec<f32> with 384 elements
///
/// # Errors
/// Returns error if blob length is not divisible by 4 (invalid f32 encoding)
fn blob_to_f32_array(blob: &[u8]) -> Result<Vec<f32>> {
    if blob.len() % 4 != 0 {
        return Err(anyhow::anyhow!(
            "Invalid embedding blob: length {} not divisible by 4",
            blob.len()
        ));
    }

    let float_count = blob.len() / 4;
    let mut floats = Vec::with_capacity(float_count);

    for chunk in blob.chunks_exact(4) {
        let bytes: [u8; 4] = chunk.try_into().unwrap();
        floats.push(f32::from_le_bytes(bytes));
    }

    Ok(floats)
}

Testing:

#[test]
fn test_blob_conversion() {
    // Generate test embedding
    let original: Vec<f32> = (0..384).map(|i| i as f32 * 0.01).collect();
    let blob = EmbeddingService::to_blob(&original);

    // Convert back
    let recovered = blob_to_f32_array(&blob).unwrap();

    // Verify
    assert_eq!(original.len(), recovered.len());
    for (a, b) in original.iter().zip(recovered.iter()) {
        assert!((a - b).abs() < 0.0001);
    }
}

Task 2: Implement search_by_embedding() Method

Location: packages/core/src/db/surreal_store.rs (replace lines 1362-1368)

Method Signature:

/// Search for nodes by embedding similarity using SurrealDB's native vector functions
///
/// Converts the query embedding from binary blob to f32 array, then uses
/// SurrealDB's `vector::similarity::cosine()` to find semantically similar nodes.
///
/// # Arguments
/// * `embedding` - Query embedding as binary blob (from EmbeddingService::to_blob)
/// * `limit` - Maximum number of results to return
/// * `threshold` - Optional minimum similarity score (0.0-1.0, default: 0.5)
///
/// # Returns
/// Vector of (Node, similarity_score) tuples, sorted by similarity descending
///
/// # Errors
/// Returns error if:
/// - Embedding blob is invalid (wrong size, not divisible by 4)
/// - SurrealDB query fails
/// - Response deserialization fails
///
/// # Example
/// ```rust
/// let embedding = service.generate_embedding("machine learning")?;
/// let blob = EmbeddingService::to_blob(&embedding);
/// let results = store.search_by_embedding(&blob, 20, Some(0.7)).await?;
///
/// for (node, similarity) in results {
///     println!("{}: {:.3}", node.content, similarity);
/// }
/// ```
pub async fn search_by_embedding(
    &self,
    embedding: &[u8],
    limit: i64,
    threshold: Option<f64>,
) -> Result<Vec<(Node, f64)>> {
    // Convert binary blob to f32 array for SurrealDB
    let query_vector = blob_to_f32_array(embedding)?;

    // Default threshold: 0.5 (moderate similarity)
    let min_similarity = threshold.unwrap_or(0.5);

    // SurrealDB query using vector::similarity::cosine
    let query = r#"
        SELECT
            *,
            vector::similarity::cosine(embedding_vector, $query_vector) AS similarity
        FROM nodes
        WHERE embedding_vector != NONE
          AND vector::similarity::cosine(embedding_vector, $query_vector) > $threshold
        ORDER BY similarity DESC
        LIMIT $limit;
    "#;

    let mut response = self
        .db
        .query(query)
        .bind(("query_vector", query_vector))
        .bind(("threshold", min_similarity))
        .bind(("limit", limit))
        .await
        .context("Failed to execute vector similarity search")?;

    // Deserialize response with similarity scores
    #[derive(Debug, Deserialize)]
    struct NodeWithSimilarity {
        #[serde(flatten)]
        node: SurrealNode,
        similarity: f64,
    }

    let results: Vec<NodeWithSimilarity> = response
        .take(0)
        .context("Failed to extract similarity search results")?;

    // Convert to (Node, f64) tuples
    Ok(results
        .into_iter()
        .map(|nws| (nws.node.into(), nws.similarity))
        .collect())
}

Key Design Points:

  • Cosine Similarity: Values 0.0-1.0, higher = more similar
  • Threshold: Filters weak matches (default 0.5 = moderate similarity)
  • Ordering: Results sorted by similarity descending
  • Error Handling: Clear error messages for invalid embeddings

Task 3: Wire Up Tauri Command

Location: packages/desktop-app/src-tauri/src/commands/embeddings.rs, line 151

Replace Current Stub:

#[tauri::command]
pub async fn search_containers(
    state: State<'_, EmbeddingState>,
    node_service: State<'_, NodeService>,
    params: SearchContainersParams,
) -> Result<Vec<Node>, CommandError> {
    // Validate query parameter
    if params.query.trim().is_empty() {
        return Err(command_error(
            "Query parameter cannot be empty".to_string(),
            "INVALID_PARAMETER",
        ));
    }

    // Validate threshold if provided
    if let Some(threshold) = params.threshold {
        if !(0.0..=1.0).contains(&threshold) {
            return Err(command_error(
                "Threshold must be between 0.0 and 1.0".to_string(),
                "INVALID_PARAMETER",
            ));
        }
    }

    // Generate embedding for search query
    let query_embedding = state
        .service
        .nlp_engine
        .generate_embedding(&params.query)
        .map_err(|e| {
            command_error_with_details(
                "Failed to generate query embedding".to_string(),
                "EMBEDDING_ERROR",
                format!("{:?}", e),
            )
        })?;

    // Convert to binary blob
    let query_blob = EmbeddingService::to_blob(&query_embedding);

    // Search with default/custom parameters
    let limit = params.limit.unwrap_or(20) as i64;
    let threshold = params.threshold.map(|t| t as f64);

    // Execute search
    let store = node_service.store();
    let results = store
        .search_by_embedding(&query_blob, limit, threshold)
        .await
        .map_err(|e| {
            command_error_with_details(
                "Vector search failed".to_string(),
                "DATABASE_ERROR",
                format!("{:?}", e),
            )
        })?;

    // Return only nodes (discard similarity scores for now)
    Ok(results.into_iter().map(|(node, _score)| node).collect())
}

What Changed:

  • ✅ Generates embedding for search query using NLP engine
  • ✅ Converts to binary blob format
  • ✅ Calls search_by_embedding() with proper parameters
  • ✅ Validates threshold range (0.0-1.0)
  • ✅ Returns results to frontend

Future Enhancement (Not in this issue):

  • Consider returning similarity scores to frontend for UI display
  • Add caching for frequent queries

Task 4: Add Comprehensive Tests

Location: packages/core/src/db/surreal_store.rs, bottom of file

Test Suite:

#[cfg(test)]
mod vector_search_tests {
    use super::*;
    use nodespace_nlp_engine::EmbeddingService;
    use std::sync::Arc;

    async fn setup_test_store() -> Result<SurrealStore> {
        let store = SurrealStore::new(None).await?;
        store.initialize_schema().await?;
        Ok(store)
    }

    #[tokio::test]
    async fn test_blob_to_f32_conversion() {
        // Test valid conversion
        let original: Vec<f32> = (0..384).map(|i| i as f32 * 0.01).collect();
        let blob = EmbeddingService::to_blob(&original);
        let recovered = blob_to_f32_array(&blob).unwrap();

        assert_eq!(original.len(), recovered.len());
        for (a, b) in original.iter().zip(recovered.iter()) {
            assert!((a - b).abs() < 0.0001);
        }
    }

    #[tokio::test]
    async fn test_blob_to_f32_invalid_length() {
        // Test invalid blob (not divisible by 4)
        let invalid_blob = vec![0u8; 385]; // 385 not divisible by 4
        let result = blob_to_f32_array(&invalid_blob);
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_search_empty_database() {
        let store = setup_test_store().await.unwrap();

        // Create dummy embedding
        let embedding = vec![0.0f32; 384];
        let blob = EmbeddingService::to_blob(&embedding);

        // Search empty database
        let results = store.search_by_embedding(&blob, 10, None).await.unwrap();
        assert_eq!(results.len(), 0);
    }

    #[tokio::test]
    async fn test_search_with_similar_nodes() {
        let store = setup_test_store().await.unwrap();
        let nlp_service = Arc::new(
            EmbeddingService::new(Default::default()).unwrap()
        );

        // Create test nodes with known content
        let texts = vec![
            "Machine learning is a subset of artificial intelligence",
            "Deep neural networks are powerful ML models",
            "The weather is sunny today",
        ];

        let mut node_ids = Vec::new();
        for text in &texts {
            let node = Node {
                id: uuid::Uuid::new_v4().to_string(),
                node_type: "text".to_string(),
                content: text.to_string(),
                parent_id: None,
                container_node_id: None,
                before_sibling_id: None,
                version: 1,
                created_at: Utc::now(),
                modified_at: Utc::now(),
                properties: serde_json::json!({}),
                embedding_vector: None,
                mentions: vec![],
                mentioned_by: vec![],
            };
            node_ids.push(node.id.clone());
            store.create_node(node).await.unwrap();

            // Generate and store embedding
            let embedding = nlp_service.generate_embedding(text).unwrap();
            let blob = EmbeddingService::to_blob(&embedding);
            store.update_embedding(&node_ids.last().unwrap(), &blob).await.unwrap();
        }

        // Search for machine learning content
        let query_embedding = nlp_service
            .generate_embedding("artificial intelligence and ML")
            .unwrap();
        let query_blob = EmbeddingService::to_blob(&query_embedding);

        let results = store
            .search_by_embedding(&query_blob, 3, Some(0.3))
            .await
            .unwrap();

        // Should find at least 2 similar nodes (first two texts)
        assert!(results.len() >= 2);

        // First result should be most similar
        let (first_node, first_score) = &results[0];
        assert!(first_score > &0.5); // High similarity
        assert!(
            first_node.content.contains("Machine learning")
                || first_node.content.contains("neural networks")
        );

        // Third node (weather) should rank lower or not appear
        let weather_node = results
            .iter()
            .find(|(n, _)| n.content.contains("weather"));
        if let Some((_, score)) = weather_node {
            assert!(score < &0.4); // Low similarity
        }
    }

    #[tokio::test]
    async fn test_search_with_threshold_filter() {
        let store = setup_test_store().await.unwrap();
        let nlp_service = Arc::new(
            EmbeddingService::new(Default::default()).unwrap()
        );

        // Create nodes with varying similarity
        let texts = vec![
            "Machine learning algorithms",
            "Deep learning networks",
            "Random unrelated content xyz123",
        ];

        for text in &texts {
            let node = Node {
                id: uuid::Uuid::new_v4().to_string(),
                node_type: "text".to_string(),
                content: text.to_string(),
                parent_id: None,
                container_node_id: None,
                before_sibling_id: None,
                version: 1,
                created_at: Utc::now(),
                modified_at: Utc::now(),
                properties: serde_json::json!({}),
                embedding_vector: None,
                mentions: vec![],
                mentioned_by: vec![],
            };
            store.create_node(node.clone()).await.unwrap();

            let embedding = nlp_service.generate_embedding(text).unwrap();
            let blob = EmbeddingService::to_blob(&embedding);
            store.update_embedding(&node.id, &blob).await.unwrap();
        }

        // Search with high threshold (0.7)
        let query_embedding = nlp_service
            .generate_embedding("machine learning")
            .unwrap();
        let query_blob = EmbeddingService::to_blob(&query_embedding);

        let results = store
            .search_by_embedding(&query_blob, 10, Some(0.7))
            .await
            .unwrap();

        // Should only return highly similar nodes
        assert!(results.len() >= 1);
        for (_node, score) in &results {
            assert!(score >= &0.7);
        }
    }

    #[tokio::test]
    async fn test_search_respects_limit() {
        let store = setup_test_store().await.unwrap();
        let nlp_service = Arc::new(
            EmbeddingService::new(Default::default()).unwrap()
        );

        // Create 10 similar nodes
        for i in 0..10 {
            let text = format!("Machine learning example number {}", i);
            let node = Node {
                id: uuid::Uuid::new_v4().to_string(),
                node_type: "text".to_string(),
                content: text.clone(),
                parent_id: None,
                container_node_id: None,
                before_sibling_id: None,
                version: 1,
                created_at: Utc::now(),
                modified_at: Utc::now(),
                properties: serde_json::json!({}),
                embedding_vector: None,
                mentions: vec![],
                mentioned_by: vec![],
            };
            store.create_node(node.clone()).await.unwrap();

            let embedding = nlp_service.generate_embedding(&text).unwrap();
            let blob = EmbeddingService::to_blob(&embedding);
            store.update_embedding(&node.id, &blob).await.unwrap();
        }

        // Search with limit of 5
        let query_embedding = nlp_service
            .generate_embedding("machine learning")
            .unwrap();
        let query_blob = EmbeddingService::to_blob(&query_embedding);

        let results = store
            .search_by_embedding(&query_blob, 5, None)
            .await
            .unwrap();

        // Should return exactly 5 results
        assert_eq!(results.len(), 5);
    }
}

Test Coverage:

  • ✅ Binary blob conversion (valid and invalid)
  • ✅ Empty database search
  • ✅ Similarity ranking correctness
  • ✅ Threshold filtering
  • ✅ Result limit enforcement
  • ✅ Real embedding generation integration

Acceptance Criteria

  • blob_to_f32_array() helper function implemented with proper error handling
  • search_by_embedding() method implemented using vector::similarity::cosine()
  • Method returns results sorted by similarity descending (highest first)
  • Threshold parameter filters results correctly (default 0.5)
  • Limit parameter enforced (returns at most N results)
  • Tauri command search_containers() wired up and functional
  • All test cases pass with real NLP engine embeddings
  • Empty database returns empty results without errors
  • Invalid embeddings (wrong size) return clear error messages
  • Search latency < 100ms for databases with 1,000 nodes
  • Search latency < 500ms for databases with 10,000 nodes
  • Code properly documented with rustdoc comments
  • Warning log removed (no more "temporarily disabled" messages)

Testing Requirements

Unit Tests

bun run test:db  # Run with database mode for integration tests

Tests to Run:

  1. Blob conversion (valid and invalid inputs)
  2. Empty database search
  3. Similarity ranking correctness
  4. Threshold filtering behavior
  5. Limit parameter enforcement

Integration Tests

Manual Testing Checklist:

  1. Start desktop app with NLP engine enabled
  2. Create 5-10 nodes with various content:
    • "Machine learning projects"
    • "Deep neural networks"
    • "AI model training"
    • "Recipe for chocolate cake"
    • "Weather forecast"
  3. Generate embeddings for all nodes (use sync_embeddings command)
  4. Test search via Tauri command:
    const results = await invoke('search_containers', {
      params: {
        query: 'artificial intelligence',
        threshold: 0.5,
        limit: 10
      }
    });
  5. Verify:
    • ML/AI nodes ranked higher than cake/weather nodes
    • Similarity scores make sense (0.0-1.0 range)
    • Results respect limit parameter
    • Empty queries handled gracefully

Performance Benchmarks

Target Latencies (on M1 MacBook Pro or equivalent):

  • 1K nodes: < 100ms per search
  • 10K nodes: < 500ms per search
  • 100K nodes: < 2 seconds per search

Measurement:

let start = std::time::Instant::now();
let results = store.search_by_embedding(&blob, 20, None).await?;
let duration = start.elapsed();
println!("Search took: {:?}", duration);

Performance Targets

Latency Expectations

Query Time (with 384-dimensional embeddings):

  • 1,000 nodes: < 100ms (good)
  • 10,000 nodes: < 500ms (acceptable)
  • 100,000 nodes: < 2 seconds (needs optimization)

Current Baseline (no optimization):

  • SurrealDB computes similarity in-query (no pre-built index)
  • Linear scan of all nodes with embeddings
  • Acceptable for <10K nodes, may need indexing for larger datasets

Future Optimizations (Out of Scope)

If search becomes slow (>2s for 100K nodes):

  1. Vector Indexing: Research SurrealDB's MTREE or HNSW index support
  2. Caching: LRU cache for frequent queries
  3. Batch Queries: Pre-compute similarity matrix for related nodes
  4. Approximate Search: Trade accuracy for speed (k-NN approximation)

Note: Start with simple implementation first, optimize only if needed.

Estimated Effort

Junior Rust Engineer with SurrealDB Experience: 4-6 hours

  • 1 hour: Understand codebase and embedding infrastructure
  • 1 hour: Implement blob conversion and core search method
  • 1 hour: Wire up Tauri command
  • 2 hours: Write comprehensive tests
  • 1 hour: Manual testing and performance validation

Mid-Level Engineer: 2-3 hours
Senior Engineer: 1-2 hours

Dependencies

Completed Issues (This work builds on):

Blocked Issues (Waiting on this work):

  • Frontend @mention autocomplete - Needs semantic search for smart suggestions
  • Related notes discovery - Needs similarity search for recommendations
  • Content clustering - Needs similarity scores for grouping

Resources / File Locations

Files to Modify

Primary Implementation:

  • packages/core/src/db/surreal_store.rs (lines 1362-1368)
    • Replace search_by_embedding() stub
    • Add blob_to_f32_array() helper function
    • Add comprehensive test suite at bottom

Tauri Command Integration:

  • packages/desktop-app/src-tauri/src/commands/embeddings.rs (line 151)
    • Replace search_containers() stub with full implementation

Files to Reference (Do NOT Modify)

Embedding Infrastructure:

  • packages/nlp-engine/src/embedding.rs - NLP embedding generation
  • packages/core/src/services/embedding_service.rs - Node embedding service
  • packages/core/src/services/embedding_processor.rs - Background processing

Data Models:

  • packages/core/src/models/node.rs - Node structure with embedding_vector field

Existing Tests:

  • packages/core/src/tests/integration/embedding_tests.rs - Embedding test patterns

External Documentation

SurrealDB Vector Functions:

Cosine Similarity:

Documentation Updates Needed

After implementation, update these docs to reflect vector search capability:

1. Technology Stack Documentation

File: docs/architecture/core/technology-stack.md
Section: Lines 256-280 (Vector Embeddings section)
Change:

  • Update to mention vector search is now implemented
  • Add performance characteristics (query latency)
  • Add example query showing semantic search

Example Addition:

### Vector Similarity Search

**Implementation**: SurrealDB native `vector::similarity::cosine()` function

**Usage**:
```rust
let results = store.search_by_embedding(&query_blob, limit, threshold).await?;

Performance:

  • 1,000 nodes: < 100ms
  • 10,000 nodes: < 500ms
  • 100,000 nodes: < 2 seconds (linear scan, no index)

### 2. NLP Embedding Service Documentation
**File**: `docs/architecture/components/nlp-embedding-service.md`
**Section**: Lines 1-15 (Features section)
**Change**:
- Update status from "Turso Integration" to "SurrealDB Integration"
- Add "Vector Similarity Search" feature with description
- Update storage format reference (F32_BLOB → bytes in SurrealDB)

**Example Addition**:
```markdown
## Features

- **Local Model Bundling**: Models bundled with application, no network required
- **Metal GPU Acceleration**: Optimized performance on macOS with automatic CPU fallback
- **Efficient Caching**: LRU cache with automatic eviction for <5ms cache hits
- **Batch Operations**: Efficient batch embedding generation
- **SurrealDB Integration**: Native storage as bytes with vector::similarity::cosine search
- **Vector Similarity Search**: Semantic discovery using cosine similarity (0.0-1.0 scale)

3. SurrealDB Architecture Documentation

File: docs/architecture/data/surrealdb-only-architecture.md
Section: After line 100 (Core Operations section)
Change:

  • Add new subsection "Vector Similarity Search"
  • Document the search_by_embedding() method
  • Include example query with explanation

Example Addition:

### Vector Similarity Search

**Method**: `search_by_embedding(embedding: &[u8], limit: i64, threshold: Option<f64>)`

**Query Pattern**:
```sql
SELECT
    *,
    vector::similarity::cosine(embedding_vector, $query_vector) AS similarity
FROM nodes
WHERE embedding_vector != NONE
  AND vector::similarity::cosine(embedding_vector, $query_vector) > $threshold
ORDER BY similarity DESC
LIMIT $limit;

Similarity Scores:

  • 1.0 = Identical content
  • 0.7-0.9 = Highly similar (semantic equivalents)
  • 0.5-0.7 = Moderately similar (related topics)
  • 0.3-0.5 = Loosely related
  • < 0.3 = Unrelated content

### 4. System Overview Documentation
**File**: `docs/architecture/core/system-overview.md`
**Section**: Lines 48-51 (Data Layer section)
**Change**:
- Update NLP Engine reference to mention semantic search capability

**Example Change**:
```markdown
│  ├── Embedded SurrealDB (universal node schema + graph relations + vector search)
│  ├── File System (raw content)
│  └── NLP Engine (mistral.rs - embeddings + semantic similarity)

Key Technical Decisions

1. Cosine Similarity (Not Euclidean Distance)

Rationale: Cosine similarity measures orientation, not magnitude. For text embeddings, this is more meaningful than absolute distance.

Example:

  • "Machine learning" vs "Deep learning" → High cosine similarity (same domain)
  • "Weather forecast" vs "Machine learning" → Low cosine similarity (different domains)

2. Default Threshold = 0.5

Rationale: Balance between recall and precision.

  • Too low (0.3): Many irrelevant results
  • Too high (0.8): Miss moderately related content
  • 0.5 = Good middle ground for semantic "relatedness"

User Control: Frontend can adjust threshold based on use case.

3. Binary Blob Storage (Not JSON Arrays)

Rationale:

  • Storage efficiency: 1536 bytes vs ~3000+ bytes as JSON
  • SurrealDB can work with both formats
  • Conversion happens in-query (negligible overhead)

4. No Vector Index (Initially)

Rationale:

  • SurrealDB's MTREE/HNSW index support is still evolving
  • Linear scan acceptable for <10K nodes (<500ms)
  • Can add index later if needed (non-breaking change)
  • Simpler implementation = faster delivery

Risks or Unknowns

1. SurrealDB Vector Function Performance (LOW RISK)

Risk: vector::similarity::cosine() might be slower than expected for large datasets.

Mitigation:

  • Test with 10K+ nodes
  • If too slow, explore MTREE/HNSW indexing
  • Worst case: implement approximate search (kNN)

Probability: Low - SurrealDB designed for this use case

2. Binary Blob Conversion Overhead (LOW RISK)

Risk: Converting Vec<u8> to Vec<f32> might add latency.

Mitigation:

  • Conversion is O(n) where n=384 (tiny)
  • ~1-5ms overhead max
  • Can cache converted vectors if needed

Probability: Low - conversion is trivial operation

3. Similarity Score Interpretation (MEDIUM RISK)

Risk: Default threshold (0.5) might not feel right to users.

Mitigation:

  • Make threshold configurable from frontend
  • Add UI hints ("High similarity", "Related", etc.)
  • Can tune based on user feedback

Probability: Medium - subjective UX decision

4. Empty Embeddings in Database (LOW RISK)

Risk: Some nodes might not have embeddings yet (stale or new).

Mitigation:

  • Query filters embedding_vector != NONE
  • Nodes without embeddings simply don't appear in results
  • Background processor will catch them eventually

Probability: Low - handled by query filter

5. SurrealDB Query Syntax Changes (LOW RISK)

Risk: SurrealDB 2.x API might change in future versions.

Mitigation:

  • Pin SurrealDB version in Cargo.toml
  • Monitor changelog for breaking changes
  • Tests will catch API breaks immediately

Probability: Low - SurrealDB has stable 2.x API

Success Criteria Summary

This issue is complete when:

  1. ✅ User can invoke search_containers Tauri command with query text
  2. ✅ Backend generates embedding for query, searches with cosine similarity
  3. ✅ Results ranked by similarity (most similar first)
  4. ✅ All tests pass (unit + integration)
  5. ✅ Performance < 500ms for 10K nodes
  6. ✅ Documentation updated to reflect vector search capability

Evidence of Success:

  • Manual test: Search "machine learning" returns AI/ML-related nodes at top
  • Manual test: Threshold=0.7 filters out weakly related nodes
  • Manual test: Limit=5 returns exactly 5 results
  • Unit tests: 100% pass rate
  • Performance test: 10K nodes search completes in <500ms

Activity

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

    @malibio
    CollaboratorAuthor

    Test Baseline (Before Implementation)

    Command: bun run test:all

    Results:

    • ✅ 1537 tests passing
    • ❌ 1 test failing: src/tests/integration/sibling-chain-integrity.test.ts > Sibling Chain Integrity > should maintain chain integrity with complex operations sequence
    • ⏭️ 49 tests skipped
    • Duration: 23.74s

    Pre-existing failure (not related to vector search):

    • Sibling chain integrity test has a persistence timeout issue
    • This failure exists before any vector search implementation

    Goal: Implement vector similarity search without introducing any new test failures.

  3. added a commit that references this issue on Nov 14, 2025
    79d6549
  4. malibio commented on Nov 14, 2025

    @malibio
    CollaboratorAuthor

    Additional Task: Re-enable MCP search_containers Method

    After completing the core vector search implementation, there's a 15-minute follow-up task to re-enable the MCP semantic search method for AI agents.

    Current MCP State

    File: packages/core/src/mcp/handlers/search.rs (lines 84-88)

    The MCP search_containers method is fully implemented (parameters, validation, error handling, 23 test cases) but currently returns empty results:

    // Lines 84-88: Currently stubbed
    // Semantic search pending NLP integration (database tracking now complete)
    // Returning empty results until full embedding generation is re-enabled
    tracing::info!("Semantic search pending NLP integration - database tracking complete");
    let results: Result<Vec<crate::models::Node>, crate::services::error::NodeServiceError> =
        Ok(Vec::new());  // ← Returns empty!

    MCP Tool Schema: Already registered in packages/core/src/mcp/handlers/tools.rs (lines 541-569)

    Implementation (15 minutes)

    Replace lines 84-88 in search.rs with:

    // Generate embedding for search query
    let embedding_vec = _service.nlp_engine
        .generate_embedding(&params.query)
        .map_err(|e| MCPError::internal_error(format!("Embedding generation failed: {}", e)))?;
    
    // Convert to binary blob
    let embedding_blob = nodespace_nlp_engine::EmbeddingService::to_blob(&embedding_vec);
    
    // Execute vector search
    let search_results = _service.store
        .search_by_embedding(&embedding_blob, limit as i64, Some(threshold as f64))
        .await
        .map_err(|e| MCPError::internal_error(format!("Search failed: {}", e)))?;
    
    // Extract nodes (discard similarity scores for MCP response)
    let nodes: Vec<Node> = search_results.into_iter()
        .map(|(node, _similarity)| node)
        .collect();

    Why This Matters

    AI Agent Use Cases:

    1. Context Discovery: "Find notes related to machine learning projects"
    2. Smart Suggestions: When agent mentions a topic, discover related nodes
    3. Knowledge Graph Navigation: Semantic exploration without exact IDs

    MCP Method Details:

    • Name: search_containers
    • Parameters: query (required), threshold (0.7 default), limit (20 default), exact (false default)
    • Response: JSON with nodes, count, query, threshold, exact metadata

    Testing

    After implementation, test with MCP client:

    {
      "method": "tools/call",
      "params": {
        "name": "search_containers",
        "arguments": {
          "query": "machine learning projects",
          "threshold": 0.6,
          "limit": 5
        }
      }
    }

    Expected Response:

    {
      "nodes": [
        { "id": "...", "content": "Deep learning neural networks...", ... },
        { "id": "...", "content": "AI model training pipeline...", ... }
      ],
      "count": 2,
      "query": "machine learning projects",
      "threshold": 0.6,
      "exact": false
    }

    Acceptance Criteria Additions

    Add these to the main issue checklist:

    • MCP search_containers method returns actual results (not empty Vec)
    • MCP method properly calls search_by_embedding() from SurrealStore
    • MCP response includes all metadata fields (nodes, count, query, threshold, exact)
    • MCP tests pass (all 23 existing test cases in search.rs)
    • MCP method callable via tools/call endpoint
    • Warning log "Semantic search pending NLP integration" removed

    Files to Modify

    • packages/core/src/mcp/handlers/search.rs (lines 84-88 only)

    Related Documentation

  5. malibio commented on Nov 14, 2025

    @malibio
    CollaboratorAuthor

    ✅ Threshold parameter documentation added (commit 574a9e5)

    Added comprehensive similarity threshold documentation to SearchContainersParams:

    Threshold Field Documentation

    /// Minimum similarity threshold (0.0-1.0, higher = more similar)
    /// - 1.0 = Identical content
    /// - 0.7-0.9 = Highly similar (semantic equivalents)
    /// - 0.5-0.7 = Moderately similar (related topics)
    /// - 0.3-0.5 = Loosely related
    /// - < 0.3 = Unrelated content
    ///
    /// Default: 0.5 (moderate similarity)
    

    Also Updated

    • Corrected similarity direction (was "lower = more similar", now correctly "higher = more similar")
    • Updated function-level docs to reflect SurrealDB implementation (removed outdated Turso references)
    • Corrected TypeScript example to use default threshold of 0.5

    Frontend developers can now easily understand what threshold values to use based on their desired similarity requirements.

  6. added a commit that references this issue on Nov 14, 2025
    dee2479
  7. added 2 commits that reference this issue on Feb 4, 2026
    f3f5477
    2b1f48b
  8. added a commit that references this issue on Feb 26, 2026
    f76e0ad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions