/** * Vector store operations for semantic search. * * Ports codemem/store/vectors.py — backfill and on-insert vector writes * against the sqlite-vec `memory_vectors` virtual table. * * All functions accept a raw better-sqlite3 Database so they work outside * the MemoryStore class. Embedding is async; callers await then write * synchronously (matches the runtime-topology decision: main thread owns DB). */ import { randomUUID } from "node:crypto"; import type { Statement } from "better-sqlite3"; import type { Database } from "./db.js"; import { isEmbeddingDisabled } from "./db.js"; import { assertEmbeddingClientIdentity, chunkText, DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL, type EmbeddingClient, embedTexts, getEmbeddingClient, getEmbeddingRuntimeStatus, hashText, resolveEmbeddingClientVectorIdentityLabel, resolveEmbeddingModel, serializeFloat32, tryResolveEmbeddingRevision, tryResolveEmbeddingVectorIdentityLabel, } from "./embeddings.js"; import type { OwnershipFilterContext } from "./filters.js"; import { completeMaintenanceJob, getMaintenanceJob, startMaintenanceJob, } from "./maintenance-jobs.js"; import { projectColumnClause } from "./project.js"; import { readCatalog, snapshot, type VectorCatalog, } from "./semantic/validated-vector-index-state.js"; import { buildAuthorizedSemanticMemoryIdsQuery, pendingVectorFreshness, resolveSemanticSearchModelFromCatalog, semanticResult, } from "./semantic-query.js"; import type { ReplicationVectorWork } from "./sync-replication.js"; import type { MemoryFilters } from "./types.js"; import { resolveVectorLayout, vectorStoreExists } from "./vector-layout.js"; import { createVectorMetadataSnapshot, withVectorMetadataSnapshot, } from "./vector-metadata-snapshot.js"; import { ensureVectorWriteModel, prepareVectorWrites } from "./vector-writes.js"; const VECTOR_MODEL_MIGRATION_JOB = "vector_model_migration"; // Keep resolved-client identity separate from migration progress: direct or // partial backfills must not claim that a model cutover completed. const VECTOR_MODEL_IDENTITY_JOB = "vector_model_identity"; const LEGACY_DEFAULT_EMBEDDING_MODEL = "Xenova/bge-small-en-v1.5"; const BACKFILL_MEMORY_PAGE_SIZE = 50; const BACKFILL_INFERENCE_BATCH_SIZE = 32; const BACKFILL_CANDIDATE_TABLE_PREFIX = "codemem_backfill_vector_candidates"; type MemoryTextRow = { id: number; title: string | null; body_text: string | null; created_at?: string; }; type PendingChunk = { text: string; chunkIndex: number; contentHash: string }; type PendingMemory = { memoryId: number; source: VectorSourceRow; chunks: PendingChunk[]; vectors: Float32Array[]; }; type VectorSourceRow = MemoryTextRow & { import_key: string | null; session_id: number; created_at: string; origin_device_id: string | null; rev: number | null; updated_at: string; active: number | null; deleted_at: string | null; }; type BackfillMemoryRow = VectorSourceRow & { snapshot_seq: number }; const VECTOR_SOURCE_COLUMNS = `id, title, body_text, import_key, session_id, created_at, origin_device_id, rev, updated_at, active, deleted_at`; const QUALIFIED_VECTOR_SOURCE_COLUMNS = VECTOR_SOURCE_COLUMNS.split(",") .map((column) => `memory_items.${column.trim()}`) .join(", "); function readVectorSource(db: Database, memoryId: number): VectorSourceRow | undefined { if (!Number.isInteger(memoryId)) return undefined; return db .prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`) .get(memoryId) as VectorSourceRow | undefined; } function currentVectorSourceHashes( saved: VectorSourceRow, current: VectorSourceRow | undefined, ): string[] { // Text equality alone cannot distinguish reuse of a deleted memory's numeric ID. if ( !current || current.import_key !== saved.import_key || current.session_id !== saved.session_id || current.created_at !== saved.created_at || current.origin_device_id !== saved.origin_device_id || current.rev !== saved.rev || current.updated_at !== saved.updated_at || current.active !== saved.active || current.deleted_at !== saved.deleted_at ) { return []; } // Redaction can change text without advancing the revision or update timestamp. return chunkHashes(memoryText(current.title, current.body_text)); } function pendingBackfillMemory(source: VectorSourceRow, chunks: PendingChunk[]): PendingMemory { return { memoryId: source.id, source, chunks, vectors: [] }; } function assertVectorMemoryId(memoryId: number): void { if (!Number.isFinite(memoryId)) throw new TypeError(`Expected finite integer, received ${String(memoryId)}`); if (!Number.isInteger(memoryId)) throw new TypeError(`Expected integer, received ${String(memoryId)}`); } function createBackfillCandidateSnapshot( db: Database, joinClause: string, where: string, params: unknown[], rowLimit: number, ): string { // randomUUID is hex plus hyphens; stripping hyphens keeps this interpolated identifier safe. const tableName = `${BACKFILL_CANDIDATE_TABLE_PREFIX}_${randomUUID().replaceAll("-", "")}`; db.exec(` CREATE TEMP TABLE ${tableName} ( seq INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL ) `); const hasFiniteLimit = Number.isFinite(rowLimit); const limitClause = hasFiniteLimit ? "LIMIT ?" : ""; const snapshotParams = hasFiniteLimit ? [...params, rowLimit] : params; try { db.prepare( `INSERT INTO ${tableName}(memory_id) SELECT memory_items.id FROM memory_items ${joinClause} WHERE ${where} ORDER BY memory_items.created_at ASC, memory_items.id ASC ${limitClause}`, ).run(...snapshotParams); } catch (error) { db.exec(`DROP TABLE IF EXISTS ${tableName}`); throw error; } return tableName; } function deleteBackfillCandidateSnapshot(db: Database, tableName: string): void { db.exec(`DROP TABLE IF EXISTS ${tableName}`); } // Deliberately omits `enforceScopeVisibility` so semantic callers can never // disable the local read boundary — scopeVisibleFilterContext() always forces // it on below. Field list otherwise mirrors OwnershipFilterContext. export type SemanticSearchScopeContext = Omit; function clampSemanticLimit(limit: number): number { if (limit === Number.POSITIVE_INFINITY) return 200; if (!Number.isFinite(limit)) return 1; return Math.min(Math.max(1, Math.trunc(limit)), 200); } /** * The validated vector catalog when it is ready, else null. Its tables mirror every * vector row and keep per-model counts, so reading them is cheaper than scanning the * sqlite-vec table, which reads vector chunks from disk. */ function readyValidatedCatalog(db: Database): VectorCatalog | null { try { const catalog = readCatalog(db); return catalog?.writerVersion === 1 && catalog.status === "ready" ? catalog : null; } catch { return null; } } function listVectorModels(db: Database): Array { if (!vectorStoreExists(db)) { return []; } const catalog = readyValidatedCatalog(db); if (catalog) return catalog.models.map(({ model }) => model); try { const rows = db.prepare("SELECT DISTINCT model FROM memory_vectors").all() as Array<{ model: string | null; }>; // Keep NULL and unknown labels: they must still prevent an unverified // mixed corpus from looking like an exclusively current-model corpus. return rows.map((row) => row.model); } catch { return []; } } function hasVectorRows(db: Database): boolean { if (!vectorStoreExists(db)) return false; try { return db.prepare("SELECT 1 FROM memory_vectors LIMIT 1").get() != null; } catch { return false; } } function tryResolveConfiguredVectorIdentityLabel(db: Database): string | null { for (const jobKind of [VECTOR_MODEL_IDENTITY_JOB, VECTOR_MODEL_MIGRATION_JOB]) { const metadata = (getMaintenanceJob(db, jobKind)?.metadata ?? {}) as Record; const targetModel = tryResolveEmbeddingVectorIdentityLabel({ targetModel: metadata.target_model, requestedModel: metadata.requested_model, requestedRevision: metadata.requested_revision, }); if (targetModel) return targetModel; } return null; } function persistVectorIdentity(db: Database, client: EmbeddingClient, targetModel: string): void { if (!client.identity) { throw new TypeError("Embedding runtime identity is required to persist vector metadata"); } const metadata = { target_model: targetModel, requested_model: client.model, requested_revision: client.identity.requestedRevision ?? client.identity.revision, }; const existing = getMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB); if ( existing?.status === "completed" && existing.metadata?.target_model === metadata.target_model && existing.metadata.requested_model === metadata.requested_model && existing.metadata.requested_revision === metadata.requested_revision ) { return; } startMaintenanceJob(db, { kind: VECTOR_MODEL_IDENTITY_JOB, title: "Embedding vector identity", message: "Recorded the canonical embedding identity used by vector writes", progressTotal: 1, metadata, }); completeMaintenanceJob(db, VECTOR_MODEL_IDENTITY_JOB, { progressCurrent: 1, progressTotal: 1, metadata, }); } export function resolveSemanticSearchModel(db: Database, currentModel?: string): string | null { if (currentModel === undefined) { currentModel = tryResolveConfiguredVectorIdentityLabel(db) ?? undefined; if (currentModel === undefined) return null; } return resolveSemanticSearchModelFromCatalog( currentModel, getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB), listVectorModels(db), ); } /** * Resolve every vector-model label that should be read together for the current * identity. During the compatible legacy-default rebuild this returns both the * legacy label and the revision-aware target so consumers see memories written * under either identity. Returns a single-element list otherwise, or `[]` when * no semantic corpus is currently serviceable. */ export function resolveSemanticSearchModels(db: Database, resolvedModel?: string): string[] { const currentModel = resolvedModel ?? tryResolveConfiguredVectorIdentityLabel(db); if (currentModel == null) return []; // Primary selection and compatible expansion share this call's catalog, // never a cross-search snapshot that could survive a model cutover. const job = getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB); const models = listVectorModels(db); const primaryModel = resolveSemanticSearchModelFromCatalog(currentModel, job, models); return expandSemanticSearchModels(db, primaryModel, currentModel, models); } function expandSemanticSearchModels( db: Database, primaryModel: string | null, currentModel: string, models?: readonly (string | null)[], ): string[] { if (!primaryModel) return []; if ( primaryModel === LEGACY_DEFAULT_EMBEDDING_MODEL && currentModel === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL && (models ?? listVectorModels(db)).includes(currentModel) ) { return [primaryModel, currentModel]; } return [primaryModel]; } function chunkHashes(text: string): string[] { return chunkText(text).map((chunk) => hashText(chunk)); } function memoryText(title: string | null, bodyText: string | null): string { return `${title ?? ""}\n${bodyText ?? ""}`.trim(); } export function memoryHasCompleteVectorCoverage( db: Database, memory: MemoryTextRow, model: string, ): boolean { const expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text)); if (expectedHashes.length === 0) return true; const existingRows = db .prepare("SELECT content_hash FROM memory_vectors WHERE memory_id = ? AND model = ?") .all(memory.id, model) as Array<{ content_hash: string | null }>; return expectedHashesExist(expectedHashes, existingRows); } export function findMemoryIdsWithCompleteActiveVectorCoverage( db: Database, memoryIds: number[], model: string, ): number[] { const ids = uniqueMemoryIds(memoryIds); if (ids.length === 0) return []; const placeholders = ids.map(() => "?").join(", "); const memories = db .prepare( `SELECT id, title, body_text FROM memory_items WHERE active = 1 AND id IN (${placeholders})`, ) .all(...ids) as MemoryTextRow[]; if (memories.length === 0) return ids; // The coverage query reads only these memories' rows for this model, so the // snapshot copies only those instead of the whole vector catalog. const incompleteIds = withVectorMetadataSnapshot( db, (metadata) => { const selectHash = prepareSnapshotHashQuery(metadata); return new Set( memories .filter((memory) => !memoryHasSnapshotCoverage(selectHash, memory, model)) .map((memory) => memory.id), ); }, { memoryIds: memories.map((memory) => memory.id), model }, ); // Missing or inactive memories have no active coverage work and must not // remain queued forever. Their deletion work is tracked separately. return ids.filter((memoryId) => !incompleteIds.has(memoryId)); } function expectedHashesExist( expectedHashes: string[], existingRows: Array<{ content_hash: string | null }>, ): boolean { const existingHashes = new Set( existingRows.map((row) => row.content_hash).filter((hash): hash is string => hash != null), ); return expectedHashSetContains(expectedHashes, existingHashes); } function expectedHashSetContains(expectedHashes: string[], existingHashes: Set): boolean { return expectedHashes.every((hash) => existingHashes.has(hash)); } type SnapshotQuery = Statement; function prepareSnapshotHashQuery(metadata: Database): SnapshotQuery { return metadata.prepare( `SELECT 1 FROM vector_metadata WHERE memory_id = ? AND model = ? AND content_hash = ? LIMIT 1`, ); } function memoryHasSnapshotCoverage( selectHash: SnapshotQuery, memory: MemoryTextRow, model: string, ): boolean { const expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text)); return snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes); } function snapshotHasExpectedHashes( selectHash: SnapshotQuery, memoryId: number, model: string, expectedHashes: string[], ): boolean { return expectedHashes.every((hash) => selectHash.get(memoryId, model, hash) != null); } export function countIncompleteActiveMemoryVectorCoverage( db: Database, model: string, options: { metadata?: Database } = {}, ): number { let incomplete = 0; visitIncompleteActiveMemoryIds(db, model, () => incomplete++, options); return incomplete; } /** Internal repair candidates, using the same current-hash coverage check as cutover. */ export function findIncompleteActiveMemoryIds( db: Database, model: string, options: { metadata?: Database } = {}, ): number[] { const ids: number[] = []; visitIncompleteActiveMemoryIds(db, model, (id) => ids.push(id), options); return ids; } function visitIncompleteActiveMemoryIds( db: Database, model: string, visit: (id: number) => void, options: { metadata?: Database }, ): void { const batchSize = 250; let afterId = 0; let metadata: Database | null = options.metadata ?? null; let selectHash: SnapshotQuery | null = null; // Keep cursor pages on the rowid range; the active/created index requires a sort per page. const selectMemories = db.prepare( `SELECT id, title, body_text FROM memory_items NOT INDEXED WHERE active = 1 AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != '' AND id > ? ORDER BY id ASC LIMIT ? /* vector-coverage-validation */`, ); try { while (true) { const memories = selectMemories.all(afterId, batchSize) as MemoryTextRow[]; if (memories.length === 0) break; if (memories.some((memory) => !Number.isSafeInteger(memory.id))) { throw new RangeError("Vector coverage requires safe integer memory IDs"); } metadata ??= createVectorMetadataSnapshot(db); selectHash ??= prepareSnapshotHashQuery(metadata); for (const memory of memories) { if (!memoryHasSnapshotCoverage(selectHash, memory, model)) visit(memory.id); } afterId = memories.at(-1)?.id ?? afterId; } } finally { if (!options.metadata) metadata?.close(); } } /** Recheck a delete batch under its writer transaction, using one metadata scan. */ export function findMemoryIdsWithCurrentTargetCoverage( db: Database, memoryIds: readonly number[], model: string, ): Set { // Unlike queue IDs, persisted metadata may reference zero or negative IDs. // Reject inexact IDs rather than checking coverage for a rounded memory ID. const ids = [...new Set(memoryIds.filter(Number.isSafeInteger))]; const covered = new Set(ids); if (ids.length === 0) return covered; const memories = db .prepare( `SELECT id, title, body_text FROM memory_items WHERE active = 1 AND id IN (SELECT value FROM json_each(?))`, ) .all(JSON.stringify(ids)) as MemoryTextRow[]; // Missing/inactive memories need no target coverage before removing fallback rows. if (memories.length === 0) return covered; return withVectorMetadataSnapshot( db, (metadata) => { const selectHash = prepareSnapshotHashQuery(metadata); for (const memory of memories) { if (!memoryHasSnapshotCoverage(selectHash, memory, model)) covered.delete(memory.id); } return covered; }, { memoryIds: memories.map((memory) => memory.id), model }, ); } /** * Prune from the same catalog later used for cutover coverage and exact equality. * Only our successful deletes alter it: an external deletion must fail equality. */ type CatalogVectorRow = { rowid: number; memory_id: number | null; model: string; content_hash: string | null; }; type CatalogPruneOptions = { signal?: AbortSignal; pruneScope?: "all" | "active-only" }; function catalogPruneCandidates( db: Database, rows: CatalogVectorRow[], options: CatalogPruneOptions, ): CatalogVectorRow[] { const expectedByMemory = new Map | null>(); const selectMemory = db.prepare("SELECT title, body_text, active FROM memory_items WHERE id = ?"); return rows.filter((row) => { if (!expectedByMemory.has(row.memory_id)) { const memory = selectMemory.get(row.memory_id) as | (MemoryTextRow & { active: number }) | undefined; const expected = memory?.active === 1 ? new Set(chunkHashes(memoryText(memory.title, memory.body_text))) : null; expectedByMemory.set(row.memory_id, expected); } const expected = expectedByMemory.get(row.memory_id); if (options.pruneScope === "active-only" && expected == null) return false; return !expected?.has(row.content_hash ?? ""); }); } function deleteCatalogPruneCandidates( db: Database, rows: CatalogVectorRow[], model: string, options: CatalogPruneOptions, ): number[] { const { signal } = options; const selectCurrent = db.prepare( "SELECT rowid, memory_id, model, content_hash FROM memory_vectors WHERE rowid = ?", ); const write = prepareVectorWrites(db); return db .transaction(() => { // Re-read bodies and metadata after acquiring the writer lock. A candidate // may now be a current chunk, or its memory may have lost target coverage. const currentRows = rows.filter((row) => { if (signal?.aborted) return false; const current = selectCurrent.get(row.rowid) as CatalogVectorRow | undefined; return sameCatalogVectorRow(row, current); }); if (signal?.aborted) return []; const obsolete = catalogPruneCandidates(db, currentRows, options); const coverage = findMemoryIdsWithCurrentTargetCoverage( db, obsolete.flatMap((row) => (row.memory_id === null ? [] : [row.memory_id])), model, ); const ids: number[] = []; for (const row of obsolete) { if (signal?.aborted) break; const covered = row.memory_id === null || coverage.has(row.memory_id); if (covered) ids.push(row.rowid); } return write({ deleteRowIds: ids, signal }).deletedRowIds; }) .immediate(); } function sameCatalogVectorRow( saved: CatalogVectorRow, current: CatalogVectorRow | undefined, ): boolean { return ( current !== undefined && current.memory_id === saved.memory_id && current.model === saved.model && current.content_hash === saved.content_hash ); } export function pruneObsoleteTargetVectorsFromCatalog( db: Database, model: string, metadata: Database, options: CatalogPruneOptions = {}, ): number { const selectPage = metadata.prepare( "SELECT rowid, memory_id, model, content_hash FROM vector_metadata WHERE model = ? AND (? IS NULL OR rowid > ?) ORDER BY rowid LIMIT 250", ); const forgetRow = metadata.prepare("DELETE FROM vector_metadata WHERE rowid = ?"); let cursor: number | null = null; let deleted = 0; while (!options.signal?.aborted) { const rows = selectPage.all(model, cursor, cursor) as CatalogVectorRow[]; if (rows.length === 0) break; const obsolete = catalogPruneCandidates(db, rows, options); const deletedIds = obsolete.length === 0 ? [] : deleteCatalogPruneCandidates(db, obsolete, model, options); metadata.transaction(() => { for (const rowid of deletedIds) forgetRow.run(rowid); })(); deleted += deletedIds.length; cursor = rows.at(-1)?.rowid ?? cursor; } return deleted; } function hasMemoryVectorRowidsShadowTable(db: Database): boolean { const layout = resolveVectorLayout(db); if (layout.kind === "absent") return false; const tables = db.prepare("PRAGMA table_list").all() as Array<{ name: string }>; return tables.some((table) => table.name === layout.rowidsName); } function vectorRowidsTable(db: Database): "memory_vectors_rowids" | "memory_vectors_v1_rowids" { const layout = resolveVectorLayout(db); if (layout.kind === "absent") throw new Error("vector_table_required"); return layout.rowidsName; } type TargetVectorRow = { rowid: number; memory_id: number; content_hash: string | null; }; type TargetVectorCoverageState = { expectedHashes: string[]; expected: Set; existing: Set; }; function collectTargetVectorRows( db: Database, model: string, batchSize: number, signal?: AbortSignal, ): boolean { const selectRowIds = db.prepare( `SELECT rowid FROM ${vectorRowidsTable(db)} WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-rowids */`, ); const selectMetadata = db.prepare( "SELECT memory_id, content_hash, model FROM memory_vectors WHERE rowid = ?", ); const insertScanRow = db.prepare( "INSERT INTO temp.vector_prune_scan(rowid, memory_id, content_hash) VALUES (?, ?, ?) /* vector-target-prune-spill */", ); const insertScanPage = db.transaction((rows: TargetVectorRow[]) => { for (const row of rows) insertScanRow.run(row.rowid, row.memory_id, row.content_hash); }); let afterRowId = 0; while (!signal?.aborted) { const rowIds = selectRowIds.all(afterRowId, batchSize) as Array<{ rowid: number }>; if (signal?.aborted) return false; if (rowIds.length === 0) return true; const targetRows: TargetVectorRow[] = []; for (const { rowid } of rowIds) { if (signal?.aborted) return false; const metadata = selectMetadata.get(rowid) as | { memory_id: number; content_hash: string | null; model: string } | undefined; if (!metadata || metadata.model !== model) continue; targetRows.push({ rowid, memory_id: metadata.memory_id, content_hash: metadata.content_hash, }); } if (signal?.aborted) return false; insertScanPage.deferred(targetRows); afterRowId = rowIds.at(-1)?.rowid ?? afterRowId; if (rowIds.length < batchSize) return true; } return false; } function visitTargetVectorRowsForMemories( db: Database, memoryIds: number[], batchSize: number, visit: (rows: TargetVectorRow[]) => void, signal?: AbortSignal, ): boolean { if (memoryIds.length === 0) return true; const placeholders = memoryIds.map(() => "?").join(", "); const selectRows = db.prepare( `SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan WHERE memory_id IN (${placeholders}) AND rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-page */`, ); let afterRowId = 0; while (!signal?.aborted) { const rows = selectRows.all(...memoryIds, afterRowId, batchSize) as TargetVectorRow[]; if (signal?.aborted) return false; if (rows.length === 0) return true; visit(rows); afterRowId = rows.at(-1)?.rowid ?? afterRowId; if (rows.length < batchSize) return true; } return false; } function deleteVectorRows(db: Database, rowIds: number[]): number { const write = prepareVectorWrites(db); return db.transaction(() => write({ deleteRowIds: rowIds }).deleted).immediate(); } function createTargetVectorCoverageStates( memories: MemoryTextRow[], ): Map { return new Map( memories.map((memory): [number, TargetVectorCoverageState] => { const expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text)); return [ memory.id, { expectedHashes, expected: new Set(expectedHashes), existing: new Set() }, ]; }), ); } function summarizeTargetVectorCoverage(states: Map): { coveredMemoryIds: number[]; incomplete: number; } { const coveredMemoryIds: number[] = []; let incomplete = 0; for (const [memoryId, state] of states) { if (!expectedHashSetContains(state.expectedHashes, state.existing)) incomplete++; else coveredMemoryIds.push(memoryId); } return { coveredMemoryIds, incomplete }; } function pruneCoveredTargetVectorRows( db: Database, states: Map, memoryIds: number[], batchSize: number, signal?: AbortSignal, ): { completed: boolean; deleted: number } { let deleted = 0; const completed = visitTargetVectorRowsForMemories( db, memoryIds, batchSize, (rows) => { const obsolete = rows .filter((row) => { const expected = states.get(row.memory_id)?.expected; return row.content_hash == null || !expected?.has(row.content_hash); }) .map((row) => row.rowid); if (obsolete.length > 0) deleted += deleteVectorRows(db, obsolete); }, signal, ); return { completed, deleted }; } function pruneActiveMemoryPage( db: Database, memories: MemoryTextRow[], batchSize: number, signal?: AbortSignal, ): { completed: boolean; deleted: number; incomplete: number } { const states = createTargetVectorCoverageStates(memories); const memoryIds = memories.map((memory) => memory.id); const covered = visitTargetVectorRowsForMemories( db, memoryIds, batchSize, (rows) => { for (const row of rows) { const state = states.get(row.memory_id); if (row.content_hash != null && state?.expected.has(row.content_hash)) { state.existing.add(row.content_hash); } } }, signal, ); if (!covered) return { completed: false, deleted: 0, incomplete: 0 }; const coverage = summarizeTargetVectorCoverage(states); const pruned = pruneCoveredTargetVectorRows( db, states, coverage.coveredMemoryIds, batchSize, signal, ); if (!pruned.completed) { return { completed: false, deleted: pruned.deleted, incomplete: coverage.incomplete }; } const placeholders = memoryIds.map(() => "?").join(", "); db.prepare(`DELETE FROM temp.vector_prune_scan WHERE memory_id IN (${placeholders})`).run( ...memoryIds, ); return { completed: true, deleted: pruned.deleted, incomplete: coverage.incomplete }; } function pruneRemainingTargetVectorRows( db: Database, batchSize: number, signal?: AbortSignal, ): { completed: boolean; deleted: number } { const selectRows = db.prepare( `SELECT rowid, memory_id, content_hash FROM temp.vector_prune_scan WHERE rowid > ? ORDER BY rowid ASC LIMIT ? /* vector-target-prune-spill-remainder */`, ); let afterRowId = 0; let deleted = 0; while (!signal?.aborted) { const rows = selectRows.all(afterRowId, batchSize) as TargetVectorRow[]; if (signal?.aborted) return { completed: false, deleted }; if (rows.length === 0) return { completed: true, deleted }; deleted += deleteVectorRows( db, rows.map((row) => row.rowid), ); afterRowId = rows.at(-1)?.rowid ?? afterRowId; if (rows.length < batchSize) return { completed: true, deleted }; } return { completed: false, deleted }; } function pruneTargetVectorRowsFromShadowTable( db: Database, model: string, options: { signal?: AbortSignal }, ): { deleted: number; incompleteActiveCoverage: number | null } { const batchSize = 250; // The connection defaults to temp_store=MEMORY, which would keep the spill // resident in SQLite's heap and leave peak memory O(total vectors). Force it // to disk for the prune so the bound is genuinely one page. temp_store cannot // change while temp tables exist, so this must bracket the CREATE/DROP. const previousTempStore = readTempStore(db); db.pragma("temp_store = FILE"); try { return pruneTargetVectorRowsWithSpill(db, model, batchSize, options.signal); } finally { db.pragma(`temp_store = ${previousTempStore}`); } } function readTempStore(db: Database): number { const value = db.pragma("temp_store", { simple: true }); return typeof value === "number" ? value : 0; } function pruneTargetVectorRowsWithSpill( db: Database, model: string, batchSize: number, signal: AbortSignal | undefined, ): { deleted: number; incompleteActiveCoverage: number | null } { const options = { signal }; db.exec(`CREATE TEMP TABLE IF NOT EXISTS vector_prune_scan ( rowid INTEGER PRIMARY KEY, memory_id INTEGER NOT NULL, content_hash TEXT )`); try { db.exec( "CREATE INDEX IF NOT EXISTS temp.vector_prune_scan_memory_id_idx ON vector_prune_scan(memory_id)", ); db.exec("DELETE FROM temp.vector_prune_scan"); if (!collectTargetVectorRows(db, model, batchSize, options.signal)) { return { deleted: 0, incompleteActiveCoverage: null }; } const selectMemories = db.prepare( `SELECT id, title, body_text FROM memory_items WHERE active = 1 AND id > ? ORDER BY id ASC LIMIT ?`, ); let afterMemoryId = 0; let deleted = 0; let incompleteActiveCoverage = 0; while (!options.signal?.aborted) { const memories = selectMemories.all(afterMemoryId, batchSize) as MemoryTextRow[]; if (memories.length === 0) break; const result = pruneActiveMemoryPage(db, memories, batchSize, options.signal); deleted += result.deleted; if (!result.completed) return { deleted, incompleteActiveCoverage: null }; incompleteActiveCoverage += result.incomplete; afterMemoryId = memories.at(-1)?.id ?? afterMemoryId; } if (options.signal?.aborted) return { deleted, incompleteActiveCoverage: null }; const remaining = pruneRemainingTargetVectorRows(db, batchSize, options.signal); deleted += remaining.deleted; return { deleted, incompleteActiveCoverage: remaining.completed ? incompleteActiveCoverage : null, }; } finally { db.exec("DROP TABLE IF EXISTS temp.vector_prune_scan"); } } function pruneTargetVectorRowsWithLegacyScan( db: Database, model: string, options: { signal?: AbortSignal }, ): number { const batchSize = 250; let afterRowId = 0; let deleted = 0; const selectBatch = db.prepare( `SELECT mv.rowid AS rowid, mv.memory_id AS memory_id, mv.content_hash AS content_hash, mi.title AS title, mi.body_text AS body_text, mi.active AS active FROM memory_vectors mv LEFT JOIN memory_items mi ON mi.id = mv.memory_id WHERE mv.model = ? AND mv.rowid > ? ORDER BY mv.rowid ASC LIMIT ?`, ); const write = prepareVectorWrites(db); while (!options.signal?.aborted) { const rows = selectBatch.all(model, afterRowId, batchSize) as Array< TargetVectorRow & { title: string | null; body_text: string | null; active: number | null } >; if (rows.length === 0) break; const obsoleteRowIds: number[] = []; const expectedByMemory = new Map>(); const coverageByMemory = new Map(); for (const row of rows) { if (row.active == null || row.active === 0) { obsoleteRowIds.push(row.rowid); continue; } let covered = coverageByMemory.get(row.memory_id); if (covered === undefined) { covered = memoryHasCompleteVectorCoverage( db, { id: row.memory_id, title: row.title, body_text: row.body_text }, model, ); coverageByMemory.set(row.memory_id, covered); } if (!covered) continue; const expected = expectedByMemory.get(row.memory_id) ?? new Set(chunkHashes(memoryText(row.title, row.body_text))); expectedByMemory.set(row.memory_id, expected); if (row.content_hash == null || !expected.has(row.content_hash)) { obsoleteRowIds.push(row.rowid); } } deleted += db.transaction(() => write({ deleteRowIds: obsoleteRowIds }).deleted).immediate(); afterRowId = rows.at(-1)?.rowid ?? afterRowId; } return deleted; } /** * Delete target-model vector rows whose content_hash is not part of their * memory's current chunk set. Coverage is a subset check, so a memory can be * "covered" while still retaining obsolete target rows — e.g. an interrupted * migration, or a title/body edit (like `codemem db scan-secrets` redaction) * without vector maintenance. Because semanticSearch ranks by MIN(distance) * across a memory's rows, those stale rows would keep pre-edit or redacted * content influencing recall after cutover. Incomplete memories are left * untouched so their current rows can still be repaired safely. Returns the * number of rows removed. */ export function pruneObsoleteTargetModelVectors( db: Database, model: string, options: { signal?: AbortSignal } = {}, ): number { return pruneObsoleteTargetModelVectorsWithCoverage(db, model, options).deleted; } export function pruneObsoleteTargetModelVectorsWithCoverage( db: Database, model: string, options: { signal?: AbortSignal } = {}, ): { deleted: number; incompleteActiveCoverage: number | null } { if (!hasMemoryVectorRowidsShadowTable(db)) { return { deleted: pruneTargetVectorRowsWithLegacyScan(db, model, options), incompleteActiveCoverage: null, }; } return pruneTargetVectorRowsFromShadowTable(db, model, options); } // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface BackfillVectorsResult { checked: number; embedded: number; inserted: number; skipped: number; } export interface BackfillVectorsOptions { limit?: number | null; since?: string | null; project?: string | null; activeOnly?: boolean; dryRun?: boolean; memoryIds?: number[] | null; /** * When provided, backfill stops between inference batches. The in-flight * batch finishes, and any memory with only partial output remains unwritten. * Used by the viewer serve shutdown sequence to bound SIGTERM latency. */ signal?: AbortSignal; /** Use an already-resolved client so vectors and their persisted label cannot diverge. */ client?: EmbeddingClient; } export interface ReplicationVectorMaintenanceResult { deleted: number; inserted: number; errors: string[]; } export type SemanticIndexState = "healthy" | "pending" | "failed" | "degraded" | "disabled"; export interface SemanticIndexDiagnostics { state: SemanticIndexState; summary: string; mode: "semantic" | "keyword_only"; current_model: string; semantic_search_model: string | null; embeddable_memory_count: number; indexed_memory_count: number; pending_memory_count: number; maintenance_job: { status: "pending" | "running" | "failed" | "completed" | "cancelled"; message: string | null; error: string | null; progress_current: number; progress_total: number | null; } | null; } export interface SemanticIndexDiagnosticsOptions { /** * Default true — runs a single indexed COUNT(DISTINCT) join. The slow * alternative does a vec0 probe per memory row, which blocks the event * loop; only set to false from non-request-path tooling that needs * per-chunk coverage precision. */ fastCounts?: boolean; } function traceSemanticDiag(label: string, fn: () => T): T { if (process.env.CODEMEM_TRACE_SEMANTIC_DIAGNOSTICS !== "1") return fn(); const startedAt = Date.now(); console.warn(`[codemem semantic] ${label} start`); try { return fn(); } finally { console.warn(`[codemem semantic] ${label} ${Date.now() - startedAt}ms`); } } function countEmbeddableActiveMemories(db: Database): number { const row = db .prepare( `SELECT COUNT(*) AS c FROM memory_items WHERE active = 1 AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''`, ) .get() as { c?: number } | undefined; return Number(row?.c ?? 0); } /** * `memory_vectors` is a sqlite-vec virtual table. Querying it requires the * `vec0` module to be loaded into the active connection — a different * concern from the table merely existing in the schema. On platforms where * sqlite-vec failed to load (e.g. Linux ARM64 without the matching * platform package), the table can persist from a previous run while the * module is gone, so a JOIN crashes with `SQLITE_ERROR: no such module: * vec0`. Diagnostic counters must treat that case as "0 indexed", same as * the explicit `CODEMEM_EMBEDDING_DISABLED` path, instead of throwing. */ function isVecModuleMissingError(error: unknown): boolean { if (!(error instanceof Error)) return false; const message = error.message ?? ""; return /no such module:\s*vec0/i.test(message); } function countIndexedActiveMemories(db: Database, models: string[]): number { if (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0; let rows: MemoryTextRow[]; try { rows = db .prepare( `SELECT id, title, body_text FROM memory_items WHERE active = 1 AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != '' ORDER BY id ASC`, ) .all() as MemoryTextRow[]; } catch (error) { if (isVecModuleMissingError(error)) return 0; throw error; } try { return withVectorMetadataSnapshot(db, (metadata) => { const selectHash = prepareSnapshotHashQuery(metadata); return rows.filter((row) => models.some((model) => memoryHasSnapshotCoverage(selectHash, row, model)), ).length; }); } catch (error) { if (isVecModuleMissingError(error)) return 0; throw error; } } /** * Active memories with text that have no vector under `model`, oldest first. The * vector catch-up uses this to repair memories whose queued vector work was lost. */ export function findActiveMemoriesMissingVectors( db: Database, model: string, limit: number, /** Memories to leave out before the limit applies, such as ones already queued. */ excludeMemoryIds: Iterable = [], ): number[] { if (isEmbeddingDisabled() || !vectorStoreExists(db)) return []; const vectorRows = readyValidatedCatalog(db) ? "SELECT 1 FROM validated_vector_rows v WHERE v.memory_id = mi.id AND v.model = ?" : "SELECT 1 FROM memory_vectors v WHERE v.memory_id = mi.id AND v.model = ?"; try { return db .prepare( `SELECT mi.id FROM memory_items mi WHERE mi.active = 1 AND TRIM(COALESCE(mi.title, '') || COALESCE(mi.body_text, '')) != '' AND NOT EXISTS (${vectorRows}) AND mi.id NOT IN (SELECT value FROM json_each(?)) ORDER BY mi.id LIMIT ?`, ) .pluck() .all( model, JSON.stringify([...excludeMemoryIds]), Math.max(1, Math.trunc(limit)), ) as number[]; } catch (error) { if (isVecModuleMissingError(error)) return []; throw error; } } function countIndexedActiveMemoriesFast(db: Database, models: string[]): number { if (isEmbeddingDisabled() || !vectorStoreExists(db)) return 0; const placeholders = models.map(() => "?").join(", "); if (readyValidatedCatalog(db)) { const row = db .prepare( `SELECT COUNT(*) AS c FROM memory_items mi WHERE mi.active = 1 AND TRIM(COALESCE(mi.title, '') || COALESCE(mi.body_text, '')) != '' AND EXISTS ( SELECT 1 FROM validated_vector_rows v WHERE v.memory_id = mi.id AND v.model IN (${placeholders}) )`, ) .get(...models) as { c?: number } | undefined; return Number(row?.c ?? 0); } try { const row = db .prepare( `SELECT COUNT(DISTINCT mi.id) AS c FROM memory_items mi JOIN memory_vectors mv ON mv.memory_id = mi.id WHERE mi.active = 1 AND mv.model IN (${placeholders}) AND TRIM(COALESCE(mi.title, '') || COALESCE(mi.body_text, '')) != ''`, ) .get(...models) as { c?: number } | undefined; return Number(row?.c ?? 0); } catch (error) { if (isVecModuleMissingError(error)) return 0; throw error; } } function resolvePendingMemoryCount( fallbackPendingCount: number, job: ReturnType, ): number { if (!(job?.status === "pending" || job?.status === "running" || job?.status === "failed")) { return fallbackPendingCount; } const metadata = job?.metadata ?? {}; const total = Number(metadata.embeddable_total ?? job?.progress.total ?? Number.NaN); const processed = Number(metadata.processed_embeddable ?? job?.progress.current ?? Number.NaN); if (Number.isFinite(total) && Number.isFinite(processed)) { return Math.max(total - processed, 0); } return fallbackPendingCount; } /** A coverage gap with no catch-up running: memories that have no vectors yet. */ function missingVectorsSummary(count: number): string { const noun = count === 1 ? "memory has" : "memories have"; return `${count} ${noun} no vectors yet; background catch-up adds them`; } function summarizeSemanticIndexState( state: SemanticIndexState, counts: { embeddable: number; indexed: number; pending: number }, job: ReturnType, runtimeUnavailable: boolean, ): string { if (state === "failed") { return job?.error ?? job?.message ?? "Semantic-index catch-up failed"; } if (state === "disabled") { return "Semantic search is off because embeddings are disabled; keyword search remains available"; } if (state === "degraded") { if (runtimeUnavailable) { return "The embedding runtime is unavailable; sync data is available in keyword-only mode"; } return "Semantic-index coverage is unavailable; sync data is effectively running in keyword-only mode"; } if (state === "pending") { const jobActive = job?.status === "pending" || job?.status === "running"; const jobMessage = jobActive ? job?.message : null; return jobMessage ?? missingVectorsSummary(counts.pending); } if (counts.embeddable === 0) { return "No embeddable memories need semantic indexing"; } return `Semantic index is current for ${counts.indexed} embeddable mem${counts.indexed === 1 ? "ory" : "ories"}`; } function resolveSemanticIndexState(options: { embeddingsDisabled: boolean; embeddingRevisionMissing: boolean; identityLabelUnresolved: boolean; jobStatus: NonNullable>["status"] | undefined; activeCatchUp: boolean; degraded: boolean; pendingMemoryCount: number; }): SemanticIndexState { // Disabled embeddings also stop the catch-up runner, so a queued job would // otherwise read as pending forever. if (options.embeddingsDisabled) return "disabled"; if (options.embeddingRevisionMissing) return "degraded"; if (options.jobStatus === "failed") return "failed"; if (options.identityLabelUnresolved) return "pending"; if (options.activeCatchUp) return "pending"; if (options.degraded) return "degraded"; if (options.pendingMemoryCount > 0) return "pending"; return "healthy"; } function resolveSemanticRuntime(db: Database): { embeddingModel: string; embeddingRevision: string | null; currentModel: string; semanticSearchModel: string | null; embeddingsDisabled: boolean; runtimeUnavailable: boolean; embeddingRevisionMissing: boolean; identityLabelUnresolved: boolean; } { const embeddingModel = traceSemanticDiag("resolveEmbeddingModel", () => resolveEmbeddingModel()); const embeddingRevision = traceSemanticDiag("tryResolveEmbeddingRevision", () => tryResolveEmbeddingRevision(embeddingModel), ); const resolvedCurrentModel = traceSemanticDiag("tryResolveConfiguredVectorIdentityLabel", () => tryResolveConfiguredVectorIdentityLabel(db), ); const embeddingRevisionMissing = embeddingRevision == null; const identityLabelUnresolved = !embeddingRevisionMissing && resolvedCurrentModel == null; const currentModel = resolvedCurrentModel ?? (embeddingRevision == null ? `${embeddingModel} (missing CODEMEM_EMBEDDING_REVISION)` : `${embeddingModel}@${embeddingRevision} (revision unresolved)`); const semanticSearchModel = embeddingRevisionMissing || identityLabelUnresolved ? null : traceSemanticDiag("resolveSemanticSearchModel", () => resolveSemanticSearchModel(db, currentModel), ); const embeddingsDisabled = traceSemanticDiag("isEmbeddingDisabled", () => isEmbeddingDisabled()); const runtimeUnavailable = getEmbeddingRuntimeStatus().state === "unavailable"; return { embeddingModel, embeddingRevision, currentModel, semanticSearchModel, embeddingsDisabled, runtimeUnavailable, embeddingRevisionMissing, identityLabelUnresolved, }; } function collectSemanticIndexCounts( db: Database, coverageModels: string[], fastCounts: boolean, ): { embeddableMemoryCount: number; indexedMemoryCount: number } { const embeddableMemoryCount = traceSemanticDiag("countEmbeddableActiveMemories", () => countEmbeddableActiveMemories(db), ); const indexedMemoryCount = traceSemanticDiag( fastCounts ? "countIndexedActiveMemoriesFast" : "countIndexedActiveMemories", () => fastCounts ? countIndexedActiveMemoriesFast(db, coverageModels) : countIndexedActiveMemories(db, coverageModels), ); return { embeddableMemoryCount, indexedMemoryCount }; } type SemanticRuntime = ReturnType; function collectSemanticCoverage( db: Database, runtime: SemanticRuntime, fastCounts: boolean, ): { embeddableMemoryCount: number; indexedMemoryCount: number } { if (runtime.embeddingRevisionMissing || runtime.identityLabelUnresolved) { const embeddableMemoryCount = traceSemanticDiag("countEmbeddableActiveMemories", () => countEmbeddableActiveMemories(db), ); return { embeddableMemoryCount, indexedMemoryCount: 0 }; } // Count coverage under the same model labels search reads, so a corpus // served from compatible legacy vectors is not reported as unindexed. const searchModels = expandSemanticSearchModels( db, runtime.semanticSearchModel, runtime.currentModel, ); return collectSemanticIndexCounts( db, searchModels.length > 0 ? searchModels : [runtime.currentModel], fastCounts, ); } function describeSemanticIndex( state: SemanticIndexState, runtime: SemanticRuntime, counts: { embeddable: number; indexed: number; pending: number }, job: ReturnType, ): string { if (state !== "disabled" && runtime.embeddingRevisionMissing) { return `Semantic search is unavailable because ${runtime.embeddingModel} has no CODEMEM_EMBEDDING_REVISION; keyword search remains available`; } if (state !== "disabled" && runtime.identityLabelUnresolved) { return `Semantic indexing is pending until ${runtime.embeddingModel}@${runtime.embeddingRevision} resolves to a canonical commit`; } return summarizeSemanticIndexState(state, counts, job, runtime.runtimeUnavailable); } export function getSemanticIndexDiagnostics( db: Database, options: SemanticIndexDiagnosticsOptions = {}, ): SemanticIndexDiagnostics { const runtime = resolveSemanticRuntime(db); const { currentModel, semanticSearchModel, embeddingsDisabled, runtimeUnavailable, embeddingRevisionMissing, identityLabelUnresolved, } = runtime; const { embeddableMemoryCount, indexedMemoryCount } = collectSemanticCoverage( db, runtime, options.fastCounts !== false, ); const fallbackPendingCount = Math.max(embeddableMemoryCount - indexedMemoryCount, 0); const job = traceSemanticDiag("getMaintenanceJob", () => getMaintenanceJob(db, VECTOR_MODEL_MIGRATION_JOB), ); const pendingMemoryCount = resolvePendingMemoryCount(fallbackPendingCount, job); const degraded = embeddingRevisionMissing || (embeddableMemoryCount > 0 && (embeddingsDisabled || runtimeUnavailable || semanticSearchModel == null)); const state = resolveSemanticIndexState({ embeddingsDisabled, embeddingRevisionMissing, identityLabelUnresolved, jobStatus: job?.status, activeCatchUp: job?.status === "pending" || job?.status === "running", degraded, pendingMemoryCount, }); const summary = describeSemanticIndex( state, runtime, { embeddable: embeddableMemoryCount, indexed: indexedMemoryCount, pending: pendingMemoryCount }, job, ); return { state, summary, mode: embeddingsDisabled || runtimeUnavailable || !semanticSearchModel ? "keyword_only" : "semantic", current_model: currentModel, semantic_search_model: semanticSearchModel, embeddable_memory_count: embeddableMemoryCount, indexed_memory_count: indexedMemoryCount, pending_memory_count: pendingMemoryCount, maintenance_job: job ? { status: job.status, message: job.message, error: job.error, progress_current: job.progress.current, progress_total: job.progress.total, } : null, }; } function uniqueMemoryIds(memoryIds: number[]): number[] { return [...new Set(memoryIds.filter((memoryId) => Number.isInteger(memoryId) && memoryId > 0))]; } function deleteVectorsForMemoryIds(db: Database, memoryIds: number[]): number { if (!vectorStoreExists(db) || memoryIds.length === 0) return 0; const write = prepareVectorWrites(db); return db.transaction(() => write({ deleteMemoryIds: memoryIds }).deleted).immediate(); } function prepareSnapshotPruneQueries(metadata: Database, rowIds: number[]) { return { selectHash: prepareSnapshotHashQuery(metadata), selectRows: metadata.prepare( "SELECT rowid, model, content_hash FROM vector_metadata WHERE memory_id = ? AND model IN (?, ?)", ), rowIds, }; } function pruneSnapshotMemoryRows( { selectHash, selectRows, rowIds }: ReturnType, memory: MemoryTextRow, model: string, ): void { const expectedHashes = chunkHashes(memoryText(memory.title, memory.body_text)); if (!snapshotHasExpectedHashes(selectHash, memory.id, model, expectedHashes)) return; const expected = new Set(expectedHashes); const compatibleLegacyModel = model === DEFAULT_EMBEDDING_VECTOR_IDENTITY_LABEL ? LEGACY_DEFAULT_EMBEDDING_MODEL : null; for (const row of selectRows.iterate(memory.id, model, compatibleLegacyModel) as Iterable<{ rowid: number; model: string; content_hash: string | null; }>) { if (row.model === model && row.content_hash != null && expected.has(row.content_hash)) continue; rowIds.push(row.rowid); } } /** * Prune stale target rows only after the memory's current target hashes are * complete. For the revision-aware default identity, also remove that memory's * compatible legacy rows so covered memories no longer rank on pre-edit content. */ export function pruneStaleCurrentModelVectors( db: Database, memoryIds: number[], model: string, ): number { const ids = uniqueMemoryIds(memoryIds); if (ids.length === 0) return 0; const batchSize = 250; const write = prepareVectorWrites(db); let deleted = 0; for (let offset = 0; offset < ids.length; offset += batchSize) { const batchIds = ids.slice(offset, offset + batchSize); const placeholders = batchIds.map(() => "?").join(", "); const pruneCoveredMemories = db.transaction(() => withVectorMetadataSnapshot( db, (metadata) => { const rowIds: number[] = []; const queries = prepareSnapshotPruneQueries(metadata, rowIds); const rows = db .prepare( `SELECT id, title, body_text FROM memory_items WHERE id IN (${placeholders}) ORDER BY id ASC`, ) .all(...batchIds) as MemoryTextRow[]; for (const row of rows) { pruneSnapshotMemoryRows(queries, row, model); } return write({ deleteRowIds: rowIds }).deleted; }, { memoryIds: batchIds }, ), ); deleted += pruneCoveredMemories.immediate(); } return deleted; } /** * Fallback-only sync maintenance path used when durable incremental queueing * fails after inbound replication has already been applied. New sync code * should prefer queueVectorBackfillForIncrementalSync so work survives restart. */ export async function bestEffortMaintainVectorsForSyncFallback( db: Database, work: ReplicationVectorWork, ): Promise { const result: ReplicationVectorMaintenanceResult = { deleted: 0, inserted: 0, errors: [] }; const deleteMemoryIds = uniqueMemoryIds(work.deleteMemoryIds); const upsertMemoryIds = uniqueMemoryIds(work.upsertMemoryIds); if (!vectorStoreExists(db)) { return result; } try { result.deleted += deleteVectorsForMemoryIds(db, deleteMemoryIds); } catch (error) { result.errors.push( `delete vectors failed: ${error instanceof Error ? error.message : String(error)}`, ); } if (upsertMemoryIds.length === 0) return result; try { const client = await getEmbeddingClient(); const backfill = await backfillVectors(db, { memoryIds: upsertMemoryIds, client: client ?? undefined, }); result.inserted = backfill.inserted; if (backfill.checked > 0 && client) { result.deleted += pruneStaleCurrentModelVectors( db, upsertMemoryIds, resolveEmbeddingClientVectorIdentityLabel(client), ); } } catch (error) { result.errors.push( `backfill vectors failed: ${error instanceof Error ? error.message : String(error)}`, ); } return result; } // --------------------------------------------------------------------------- // storeVectors — called inline when a memory is created/remembered // --------------------------------------------------------------------------- /** * Embed and store vectors for a single memory item. * No-op when embeddings are disabled or the client is unavailable. */ export async function storeVectors( db: Database, memoryId: number, title: string, bodyText: string, options: { signal?: AbortSignal } = {}, ): Promise { if (options.signal?.aborted) return; // Capture before client initialization yields, so ID reuse during that wait is visible. const source = readVectorSource(db, memoryId); const client = await getEmbeddingClient(); if (options.signal?.aborted) return; if (!client) return; assertEmbeddingClientIdentity(client); assertVectorMemoryId(memoryId); if (!source) return; const text = `${title}\n${bodyText}`.trim(); const chunks = chunkText(text); if (chunks.length === 0) return; const embeddings = await embedTexts(chunks, client); // Inference cannot be canceled here; a closed owner must never commit its late result. if (options.signal?.aborted) return; if (embeddings.length !== chunks.length) throw new TypeError("vector_count_mismatch"); const model = resolveEmbeddingClientVectorIdentityLabel(client); const persistVectors = db.transaction( (entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }>) => { if (options.signal?.aborted) return; const hashes = currentVectorSourceHashes(source, readVectorSource(db, memoryId)); const currentEntries = entries.filter( (entry) => hashes[entry.chunkIndex] === entry.contentHash, ); if (currentEntries.length === 0) return; ensureVectorWriteModel(db, model); prepareVectorWrites(db)({ insert: { model, rows: currentEntries.map((entry) => ({ ...entry, memoryId })), expectedCount: currentEntries.length, }, }); persistVectorIdentity(db, client, model); }, ); const entries: Array<{ vector: Float32Array; chunkIndex: number; contentHash: string }> = []; for (let i = 0; i < chunks.length; i++) { const vector = embeddings[i]; const chunk = chunks[i]; if (!vector || vector.length === 0) throw new TypeError("invalid_vector_shape"); if (!chunk) throw new TypeError("invalid_vector_chunk"); entries.push({ vector, chunkIndex: i, contentHash: hashText(chunk) }); } if (entries.length === 0) return; persistVectors.immediate(entries); } // --------------------------------------------------------------------------- // backfillVectors — CLI batch backfill // --------------------------------------------------------------------------- function insertCompletedBackfillMemories( db: Database, completed: Set, model: string, ): number { if (completed.size === 0) return 0; const memoryIds = Array.from(completed, (memory) => memory.memoryId); // All memories completed by this inference batch intentionally commit or // roll back together; a write failure must not leave a partially inserted batch. return db .transaction(() => withVectorMetadataSnapshot( db, (metadata) => { const entries = collectCompletedBackfillRows(db, metadata, completed, model); if (!entries.length) return 0; ensureVectorWriteModel(db, model); return prepareVectorWrites(db)({ insert: { model, rows: entries, expectedCount: entries.length }, }).inserted; }, { memoryIds }, ), ) .immediate(); } function collectCompletedBackfillRows( db: Database, metadata: Database, completed: Set, model: string, ) { const selectHash = prepareSnapshotHashQuery(metadata); const selectSource = db.prepare(`SELECT ${VECTOR_SOURCE_COLUMNS} FROM memory_items WHERE id = ?`); const entries: Array<{ memoryId: number; vector: Float32Array; chunkIndex: number; contentHash: string; }> = []; for (const memory of completed) { const current = selectSource.get(memory.memoryId) as VectorSourceRow | undefined; const hashes = currentVectorSourceHashes(memory.source, current); for (const [index, chunk] of memory.chunks.entries()) { if (hashes[chunk.chunkIndex] !== chunk.contentHash) continue; if (selectHash.get(memory.memoryId, model, chunk.contentHash)) continue; entries.push({ vector: memory.vectors[index] as Float32Array, memoryId: memory.memoryId, chunkIndex: chunk.chunkIndex, contentHash: chunk.contentHash, }); } } return entries; } function snapshotHashesByMemory( selectRows: SnapshotQuery, memoryIds: number[], model: string, ): Map> { const hashesByMemory = new Map>(); for (const row of selectRows.iterate(model, JSON.stringify(memoryIds)) as Iterable<{ memory_id: number; content_hash: string | null; }>) { if (row.content_hash == null) continue; const hashes = hashesByMemory.get(row.memory_id) ?? new Set(); hashes.add(row.content_hash); hashesByMemory.set(row.memory_id, hashes); } return hashesByMemory; } function validateBackfillEmbeddings( embeddings: Float32Array[], expectedCount: number, dimensions: number, ): void { if (embeddings.length !== expectedCount) { throw new TypeError( `Embedding client returned ${embeddings.length} vectors for ${expectedCount} texts`, ); } for (const vector of embeddings) { if (vector.length !== dimensions) { throw new TypeError( `Embedding client returned vector dimension ${vector.length}, expected ${dimensions}`, ); } for (const value of vector) { if (!Number.isFinite(value)) { throw new TypeError("Embedding client returned a non-finite vector value"); } } } } function collectCompletedBackfillMemories( batch: Array<{ memory: PendingMemory; chunk: PendingChunk }>, embeddings: Float32Array[], ): Set { const completed = new Set(); for (const [index, { memory }] of batch.entries()) { const vector = embeddings[index]; if (!vector) throw new TypeError("Embedding client omitted a validated vector"); memory.vectors.push(vector); if (memory.vectors.length === memory.chunks.length) completed.add(memory); } return completed; } /** * Backfill vectors for memories that don't have them yet. * Matches Python's `backfill_vectors()` in store/vectors.py. */ export async function backfillVectors( db: Database, opts: BackfillVectorsOptions = {}, ): Promise { if (opts.client) assertEmbeddingClientIdentity(opts.client); const client = opts.client ?? (await getEmbeddingClient()); if (!client) return { checked: 0, embedded: 0, inserted: 0, skipped: 0 }; const { limit, since, project, activeOnly = true, dryRun = false, memoryIds, signal } = opts; const params: unknown[] = []; const whereClauses: string[] = []; if (activeOnly) whereClauses.push("memory_items.active = 1"); if (since) { whereClauses.push("memory_items.created_at >= ?"); params.push(since); } if (project) { const pc = projectColumnClause("COALESCE(sessions.project, memory_items.project)", project); if (pc.clause) { whereClauses.push(pc.clause); params.push(...pc.params); } } if (memoryIds && memoryIds.length > 0) { const placeholders = memoryIds.map(() => "?").join(","); whereClauses.push(`memory_items.id IN (${placeholders})`); params.push(...memoryIds); } const where = whereClauses.length > 0 ? whereClauses.join(" AND ") : "1=1"; const joinSessions = project != null; const joinClause = joinSessions ? "JOIN sessions ON sessions.id = memory_items.session_id" : ""; const model = resolveEmbeddingClientVectorIdentityLabel(client); let checked = 0; let embedded = 0; let inserted = 0; let skipped = 0; const rowLimit = limit != null && limit > 0 ? limit : Infinity; const candidateTable = createBackfillCandidateSnapshot(db, joinClause, where, params, rowLimit); let metadata: Database | null = null; let selectPageHashes: SnapshotQuery | null = null; try { const selectPage = db.prepare( `SELECT candidates.seq AS snapshot_seq, ${QUALIFIED_VECTOR_SOURCE_COLUMNS} FROM ${candidateTable} AS candidates JOIN memory_items ON memory_items.id = candidates.memory_id WHERE candidates.seq > ? ORDER BY candidates.seq ASC LIMIT ?`, ); let cursorSeq = 0; while (!signal?.aborted) { const rows = selectPage.all(cursorSeq, BACKFILL_MEMORY_PAGE_SIZE) as BackfillMemoryRow[]; if (rows.length === 0) break; const lastRow = rows.at(-1) as BackfillMemoryRow; // This cursor lives only for this invocation. An aborted caller starts a fresh pass. cursorSeq = lastRow.snapshot_seq; // Reuse only during uninterrupted synchronous reads. Inference closes // this snapshot before yielding; the next page then reads current state. metadata ??= createVectorMetadataSnapshot(db); selectPageHashes ??= metadata.prepare( `SELECT memory_id, content_hash FROM vector_metadata WHERE model = ? AND memory_id IN (SELECT value FROM json_each(?))`, ); const existingHashesByMemory = snapshotHashesByMemory( selectPageHashes, rows.map((row) => row.id), model, ); let batch: Array<{ memory: PendingMemory; chunk: PendingChunk }> = []; const flushBatch = async (): Promise => { if (batch.length === 0) return; const currentBatch = batch; batch = []; metadata?.close(); metadata = null; selectPageHashes = null; const embeddings = await embedTexts( currentBatch.map(({ chunk }) => chunk.text), client, ); validateBackfillEmbeddings(embeddings, currentBatch.length, client.dimensions); embedded += embeddings.length; const completed = collectCompletedBackfillMemories(currentBatch, embeddings); // Page hashes are planning hints only. Recheck the completed batch // after inference inside the immediate write boundary: vec0 has no // uniqueness constraint. Do not add our inserts to that snapshot; // distinct chunk_index rows may legitimately share the same hash. if (!dryRun) inserted += insertCompletedBackfillMemories(db, completed, model); for (const memory of completed) { if (dryRun) inserted += memory.chunks.length; memory.vectors.length = 0; memory.chunks.length = 0; } }; for (const row of rows) { if (signal?.aborted) return { checked, embedded, inserted, skipped }; checked++; const chunks = chunkText(memoryText(row.title, row.body_text)); const existingHashes = existingHashesByMemory.get(row.id) ?? new Set(); const pendingChunks: PendingChunk[] = []; for (const [chunkIndex, text] of chunks.entries()) { const contentHash = hashText(text); if (existingHashes.has(contentHash)) { skipped++; continue; } pendingChunks.push({ text, chunkIndex, contentHash }); } if (pendingChunks.length === 0) continue; const memory = pendingBackfillMemory(row, pendingChunks); for (const chunk of pendingChunks) { batch.push({ memory, chunk }); if (batch.length < BACKFILL_INFERENCE_BATCH_SIZE) continue; await flushBatch(); if (!signal?.aborted) continue; // `embedded` includes valid inference discarded for an incomplete memory; // `inserted` counts only memories completed by this batch (also for dry-run). return { checked, embedded, inserted, skipped }; } } if (batch.length > 0) await flushBatch(); if (signal?.aborted) return { checked, embedded, inserted, skipped }; } } finally { metadata?.close(); deleteBackfillCandidateSnapshot(db, candidateTable); } if (!dryRun && (inserted > 0 || skipped > 0)) { persistVectorIdentity(db, client, model); } return { checked, embedded, inserted, skipped }; } // --------------------------------------------------------------------------- // semanticSearch — vector KNN query // --------------------------------------------------------------------------- export interface SemanticSearchResult { id: number; kind: string; title: string; body_text: string; confidence: number; tags_text: string; metadata_json: string | null; created_at: string; updated_at: string; session_id: number; score: number; distance: number; /** Structured narrative from observation (carried through from memory_items.*). */ narrative: string | null; /** JSON-encoded string array of extracted facts. */ facts: string | null; } export { semanticResult }; /** * Search for memories by vector similarity using exact sqlite-vec distance. * Returns an empty array when embeddings are disabled or unavailable. * * Matches Python's `_semantic_search()` in store/search.py. */ export async function semanticSearch( db: Database, query: string, limit: number, filters: MemoryFilters | null, context: SemanticSearchScopeContext, summarySessionId?: number | null, ): Promise { if (query.trim().length < 3) return []; if (!hasVectorRows(db)) return []; const client = await getEmbeddingClient(); if (!client) return []; const searchModels = resolveSemanticSearchModels( db, resolveEmbeddingClientVectorIdentityLabel(client), ); if (searchModels.length === 0) return []; if (!context?.deviceId?.trim()) { throw new Error("semantic_search_scope_context_required"); } const embeddings = await embedTexts([query], client); if (embeddings.length === 0) return []; const firstEmbedding = embeddings[0]; if (!firstEmbedding) return []; const queryEmbedding = serializeFloat32(firstEmbedding); return rankSemanticEmbedding( db, queryEmbedding, searchModels, limit, filters, context, summarySessionId, ); } /** Internal exact ranking stage shared with the read-only semantic worker. */ export function rankSemanticEmbedding( db: Database, queryEmbedding: Buffer, searchModels: string[], limit: number, filters: MemoryFilters | null, context: SemanticSearchScopeContext, summarySessionId?: number | null, ): SemanticSearchResult[] { if (searchModels.length === 0) return []; return snapshot(db, () => rankSemanticEmbeddingSnapshot( db, queryEmbedding, searchModels, limit, filters, context, summarySessionId, ), ); } function rankSemanticEmbeddingSnapshot( db: Database, queryEmbedding: Buffer, searchModels: string[], limit: number, filters: MemoryFilters | null, context: SemanticSearchScopeContext, summarySessionId?: number | null, ): SemanticSearchResult[] { const effectiveLimit = clampSemanticLimit(limit); const authorizedIds = buildAuthorizedSemanticMemoryIdsQuery(filters, context, summarySessionId); const freshness = pendingVectorFreshness( db, filters, context, summarySessionId, "memory_vectors.", ); const modelPlaceholders = searchModels.map(() => "?").join(", "); // Scope predicates must apply before vector ranking. sqlite-vec's MATCH/k // query ranks inside the virtual table before joined memory_items filters can // reliably constrain the candidate set, so use an exact distance scan over the // already-authorized memory rows instead of widening post-KNN candidates. // Materialize IDs so vec0 metadata probes do not reopen wide memory rows; // materialize the limited ranking before fetching the final result payloads. const sql = ` WITH authorized_ids AS MATERIALIZED (${authorizedIds.sql}), scoped_vectors AS MATERIALIZED ( SELECT memory_vectors.memory_id, MIN(vec_distance_l2(memory_vectors.embedding, ?)) AS distance FROM memory_vectors JOIN authorized_ids ON authorized_ids.id = memory_vectors.memory_id WHERE memory_vectors.model IN (${modelPlaceholders}) ${freshness.sql} GROUP BY memory_vectors.memory_id ORDER BY distance ASC LIMIT ? ) SELECT memory_items.*, scoped_vectors.distance FROM scoped_vectors JOIN memory_items ON memory_items.id = scoped_vectors.memory_id ORDER BY scoped_vectors.distance ASC `; const statement = db.prepare(sql); const rows = statement.all( ...authorizedIds.params, queryEmbedding, ...searchModels, ...freshness.params, effectiveLimit, ) as Array>; return rows.map(semanticResult).slice(0, effectiveLimit); }