Skip to content

Root-Aggregate Embedding Architecture for Semantic Search #729

Closed

Description

@malibio

Overview

Redesign the embedding system to use a root-aggregate model where only root nodes (nodes without parents) of embeddable types get embedded. The embedding represents the semantic content of the entire subtree (root + all descendants).

This addresses several issues with the current implementation:

  • Schema defines embedding table but code uses node.embedding_vector (never uses the table)
  • Per-node embedding model doesn't capture semantic meaning (child nodes often meaningless alone)
  • New nodes created with embedding_stale = false, never queued for embedding
  • Child edits don't invalidate parent/root embeddings

Problem Statement

Current State:

  • schema.surql defines an embedding table that is never used
  • Code stores embeddings on node.embedding_vector and node.embedding_stale
  • Every node is treated as potentially embeddable (wrong model)
  • No staleness propagation from child to root

Desired State:

  • Use the embedding table (with corrections)
  • Only root nodes of embeddable types get embedded
  • Child changes propagate staleness to root
  • Backend-managed debounced queue for efficient re-embedding

Proposed Solution

Implement root-aggregate embedding with:

  1. Corrected embedding table schema
  2. Remove embedding_vector and embedding_stale from node table
  3. Backend-managed embedding queue with debouncing
  4. Chunked embeddings for large content (512 token limit)

Implementation Approach

Phase 1: Schema Updates

Update embedding table in schema.surql:

DEFINE TABLE embedding SCHEMAFULL;

-- Link to root node (consistent with spoke pattern)
DEFINE FIELD node ON embedding TYPE record<node>;

-- Vector data
DEFINE FIELD vector ON embedding TYPE array<float>;
DEFINE FIELD dimension ON embedding TYPE int DEFAULT 384;

-- Model info (future multi-model support)
DEFINE FIELD model_name ON embedding TYPE string DEFAULT 'bge-small-en-v1.5';

-- Chunking support
DEFINE FIELD chunk_index ON embedding TYPE int DEFAULT 0;
DEFINE FIELD chunk_start ON embedding TYPE int DEFAULT 0;
DEFINE FIELD chunk_end ON embedding TYPE int;
DEFINE FIELD total_chunks ON embedding TYPE int DEFAULT 1;

-- Content tracking
DEFINE FIELD content_hash ON embedding TYPE string;
DEFINE FIELD token_count ON embedding TYPE int;

-- Staleness
DEFINE FIELD stale ON embedding TYPE bool DEFAULT true;

-- Error tracking
DEFINE FIELD error_count ON embedding TYPE int DEFAULT 0;
DEFINE FIELD last_error ON embedding TYPE string;

-- Timestamps
DEFINE FIELD created_at ON embedding TYPE datetime DEFAULT time::now();
DEFINE FIELD modified_at ON embedding TYPE datetime DEFAULT time::now();

-- Indexes
DEFINE INDEX idx_embedding_node ON embedding COLUMNS node;
DEFINE INDEX idx_embedding_stale ON embedding COLUMNS stale;
DEFINE INDEX idx_embedding_unique ON embedding COLUMNS node, model_name, chunk_index UNIQUE;

Remove from node table:

  • embedding_vector field
  • embedding_stale field

Phase 2: Backend Embedding Queue

Implement EmbeddingQueue in NodeService:

struct EmbeddingQueue {
    pending: HashMap<String, Instant>,  // root_id -> last_change_time
    debounce_duration: Duration,        // 30 seconds default
}

Change flow (all events):

Event Action
New root node created (embeddable type) Add root_id to queue, start debounce
Root node edited Add root_id to queue, reset debounce
Child node created/edited/deleted Find root via graph → add root_id to queue
Child node moved Add old root + new root to queue

Phase 3: Content Aggregation and Chunking

When debounce expires:

  1. Fetch root node fresh
  2. Fetch ALL descendants via get_descendants(root_id)
  3. Aggregate content (root + children)
  4. Chunk if > 512 tokens (with ~100 token overlap)
  5. Generate embeddings (one per chunk)
  6. Store in embedding table

Chunking config:

  • max_tokens_per_chunk: 512 (model limit)
  • overlap_tokens: 100
  • min_chunk_size: 50 (merge tiny final chunks)

