Skip to content

Refactor embedding service to use NodeBehavior via NodeService for content extraction #1018

Closed

Description

@malibio

Overview

Refactor the embedding pipeline so that each node type's NodeBehavior is the single source of truth for embedding decisions. Uses a two-phase content extraction approach (sync + async) and introduces a NodeAccessor trait so the embedding service goes through NodeService instead of SurrealStore directly.

Architecture decision: ADR-029

Problem

Current architecture has split responsibilities:

  1. NodeBehavior trait defines get_embeddable_content() and get_parent_contribution() — each type implements these correctly
  2. NodeEmbeddingService ignores these methods entirely:
    • Uses is_embeddable_type() (hardcoded EMBEDDABLE_NODE_TYPES list) to decide root embeddability
    • Calls SurrealStore directly to fetch subtree nodes
    • Concatenates node.content from root + descendants, ignoring behavior methods
  3. Existing bug: TableNodeBehavior.get_embeddable_content() returns Some(content) but table is missing from EMBEDDABLE_NODE_TYPES — the dual source of truth problem is already causing issues

This means:

  • Types cannot customize what content gets embedded (e.g., ai-chat extracting messages from properties.messages[])
  • Adding a new embeddable type requires editing TWO places
  • Embedding service bypasses NodeService business rules

Proposed Architecture

Two-Phase Content Extraction (ADR-029)

/// Phase 1: Content from this node alone. Synchronous, no I/O.
/// Returns Some(text) if embeddable, None if not.
fn get_embeddable_content(&self, node: &Node) -> Option<String>;

/// Phase 2: Additional content aggregated from related nodes.
/// Called only when the embedding service is building a composite embedding.
/// Default: None (no aggregation needed). Async, opt-in.
async fn get_aggregated_content(
    &self,
    node: &Node,
    accessor: &dyn NodeAccessor,
) -> Option<String> {
    None  // default: no aggregation
}

/// Content this node contributes to its parent's embedding.
/// Synchronous, no I/O. Unchanged from current trait.
fn get_parent_contribution(&self, node: &Node) -> Option<String>;

Rationale: Most types only need the sync path. Only tree-walking types (text, header) need async aggregation. Keeps the common case fast.

NodeAccessor Trait (new, minimal)

#[async_trait]
pub trait NodeAccessor: Send + Sync {
    async fn get_node(&self, id: &str) -> Result<Option<Node>, NodeServiceError>;
    async fn get_children(&self, id: &str) -> Result<Vec<Node>, NodeServiceError>;
    async fn get_nodes(&self, ids: &[&str]) -> Result<Vec<Node>, NodeServiceError>;
}
  • NodeService implements NodeAccessor
  • get_nodes_in_subtree() excluded — no current behavior needs arbitrary-depth traversal
  • get_nodes() (batch) included for efficient multi-node fetching
  • Read-only — behaviors cannot mutate through this interface
  • Minimal — resist scope creep

SearchScope Enum

pub enum SearchScope {
    /// Default: knowledge nodes (text, header, code-block, schema, table)
    Knowledge,
    /// Include conversations
    Everything,
    /// Only conversations
    Conversations,
    /// Custom type filter
    Custom { include_types: Vec<String>, exclude_types: Vec<String> },
}

Replaces exclude_types parameter approach. More stable as new types are added — callers don't need to know about every type.

Dependency Change

Before:
  NodeEmbeddingService -> SurrealStore (direct)

After:
  NodeEmbeddingService -> NodeService (via NodeAccessor trait)
                               |
                         BehaviorRegistry + SurrealStore

Circular Dependency Prevention

  • NodeService -> EmbeddingWaker (lightweight mpsc channel, not the service)
  • NodeEmbeddingService -> NodeService (via NodeAccessor for reads)
  • No circular reference. Waker pattern already breaks the cycle.

Embedding Service Simplification

