248 lines
14 KiB
TypeScript
248 lines
14 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import test from "node:test";
|
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
import { createApp } from "../../src/app.js";
|
|
import { env } from "../../src/config/env.js";
|
|
import { IndexingCheckpoint, readIndexingProgress } from "../../src/modules/ingest/indexing-checkpoint.js";
|
|
import { classifyTransferFailure, transferPoints, transferPolicy, type TransferJournal, type TransferPoint,
|
|
type TransferState, type TransferTransport } from "../../src/modules/vectorstore/transfer.js";
|
|
import { sha256Hex } from "../../src/shared/utils/ids.js";
|
|
|
|
const versionId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
|
|
const fastPolicy = { ...transferPolicy, maxBytes: 600, attemptTimeoutMs: 200, totalTimeoutMs: 2_000,
|
|
heartbeatMs: 5, retryDelayMs: 1, verificationIntervalMs: 2 };
|
|
|
|
function points(count = 6): TransferPoint[] {
|
|
return Array.from({ length: count }, (_, index) => ({ id: `point-${index}`, vector: [0.1, 0.2, 0.3],
|
|
payload: { source_version_id: versionId, content: `Text ${index} ${"x".repeat(50)}` } }));
|
|
}
|
|
|
|
function memoryJournal() {
|
|
let state: TransferState | undefined;
|
|
const snapshots: TransferState[] = [];
|
|
const journal: TransferJournal = { async load() { return state && structuredClone(state); },
|
|
async save(next) { state = structuredClone(next); snapshots.push(structuredClone(next)); } };
|
|
return { journal, snapshots, state: () => state! };
|
|
}
|
|
|
|
function transportHarness() {
|
|
const stored = new Set<string>();
|
|
const sent: string[][] = [];
|
|
const transport: TransferTransport = { async verify(batch) { return batch.every(({ id }) => stored.has(id)); },
|
|
async send(batch) { sent.push(batch.map(({ id }) => id)); for (const { id } of batch) stored.add(id); return "completed"; } };
|
|
return { transport, stored, sent };
|
|
}
|
|
|
|
test("expected connection, server, quota, payload and deterministic failures are classified", () => {
|
|
assert.equal(classifyTransferFailure({ cause: { code: "ECONNRESET" } }).kind, "connection");
|
|
assert.equal(classifyTransferFailure({ code: "ENOTFOUND" }).kind, "connection");
|
|
assert.equal(classifyTransferFailure({ name: "AbortError" }).kind, "timeout");
|
|
assert.equal(classifyTransferFailure({ status: 503 }).kind, "server");
|
|
assert.deepEqual(classifyTransferFailure({ status: 429, headers: { "retry-after": "2" } }),
|
|
{ kind: "overloaded", code: "INDEXING_TRANSFER_OVERLOADED", httpStatus: 429, retryAfterMs: 2000 });
|
|
assert.equal(classifyTransferFailure({ status: 400, data: { error: "JSON payload is larger than allowed limit" } }).kind, "payload_size");
|
|
assert.equal(classifyTransferFailure({ status: 401 }).kind, "invalid");
|
|
assert.equal(classifyTransferFailure({ statusCode: 503, code: "EMBEDDING_DIMENSIONS_INVALID" }).kind, "invalid");
|
|
assert.equal(classifyTransferFailure(new Error("unrecognized failure")).kind, "unknown");
|
|
});
|
|
|
|
test("three failed attempts pause durably and a later invocation cannot reset the budget", async () => {
|
|
const h = memoryJournal();
|
|
let sends = 0;
|
|
const transport: TransferTransport = { async verify() { return false; }, async send() { sends += 1; throw { status: 503 }; } };
|
|
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /RETRY_EXHAUSTED/u);
|
|
assert.equal(sends, 3);
|
|
assert.equal(h.state().phase, "paused");
|
|
assert.equal(h.state().batches[0].attempts, 3);
|
|
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /RETRY_EXHAUSTED/u);
|
|
assert.equal(sends, 3);
|
|
});
|
|
|
|
test("timeouts abort the actual pending operation, rather than merely abandoning its promise", async () => {
|
|
const h = memoryJournal();
|
|
let aborts = 0;
|
|
let pending = 0;
|
|
const transport: TransferTransport = { async verify() { return false; }, send(_batch, signal) {
|
|
pending += 1;
|
|
return new Promise((_resolve, reject) => signal.addEventListener("abort", () => {
|
|
pending -= 1; aborts += 1; reject(signal.reason);
|
|
}, { once: true }));
|
|
} };
|
|
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, { ...fastPolicy, attemptTimeoutMs: 20 }), /RETRY_EXHAUSTED/u);
|
|
assert.equal(aborts, 3);
|
|
assert.equal(pending, 0);
|
|
});
|
|
|
|
test("Retry-After is honored and cannot extend the total persisted deadline", async () => {
|
|
const h = memoryJournal();
|
|
let sends = 0;
|
|
const transport: TransferTransport = { async verify() { return false; }, async send() {
|
|
sends += 1; throw { status: 429, headers: new Headers({ "retry-after": "60" }) };
|
|
} };
|
|
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /BUDGET_EXHAUSTED/u);
|
|
assert.equal(sends, 1);
|
|
assert.equal(h.state().phase, "paused");
|
|
assert.ok(h.snapshots.some(({ phase }) => phase === "retry_wait"));
|
|
});
|
|
|
|
test("an explicit smaller server payload limit splits the affected batch and retains deadlines and attempt counts", async () => {
|
|
const h = memoryJournal();
|
|
const stored = new Set<string>();
|
|
const sizes: number[] = [];
|
|
const transport: TransferTransport = { async verify(batch) { return batch.every(({ id }) => stored.has(id)); }, async send(batch) {
|
|
sizes.push(batch.length);
|
|
if (batch.length > 2) throw { status: 413 };
|
|
for (const { id } of batch) stored.add(id);
|
|
return "completed";
|
|
} };
|
|
await transferPoints(points(4), transport, { journal: h.journal }, { ...fastPolicy, maxBytes: 2000 });
|
|
assert.deepEqual(sizes, [4, 2, 2]);
|
|
assert.equal(stored.size, 4);
|
|
assert.ok(h.state().batches.every(({ attempts }) => attempts === 2));
|
|
assert.equal(new Set(h.state().batches.map(({ deadlineAt }) => deadlineAt)).size, 1);
|
|
});
|
|
|
|
test("heartbeats persist activity during an in-flight operation without inventing confirmed progress", async () => {
|
|
const h = memoryJournal();
|
|
const base = transportHarness();
|
|
let release: (() => void) | undefined;
|
|
let sendingSignals = 0;
|
|
const journal: TransferJournal = { load: h.journal.load, async save(state) {
|
|
await h.journal.save(state);
|
|
if (state.phase === "sending" && ++sendingSignals >= 3) release?.();
|
|
} };
|
|
const transport: TransferTransport = { verify: base.transport.verify, async send(batch, signal) {
|
|
await new Promise<void>((resolve) => { release = resolve; });
|
|
return base.transport.send(batch, signal);
|
|
} };
|
|
await transferPoints(points(1), transport, { journal }, fastPolicy);
|
|
const sending = h.snapshots.filter(({ phase }) => phase === "sending");
|
|
assert.ok(sending.length >= 3);
|
|
assert.ok(sending.at(-1)!.updatedAt > sending[0].updatedAt);
|
|
assert.ok(sending.every((state) => state.batches.every(({ confirmed }) => !confirmed)));
|
|
assert.equal(h.state().phase, "complete");
|
|
});
|
|
|
|
test("slow checkpoint storage coalesces periodic signals instead of accumulating an unbounded write queue", async () => {
|
|
const h = memoryJournal();
|
|
let writes = 0;
|
|
const journal: TransferJournal = { load: h.journal.load, async save(state) {
|
|
writes += 1; await sleep(10); await h.journal.save(state);
|
|
} };
|
|
await transferPoints(points(1), transportHarness().transport, { journal }, { ...fastPolicy, heartbeatMs: 1 });
|
|
assert.equal(h.state().phase, "complete");
|
|
assert.ok(writes < 25, `Unexpected write backlog: ${writes}`);
|
|
});
|
|
|
|
test("vector preparation retries temporary failures and later processes reload the persisted result", async (t) => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "rag-vector-preparation-retry-"));
|
|
t.after(() => rm(root, { recursive: true, force: true }));
|
|
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
let calls = 0;
|
|
const cached = await checkpoint.preparePoints(async () => {
|
|
calls += 1;
|
|
if (calls < 3) throw { status: 503 };
|
|
return points(1);
|
|
}, 1, 1, { ...fastPolicy, heartbeatMs: 20, attemptTimeoutMs: 2000, totalTimeoutMs: 10000 });
|
|
assert.equal(calls, 3);
|
|
const restarted = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
assert.deepEqual(await restarted.preparePoints(async () => { calls += 1; throw new Error("must not call provider again"); }, 1, 1), cached);
|
|
assert.equal(calls, 3);
|
|
});
|
|
|
|
test("a persisted deadline exhausted during downtime pauses before any new request", async () => {
|
|
const h = memoryJournal();
|
|
await transferPoints(points(1), { async verify() { return false; }, async send() { throw { status: 429, headers: { "retry-after": "60" } }; } },
|
|
{ journal: h.journal }, fastPolicy).catch(() => {});
|
|
const state = h.state();
|
|
state.phase = "retry_wait"; state.failure = undefined;
|
|
state.batches[0].deadlineAt = Date.now() - 1;
|
|
await h.journal.save(state);
|
|
const transport = transportHarness();
|
|
await assert.rejects(transferPoints(points(1), transport.transport, { journal: h.journal }, fastPolicy), /BUDGET_EXHAUSTED/u);
|
|
assert.equal(transport.sent.length, 0);
|
|
});
|
|
|
|
test("a restart reloads cached vectors and verifies ambiguous/confirmed batches without retransmitting them", async (t) => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "rag-transfer-restart-"));
|
|
t.after(() => rm(root, { recursive: true, force: true }));
|
|
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
const durablePolicy = { ...fastPolicy, heartbeatMs: 20, attemptTimeoutMs: 5000, totalTimeoutMs: 20000 };
|
|
let embeddingCalls = 0;
|
|
const input = await checkpoint.preparePoints(async () => { embeddingCalls += 1; return points(); }, 6, 6, durablePolicy);
|
|
const h = transportHarness();
|
|
const crash: TransferJournal = { load: () => checkpoint.load(), async save(state) {
|
|
await checkpoint.save(state);
|
|
if (state.activeBatch === 1 && state.phase === "verifying") throw new Error("simulated process loss after durable checkpoint");
|
|
} };
|
|
await assert.rejects(transferPoints(input, h.transport, { journal: crash }, durablePolicy), /simulated process loss/u);
|
|
const before = await readIndexingProgress(root, versionId);
|
|
assert.ok(before!.confirmedPoints > 0 && before!.confirmedPoints < 6);
|
|
const restarted = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
const cached = await restarted.preparePoints(async () => { embeddingCalls += 1; throw new Error("must not regenerate vectors"); }, 6, 6, durablePolicy);
|
|
await transferPoints(cached, h.transport, { journal: restarted }, durablePolicy);
|
|
assert.equal(embeddingCalls, 1);
|
|
assert.equal(h.stored.size, 6);
|
|
assert.equal(new Set(h.sent.flat()).size, h.sent.flat().length);
|
|
const after = await readIndexingProgress(root, versionId);
|
|
assert.equal(after!.confirmedPoints, 6);
|
|
assert.equal(after!.paused, false);
|
|
const missing = cached[0].id;
|
|
h.stored.delete(missing);
|
|
await transferPoints(cached, h.transport, { journal: restarted }, durablePolicy);
|
|
assert.equal(h.stored.size, 6);
|
|
assert.ok(h.sent.at(-1)!.includes(missing));
|
|
assert.equal(embeddingCalls, 1);
|
|
});
|
|
|
|
test("cached vector corruption fails before any new embedding request", async (t) => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "rag-vector-cache-integrity-"));
|
|
t.after(() => rm(root, { recursive: true, force: true }));
|
|
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
await checkpoint.preparePoints(async () => points(1), 1, 1, fastPolicy);
|
|
const file = path.join(root, versionId, "indexing", `${sha256Hex("doc:book")}.points.json`);
|
|
const value = JSON.parse(await readFile(file, "utf8"));
|
|
value.points[0].vector[0] = 0.9;
|
|
await writeFile(file, JSON.stringify(value), { mode: 0o600 });
|
|
let calls = 0;
|
|
await assert.rejects(checkpoint.preparePoints(async () => { calls += 1; return points(1); }, 1, 1, fastPolicy), /integrity mismatch/u);
|
|
assert.equal(calls, 0);
|
|
});
|
|
|
|
test("authenticated ingestion status exposes progress without returning cached vectors", async (t) => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "rag-transfer-status-"));
|
|
t.after(() => rm(root, { recursive: true, force: true }));
|
|
const previous = { ocrIngestEnabled: env.ocrIngestEnabled, ocrArtifactRoot: env.ocrArtifactRoot, lifecycleAdminToken: env.lifecycleAdminToken };
|
|
Object.assign(env, { ocrIngestEnabled: true, ocrArtifactRoot: root, lifecycleAdminToken: "local-transfer-status-token" });
|
|
t.after(() => Object.assign(env, previous));
|
|
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
|
const h = transportHarness();
|
|
await transferPoints(points(1), h.transport, { journal: checkpoint }, fastPolicy);
|
|
const app = createApp({ startReconciler: false, catalog: { async getIngestionStatus() {
|
|
return { versionId, state: "indexing", phase: "indexing", documents: [] };
|
|
} } as never, vectorStore: {} as never });
|
|
const server = app.listen(0, "127.0.0.1");
|
|
t.after(() => { server.closeAllConnections(); server.close(); });
|
|
await new Promise<void>((resolve) => server.once("listening", resolve));
|
|
const address = server.address() as { port: number };
|
|
const url = `http://127.0.0.1:${address.port}/ingestions/${versionId}`;
|
|
assert.equal((await fetch(url)).status, 401);
|
|
const response = await fetch(url, { headers: { Authorization: "Bearer local-transfer-status-token" } });
|
|
assert.equal(response.status, 200);
|
|
const body = await response.json();
|
|
assert.equal(body.indexingTransfer.heartbeatMs, 5000);
|
|
assert.equal(body.indexingTransfer.confirmedPoints, 1);
|
|
assert.ok(!JSON.stringify(body).includes('"vector"'));
|
|
const state = (await checkpoint.load())!;
|
|
state.phase = "paused";
|
|
state.failure = { kind: "connection", code: "INDEXING_TRANSFER_RETRY_EXHAUSTED" };
|
|
await checkpoint.save(state);
|
|
const paused = await (await fetch(url, { headers: { Authorization: "Bearer local-transfer-status-token" } })).json();
|
|
assert.equal(paused.phase, "indexing_paused");
|
|
assert.equal(paused.error.code, "INDEXING_TRANSFER_RETRY_EXHAUSTED");
|
|
assert.equal(paused.error.retryable, false);
|
|
assert.equal(paused.indexingTransfer.paused, true);
|
|
});
|