diff --git a/web/scripts/embedding-readiness-memory.test.cjs b/web/scripts/embedding-readiness-memory.test.cjs new file mode 100644 index 0000000..b29b71e --- /dev/null +++ b/web/scripts/embedding-readiness-memory.test.cjs @@ -0,0 +1,89 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const Module = require("node:module"); +const ts = require("typescript"); +const dir = fs.mkdtempSync(path.join(os.tmpdir(), "intellirag-memory-readiness-")); +const snapshot = path.join(dir, "memory.json"); +const originalLoad = Module._load; +const originalTs = require.extensions[".ts"]; +require.extensions[".ts"] = (mod, file) => + mod._compile( + ts.transpileModule(fs.readFileSync(file, "utf8"), { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + esModuleInterop: true, + }, + }).outputText, + file, + ); +Module._load = function (id, parent, ...rest) { + if (parent?.filename?.endsWith("/rag/memory.server.ts")) { + if (id === "node:fs") + return { + ...fs, + readFileSync: (p, ...args) => + fs.readFileSync(p === "/tmp/intellirag-memory.json" ? snapshot : p, ...args), + writeFileSync: (p, ...args) => + fs.writeFileSync(p === "/tmp/intellirag-memory.json" ? snapshot : p, ...args), + }; + // Suggestions are unrelated to embedding readiness; no SQL or provider is opened. + if (id === "./suggested-questions.server") return { seedPredictedQuestions: async () => {} }; + } + return originalLoad.call(this, id, parent, ...rest); +}; +const store = require("../src/lib/rag/memory.server.ts"); +test.after(() => { + Module._load = originalLoad; + if (originalTs) require.extensions[".ts"] = originalTs; + else delete require.extensions[".ts"]; + fs.rmSync(dir, { recursive: true, force: true }); +}); + +test("memory readiness follows each document across partial and mixed-model replacement", async () => { + const oldV = process.env.VERCEL; + const oldD = process.env.DATABASE_URL; + delete process.env.VERCEL; + delete process.env.DATABASE_URL; + store.resetMemoryForTests(); + try { + const a = await store.upsertDocument({ + title: "Memory readiness a", + body: "Workers enforce queue backpressure. ".repeat(240), + sourceType: "markdown", + sourceUri: "test://memory-ready-a", + }); + const b = await store.upsertDocument({ + title: "Memory readiness b", + body: "Timeout starts after execution begins. ".repeat(240), + sourceType: "markdown", + sourceUri: "test://memory-ready-b", + }); + const chunks = await store.loadSearchableChunks({ kind: "all" }); + const rows = (id) => chunks.filter((r) => r.chunk.document_id === id); + const updates = (id, model) => + rows(id).map((r) => ({ id: r.chunk.id, embedding: [0.1, 0.2], model })); + assert.ok(rows(a.id).length > 1); + await store.saveChunkEmbeddings([...updates(a.id, "model-a"), ...updates(b.id, "model-b")]); + assert.equal((await store.getDocumentBySlug(a.slug)).embedding_model, "model-a"); + assert.equal((await store.getDocumentBySlug(b.slug)).embedding_model, "model-b"); + await store.saveChunkEmbeddings([ + { id: rows(a.id)[0].chunk.id, embedding: [0.4, 0.5], model: "model-c" }, + ]); + assert.equal((await store.getDocumentBySlug(a.slug)).embedding_model, null); + assert.equal((await store.getDocumentBySlug(a.slug)).indexed_at, null); + assert.ok((await store.getDocumentBySlug(b.slug)).indexed_at); + await store.replaceChunks(b.id, "Direct replacement. ".repeat(180), undefined, b.corpusId); + assert.equal((await store.getDocumentBySlug(b.slug)).indexed_at, null); + assert.equal((await store.getDocumentBySlug(b.slug)).embedding_model, null); + } finally { + store.resetMemoryForTests(); + if (oldV === undefined) delete process.env.VERCEL; + else process.env.VERCEL = oldV; + if (oldD === undefined) delete process.env.DATABASE_URL; + else process.env.DATABASE_URL = oldD; + } +}); diff --git a/web/src/lib/rag/embedding-readiness-transition.test.ts b/web/src/lib/rag/embedding-readiness-transition.test.ts new file mode 100644 index 0000000..8c36192 --- /dev/null +++ b/web/src/lib/rag/embedding-readiness-transition.test.ts @@ -0,0 +1,127 @@ +import "./testing/isolated-pglite-dir.mjs"; +import "./testing/close-database.mjs"; +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { EMBEDDING_MODEL } from "./types"; + +delete process.env.VERCEL; +delete process.env.VERCEL_ENV; +delete process.env.DATABASE_URL; +const store = await import("./store.server"); + +async function document(slug: string) { + const up = await store.upsertDocument({ + title: slug, + slugHint: slug, + body: "Queue backpressure prevents producers overwhelming workers. ".repeat(180), + sourceType: "markdown", + sourceUri: `test://${slug}`, + }); + const rows = (await store.loadSearchableChunks({ kind: "corpus", corpusId: up.corpusId })).filter( + (r) => r.chunk.document_id === up.id, + ); + assert.ok(rows.length > 1); + return { up, rows }; +} + +test("partial model replacement revokes an earlier complete indexing claim", async () => { + const { up, rows } = await document("model-readiness"); + await store.saveChunkEmbeddings( + rows.map((r) => ({ id: r.chunk.id, embedding: [0.1, 0.2], model: EMBEDDING_MODEL })), + ); + assert.ok((await store.getDocumentBySlug(up.slug))?.indexed_at); + await store.saveChunkEmbeddings([ + { id: rows[0]!.chunk.id, embedding: [0.3, 0.4], model: "replacement-model" }, + ]); + const changed = await store.getDocumentBySlug(up.slug); + assert.equal(changed?.embedding_model, null); + assert.equal(changed?.indexed_at, null); +}); + +test("mixed-model batches mark each complete document with its actual model", async () => { + const a = await document("batch-model-a"); + const b = await document("batch-model-b"); + await store.saveChunkEmbeddings([ + ...a.rows.map((r) => ({ id: r.chunk.id, embedding: [0.1, 0.2], model: "model-a" })), + ...b.rows.map((r) => ({ id: r.chunk.id, embedding: [0.3, 0.4], model: "model-b" })), + ]); + assert.equal((await store.getDocumentBySlug(a.up.slug))?.embedding_model, "model-a"); + assert.equal((await store.getDocumentBySlug(b.up.slug))?.embedding_model, "model-b"); + assert.ok((await store.getDocumentBySlug(b.up.slug))?.indexed_at); +}); + +test("a metadata write failure rolls back every chunk in the embedding batch", async () => { + const { up, rows } = await document("atomic-embedding-failure"); + const { getSql } = await import("../db"); + const sql = await getSql(); + await sql.query(`create function reject_readiness() returns trigger language plpgsql as $$ + begin raise exception 'injected readiness failure'; end $$`); + await sql.query(`create trigger reject_readiness before update on documents + for each row execute function reject_readiness()`); + try { + await assert.rejects( + store.saveChunkEmbeddings( + rows.map((r) => ({ + id: r.chunk.id, + embedding: [0.1, 0.2], + model: "atomic-model", + })), + ), + /injected readiness failure/, + ); + } finally { + await sql.query("drop trigger reject_readiness on documents"); + await sql.query("drop function reject_readiness()"); + } + const after = await sql<{ + embedding: string | null; + }>`select embedding from chunks where document_id = ${up.id}`; + assert.ok(after.every((r) => r.embedding === null)); + assert.equal((await store.getDocumentBySlug(up.slug))?.indexed_at, null); +}); + +test("duplicate ids retain last nonempty update and unknown ids do not affect readiness", async () => { + const { up, rows } = await document("duplicate-embedding-update"); + await store.saveChunkEmbeddings([ + ...rows.map((r) => ({ id: r.chunk.id, embedding: [0.1, 0.2], model: "earlier-model" })), + ...rows.map((r) => ({ id: r.chunk.id, embedding: [0.3, 0.4], model: "latest-model" })), + { id: rows[0]!.chunk.id, embedding: [], model: "ignored-empty" }, + { id: "not-a-real-chunk", embedding: [0.1], model: "unknown-model" }, + ]); + assert.equal((await store.getDocumentBySlug(up.slug))?.embedding_model, "latest-model"); + assert.ok((await store.getDocumentBySlug(up.slug))?.indexed_at); +}); + +test("concurrent partial batches converge on one complete readiness marker", async () => { + const { up, rows } = await document("concurrent-embedding-update"); + await Promise.all( + rows.map((r) => + store.saveChunkEmbeddings([ + { id: r.chunk.id, embedding: [0.1, 0.2], model: "concurrent-model" }, + ]), + ), + ); + const ready = await store.getDocumentBySlug(up.slug); + assert.equal(ready?.embedding_model, "concurrent-model"); + assert.ok(ready?.indexed_at); +}); + +test("direct chunk replacement clears readiness, including an empty replacement", async () => { + const { up, rows } = await document("direct-replacement-readiness"); + await store.saveChunkEmbeddings( + rows.map((r) => ({ id: r.chunk.id, embedding: [0.1, 0.2], model: "ready-model" })), + ); + assert.ok((await store.getDocumentBySlug(up.slug))?.indexed_at); + await store.replaceChunks(up.id, "Replacement content. ".repeat(180), undefined, up.corpusId); + assert.equal((await store.getDocumentBySlug(up.slug))?.indexed_at, null); + const replacement = ( + await store.loadSearchableChunks({ kind: "corpus", corpusId: up.corpusId }) + ).filter((r) => r.chunk.document_id === up.id); + await store.saveChunkEmbeddings( + replacement.map((r) => ({ id: r.chunk.id, embedding: [0.2, 0.3], model: "ready-model" })), + ); + assert.ok((await store.getDocumentBySlug(up.slug))?.indexed_at); + assert.equal(await store.replaceChunks(up.id, "", undefined, up.corpusId), 0); + assert.equal((await store.getDocumentBySlug(up.slug))?.embedding_model, null); + assert.equal((await store.getDocumentBySlug(up.slug))?.indexed_at, null); +}); diff --git a/web/src/lib/rag/memory.server.ts b/web/src/lib/rag/memory.server.ts index da95c5d..feafc5e 100644 --- a/web/src/lib/rag/memory.server.ts +++ b/web/src/lib/rag/memory.server.ts @@ -123,6 +123,12 @@ async function replaceChunks( corpusId: string = SEED_CORPUS_ID, ): Promise { const s = state(); + const document = s.documents.find((d) => d.id === documentId); + if (document) { + document.embedding_model = null; + document.indexed_at = null; + document.updated_at = nowIso(); + } s.chunks = s.chunks.filter((c) => c.document_id !== documentId); const drafts = chunkDocument(body, opts); const created = nowIso(); @@ -347,20 +353,17 @@ export async function saveChunkEmbeddings( chunk.embedding_model = u.model; touched.add(chunk.document_id); } - const expected = updates[0]?.model ?? EMBEDDING_MODEL; for (const documentId of touched) { - const leftover = s.chunks.filter( - (c) => - c.document_id === documentId && - (!c.embedding || (c.embedding_model ?? "") !== expected), - ).length; - if (leftover === 0) { - const doc = s.documents.find((d) => d.id === documentId); - if (doc) { - doc.embedding_model = expected; - doc.indexed_at = nowIso(); - doc.updated_at = nowIso(); - } + const chunks = s.chunks.filter((c) => c.document_id === documentId); + const model = chunks[0]?.embedding_model; + const complete = Boolean(model) && chunks.every( + (c) => c.embedding && c.embedding_model === model, + ); + const doc = s.documents.find((d) => d.id === documentId); + if (doc) { + doc.embedding_model = complete ? model! : null; + doc.indexed_at = complete ? nowIso() : null; + doc.updated_at = nowIso(); } } persist(); diff --git a/web/src/lib/rag/store.server.ts b/web/src/lib/rag/store.server.ts index 153eee4..930a0fb 100644 --- a/web/src/lib/rag/store.server.ts +++ b/web/src/lib/rag/store.server.ts @@ -90,6 +90,10 @@ export async function replaceChunks( const sql = transaction ?? (await getSql()); if (!transaction) return sql.transaction((tx) => replaceChunks(documentId, body, opts, corpusId, tx)); + // Chunk membership and readiness change together under the same parent + // lock used by embedding writers, including direct/empty replacements. + await sql`update documents set embedding_model = null, indexed_at = null, + updated_at = now() where id = ${documentId}`; await sql`delete from chunks where document_id = ${documentId}`; const drafts = chunkDocument(body, opts); for (const draft of drafts) { @@ -365,35 +369,48 @@ export async function saveChunkEmbeddings( if (!getStorageStatus().denseAvailable) return; if (vercelWithoutDatabase()) return memory.saveChunkEmbeddings(updates); const sql = await getSql(); - const touched = new Set(); - for (const u of updates) { - if (!u.embedding.length) continue; - const json = JSON.stringify(u.embedding); - const rows = await sql<{ document_id: string }>` - update chunks - set embedding = ${json}, embedding_model = ${u.model} - where id = ${u.id} - returning document_id - `; - if (rows[0]) touched.add(rows[0].document_id); - } - const expected = updates[0]?.model ?? EMBEDDING_MODEL; - for (const documentId of touched) { - const leftover = await sql<{ n: number }>` - select count(*)::int as n from chunks - where document_id = ${documentId} - and (embedding is null or coalesce(embedding_model, '') <> ${expected}) + await sql.transaction(async (tx) => { + // Serialize batches touching the same document, including batches writing + // different chunks. Otherwise each can inspect an incomplete snapshot and + // race the document's final readiness marker. Stable order avoids deadlocks. + await tx` + select id from documents + where id in ( + select document_id from chunks where id = any(${updates.map((u) => u.id)}::text[]) + ) + order by id for update `; - if ((leftover[0]?.n ?? 1) === 0) { - await sql` - update documents - set embedding_model = ${updates[0]!.model}, - indexed_at = now(), - updated_at = now() - where id = ${documentId} - `; + const batch = new Map(); + for (const update of updates) { + if (update.embedding.length) batch.set(update.id, update); } - } + const rows = await tx<{ document_id: string }>` + update chunks as c + set embedding = u.embedding::text, embedding_model = u.model + from jsonb_to_recordset(${JSON.stringify([...batch.values()])}::jsonb) + as u(id text, embedding jsonb, model text) + where c.id = u.id + returning c.document_id + `; + const touched = [...new Set(rows.map((row) => row.document_id))]; + await tx` + update documents as d + set embedding_model = readiness.model, + indexed_at = case when readiness.model is not null then now() else null end, + updated_at = now() + from ( + select document_id, + case when count(embedding) = count(*) + and count(embedding_model) = count(*) + and count(distinct embedding_model) = 1 + and min(embedding_model) <> '' + then min(embedding_model) else null end as model + from chunks where document_id = any(${touched}::text[]) + group by document_id + ) as readiness + where d.id = readiness.document_id + `; + }); } export async function listCorpora(): Promise {