codescout icon indicating copy to clipboard operation
codescout copied to clipboard

Track sqlite-vec TODO: push cosine similarity into SQLite

Open mareurs opened this issue 9 months ago • 1 comments

What

semantic_search currently loads all embeddings into memory and computes cosine similarity in a pure Rust loop (src/embed/index.rs:249). The sqlite-vec extension is commented out throughout index.rs with multiple TODO markers.

Why it matters

O(n) memory and CPU for every search query. For large codebases (thousands of chunks), this is a meaningful bottleneck. sqlite-vec would push similarity computation into SQLite with proper ANN indexing.

Current state

src/embed/index.rs has TODOs at lines 19, 45, 70, 251:

// TODO: load sqlite-vec extension here
// conn.load_extension("sqlite_vec", None)?;

-- TODO: replace with sqlite-vec virtual table once extension is loaded:
--   USING vec0(embedding float[768]);

/// Naive cosine similarity search (pure Rust fallback, no sqlite-vec).
/// TODO: Replace with sqlite-vec virtual table query for production

Scope

  • Load sqlite_vec extension at connection time (open_db in index.rs)
  • Replace chunk_embeddings plain table with vec0 virtual table
  • Replace Rust cosine loop with vec_distance_cosine SQL query
  • Embeddings stored as little-endian f32 bytes (already the case per line 144)

References

  • rusqlite supports load_extension behind the loadable-extension feature flag
  • sqlite-vec: https://github.com/asg017/sqlite-vec
  • cocoindex-code (inspiration): SQLite + sqlite-vec approach

mareurs avatar Feb 27 '26 15:02 mareurs

This has been implemented. The TODOs mentioned in the issue no longer exist.

What was done:

  • sqlite-vec = "0.1" added to Cargo.toml
  • init_sqlite_vec() registers the extension globally via sqlite3_auto_extension (once per process, behind a Once guard) — called in open_db()
  • search_scoped() uses vec_distance_cosine(vec_f32(ce.embedding), vec_f32(?1)) with ORDER BY distance ASC LIMIT ? pushed entirely into SQLite — no more Rust-side cosine loop

Note: The current implementation calls vec_distance_cosine on a plain BLOB table (chunk_embeddings), not a vec0 virtual table. Search is still O(n) full-scan, just executed inside SQLite rather than in Rust. Migrating to a vec0 virtual table for true ANN indexing would be a separate effort if needed.

mareurs avatar Feb 28 '26 08:02 mareurs