pub async fn embed_root_node(&self, root_id: &str) -> Result<(), NodeServiceError> {
    let node = self.node_service.get_node(root_id).await?;
    let behavior = self.node_service.behavior_for(&node.node_type);
    
    // Phase 1: node's own content (sync, no I/O)
    let own_content = behavior.get_embeddable_content(&node);
    if own_content.is_none() {
        self.delete_embeddings(root_id).await?;
        return Ok(());
    }
    
    // Phase 2: aggregated content (async, optional)
    let aggregated = behavior.get_aggregated_content(&node, &*self.node_service).await;
    
    let full_content = match (own_content, aggregated) {
        (Some(own), Some(agg)) => format!("{}\n\n{}", own, agg),
        (Some(own), None) => own,
        _ => return Ok(()),
    };
    
    // Chunk, generate vectors, store (unchanged)
    let chunks = self.chunk_content(&full_content);
    // ...
}

No aggregate_subtree_content(). No is_embeddable_type(). No EMBEDDABLE_NODE_TYPES.

Acceptance Criteria

  • NodeAccessor trait defined with get_node, get_children, get_nodes
  • NodeService implements NodeAccessor
  • get_aggregated_content() added to NodeBehavior trait with default None implementation
  • Text/header behaviors implement get_aggregated_content() to fetch and aggregate children
  • NodeEmbeddingService depends on NodeService (via NodeAccessor), not SurrealStore directly
  • aggregate_subtree_content() removed from embedding service
  • EMBEDDABLE_NODE_TYPES constant and is_embeddable_type() function removed
  • should_embed_root() removed (behavior decides via get_embeddable_content())
  • SearchScope enum implemented in semantic search API
  • MCP search_semantic tool accepts optional scope parameter defaulting to Knowledge
  • table type now correctly embeddable (was excluded from hardcoded list despite behavior returning content)
  • All existing embedding tests pass unchanged
  • New test: mock NodeAccessor, verify behavior controls content extraction
  • Batch processing (10 roots per pass) still works correctly
  • Code passes bun run quality:fix

Technical Specifications

Files to Modify

  • packages/core/src/services/embedding_service.rs — replace SurrealStore with NodeService, remove aggregate_subtree_content(), should_embed_root()
  • packages/core/src/services/embedding_processor.rs — wire NodeService through
  • packages/core/src/behaviors/mod.rs — add get_aggregated_content(), update existing implementations
  • packages/core/src/models/embedding.rs — remove EMBEDDABLE_NODE_TYPES, is_embeddable_type()
  • packages/core/src/services/mod.rs — define NodeAccessor trait
  • packages/core/src/mcp/handlers/search.rs — add SearchScope support
  • Tests referencing removed functions

How Each Type Works After Refactor

Type get_embeddable_content get_aggregated_content get_parent_contribution
text Some(node.content) Fetches children, aggregates Some(node.content)
header Some(node.content) Fetches children, aggregates Some(node.content)
ai-chat Extracts user+assistant from properties.messages[] None None
task None N/A None
date None N/A None
table Some(node.content) (BUG FIX: now actually embedded) None Some(node.content)
collection None N/A None

Batch Processing

Unchanged. Processor still fetches stale root IDs in batches of 10, calls embed_root_node() per root. The behavior handles content extraction instead of the embedding service.

Dependencies

  • None (refactor of existing code)

Related Issues

Activity

  1. changed the title [-]Wire embedding service to use NodeBehavior methods for content extraction[/-] [+]Refactor embedding service to use NodeBehavior via NodeService for content extraction[/+] on Apr 3, 2026
  2. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Baseline: 119 test files, 3748 tests passing

  3. self-assigned this
    on Apr 3, 2026
  4. malibio commented on Apr 3, 2026

    @malibio
    CollaboratorAuthor

    Baseline: 119 test files, 3748 tests passing

  5. added a commit that references this issue on Apr 3, 2026
    3e25350
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