Phase 4: Search Query Updates

Update search to use embedding table with chunk handling:

SELECT
    node,
    math::max(vector::similarity::cosine(vector, $query_vector)) AS best_similarity
FROM embedding
WHERE stale = false
GROUP BY node
HAVING best_similarity > $threshold
ORDER BY best_similarity DESC
LIMIT $limit;

Phase 5: Cleanup

  • Remove old embedding code that uses node.embedding_vector
  • Update Tauri commands to use new service
  • Clean up any backward compatibility code

Acceptance Criteria

  • embedding table schema updated with corrected fields
  • embedding_vector and embedding_stale removed from node table
  • EmbeddingQueue implemented in NodeService with debouncing
  • Root node detection working (no parent edge + embeddable type)
  • Embeddable types: text, header, code-block, schema
  • Non-embeddable types: task, date, any child node
  • Child changes propagate staleness to root
  • Content aggregation includes root + all descendants
  • Chunking works for content > 512 tokens
  • Search returns best-matching chunk per node
  • New root nodes automatically queued for embedding
  • Graph query finds root from any descendant
  • Error tracking (error_count, last_error) working
  • Old node.embedding_vector code removed (no backward compatibility)
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Schema: packages/core/src/db/schema.surql - Update embedding table
  • SurrealStore: packages/core/src/db/surreal_store.rs - Remove embedding_vector methods
  • NodeService: packages/core/src/services/node_service.rs - Add EmbeddingQueue
  • EmbeddingService: packages/core/src/services/embedding_service.rs - Refactor for root-aggregate
  • NLP Engine: packages/nlp-engine/src/embedding.rs - Existing, no changes needed

Key Design Decisions

  1. No forward link from node→embedding - All access starts from embedding table
  2. 30 second debounce - Configurable, batches rapid edits
  3. Fresh content at processing time - Queue only tracks "needs re-embed"
  4. No backward compatibility - Clean break, remove old code immediately

Configuration Defaults

pub struct EmbeddingConfig {
    pub debounce_duration: Duration,    // 30 seconds
    pub max_tokens_per_chunk: usize,    // 512
    pub overlap_tokens: usize,          // 100
    pub max_descendants: usize,         // 1000
    pub max_content_size: usize,        // 10MB
    pub max_retries: u8,                // 3
}

Graph Query to Find Root

-- Traverse up from child to find root (no incoming has_child edge)
SELECT VALUE in FROM has_child
WHERE out = $child_id
CONNECT BY out = in
-- Then filter to node with no parent

Documentation Updates

Documentation has been updated to reflect this architecture:

  • docs/architecture/components/nlp-embedding-service.md - Complete rewrite
  • docs/architecture/data/surrealdb-schema-design.md - Updated embedding references

Dependencies

None - this is a self-contained refactor.

Related Issues

Out of Scope

  • App diagnostics UI (separate issue)
  • Multi-model embedding support (schema supports it, implement later)
  • Node type plugin determines embeddability (future architecture)
  • Vector index optimization (HNSW/DiskANN)

Activity

  1. added
    enhancement
    on Dec 4, 2025
  2. self-assigned this
    on Dec 4, 2025
  3. malibio commented on Dec 4, 2025

    @malibio
    CollaboratorAuthor

    Test Baseline

    Frontend: 1569 passed, 0 failed
    Rust: 567 passed, 1 failed (pre-existing failure in tools_test::test_tools_list_returns_tier1_core_tools)

    Starting implementation of root-aggregate embedding architecture.

  4. malibio commented on Dec 5, 2025

    @malibio
    CollaboratorAuthor

    Reopening - implementation incomplete:

    1. New root creation via MCP - Fixed in current PR (creates stale marker)
    2. Child node updates - Still using old mark_embedding_stale() on node table instead of finding root and marking embedding.stale
    3. Child node creation - Not handled (should trigger root's embedding to be stale)
    4. Child node deletion - Not handled (should trigger root's embedding to be stale)

    Also investigating: What happens if app shuts down before embedding queue is processed?

  5. reopened this on Dec 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

aibackendenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions