Repository navigation
Labels
Description
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
embeddingtable but code usesnode.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.surqldefines anembeddingtable that is never used- Code stores embeddings on
node.embedding_vectorandnode.embedding_stale - Every node is treated as potentially embeddable (wrong model)
- No staleness propagation from child to root
Desired State:
- Use the
embeddingtable (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:
- Corrected
embeddingtable schema - Remove
embedding_vectorandembedding_stalefrom node table - Backend-managed embedding queue with debouncing
- 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_vectorfieldembedding_stalefield
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:
- Fetch root node fresh
- Fetch ALL descendants via
get_descendants(root_id) - Aggregate content (root + children)
- Chunk if > 512 tokens (with ~100 token overlap)
- Generate embeddings (one per chunk)
- Store in
embeddingtable
Chunking config:
max_tokens_per_chunk: 512 (model limit)overlap_tokens: 100min_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
-
embeddingtable schema updated with corrected fields -
embedding_vectorandembedding_staleremoved from node table -
EmbeddingQueueimplemented 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_vectorcode 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
- No forward link from node→embedding - All access starts from embedding table
- 30 second debounce - Configurable, batches rapid edits
- Fresh content at processing time - Queue only tracks "needs re-embed"
- 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 parentDocumentation Updates
Documentation has been updated to reflect this architecture:
docs/architecture/components/nlp-embedding-service.md- Complete rewritedocs/architecture/data/surrealdb-schema-design.md- Updated embedding references
Dependencies
None - this is a self-contained refactor.
Related Issues
- Implement multi-model embeddings system with two-level embeddability #573 (superseded - two-level embeddability, now simplified to root-aggregate)
- Implement MCP semantic_search tool with Claude Code compatibility #574 (MCP semantic search - will use new embedding table)
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
malibio commentedon Dec 4, 2025
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.
Implement root-aggregate embedding architecture (Issue #729)
Implement root-aggregate embedding architecture (Issue #729)
Root-Aggregate Embedding Architecture for Semantic Search (#732)
malibio commentedon Dec 5, 2025
Reopening - implementation incomplete:
mark_embedding_stale()on node table instead of finding root and markingembedding.staleAlso investigating: What happens if app shuts down before embedding queue is processed?
Complete root-aggregate embedding staleness tracking (Issue #729)
Refactor EmbeddingProcessor to event-driven model (Issue #729)
Address code review feedback for Issue #729
Root-Aggregate Embedding Architecture for Semantic Search (#734)
fix: Add per-root debounce and fix infinite chunk loop in embedding s…
Root-Aggregate Embedding Architecture for Semantic Search (#732)
Root-Aggregate Embedding Architecture for Semantic Search (#734)
fix: Add per-root debounce and fix infinite chunk loop in embedding s…
Root-Aggregate Embedding Architecture for Semantic Search (#732)
Root-Aggregate Embedding Architecture for Semantic Search (#734)
fix: Add per-root debounce and fix infinite chunk loop in embedding s…
Root-Aggregate Embedding Architecture for Semantic Search (#732)
Root-Aggregate Embedding Architecture for Semantic Search (#734)
fix: Add per-root debounce and fix infinite chunk loop in embedding s…