Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311import Database, { Database as DatabaseType } from 'better-sqlite3';import { CONFIG } from '../../config';import type { EmbeddingRecord, SearchResult, SearchOptions } from './types';
export class VectorStore { private db: DatabaseType | null = null; private dimensions: number;
constructor() { this.dimensions = CONFIG.EMBEDDINGS.DIMENSIONS; }
async init(): Promise<void> { this.db = new Database(CONFIG.EMBEDDINGS.DB_PATH);
// Enable WAL mode for better concurrent read performance this.db.pragma('journal_mode = WAL');
// Load sqlite-vec extension const vecPaths = [ '/usr/local/lib/vec0', '/usr/local/lib/vec0.so', '/usr/lib/vec0', '/app/vec0', 'vec0', ];
// Log which paths exist for debugging const fs = await import('fs'); for (const p of vecPaths) { const fullPath = p.endsWith('.so') ? p : `${p}.so`; const exists = fs.existsSync(fullPath); console.log(`[VectorStore] Checking ${fullPath}: ${exists ? 'EXISTS' : 'not found'}`); }
let loaded = false; let lastError = ''; for (const p of vecPaths) { try { this.db.loadExtension(p); loaded = true; console.log(`[VectorStore] Loaded sqlite-vec from ${p}`); break; } catch (err: any) { lastError = err.message; console.log(`[VectorStore] Failed to load ${p}: ${err.message}`); } } if (!loaded) { throw new Error(`Failed to load sqlite-vec extension. Last error: ${lastError}`); }
// Create metadata table this.db.exec(` CREATE TABLE IF NOT EXISTS embedded_records ( id INTEGER PRIMARY KEY AUTOINCREMENT, uri TEXT NOT NULL UNIQUE, did TEXT NOT NULL, collection TEXT NOT NULL, rkey TEXT NOT NULL, cid TEXT, content_hash TEXT NOT NULL, embedded_at TEXT NOT NULL, text_preview TEXT ) `);
this.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedded_uri ON embedded_records(uri)`); this.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedded_did ON embedded_records(did)`); this.db.exec(`CREATE INDEX IF NOT EXISTS idx_embedded_collection ON embedded_records(collection)`);
// Create vector virtual table this.db.exec(` CREATE VIRTUAL TABLE IF NOT EXISTS vec_embeddings USING vec0( record_id INTEGER PRIMARY KEY, embedding float[${this.dimensions}] ) `);
console.log(`[VectorStore] Initialized at ${CONFIG.EMBEDDINGS.DB_PATH} (${this.dimensions}d)`); }
upsert( uri: string, did: string, collection: string, rkey: string, cid: string | null, contentHash: string, textPreview: string, embedding: number[], ): void { if (!this.db) throw new Error('VectorStore not initialized');
const now = new Date().toISOString(); const preview = textPreview.slice(0, 300);
const txn = this.db.transaction(() => { // Check if record already exists const existing = this.db!.prepare('SELECT id FROM embedded_records WHERE uri = ?').get(uri) as | { id: number | bigint } | undefined;
if (existing) { const id = Number(existing.id); // Update metadata this.db!.prepare( `UPDATE embedded_records SET cid = ?, content_hash = ?, embedded_at = ?, text_preview = ? WHERE id = ?`, ).run(cid, contentHash, now, preview, id);
// Update vector — delete + insert (sqlite-vec doesn't support UPDATE on virtual tables) // CAST required: better-sqlite3 binds JS numbers as REAL, but vec0 requires INTEGER PKs this.db!.prepare('DELETE FROM vec_embeddings WHERE record_id = CAST(? AS INTEGER)').run(id); this.db!.prepare('INSERT INTO vec_embeddings (record_id, embedding) VALUES (CAST(? AS INTEGER), ?)').run( id, new Float32Array(embedding), ); } else { // Insert new record const result = this.db!.prepare( `INSERT INTO embedded_records (uri, did, collection, rkey, cid, content_hash, embedded_at, text_preview) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, ).run(uri, did, collection, rkey, cid, contentHash, now, preview);
const recordId = Number(result.lastInsertRowid); this.db!.prepare('INSERT INTO vec_embeddings (record_id, embedding) VALUES (CAST(? AS INTEGER), ?)').run( recordId, new Float32Array(embedding), ); } });
txn(); }
delete(uri: string): boolean { if (!this.db) throw new Error('VectorStore not initialized');
const existing = this.db.prepare('SELECT id FROM embedded_records WHERE uri = ?').get(uri) as | { id: number | bigint } | undefined; if (!existing) return false;
const id = Number(existing.id); const txn = this.db.transaction(() => { this.db!.prepare('DELETE FROM vec_embeddings WHERE record_id = CAST(? AS INTEGER)').run(id); this.db!.prepare('DELETE FROM embedded_records WHERE id = ?').run(id); });
txn(); return true; }
search(queryVector: number[], opts: SearchOptions = {}): SearchResult[] { if (!this.db) throw new Error('VectorStore not initialized');
const limit = Math.min(opts.limit ?? 10, 100); const vecBuffer = new Float32Array(queryVector);
// Build the query with optional filters let filterClauses = ''; const params: any[] = [vecBuffer, limit];
if (opts.collection) { filterClauses += ' AND er.collection = ?'; params.push(opts.collection); } if (opts.did) { filterClauses += ' AND er.did = ?'; params.push(opts.did); }
// sqlite-vec KNN query with join for filtering const sql = ` SELECT er.uri, er.did, er.collection, er.rkey, er.text_preview, ve.distance FROM vec_embeddings ve JOIN embedded_records er ON er.id = ve.record_id WHERE ve.embedding MATCH ? AND k = ?${filterClauses} ORDER BY ve.distance `;
const rows = this.db.prepare(sql).all(...params) as Array<{ uri: string; did: string; collection: string; rkey: string; text_preview: string; distance: number; }>;
return rows.map((row) => ({ ...row, similarity: 1 - row.distance, // Convert distance to similarity score })); }
getEmbedding(uri: string): number[] | null { if (!this.db) throw new Error('VectorStore not initialized');
const record = this.db.prepare('SELECT id FROM embedded_records WHERE uri = ?').get(uri) as | { id: number | bigint } | undefined; if (!record) return null;
const row = this.db .prepare('SELECT embedding FROM vec_embeddings WHERE record_id = CAST(? AS INTEGER)') .get(Number(record.id)) as { embedding: Buffer } | undefined; if (!row) return null;
return Array.from(new Float32Array(row.embedding.buffer)); }
getContentHash(uri: string): string | null { if (!this.db) throw new Error('VectorStore not initialized');
const row = this.db.prepare('SELECT content_hash FROM embedded_records WHERE uri = ?').get(uri) as | { content_hash: string } | undefined; return row?.content_hash ?? null; }
getStatus(): { totalEmbedded: number; collections: { collection: string; count: number }[] } { if (!this.db) throw new Error('VectorStore not initialized');
const total = this.db.prepare('SELECT COUNT(*) as count FROM embedded_records').get() as { count: number };
const collections = this.db .prepare('SELECT collection, COUNT(*) as count FROM embedded_records GROUP BY collection ORDER BY count DESC') .all() as { collection: string; count: number }[];
return { totalEmbedded: total.count, collections, }; }
getAllVectors(opts: { collection?: string; limit?: number; offset?: number } = {}): { records: Array<{ uri: string; did: string; collection: string; rkey: string; text_preview: string }>; vectors: Buffer[]; total: number; } { if (!this.db) throw new Error('VectorStore not initialized');
const limit = Math.min(opts.limit ?? 3000, 10000); const offset = opts.offset ?? 0;
let filterClause = ''; const params: any[] = [];
if (opts.collection) { filterClause = ' WHERE er.collection = ?'; params.push(opts.collection); }
// Get total count const countSql = `SELECT COUNT(*) as count FROM embedded_records er${filterClause}`; const total = (this.db.prepare(countSql).get(...params) as { count: number }).count;
// Get records with their vectors const sql = ` SELECT er.uri, er.did, er.collection, er.rkey, er.text_preview, ve.embedding FROM embedded_records er JOIN vec_embeddings ve ON ve.record_id = er.id ${filterClause} ORDER BY er.id LIMIT ? OFFSET ? `;
const rows = this.db.prepare(sql).all(...params, limit, offset) as Array<{ uri: string; did: string; collection: string; rkey: string; text_preview: string; embedding: Buffer; }>;
return { records: rows.map(({ embedding, ...meta }) => meta), vectors: rows.map(r => r.embedding), total, }; }
getAllEmbeddedUris(): Set<string> { if (!this.db) throw new Error('VectorStore not initialized');
const rows = this.db.prepare('SELECT uri FROM embedded_records').all() as { uri: string }[]; return new Set(rows.map((r) => r.uri)); }
clear(): void { if (!this.db) throw new Error('VectorStore not initialized');
this.db.exec('DELETE FROM vec_embeddings'); this.db.exec('DELETE FROM embedded_records'); console.log('[VectorStore] Cleared all embeddings'); }
close(): void { if (this.db) { this.db.close(); this.db = null; } }}