Skip to content

Implement Topic Node Embeddings with Adaptive Chunking #183

Closed

Description

@malibio

Overview

Implement embedding generation for topic nodes (@ mention pages) with adaptive chunking based on content size. Topic nodes are user-created pages that serve as knowledge units and should be the primary semantic search targets.

CRITICAL: Use Turso's native vector search capabilities - NO in-memory implementation needed.

Implementation Status Report

✅ Dependencies Ready (Issue #108 - Fully Implemented)

The NLP engine exists at /packages/nlp-engine/ with complete production-ready code:

Available API:

use nodespace_nlp_engine::{EmbeddingService, EmbeddingConfig};

// Initialize once at app startup
let mut embedding_service = EmbeddingService::new(EmbeddingConfig::default())?;
embedding_service.initialize()?;

// API methods available:
pub fn generate_embedding(&self, text: &str) -> Result<Vec<f32>>
pub fn generate_batch(&self, texts: Vec<&str>) -> Result<Vec<Vec<f32>>>
pub fn to_blob(embedding: &[f32]) -> Vec<u8>      // F32_BLOB for Turso
pub fn from_blob(blob: &[u8]) -> Vec<f32>

// Features:
// - BAAI/bge-small-en-v1.5 (384 dimensions)
// - Metal GPU acceleration with CPU fallback
// - LRU cache (10k capacity, <5ms cache hits)
// - Batch operations

⚠️ Database Schema Updates Required

Current State:

-- packages/core/src/db/database.rs:175
embedding_vector BLOB,  -- Generic BLOB, not native vector type

Required Changes:

-- Change to native Turso vector type
embedding_vector F32_BLOB(384),  -- Native vector with dimension declaration

Required Index (add to create_core_indexes() in database.rs):

// Add after line 345 in packages/core/src/db/database.rs
conn.execute(
    "CREATE INDEX IF NOT EXISTS idx_nodes_embedding_vector 
     ON nodes(libsql_vector_idx(embedding_vector))",
    (),
)
.await
.map_err(|e| {
    DatabaseError::sql_execution(format!(
        "Failed to create vector index: {}", e
    ))
})?;

🟡 LLM Summarization - Defer for MVP

Status: Gemma 3 4B-QAT planned but not yet implemented

MVP Alternative: Use simple text truncation for topics >2048 tokens

fn simple_summarize(content: &str, max_tokens: usize) -> String {
    let max_chars = max_tokens * 4; // Rough estimate: 4 chars ≈ 1 token
    if content.len() <= max_chars {
        content.to_string()
    } else {
        format!("{}...", &content[..max_chars])
    }
}

Future: Separate issue for LLM integration with Gemma 3 4B-QAT


Technical Implementation Guide

1. Service Layer Structure

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

use nodespace_nlp_engine::{EmbeddingService, EmbeddingConfig};
use std::sync::Arc;
use tokio::time::Duration;

pub struct TopicEmbeddingService {
    nlp_engine: Arc<EmbeddingService>,
    db: Arc<DatabaseService>,
    node_service: Arc<NodeService>,
}

impl TopicEmbeddingService {
    pub fn new(
        nlp_engine: Arc<EmbeddingService>,
        db: Arc<DatabaseService>,
        node_service: Arc<NodeService>,
    ) -> Self {
        Self {
            nlp_engine,
            db,
            node_service,
        }
    }

    /// Embed a topic with adaptive chunking strategy
    pub async fn embed_topic(&self, topic_id: &str) -> Result<()> {
        // 1. Fetch topic and children
        let topic = self.node_service.get_node(topic_id).await?;
        let children = self.node_service.get_children(topic_id).await?;
        
        // 2. Estimate tokens
        let total_tokens = self.estimate_topic_tokens(&topic, &children);
        
        // 3. Apply adaptive chunking
        match total_tokens {
            0..512 => self.embed_complete_topic(topic_id, &topic, &children).await?,
            512..2048 => self.embed_with_sections(topic_id, &topic, &children, false).await?,
            _ => self.embed_with_sections(topic_id, &topic, &children, true).await?,
        }
        
        Ok(())
    }
    
    /// Search topics using Turso native vector search
    pub async fn search_topics(
        &self,
        query: &str,
        threshold: f32,
        limit: usize,
    ) -> Result<Vec<Node>> {
        // 1. Generate query embedding
        let query_embedding = self.nlp_engine.generate_embedding(query)?;
        let query_blob = EmbeddingService::to_blob(&query_embedding);
        
        // 2. Use Turso's native vector_top_k function (NO in-memory processing!)
        let conn = self.db.connect_with_timeout().await?;
        let mut stmt = conn.prepare(
            "SELECT * FROM vector_top_k('idx_nodes_embedding_vector', vector(?), ?)
             WHERE node_type = 'topic'"
        ).await?;
        
        let mut rows = stmt.query(params![query_blob, limit]).await?;
        
        // 3. Convert rows to nodes
        let mut nodes = Vec::new();
        while let Some(row) = rows.next().await? {
            nodes.push(Node::from_row(&row)?);
        }
        
        Ok(nodes)
    }
    
    /// Debounced re-embedding on content changes
    pub async fn update_topic_embedding(&self, topic_id: &str) -> Result<()> {
        // Re-embed with same adaptive logic
        self.embed_topic(topic_id).await
    }
    
    // Private helper methods
    
    fn estimate_tokens(&self, content: &str) -> usize {
        (content.len() / 4).max(1)
    }
    
    fn estimate_topic_tokens(&self, topic: &Node, children: &[Node]) -> usize {
        let topic_content = topic.content.as_ref().map(|s| s.as_str()).unwrap_or("");
        let children_content: String = children
            .iter()
            .map(|n| n.content.as_ref().map(|s| s.as_str()).unwrap_or(""))
            .collect::<Vec<_>>()
            .join("\n");
        
        self.estimate_tokens(&format!("{}\n{}", topic_content, children_content))
    }
    
    async fn embed_complete_topic(
        &self,
        topic_id: &str,
        topic: &Node,
        children: &[Node],
    ) -> Result<()> {
        // Combine all content
        let content = self.combine_content(topic, children);
        
        // Generate embedding
        let embedding = self.nlp_engine.generate_embedding(&content)?;
        let blob = EmbeddingService::to_blob(&embedding);
        
        // Store with metadata
        let metadata = json!({
            "type": "complete_topic",
            "generated_at": Utc::now().to_rfc3339(),
            "token_count": self.estimate_tokens(&content),
        });
        
        self.store_embedding(topic_id, blob, metadata).await
    }
    
    async fn embed_with_sections(
        &self,
        topic_id: &str,
        topic: &Node,
        children: &[Node],
        hierarchical: bool,
    ) -> Result<()> {
        // 1. Generate summary (simple truncation for MVP)
        let full_content = self.combine_content(topic, children);
        let summary = self.simple_summarize(&full_content, 512);
        
        // 2. Embed summary
        let summary_embedding = self.nlp_engine.generate_embedding(&summary)?;
        let summary_blob = EmbeddingService::to_blob(&summary_embedding);
        
        let summary_metadata = json!({
            "type": "topic_summary",
            "parent_topic": topic_id,
            "generated_at": Utc::now().to_rfc3339(),
            "token_count": self.estimate_tokens(&summary),
        });
        
        self.store_embedding(topic_id, summary_blob, summary_metadata).await?;
        
        // 3. Embed sections
        if hierarchical {
            self.embed_sections_hierarchical(topic_id, children, 0).await?;
        } else {
            self.embed_top_level_sections(topic_id, children).await?;
        }
        
        Ok(())
    }
    
    async fn embed_top_level_sections(
        &self,
        topic_id: &str,
        children: &[Node],
    ) -> Result<()> {
        for child in children {
            let content = child.content.as_ref().map(|s| s.as_str()).unwrap_or("");
            let embedding = self.nlp_engine.generate_embedding(content)?;
            let blob = EmbeddingService::to_blob(&embedding);
            
            let metadata = json!({
                "type": "topic_section",
                "parent_topic": topic_id,
                "depth": 0,
                "generated_at": Utc::now().to_rfc3339(),
            });
            
            self.store_embedding(&child.id, blob, metadata).await?;
        }
        Ok(())
    }
    
    async fn embed_sections_hierarchical(
        &self,
        topic_id: &str,
        children: &[Node],
        depth: usize,
    ) -> Result<()> {
        for child in children {
            let content = child.content.as_ref().map(|s| s.as_str()).unwrap_or("");
            let embedding = self.nlp_engine.generate_embedding(content)?;
            let blob = EmbeddingService::to_blob(&embedding);
            
            let metadata = json!({
                "type": "topic_section",
                "parent_topic": topic_id,
                "depth": depth,
                "generated_at": Utc::now().to_rfc3339(),
            });
            
            self.store_embedding(&child.id, blob, metadata).await?;
            
            // Recurse for nested sections
            let grandchildren = self.node_service.get_children(&child.id).await?;
            if !grandchildren.is_empty() {
                self.embed_sections_hierarchical(topic_id, &grandchildren, depth + 1).await?;
            }
        }
        Ok(())
    }
    
    fn combine_content(&self, topic: &Node, children: &[Node]) -> String {
        let topic_content = topic.content.as_ref().map(|s| s.as_str()).unwrap_or("");
        let children_content: String = children
            .iter()
            .map(|n| n.content.as_ref().map(|s| s.as_str()).unwrap_or(""))
            .collect::<Vec<_>>()
            .join("\n");
        
        format!("{}\n{}", topic_content, children_content)
    }
    
    fn simple_summarize(&self, content: &str, max_tokens: usize) -> String {
        let max_chars = max_tokens * 4;
        if content.len() <= max_chars {
            content.to_string()
        } else {
            format!("{}...", &content[..max_chars])
        }
    }
    
    async fn store_embedding(
        &self,
        node_id: &str,
        blob: Vec<u8>,
        metadata: serde_json::Value,
    ) -> Result<()> {
        let conn = self.db.connect_with_timeout().await?;
        conn.execute(
            "UPDATE nodes SET 
                embedding_vector = ?,
                properties = json_set(properties, '$.embedding_metadata', ?),
                modified_at = CURRENT_TIMESTAMP
             WHERE id = ?",
            params![blob, metadata.to_string(), node_id],
        ).await?;
        Ok(())
    }
}

2. Tauri Command Integration

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

use tauri::State;
use crate::state::AppState;

#[tauri::command]
pub async fn generate_topic_embedding(
    state: State<'_, AppState>,
    topic_id: String,
) -> Result<(), String> {
    state
        .embedding_service
        .embed_topic(&topic_id)
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn search_topics(
    state: State<'_, AppState>,
    query: String,
    threshold: Option<f32>,
    limit: Option<usize>,
) -> Result<Vec<Node>, String> {
    state
        .embedding_service
        .search_topics(
            &query,
            threshold.unwrap_or(0.7),
            limit.unwrap_or(20),
        )
        .await
        .map_err(|e| e.to_string())
}

#[tauri::command]
pub async fn update_topic_embedding(
    state: State<'_, AppState>,
    topic_id: String,
) -> Result<(), String> {
    state
        .embedding_service
        .update_topic_embedding(&topic_id)
        .await
        .map_err(|e| e.to_string())
}

Register commands in main.rs:

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            generate_topic_embedding,
            search_topics,
            update_topic_embedding,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

3. Debouncing Implementation

Using tokio for debouncing:

use tokio::time::{sleep, Duration, Instant};
use std::sync::Arc;
use tokio::sync::Mutex;

pub struct Debouncer {
    delay: Duration,
    last_call: Arc<Mutex<Option<Instant>>>,
}

impl Debouncer {
    pub fn new(delay: Duration) -> Self {
        Self {
            delay,
            last_call: Arc::new(Mutex::new(None)),
        }
    }
    
    pub async fn schedule<F, Fut>(&self, f: F)
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = ()> + Send,
    {
        let mut last = self.last_call.lock().await;
        *last = Some(Instant::now());
        let target_time = last.unwrap() + self.delay;
        drop(last);
        
        tokio::spawn({
            let last_call = Arc::clone(&self.last_call);
            let delay = self.delay;
            async move {
                sleep(delay).await;
                
                let last = last_call.lock().await;
                if let Some(time) = *last {
                    if Instant::now() >= time + delay {
                        drop(last);
                        f().await;
                    }
                }
            }
        });
    }
}

// Usage in content change handler:
let debouncer = Debouncer::new(Duration::from_secs(5));

// When topic content changes:
debouncer.schedule(|| async {
    embedding_service.update_topic_embedding(topic_id).await
}).await;

4. Native Vector Search Implementation (Turso)

Turso provides out-of-the-box vector search - NO in-memory implementation needed!

/// Vector similarity search using Turso's native functions
pub async fn search_topics(
    &self,
    query: &str,
    threshold: f32,
    limit: usize,
) -> Result<Vec<Node>> {
    // 1. Generate query embedding
    let query_embedding = self.nlp_engine.generate_embedding(query)?;
    let query_blob = EmbeddingService::to_blob(&query_embedding);
    
    // 2. Use Turso's native vector_top_k function
    // DiskANN algorithm provides fast approximate nearest neighbors
    let conn = self.db.connect_with_timeout().await?;
    let mut stmt = conn.prepare(
        "SELECT 
            n.*,
            vt.distance
         FROM vector_top_k('idx_nodes_embedding_vector', vector(?), ?) vt
         JOIN nodes n ON n.rowid = vt.rowid
         WHERE n.node_type = 'topic'"
    ).await?;
    
    let mut rows = stmt.query(params![query_blob, limit]).await?;
    
    // 3. Convert to Node objects
    let mut nodes = Vec::new();
    while let Some(row) = rows.next().await? {
        nodes.push(Node::from_row(&row)?);
    }
    
    Ok(nodes)
}

// Alternative: Using vector_distance_cosine for exact search (no index required)
pub async fn exact_search_topics(
    &self,
    query: &str,
    threshold: f32,
    limit: usize,
) -> Result<Vec<Node>> {
    let query_embedding = self.nlp_engine.generate_embedding(query)?;
    let query_blob = EmbeddingService::to_blob(&query_embedding);
    
    let conn = self.db.connect_with_timeout().await?;
    let mut stmt = conn.prepare(
        "SELECT 
            *,
            vector_distance_cosine(embedding_vector, vector(?)) as distance
         FROM nodes
         WHERE node_type = 'topic'
           AND embedding_vector IS NOT NULL
           AND vector_distance_cosine(embedding_vector, vector(?)) < ?
         ORDER BY distance ASC
         LIMIT ?"
    ).await?;
    
    let mut rows = stmt.query(params![query_blob, query_blob, threshold, limit]).await?;
    
    let mut nodes = Vec::new();
    while let Some(row) = rows.next().await? {
        nodes.push(Node::from_row(&row)?);
    }
    
    Ok(nodes)
}

5. App Initialization

Update app state to include embedding service:

// In src-tauri/src/main.rs or state.rs
use nodespace_nlp_engine::{EmbeddingService, EmbeddingConfig};

pub struct AppState {
    pub db: Arc<DatabaseService>,
    pub node_service: Arc<NodeService>,
    pub embedding_service: Arc<TopicEmbeddingService>,
}

impl AppState {
    pub async fn new(db_path: PathBuf) -> Result<Self> {
        // Initialize database
        let db = Arc::new(DatabaseService::new(db_path).await?);
        
        // Initialize node service
        let node_service = Arc::new(NodeService::new(Arc::clone(&db)));
        
        // Initialize NLP engine
        let mut nlp_engine = EmbeddingService::new(EmbeddingConfig::default())?;
        nlp_engine.initialize()?;
        let nlp_engine = Arc::new(nlp_engine);
        
        // Initialize embedding service
        let embedding_service = Arc::new(TopicEmbeddingService::new(
            nlp_engine,
            Arc::clone(&db),
            Arc::clone(&node_service),
        ));
        
        Ok(Self {
            db,
            node_service,
            embedding_service,
        })
    }
}

Implementation Checklist

Phase 1: Database Schema Updates

  • Update embedding_vector column type: BLOB → F32_BLOB(384) in database.rs:175
  • Add vector index in create_core_indexes() using libsql_vector_idx(embedding_vector)
  • Test database initialization with new schema
  • Verify index creation with PRAGMA index_list('nodes')

Phase 2: Core Service Implementation

  • Create /packages/core/src/services/embedding_service.rs
  • Add nodespace-nlp-engine dependency to packages/core/Cargo.toml
  • Implement TopicEmbeddingService struct with all methods
  • Implement token estimation functions
  • Implement adaptive chunking logic (< 512, 512-2048, > 2048)
  • Implement embed_topic() with database storage
  • Add embedding metadata to properties JSON

Phase 3: Vector Search

  • Implement search_topics() using Turso's vector_top_k function
  • Test vector search with sample embeddings
  • Verify DiskANN index performance
  • Add optional exact search using vector_distance_cosine

Phase 4: Debouncing

  • Implement Debouncer struct with tokio
  • Hook into topic content change events
  • Add 5-second debounce logic
  • Test debouncing with rapid content changes

Phase 5: Tauri Integration

  • Create /packages/desktop-app/src-tauri/src/commands/embeddings.rs
  • Add Tauri commands for frontend
  • Update app state initialization with embedding service
  • Register commands in main.rs
  • Add error handling and logging

Phase 6: Testing

  • Unit tests for token estimation
  • Unit tests for chunking strategies (< 512, 512-2048, > 2048)
  • Integration tests for embedding generation
  • Integration tests for vector search
  • Integration tests for debouncing
  • Performance tests (embedding time, search latency)
  • Test with real topic content at various sizes

Acceptance Criteria

  • Database schema updated with F32_BLOB(384) and vector index
  • Topic nodes with < 512 tokens embed as single unit
  • Topic nodes with 512-2048 tokens embed summary + top-level sections
  • Topic nodes with > 2048 tokens embed summary + hierarchical sections
  • Content changes trigger debounced re-embedding (5 second delay)
  • Embeddings stored in Turso embedding_vector column with metadata
  • Vector similarity search uses Turso's native vector_top_k function
  • Vector search returns relevant topic nodes (threshold filtering works)
  • Tests cover all three chunking strategies
  • Performance: Embedding generation < 3 seconds (CPU), < 1 second (GPU)
  • Performance: Vector search < 100ms for 10k+ nodes (using DiskANN index)

Technical Notes

Turso Vector Search Capabilities (GA since October 2024)

Native Features:

  • F32_BLOB(dimension) column type for vector storage
  • libsql_vector_idx() for creating DiskANN indexes
  • vector_top_k(index_name, query_vector, k) for approximate nearest neighbors
  • vector_distance_cosine() for exact cosine similarity
  • Works offline in embedded libSQL (no cloud dependency)
  • No extensions needed - vectors are a built-in column type

Performance:

  • DiskANN algorithm for fast ANN queries
  • Scales to millions of vectors
  • <100ms query time with proper indexing
  • Works across Turso cloud and embedded libSQL

Migration Notes

Existing databases have embedding_vector BLOB which needs migration to F32_BLOB(384). Options:

  1. ALTER TABLE (if Turso supports):

    ALTER TABLE nodes MODIFY COLUMN embedding_vector F32_BLOB(384);
  2. Recreate table (if ALTER not supported):

    CREATE TABLE nodes_new (
        -- ... all columns with F32_BLOB(384)
    );
    INSERT INTO nodes_new SELECT * FROM nodes;
    DROP TABLE nodes;
    ALTER TABLE nodes_new RENAME TO nodes;
  3. Schema versioning: Add version tracking to handle migrations gracefully


Dependencies

Related

Future Enhancements (Not in Scope)

  • LLM-based summarization with Gemma 3 4B-QAT (separate issue)
  • DateNode section detection and embedding
  • Fine-tuning embeddings for NodeSpace-specific content
  • Cross-lingual topic search
  • Image-based topic search (when multimodal added)

Activity

  1. self-assigned this
    on Oct 10, 2025
  2. added a commit that references this issue on Oct 10, 2025
    bc53b2c
  3. added 2 commits that reference this issue on Oct 10, 2025
    233c47d
    8522416
  4. added 4 commits that reference this issue on Feb 4, 2026
    5ef40e4
    3183882
    7cd4b4e
    49dcaf3
  5. added 2 commits that reference this issue on Feb 26, 2026
    3e138d3
    5319e23
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