rag-service/tests/vectorstore/upsert.test.ts

230 lines
12 KiB
TypeScript

import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import test, { type TestContext } from "node:test";
import { QdrantClient } from "@qdrant/js-client-rest";
import { env } from "../../src/config/env.js";
import { OcrIndexingService, type ApprovedOcrCandidate } from "../../src/modules/ocr/indexing.js";
import { verifyVersionedDocuments, writeVersionedDocuments } from "../../src/modules/ingest/versioned-indexing.js";
import { QdrantVectorStoreClient } from "../../src/modules/vectorstore/client.js";
import type { IngestedChunk } from "../../src/shared/types/rag.js";
import { transferPolicy } from "../../src/modules/vectorstore/transfer.js";
const requestBudget = 8 * 1024 * 1024;
const versionId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
type Point = Pick<IngestedChunk, "id" | "vector" | "payload">;
async function httpHarness(t: TestContext, dimensions: number, policy = transferPolicy) {
const requests: Array<{ bytes: number; ids: string[]; wait: string | null }> = [];
const stored = new Map<string, Point>();
const control = { failRequest: 0, failStatus: 400, retryAfter: "", dropResponse: 0, holdResponse: 0, abortedResponses: 0, responseStatus: "completed", countOffset: 0 };
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url!, "http://localhost");
const respond = (result: unknown, status = 200) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify({ result, status: status === 200 ? "ok" : { error: "simulated batch failure" }, time: 0 }));
};
if (req.method === "GET") {
respond(url.pathname === "/collections" ? { collections: [{ name: env.qdrantCollection }] } : {
config: { params: { vectors: { size: dimensions } } },
payload_schema: Object.fromEntries(["source_id", "source_version_id", "document_id", "chunk_mode", "tags"].map((key) => [key, {}]))
});
return;
}
const buffers: Buffer[] = [];
for await (const buffer of req) buffers.push(Buffer.from(buffer));
const raw = Buffer.concat(buffers);
const body = JSON.parse(raw.toString("utf8"));
if (url.pathname.endsWith("/points/count")) {
assert.equal(body.exact, true);
const id = body.filter.must[0].match.value;
respond({ count: [...stored.values()].filter((point) => point.payload.source_version_id === id).length + control.countOffset });
return;
}
if (req.method === "POST" && url.pathname.endsWith("/points")) {
respond(body.ids.flatMap((id: string) => stored.has(id) ? [stored.get(id)] : []));
return;
}
assert.equal(req.method, "PUT");
assert.ok(url.pathname.endsWith("/points"));
const points: Point[] = body.points;
requests.push({ bytes: raw.length, ids: points.map(({ id }) => id), wait: url.searchParams.get("wait") });
if (requests.length === control.failRequest || raw.length > 32 * 1024 * 1024) {
if (control.retryAfter) res.setHeader("Retry-After", control.retryAfter);
respond(null, control.failStatus);
return;
}
if (control.responseStatus === "completed") {
for (const point of points) stored.set(point.id, point);
}
if (requests.length === control.dropResponse) { res.destroy(); return; }
if (requests.length === control.holdResponse) { res.on("close", () => { control.abortedResponses += 1; }); return; }
respond({ status: control.responseStatus, operation_id: requests.length });
} catch (error) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: { error: String(error) } }));
}
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
t.after(() => new Promise<void>((resolve, reject) => {
server.close((error) => error ? reject(error) : resolve());
server.closeAllConnections();
}));
const client = new QdrantClient({ url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, checkCompatibility: false, timeout: Infinity });
return { vectors: new QdrantVectorStoreClient(client, { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, apiKey: "" }, policy), requests, stored, control };
}
function chunks(count: number, dimensions = 3): IngestedChunk[] {
const vector = Array(dimensions).fill(0.12345678901234568);
return Array.from({ length: count }, (_, index) => ({
id: `00000000-0000-4000-8000-${index.toString(16).padStart(12, "0")}`, vector,
payload: { source_id: "test:book", source_version_id: versionId, content: `Page content ${index}` }
}));
}
test("a 740-point, 4096-dimensional document crosses the old limit but all HTTP batches fit", async (t) => {
const input = chunks(740, 4096);
assert.ok(Buffer.byteLength(JSON.stringify({ points: input })) > 32 * 1024 * 1024);
const h = await httpHarness(t, 4096);
await h.vectors.upsert(input);
assert.ok(h.requests.length > 1);
assert.ok(h.requests.every((request) => request.bytes <= requestBudget && request.wait === "true"));
assert.deepEqual(h.requests.flatMap(({ ids }) => ids), input.map(({ id }) => id));
assert.equal(await h.vectors.countVersionPoints(versionId), 740);
assert.deepEqual(h.stored.get(input[739]!.id), input[739]);
});
test("a temporary server error retries only the affected batch", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, maxBytes: 15_000, retryDelayMs: 1 });
h.control.failRequest = 2;
h.control.failStatus = 503;
const input = chunks(300);
await h.vectors.upsert(input);
assert.deepEqual(h.requests[1].ids, h.requests[2].ids);
assert.equal(h.stored.size, input.length);
assert.ok(!h.requests.slice(1).some(({ ids }) => ids.includes(input[0].id)));
});
test("a lost response is resolved by verifying stored IDs before any resend", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, retryDelayMs: 1 });
h.control.dropResponse = 1;
await h.vectors.upsert(chunks(30));
assert.equal(h.requests.length, 1);
assert.equal(h.stored.size, 30);
});
test("the HTTP request is actually cancelled on timeout and an applied batch is not resent", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, attemptTimeoutMs: 100, totalTimeoutMs: 2000, heartbeatMs: 10, retryDelayMs: 1 });
h.control.holdResponse = 1;
await h.vectors.upsert(chunks(10));
assert.equal(h.requests.length, 1);
assert.equal(h.control.abortedResponses, 1);
assert.equal(h.stored.size, 10);
});
test("HTTP Retry-After retains all digits and pauses when the prescribed delay exceeds the budget", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, totalTimeoutMs: 2000 });
h.control.failRequest = 1; h.control.failStatus = 429; h.control.retryAfter = "60";
let snapshot: import("../../src/modules/vectorstore/transfer.js").TransferState | undefined;
await assert.rejects(h.vectors.upsert(chunks(10), { journal: {
async load() { return undefined; }, async save(state) { snapshot = structuredClone(state); }
} }), /BUDGET_EXHAUSTED/u);
assert.equal(h.requests.length, 1);
assert.equal(snapshot!.batches[0].failure?.retryAfterMs, 60000);
});
test("small points are sized only by bytes, without an artificial point-count limit", async (t) => {
const h = await httpHarness(t, 3);
await h.vectors.upsert(chunks(257));
assert.deepEqual(h.requests.map(({ ids }) => ids.length), [257]);
assert.equal(h.stored.size, 257);
});
test("UTF-8 payload bytes, rather than character count, bound requests", async (t) => {
const h = await httpHarness(t, 3);
const input = chunks(3);
for (const point of input) point.payload.content = "é".repeat(1_500_000);
await h.vectors.upsert(input);
assert.deepEqual(h.requests.map(({ ids }) => ids.length), [2, 1]);
assert.ok(h.requests.every(({ bytes }) => bytes <= requestBudget));
assert.deepEqual(h.stored.get(input[2]!.id), input[2]);
});
test("an oversized individual point is rejected before any batch is written", async (t) => {
const h = await httpHarness(t, 3);
const input = chunks(130);
input[129]!.payload.content = "x".repeat(requestBudget);
await assert.rejects(h.vectors.upsert(input), /INDEXING_TRANSFER_POINT_TOO_LARGE/u);
assert.equal(h.requests.length, 0);
assert.equal(h.stored.size, 0);
});
test("empty input is a no-op and inconsistent dimensions fail before writes", async (t) => {
const h = await httpHarness(t, 3);
await h.vectors.upsert([]);
const input = chunks(130);
input[129]!.vector = [0.1];
await assert.rejects(h.vectors.upsert(input), /consistent dimensions/u);
assert.equal(h.requests.length, 0);
});
test("an acknowledged batch is verified and bounded by three timed attempts", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, attemptTimeoutMs: 100, totalTimeoutMs: 400,
heartbeatMs: 10, retryDelayMs: 1, verificationIntervalMs: 5 });
h.control.responseStatus = "acknowledged";
await assert.rejects(h.vectors.upsert(chunks(300)), /INDEXING_TRANSFER_RETRY_EXHAUSTED/u);
assert.equal(h.requests.length, 3);
assert.equal(h.stored.size, 0);
});
test("partial HTTP failure retries the same IDs and activates only after the global count matches", async (t) => {
const h = await httpHarness(t, 3, { ...transferPolicy, maxBytes: 80_000 });
const document = { documentId: "doc:book", documentKey: "book.pdf", contentHash: "content-hash", title: "Book",
mimeType: "application/pdf", chunkMode: "documental" as const,
chunks: Array.from({ length: 300 }, (_, index) => ({ index, sectionTitle: "Book", startLine: index + 1, endLine: index + 1, content: `Text ${index}` })) };
let readyCount = 0;
let activated = false;
const service = new OcrIndexingService({
async findReusableVersion() { return undefined; },
async indexReviewed() {
const written = await writeVersionedDocuments({
identity: { sourceId: "test:book", versionId, versionNumber: 1, sourceType: "file", sourceRef: "book.pdf", tags: [],
processingFingerprint: "fingerprint", expectedEmbeddingDimensions: 3 },
documents: [document], vectorStore: h.vectors,
embeddingProvider: { providerName: "test", modelName: "test", dimensions: 3, async embed(input) { return input.map(() => [0.1, 0.2, 0.3]); } }
});
return verifyVersionedDocuments({ versionId, expectedPointCount: 300, chunksWritten: written, vectorStore: h.vectors });
},
async markReady(_id, count) { readyCount = count; },
async activateVersion() { assert.equal(readyCount, 300); activated = true; return versionId; },
async settleReusable() { throw new Error("Unexpected reuse"); }
});
const candidate: ApprovedOcrCandidate = { versionId, sourceId: "test:book", state: "indexing", activateRequested: true,
expectedActiveVersionId: null, reviewedText: "reviewed", reviewedTextSha256: "hash", processingFingerprint: "fingerprint", metadataHash: "metadata" };
h.control.failRequest = 2;
await assert.rejects(service.index(candidate));
assert.equal(h.requests.length, 2);
assert.equal(h.stored.size, h.requests[0]!.ids.length);
assert.ok(h.stored.size > 0 && h.stored.size < 300);
const initialIds = [...h.stored.keys()];
assert.equal(readyCount, 0);
assert.equal(activated, false);
h.control.failRequest = 0;
h.control.countOffset = -1;
await assert.rejects(service.index(candidate), /expected catalog count/u);
assert.equal(h.stored.size, 300);
assert.equal(readyCount, 0);
assert.equal(activated, false);
h.control.countOffset = 0;
const result = await service.index(candidate);
assert.equal(result.state, "active");
assert.equal(result.activated, true);
assert.equal(h.stored.size, 300);
assert.deepEqual(h.requests[2]!.ids, h.requests[1]!.ids);
assert.equal(h.requests.filter(({ ids }) => ids.includes(initialIds[0])).length, 1);
assert.equal(readyCount, 300);
assert.equal(activated, true);
});