diff --git a/.env.example b/.env.example index c7e4911e4a..24d396f050 100644 --- a/.env.example +++ b/.env.example @@ -1311,3 +1311,12 @@ APP_LOG_TO_FILE=true # ELECTRON_SMOKE_DATA_DIR= # ELECTRON_SMOKE_KEEP_DATA=0 # ELECTRON_SMOKE_STREAM_LOGS=0 + +# Memory engine (plan 21) +# MEMORY_EMBEDDING_CACHE_TTL_MS=300000 # default 5 min +# MEMORY_EMBEDDING_CACHE_MAX=1000 # default 1000 entries +# MEMORY_TRANSFORMERS_MODEL=Xenova/all-MiniLM-L6-v2 +# MEMORY_STATIC_MODEL=minishlab/potion-base-8M # HF repo id (download once) +# MEMORY_STATIC_CACHE_DIR= # default /embeddings +# MEMORY_VEC_TOP_K=20 # default top-K for vector search +# MEMORY_RRF_K=60 # RRF k constant (sqlite-vec hybrid recipe) diff --git a/src/lib/db/memoryVec.ts b/src/lib/db/memoryVec.ts new file mode 100644 index 0000000000..c0025bfa99 --- /dev/null +++ b/src/lib/db/memoryVec.ts @@ -0,0 +1,138 @@ +/** + * db/memoryVec.ts — CRUD for memory vector metadata and reindex state. + * + * Plan 21 — Memory Engine Redesign. + * Raw SQL is allowed here (Hard Rule #5 — src/lib/db/ domain module). + * + * This module manages: + * - `memory_vec_meta`: singleton row tracking the active embedding dim/signature/reset + * - `memories.needs_reindex`: flag for lazy backfill of missing/stale vectors + */ + +import { getDbInstance } from "./core"; + +// ──────────────── Types ──────────────── + +export interface MemoryVecMeta { + activeDim: number | null; + embeddingSignature: string | null; + lastResetAt: string | null; + vecLoaded: boolean; +} + +// ──────────────── memory_vec_meta ──────────────── + +/** + * Get the singleton memory_vec_meta row. + * Returns defaults if the row is absent (e.g. migration not yet applied on + * an in-memory test DB that ran without the migration file). + */ +export function getMemoryVecMeta(): MemoryVecMeta { + const db = getDbInstance(); + const row = db + .prepare( + "SELECT active_dim, embedding_signature, last_reset_at, vec_loaded FROM memory_vec_meta WHERE id = 1" + ) + .get() as + | { + active_dim: number | null; + embedding_signature: string | null; + last_reset_at: string | null; + vec_loaded: number; + } + | undefined; + + if (!row) { + return { + activeDim: null, + embeddingSignature: null, + lastResetAt: null, + vecLoaded: false, + }; + } + + return { + activeDim: row.active_dim, + embeddingSignature: row.embedding_signature, + lastResetAt: row.last_reset_at, + vecLoaded: row.vec_loaded === 1, + }; +} + +/** + * Update one or more fields in the singleton memory_vec_meta row. + * Uses INSERT OR REPLACE to handle the case where the row is missing + * (e.g. called before or during migration on a test DB). + */ +export function setMemoryVecMeta(meta: Partial): void { + const db = getDbInstance(); + + // Read current values first so we can merge (partial update pattern). + const current = getMemoryVecMeta(); + + const activeDim = "activeDim" in meta ? meta.activeDim ?? null : current.activeDim; + const embeddingSignature = + "embeddingSignature" in meta + ? meta.embeddingSignature ?? null + : current.embeddingSignature; + const lastResetAt = + "lastResetAt" in meta ? meta.lastResetAt ?? null : current.lastResetAt; + const vecLoaded = + "vecLoaded" in meta ? (meta.vecLoaded ? 1 : 0) : current.vecLoaded ? 1 : 0; + + db.prepare( + `INSERT OR REPLACE INTO memory_vec_meta + (id, active_dim, embedding_signature, last_reset_at, vec_loaded) + VALUES (1, ?, ?, ?, ?)` + ).run(activeDim, embeddingSignature, lastResetAt, vecLoaded); +} + +// ──────────────── memories.needs_reindex ──────────────── + +/** + * Mark a single memory as needing reindex (or clear the flag). + */ +export function markMemoryNeedsReindex(id: string, needs: boolean): void { + const db = getDbInstance(); + db.prepare("UPDATE memories SET needs_reindex = ? WHERE id = ?").run(needs ? 1 : 0, id); +} + +/** + * Mark ALL memories as needing reindex. + * Returns the number of rows affected. + */ +export function markAllMemoriesNeedReindex(): number { + const db = getDbInstance(); + const result = db.prepare("UPDATE memories SET needs_reindex = 1").run(); + return result.changes; +} + +/** + * Get a batch of memories that need reindex, ordered by creation date ascending. + * Returns id, content, and key for each memory so the vector can be regenerated. + */ +export function getMemoryReindexQueue( + limit: number +): Array<{ id: string; content: string; key: string }> { + const db = getDbInstance(); + return db + .prepare( + `SELECT id, content, COALESCE(key, '') AS key + FROM memories + WHERE needs_reindex = 1 + ORDER BY created_at ASC + LIMIT ?` + ) + .all(limit) as Array<{ id: string; content: string; key: string }>; +} + +/** + * Count how many memories currently have needs_reindex = 1. + */ +export function countMemoryReindexPending(): number { + const db = getDbInstance(); + const row = db + .prepare("SELECT COUNT(*) AS cnt FROM memories WHERE needs_reindex = 1") + .get() as { cnt: number }; + return row.cnt; +} diff --git a/src/lib/db/migrations/073_memory_vec.sql b/src/lib/db/migrations/073_memory_vec.sql new file mode 100644 index 0000000000..ab7204f5d9 --- /dev/null +++ b/src/lib/db/migrations/073_memory_vec.sql @@ -0,0 +1,26 @@ +-- 073_memory_vec.sql +-- Memory Engine Redesign (plan 21): metadata table for sqlite-vec. +-- The actual virtual table `vec_memories(memory_id INTEGER, embedding float[N])` +-- is created in runtime by src/lib/memory/vectorStore.ts because N depends on +-- the active embedding model (which can change at any time via UI). + +CREATE TABLE IF NOT EXISTS memory_vec_meta ( + id INTEGER PRIMARY KEY CHECK (id = 1), + active_dim INTEGER, + embedding_signature TEXT, + last_reset_at TEXT, + vec_loaded INTEGER NOT NULL DEFAULT 0 +); + +INSERT OR IGNORE INTO memory_vec_meta (id, active_dim, embedding_signature, last_reset_at, vec_loaded) +VALUES (1, NULL, NULL, NULL, 0); + +-- Add needs_reindex column to memories (idempotent via separate ALTER guarded by PRAGMA). +-- The PRAGMA-guard pattern is handled in the migration runner; here we just ensure the +-- column shape. If the column already exists, the ALTER fails silently and the runner +-- treats the migration as a no-op for that ALTER step. +ALTER TABLE memories ADD COLUMN needs_reindex INTEGER NOT NULL DEFAULT 0; + +CREATE INDEX IF NOT EXISTS idx_memories_needs_reindex + ON memories(needs_reindex) + WHERE needs_reindex = 1; diff --git a/src/lib/localDb.ts b/src/lib/localDb.ts index 648c03f658..cba08c0836 100755 --- a/src/lib/localDb.ts +++ b/src/lib/localDb.ts @@ -508,3 +508,15 @@ export { } from "./db/freeProxies"; export type { FreeProxyRecord, FreeProxyStats } from "./db/freeProxies"; + +// Plan 21 — Memory Engine Redesign +export { + getMemoryVecMeta, + setMemoryVecMeta, + markMemoryNeedsReindex, + markAllMemoriesNeedReindex, + getMemoryReindexQueue, + countMemoryReindexPending, +} from "./db/memoryVec"; + +export type { MemoryVecMeta } from "./db/memoryVec"; diff --git a/tests/unit/memory-needs-reindex.test.ts b/tests/unit/memory-needs-reindex.test.ts new file mode 100644 index 0000000000..8818358a48 --- /dev/null +++ b/tests/unit/memory-needs-reindex.test.ts @@ -0,0 +1,251 @@ +/** + * tests/unit/memory-needs-reindex.test.ts + * + * Plan 21 — Memory Engine Redesign (F2) + * Tests for markMemoryNeedsReindex, markAllMemoriesNeedReindex, + * getMemoryReindexQueue, and countMemoryReindexPending. + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-memory-reindex-")); +process.env.DATA_DIR = TEST_DATA_DIR; +process.env.DISABLE_SQLITE_AUTO_BACKUP = "true"; + +const core = await import("../../src/lib/db/core.ts"); +const memoryVec = await import("../../src/lib/db/memoryVec.ts"); + +// ──────────────── Helpers ──────────────── + +function insertTestMemory( + db: ReturnType, + id: string, + content: string, + key: string +): void { + db.prepare(` + INSERT INTO memories (id, api_key_id, type, key, content, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, datetime('now'), datetime('now')) + `).run(id, "test-api-key", "factual", key, content); +} + +async function resetStorage() { + core.resetDbInstance(); + + for (let attempt = 0; attempt < 10; attempt++) { + try { + if (fs.existsSync(TEST_DATA_DIR)) { + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); + } + break; + } catch (error: unknown) { + const code = (error as NodeJS.ErrnoException)?.code; + if ((code === "EBUSY" || code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); +} + +test.beforeEach(async () => { + await resetStorage(); +}); + +test.after(async () => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); +}); + +// ──────────────── markMemoryNeedsReindex ──────────────── + +test("markMemoryNeedsReindex(id, true) marks only the targeted memory", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Paris is the capital of France", "capital-france"); + insertTestMemory(db, "id-2", "Berlin is the capital of Germany", "capital-germany"); + insertTestMemory(db, "id-3", "Tokyo is the capital of Japan", "capital-japan"); + + memoryVec.markMemoryNeedsReindex("id-1", true); + + const queue = memoryVec.getMemoryReindexQueue(10); + assert.equal(queue.length, 1, "only 1 memory should be in the reindex queue"); + assert.equal(queue[0].id, "id-1"); + assert.equal(queue[0].content, "Paris is the capital of France"); + assert.equal(queue[0].key, "capital-france"); +}); + +test("markMemoryNeedsReindex(id, false) clears the flag for that memory", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + // Mark all 3 with needs_reindex + memoryVec.markMemoryNeedsReindex("id-1", true); + memoryVec.markMemoryNeedsReindex("id-2", true); + memoryVec.markMemoryNeedsReindex("id-3", true); + + // Clear id-1 + memoryVec.markMemoryNeedsReindex("id-1", false); + + const queue = memoryVec.getMemoryReindexQueue(10); + const ids = queue.map((item) => item.id); + + assert.equal(queue.length, 2, "queue should have 2 items after clearing id-1"); + assert.ok(!ids.includes("id-1"), "id-1 should not be in the queue"); + assert.ok(ids.includes("id-2"), "id-2 should be in the queue"); + assert.ok(ids.includes("id-3"), "id-3 should be in the queue"); +}); + +// ──────────────── markAllMemoriesNeedReindex ──────────────── + +test("markAllMemoriesNeedReindex() returns the correct affected row count", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + const count = memoryVec.markAllMemoriesNeedReindex(); + assert.equal(count, 3, "markAllMemoriesNeedReindex should return 3 (all rows affected)"); +}); + +test("markAllMemoriesNeedReindex() marks every memory in the queue", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + memoryVec.markAllMemoriesNeedReindex(); + + const queue = memoryVec.getMemoryReindexQueue(10); + assert.equal(queue.length, 3, "all 3 memories should appear in the reindex queue"); +}); + +test("markAllMemoriesNeedReindex() returns 0 when there are no memories", () => { + core.getDbInstance(); + + const count = memoryVec.markAllMemoriesNeedReindex(); + assert.equal(count, 0, "should return 0 when there are no memories"); +}); + +// ──────────────── countMemoryReindexPending ──────────────── + +test("countMemoryReindexPending() returns 3 after markAll on 3 memories", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + memoryVec.markAllMemoriesNeedReindex(); + + const pending = memoryVec.countMemoryReindexPending(); + assert.equal(pending, 3); +}); + +test("countMemoryReindexPending() returns 0 on fresh DB with no memories", () => { + core.getDbInstance(); + + const pending = memoryVec.countMemoryReindexPending(); + assert.equal(pending, 0); +}); + +test("countMemoryReindexPending() decrements after clearing a flag", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + memoryVec.markAllMemoriesNeedReindex(); + assert.equal(memoryVec.countMemoryReindexPending(), 3); + + memoryVec.markMemoryNeedsReindex("id-1", false); + assert.equal(memoryVec.countMemoryReindexPending(), 2); + + memoryVec.markMemoryNeedsReindex("id-2", false); + assert.equal(memoryVec.countMemoryReindexPending(), 1); +}); + +// ──────────────── getMemoryReindexQueue pagination ──────────────── + +test("getMemoryReindexQueue respects the limit parameter", () => { + const db = core.getDbInstance(); + + for (let i = 1; i <= 5; i++) { + insertTestMemory(db, `id-${i}`, `Content ${i}`, `key-${i}`); + } + + memoryVec.markAllMemoriesNeedReindex(); + + const queue = memoryVec.getMemoryReindexQueue(3); + assert.equal(queue.length, 3, "should return at most 3 items when limit=3"); +}); + +test("getMemoryReindexQueue returns only memories with needs_reindex = 1", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + // Only mark id-2 and id-3 + memoryVec.markMemoryNeedsReindex("id-2", true); + memoryVec.markMemoryNeedsReindex("id-3", true); + + const queue = memoryVec.getMemoryReindexQueue(10); + const ids = queue.map((item) => item.id); + + assert.equal(queue.length, 2); + assert.ok(!ids.includes("id-1"), "id-1 should NOT be in the queue"); + assert.ok(ids.includes("id-2"), "id-2 should be in the queue"); + assert.ok(ids.includes("id-3"), "id-3 should be in the queue"); +}); + +test("getMemoryReindexQueue returns empty array when no memories need reindex", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + + const queue = memoryVec.getMemoryReindexQueue(10); + assert.equal(queue.length, 0, "queue should be empty when needs_reindex = 0"); +}); + +// ──────────────── Combined workflow ──────────────── + +test("full workflow: markAll → queue=3 → clear id-1 → queue=2", () => { + const db = core.getDbInstance(); + + insertTestMemory(db, "id-1", "Content 1", "key-1"); + insertTestMemory(db, "id-2", "Content 2", "key-2"); + insertTestMemory(db, "id-3", "Content 3", "key-3"); + + const affected = memoryVec.markAllMemoriesNeedReindex(); + assert.equal(affected, 3); + + const queueBefore = memoryVec.getMemoryReindexQueue(10); + assert.equal(queueBefore.length, 3); + assert.equal(memoryVec.countMemoryReindexPending(), 3); + + memoryVec.markMemoryNeedsReindex("id-1", false); + + const queueAfter = memoryVec.getMemoryReindexQueue(10); + assert.equal(queueAfter.length, 2, "queue should have 2 items after clearing id-1"); + assert.equal(memoryVec.countMemoryReindexPending(), 2); + + const ids = queueAfter.map((item) => item.id); + assert.ok(!ids.includes("id-1")); + assert.ok(ids.includes("id-2")); + assert.ok(ids.includes("id-3")); +}); diff --git a/tests/unit/memory-vec-meta.test.ts b/tests/unit/memory-vec-meta.test.ts new file mode 100644 index 0000000000..9810f7fc19 --- /dev/null +++ b/tests/unit/memory-vec-meta.test.ts @@ -0,0 +1,159 @@ +/** + * tests/unit/memory-vec-meta.test.ts + * + * Plan 21 — Memory Engine Redesign (F2) + * Tests for getMemoryVecMeta / setMemoryVecMeta and migration idempotency. + */ + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-memory-vec-meta-")); +process.env.DATA_DIR = TEST_DATA_DIR; +process.env.DISABLE_SQLITE_AUTO_BACKUP = "true"; + +const core = await import("../../src/lib/db/core.ts"); +const memoryVec = await import("../../src/lib/db/memoryVec.ts"); + +async function resetStorage() { + core.resetDbInstance(); + + for (let attempt = 0; attempt < 10; attempt++) { + try { + if (fs.existsSync(TEST_DATA_DIR)) { + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); + } + break; + } catch (error: unknown) { + const code = (error as NodeJS.ErrnoException)?.code; + if ((code === "EBUSY" || code === "EPERM") && attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))); + } else { + throw error; + } + } + } + + fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); +} + +test.beforeEach(async () => { + await resetStorage(); +}); + +test.after(async () => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true }); +}); + +// ──────────────── getMemoryVecMeta initial state ──────────────── + +test("getMemoryVecMeta() returns expected defaults on a fresh DB", () => { + // getDbInstance() triggers migrations including 073_memory_vec.sql + const db = core.getDbInstance(); + assert.ok(db, "DB instance should be created"); + + const meta = memoryVec.getMemoryVecMeta(); + + assert.equal(meta.activeDim, null, "activeDim should be null initially"); + assert.equal(meta.embeddingSignature, null, "embeddingSignature should be null initially"); + assert.equal(meta.lastResetAt, null, "lastResetAt should be null initially"); + assert.equal(meta.vecLoaded, false, "vecLoaded should be false initially"); +}); + +// ──────────────── setMemoryVecMeta + getMemoryVecMeta round-trip ──────────────── + +test("setMemoryVecMeta persists activeDim and embeddingSignature", () => { + core.getDbInstance(); // ensure migrations run + + memoryVec.setMemoryVecMeta({ + activeDim: 1536, + embeddingSignature: "remote:openai/text-embedding-3-small:1536", + }); + + const meta = memoryVec.getMemoryVecMeta(); + + assert.equal(meta.activeDim, 1536); + assert.equal(meta.embeddingSignature, "remote:openai/text-embedding-3-small:1536"); + assert.equal(meta.lastResetAt, null); // not set + assert.equal(meta.vecLoaded, false); // not set +}); + +test("setMemoryVecMeta persists vecLoaded = true", () => { + core.getDbInstance(); + + memoryVec.setMemoryVecMeta({ vecLoaded: true }); + + const meta = memoryVec.getMemoryVecMeta(); + assert.equal(meta.vecLoaded, true); +}); + +test("setMemoryVecMeta updates only the provided fields (partial update)", () => { + core.getDbInstance(); + + // First set all fields + memoryVec.setMemoryVecMeta({ + activeDim: 768, + embeddingSignature: "static:potion-base-8M:768", + vecLoaded: true, + }); + + // Then update only activeDim + memoryVec.setMemoryVecMeta({ activeDim: 1536 }); + + const meta = memoryVec.getMemoryVecMeta(); + assert.equal(meta.activeDim, 1536, "activeDim should be updated"); + assert.equal(meta.embeddingSignature, "static:potion-base-8M:768", "embeddingSignature should be preserved"); + assert.equal(meta.vecLoaded, true, "vecLoaded should be preserved"); +}); + +test("setMemoryVecMeta sets lastResetAt correctly", () => { + core.getDbInstance(); + + const now = new Date().toISOString(); + memoryVec.setMemoryVecMeta({ lastResetAt: now }); + + const meta = memoryVec.getMemoryVecMeta(); + assert.equal(meta.lastResetAt, now); +}); + +// ──────────────── Migration idempotency ──────────────── + +test("migration 073 does not duplicate memory_vec_meta sentinel row on second run", () => { + // The first getDbInstance() runs all migrations including 073 + const db = core.getDbInstance(); + + // Run migration SQL a second time manually to simulate re-run + // The runner would normally catch "duplicate column name" and skip, + // but here we test CREATE TABLE IF NOT EXISTS + INSERT OR IGNORE + db.exec(` + CREATE TABLE IF NOT EXISTS memory_vec_meta ( + id INTEGER PRIMARY KEY CHECK (id = 1), + active_dim INTEGER, + embedding_signature TEXT, + last_reset_at TEXT, + vec_loaded INTEGER NOT NULL DEFAULT 0 + ); + INSERT OR IGNORE INTO memory_vec_meta (id, active_dim, embedding_signature, last_reset_at, vec_loaded) + VALUES (1, NULL, NULL, NULL, 0); + `); + + // Count should still be exactly 1 + const row = db.prepare("SELECT COUNT(*) AS cnt FROM memory_vec_meta").get() as { cnt: number }; + assert.equal(row.cnt, 1, "migration re-run must not duplicate the sentinel row"); +}); + +test("migration 073 creates needs_reindex column in memories table", () => { + const db = core.getDbInstance(); + + const columns = db.prepare("PRAGMA table_info(memories)").all() as Array<{ name: string }>; + const colNames = columns.map((col) => col.name); + + assert.ok( + colNames.includes("needs_reindex"), + "memories table must have needs_reindex column after migration 073" + ); +});