Repository navigation
Description
Problem Statement
The current embedding re-generation system (from #183) uses a 5-second debounce approach that is inefficient for real-world editing workflows:
Problems with Debounce Approach
-
Wastes CPU during active editing
- User types continuously for 10 minutes
- System attempts to re-embed every 5 seconds when user pauses briefly
- Results in multiple redundant re-embedding operations during single edit session
-
Poor collaborative editing support
- Multiple users editing same topic → Multiple separate re-embedding operations
- No batching of concurrent changes
- Each user's pause triggers re-embed
-
Doesn't respect user workflow
- Re-embeds while user is still actively working on the topic
- No way to defer re-embedding until user is "done"
- Battery drain on laptops from constant CPU usage
Industry Best Practices (Notion, Confluence, RAG Systems)
What successful systems do:
- ✅ Content persists immediately (real-time saves)
- ✅ Search indexes/embeddings update asynchronously (lazy/batched)
- ✅ Mark documents as "stale" and reindex during low-activity periods
- ✅ Batch multiple changes together (delta indexing)
Sources:
- Confluence: "Changes automatically saved in real-time" but "embed refreshes every few minutes"
- RAG systems: "Lazy index updates delay reindexing to batch operations"
- Vector DBs: "Incremental indexing - only changes between versions"
Proposed Solution: Stale Flag + Smart Triggers
Replace debounce with a stale tracking system that defers re-embedding until appropriate trigger points.
Architecture Overview
// Core concept: Separate content persistence from embedding updates
// 1. Content saves immediately (no debounce)
on_content_change(node_id, content) {
db.update_content(node_id, content).await; // ✅ <5ms
db.mark_topic_stale(parent_topic_id).await; // ✅ Set flag
}
// 2. Re-embedding happens on smart triggers (not time-based debounce)
enum EmbeddingTrigger {
TopicClosed, // User closes/unfocuses topic
IdleTimeout, // No edits for 30+ seconds
BackgroundBatch, // Periodic job every 5 minutes
ManualSync, // User clicks "sync now"
AppShutdown, // Before app closes
}Implementation Details
1. Database Schema Changes
Update nodes table schema in packages/core/src/db/database.rs:
CREATE TABLE IF NOT EXISTS nodes (
id TEXT PRIMARY KEY,
node_type TEXT NOT NULL,
content TEXT NOT NULL,
parent_id TEXT,
origin_node_id TEXT,
before_sibling_id TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
modified_at DATETIME DEFAULT CURRENT_TIMESTAMP,
properties JSON NOT NULL DEFAULT '{}',
embedding_vector F32_BLOB(384),
-- NEW: Stale tracking columns
embedding_stale BOOLEAN DEFAULT FALSE,
last_content_update DATETIME,
last_embedding_update DATETIME,
FOREIGN KEY (parent_id) REFERENCES nodes(id) ON DELETE CASCADE,
FOREIGN KEY (origin_node_id) REFERENCES nodes(id) ON DELETE CASCADE,
FOREIGN KEY (before_sibling_id) REFERENCES nodes(id) ON DELETE SET NULL
);
-- NEW: Index for efficiently querying stale topics
CREATE INDEX IF NOT EXISTS idx_nodes_stale ON nodes(embedding_stale, node_type);Note: No ALTER TABLE needed - we're in early development, clean state.
2. Content Update Handler (Immediate Persistence)
// In packages/core/src/services/node_service.rs
pub async fn update_node_content(&self, node_id: &str, content: String) -> Result<()> {
let conn = self.db.connect_with_timeout().await?;
// Save content immediately, mark as stale
conn.execute(
"UPDATE nodes
SET content = ?,
modified_at = CURRENT_TIMESTAMP,
embedding_stale = TRUE,
last_content_update = CURRENT_TIMESTAMP
WHERE id = ?",
params![content, node_id]
).await?;
// If this is a section node, mark parent topic as stale too
let parent_id = self.get_parent_topic(node_id).await?;
if let Some(topic_id) = parent_id {
conn.execute(
"UPDATE nodes
SET embedding_stale = TRUE,
last_content_update = CURRENT_TIMESTAMP
WHERE id = ?",
params![topic_id]
).await?;
}
Ok(())
}3. Background Embedding Processor (Single Long-Running Task)
Replace task-per-edit pattern with single background processor:
// In packages/core/src/services/embedding_service.rs
pub struct EmbeddingProcessor {
db: Arc<DatabaseService>,
embedding_service: Arc<TopicEmbeddingService>,
interval: Duration,
}
impl EmbeddingProcessor {
pub fn new(
db: Arc<DatabaseService>,
embedding_service: Arc<TopicEmbeddingService>,
) -> Self {
Self {
db,
embedding_service,
interval: Duration::from_secs(300), // 5 minutes
}
}
/// Start background processor (runs forever)
pub fn start(self: Arc<Self>) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
let mut interval = tokio::time::interval(self.interval);
loop {
interval.tick().await;
if let Err(e) = self.process_stale_topics().await {
eprintln!("Error processing stale topics: {}", e);
}
}
})
}
/// Process all stale topics (prioritized)
async fn process_stale_topics(&self) -> Result<()> {
// Get stale topics ordered by priority
let stale_topics = self.get_prioritized_stale_topics().await?;
for topic_id in stale_topics {
// Re-embed the topic
self.embedding_service.embed_topic(&topic_id).await?;
// Mark as fresh
self.db.connect_with_timeout().await?.execute(
"UPDATE nodes
SET embedding_stale = FALSE,
last_embedding_update = CURRENT_TIMESTAMP
WHERE id = ?",
params![topic_id]
).await?;
}
Ok(())
}
/// Get stale topics with smart prioritization
async fn get_prioritized_stale_topics(&self) -> Result<Vec<String>> {
let conn = self.db.connect_with_timeout().await?;
let mut stmt = conn.prepare(
"SELECT id,
-- Priority score calculation
CASE
-- High priority: Recently viewed (metadata tracking needed)
WHEN json_extract(properties, '$.last_viewed_at') > datetime('now', '-5 minutes') THEN 100
-- Medium priority: Recent edits
WHEN last_content_update > datetime('now', '-10 minutes') THEN 50
-- Low priority: Old edits
ELSE 10
END as priority
FROM nodes
WHERE node_type = 'topic'
AND embedding_stale = TRUE
ORDER BY priority DESC, last_content_update DESC
LIMIT 10" // Process 10 at a time to avoid overload
).await?;
let mut rows = stmt.query(()).await?;
let mut topic_ids = Vec::new();
while let Some(row) = rows.next().await? {
topic_ids.push(row.get::<String>(0)?);
}
Ok(topic_ids)
}
}4. Smart Trigger Points
Implement multiple trigger mechanisms:
// In packages/core/src/services/embedding_service.rs
impl TopicEmbeddingService {
/// Trigger 1: Topic closed/unfocused
pub async fn on_topic_closed(&self, topic_id: &str) -> Result<()> {
let is_stale = self.is_topic_stale(topic_id).await?;
let last_edit = self.get_last_content_update(topic_id).await?;
// Only re-embed if stale AND recently edited (< 5 minutes ago)
if is_stale && last_edit < Duration::from_secs(300) {
self.embed_topic(topic_id).await?;
self.mark_topic_fresh(topic_id).await?;
}
// Otherwise, let background processor handle it
Ok(())
}
/// Trigger 2: Idle timeout (30 seconds of no edits)
pub async fn on_idle_timeout(&self, topic_id: &str) -> Result<()> {
if self.is_topic_stale(topic_id).await? {
self.embed_topic(topic_id).await?;
self.mark_topic_fresh(topic_id).await?;
}
Ok(())
}
/// Trigger 3: Manual sync (user action)
pub async fn sync_all_stale_topics(&self) -> Result<usize> {
let stale_topics = self.get_all_stale_topics().await?;
let count = stale_topics.len();
for topic_id in stale_topics {
self.embed_topic(&topic_id).await?;
self.mark_topic_fresh(&topic_id).await?;
}
Ok(count)
}
/// Trigger 4: App shutdown (critical topics only)
pub async fn on_app_shutdown(&self) -> Result<()> {
// Only sync recently edited topics (last 10 minutes)
let conn = self.db.connect_with_timeout().await?;
let mut stmt = conn.prepare(
"SELECT id FROM nodes
WHERE node_type = 'topic'
AND embedding_stale = TRUE
AND last_content_update > datetime('now', '-10 minutes')"
).await?;
let mut rows = stmt.query(()).await?;
while let Some(row) = rows.next().await? {
let topic_id: String = row.get(0)?;
self.embed_topic(&topic_id).await?;
self.mark_topic_fresh(&topic_id).await?;
}
Ok(())
}
// Helper methods
async fn is_topic_stale(&self, topic_id: &str) -> Result<bool> {
let conn = self.db.connect_with_timeout().await?;
let mut stmt = conn.prepare(
"SELECT embedding_stale FROM nodes WHERE id = ?"
).await?;
let mut rows = stmt.query(params![topic_id]).await?;
if let Some(row) = rows.next().await? {
Ok(row.get::<bool>(0)?)
} else {
Ok(false)
}
}
async fn get_last_content_update(&self, topic_id: &str) -> Result<Duration> {
let conn = self.db.connect_with_timeout().await?;
let mut stmt = conn.prepare(
"SELECT (julianday('now') - julianday(last_content_update)) * 86400 as seconds_ago
FROM nodes WHERE id = ?"
).await?;
let mut rows = stmt.query(params![topic_id]).await?;
if let Some(row) = rows.next().await? {
let seconds: f64 = row.get(0)?;
Ok(Duration::from_secs(seconds as u64))
} else {
Ok(Duration::from_secs(0))
}
}
async fn mark_topic_fresh(&self, topic_id: &str) -> Result<()> {
let conn = self.db.connect_with_timeout().await?;
conn.execute(
"UPDATE nodes
SET embedding_stale = FALSE,
last_embedding_update = CURRENT_TIMESTAMP
WHERE id = ?",
params![topic_id]
).await?;
Ok(())
}
async fn get_all_stale_topics(&self) -> Result<Vec<String>> {
let conn = self.db.connect_with_timeout().await?;
let mut stmt = conn.prepare(
"SELECT id FROM nodes
WHERE node_type = 'topic' AND embedding_stale = TRUE"
).await?;
let mut rows = stmt.query(()).await?;
let mut topics = Vec::new();
while let Some(row) = rows.next().await? {
topics.push(row.get(0)?);
}
Ok(topics)
}
}5. Tauri Command Integration
Add commands for frontend to trigger re-embedding:
// In packages/desktop-app/src-tauri/src/commands/embeddings.rs
#[tauri::command]
pub async fn on_topic_closed(
state: State<'_, AppState>,
topic_id: String,
) -> Result<(), String> {
state
.embedding_service
.on_topic_closed(&topic_id)
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn on_topic_idle(
state: State<'_, AppState>,
topic_id: String,
) -> Result<(), String> {
state
.embedding_service
.on_idle_timeout(&topic_id)
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn sync_embeddings(
state: State<'_, AppState>,
) -> Result<usize, String> {
state
.embedding_service
.sync_all_stale_topics()
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn get_stale_topic_count(
state: State<'_, AppState>,
) -> Result<usize, String> {
state
.embedding_service
.get_all_stale_topics()
.await
.map(|topics| topics.len())
.map_err(|e| e.to_string())
}6. App Initialization
Start background processor on app startup:
// In src-tauri/src/main.rs
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<()> {
// Initialize services
let db = Arc::new(DatabaseService::new(db_path).await?);
let embedding_service = Arc::new(TopicEmbeddingService::new(...));
// Start background embedding processor
let processor = Arc::new(EmbeddingProcessor::new(
Arc::clone(&db),
Arc::clone(&embedding_service),
));
let processor_handle = processor.start();
// Register shutdown handler
let embedding_service_clone = Arc::clone(&embedding_service);
tokio::spawn(async move {
tokio::signal::ctrl_c().await.expect("Failed to listen for ctrl-c");
println!("Shutting down, syncing critical embeddings...");
embedding_service_clone.on_app_shutdown().await.ok();
std::process::exit(0);
});
// Build Tauri app
tauri::Builder::default()
.manage(AppState {
db,
embedding_service,
})
.invoke_handler(tauri::generate_handler![
on_topic_closed,
on_topic_idle,
sync_embeddings,
get_stale_topic_count,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Ok(())
}7. Frontend Integration (Svelte)
Detect user activity and trigger appropriate re-embedding:
<script lang="ts">
import { invoke } from '@tauri-apps/api/tauri';
let topicId: string;
let idleTimer: ReturnType<typeof setTimeout>;
let isEditing = false;
// Track content changes
function onContentChange(content: string) {
isEditing = true;
// Clear existing idle timer
clearTimeout(idleTimer);
// Start new idle timer (30 seconds)
idleTimer = setTimeout(async () => {
await invoke('on_topic_idle', { topicId });
isEditing = false;
}, 30000);
}
// When user closes/navigates away from topic
async function onTopicClose() {
clearTimeout(idleTimer);
await invoke('on_topic_closed', { topicId });
}
// Manual sync button
async function syncEmbeddings() {
const count = await invoke<number>('sync_embeddings');
console.log(`Synced ${count} stale topics`);
}
// Show stale indicator in UI
async function updateStaleCount() {
const count = await invoke<number>('get_stale_topic_count');
// Display badge: "5 topics need indexing"
}
</script>Performance Comparison
Scenario: User edits topic continuously for 10 minutes
Current Debounce Approach (#183):
00:00 - Type paragraph 1
00:05 - Re-embed (5 sec pause)
00:07 - Type paragraph 2
00:12 - Re-embed (5 sec pause)
00:15 - Type paragraph 3
00:20 - Re-embed (5 sec pause)
... repeats ~120 times (10 min / 5 sec)
Result: ~120 re-embedding operations during active editing ❌
Time wasted: ~360ms × 120 = 43 seconds of CPU time
New Stale Flag Approach:
00:00-10:00 - Type continuously (500 words)
- Content saves continuously ✅
- Topic marked STALE once
- NO re-embedding during editing
10:00 - User closes topic or 30 sec idle
10:00 - Re-embed ONCE for all changes ✅
Result: 1 re-embedding operation ✅
Time: ~360ms total (120x improvement!)
Scenario: Collaborative editing (Alice + Bob)
Current Debounce Approach:
Alice edits → Wait 5s → Re-embed
Bob edits → Wait 5s → Re-embed
Alice edits → Wait 5s → Re-embed
Result: 3 separate re-embedding operations
New Stale Flag Approach:
Alice edits → Mark STALE
Bob edits → Already STALE (no-op)
Alice edits → Already STALE (no-op)
30s idle → Re-embed ONCE
Result: 1 re-embedding operation (3x improvement!)
Implementation Checklist
Phase 1: Database Schema (Immediate)
- Update
nodestable schema indatabase.rswith stale tracking columns - Add
idx_nodes_staleindex for efficient queries - Update
seed_core_schemas()to setembedding_stale = FALSEfor initial schemas - Test database initialization with new schema
Phase 2: Core Service Updates
- Update
update_node_content()to mark topics as stale instead of scheduling re-embed - Implement stale tracking helper methods (
is_topic_stale,mark_topic_fresh, etc.) - Remove old debounce logic from Implement Topic Node Embeddings with Adaptive Chunking #183 implementation
- Update metadata tracking in properties JSON
Phase 3: Background Processor
- Implement
EmbeddingProcessorstruct with background task - Add smart prioritization logic (recently viewed > recent edits > old edits)
- Implement graceful shutdown (process critical topics before exit)
- Add configurable batch size (default 10 topics per cycle)
Phase 4: Smart Triggers
- Implement
on_topic_closed()trigger - Implement
on_idle_timeout()trigger (30 seconds) - Implement
sync_all_stale_topics()for manual sync - Implement
on_app_shutdown()for critical topic sync
Phase 5: Tauri Integration
- Add Tauri commands for all triggers
- Add
get_stale_topic_count()for UI indicator - Register commands in main.rs
- Start background processor on app initialization
- Add shutdown handler to sync critical topics
Phase 6: Frontend Integration
- Add idle detection (30 second timer)
- Call
on_topic_closedwhen navigating away - Call
on_topic_idlewhen user pauses for 30 seconds - Add manual "Sync Embeddings" button (optional)
- Add stale topic count indicator in UI (optional)
Phase 7: Testing
- Test immediate content persistence (no data loss)
- Test stale flag marking on content changes
- Test background processor (batch re-embedding)
- Test smart triggers (topic closed, idle, shutdown)
- Test collaborative editing (multiple users, single re-embed)
- Test prioritization (recently viewed topics first)
- Performance test: 10-minute editing session (no CPU churn)
Acceptance Criteria
- Content persists immediately on every edit (<5ms, no debounce)
- Editing continuously for 10 minutes results in 1 re-embed, not 120
- Collaborative editing batches all users' changes into single re-embed
- Background processor runs every 5 minutes, processes up to 10 stale topics
- Topic closed trigger re-embeds recently edited topics immediately
- Idle timeout (30 sec) triggers re-embed if topic is stale
- App shutdown syncs critical topics (edited in last 10 minutes)
- Stale flag accurately tracks which topics need re-embedding
- Prioritization works (recently viewed topics process first)
- No data loss (content always persisted before re-embedding)
- Memory efficient (single background task, not task-per-edit)
- UI shows stale topic count (optional indicator)
Benefits Over Debounce Approach
Performance
- ✅ 120x fewer re-embedding operations during active editing
- ✅ 3x improvement for collaborative editing
- ✅ Better battery life (no constant CPU churn)
User Experience
- ✅ No lag during editing (re-embedding happens when you're done)
- ✅ Instant saves (content never delayed)
- ✅ Smart batching (all edits in session → single re-embed)
Scalability
- ✅ Prioritization (important topics first)
- ✅ Rate limiting (batch size prevents overload)
- ✅ Resource-aware (re-embed during idle periods)
Developer Experience
- ✅ Simpler mental model (stale flag vs. timer juggling)
- ✅ Single background task (easier to debug)
- ✅ Clear trigger points (explicit user actions)
Migration Notes
No migration needed - we're in early development with clean state:
- Database schema updates apply to fresh databases
- No ALTER TABLE required
- No backward compatibility concerns
For future reference: If migration becomes needed later, track schema version:
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO schema_version (version) VALUES (2); -- Stale tracking schemaDependencies
- Depends on: Implement Topic Node Embeddings with Adaptive Chunking #183 (Topic Node Embeddings - base implementation)
Priority
CRITICAL - This addresses fundamental UX and performance issues with the debounce approach. Should be implemented immediately as part of #183 rollout.
References
- Industry best practices: Notion, Confluence (lazy index updates)
- RAG systems: Incremental/delta indexing patterns
- Vector DBs: Stale flag + batch reindexing strategies
- Issue Implement Topic Node Embeddings with Adaptive Chunking #183: Base embedding implementation
Activity
Optimize embedding re-generation with stale flag tracking
Optimize embedding re-generation with stale flag tracking
Address code review feedback for issue #200
Address nitpick/suggestion items from code review
Merge branch 'feature/issue-200-optimize-embedding-regeneration' into…
Optimize embedding re-generation with stale flag tracking
Address code review feedback for issue #200
Address nitpick/suggestion items from code review
Merge branch 'feature/issue-200-optimize-embedding-regeneration' into…
Optimize embedding re-generation with stale flag tracking
Address code review feedback for issue #200
Address nitpick/suggestion items from code review
Merge branch 'feature/issue-200-optimize-embedding-regeneration' into…
Optimize embedding re-generation with stale flag tracking
Address code review feedback for issue #200
Address nitpick/suggestion items from code review
Merge branch 'feature/issue-200-optimize-embedding-regeneration' into…