rag-service/tests/ocr/content-policy.test.ts

194 lines
15 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 { CONTENT_POLICY_VERSION, isNativeTextUsable, selectPageContent } from "../../src/modules/ocr/content-policy.js";
import { composeCandidate } from "../../src/modules/ocr/composition.js";
import { chunkSelectedPages } from "../../src/modules/ocr/chunking.js";
import { chunkDocument, documentalChunkingPolicy } from "../../src/modules/process/chunking.js";
import { buildOcrIdentity, type OcrResult } from "../../src/modules/ocr/client.js";
import { persistComposedCandidateArtifact, persistOcrResultArtifact, persistReviewImageArtifacts,
readComposedCandidateArtifact, readReviewedPagesArtifactForRecovery, stageOcrArtifacts } from "../../src/modules/ocr/artifacts.js";
import { DurableOcrReviewReader, OcrReviewService, PostgresOcrReviewStore, type OcrReviewCandidate } from "../../src/modules/ocr/review.js";
import { canonicalJson, normalizeContentForHash, sha256Hex } from "../../src/shared/utils/ids.js";
test("native fallback accepts short Unicode captions without admitting punctuation or corrupt text", () => {
for (const text of ["Título", "图3", "٣", "A\n"]) assert.equal(isNativeTextUsable(text), true, text);
for (const text of ["", " \n", "...", "\uFFFD", "A\u0000", "A\uFFFD"]) assert.equal(isNativeTextUsable(text), false, text);
assert.equal(isNativeTextUsable("A".repeat(100) + "\uFFFD"), true);
assert.equal(isNativeTextUsable("A".repeat(98) + "\uFFFD"), false);
});
test("selection separates OCR diagnosis from chosen content for every policy branch", () => {
const choose = (method: "native" | "ocr" | "blank", qualityOutcome: "accepted" | "warning" | "blocked", nativeText = "") =>
selectPageContent({ method, qualityOutcome, nativeText });
assert.equal(choose("native", "accepted", "Text").reason, "native_only");
assert.equal(choose("ocr", "accepted", "Native").source, "ocr");
assert.equal(choose("ocr", "warning", "Caption").source, "native");
assert.equal(choose("ocr", "blocked", "Caption").issue, "visual_content_not_incorporated");
assert.equal(choose("ocr", "warning").source, "ocr");
assert.equal(choose("ocr", "blocked").contentUnrecovered, true);
assert.equal(choose("blank", "accepted", "Caption").reason, "blank_discrepancy");
assert.equal(choose("blank", "accepted").reason, "verified_blank");
});
test("best-effort composition keeps rejected OCR lines as evidence and cannot collide with legacy candidate identity", () => {
const input = [{ page: 1, method: "ocr" as const, nativeText: "Título", rawOcrText: "garbled",
lines: [{ lineId: "l1", text: "garbled", confidence: 0.6, bbox: [0, 0, 10, 10] as [number, number, number, number] }],
qualityOutcome: "blocked" as const, blockingReasons: ["LOW_MEDIAN_CONFIDENCE" as const], primaryBlockingReason: "LOW_MEDIAN_CONFIDENCE" as const }];
const legacy = composeCandidate(input);
const selected = composeCandidate(input, true);
assert.equal(legacy.pages[0]!.candidateText, "garbled");
assert.equal(selected.pages[0]!.candidateText, "Título");
assert.equal(selected.pages[0]!.rawOcrText, "garbled");
assert.equal(selected.pages[0]!.lines[0]!.text, "garbled");
assert.equal(selected.pages[0]!.qualityOutcome, "blocked");
assert.notEqual(legacy.candidateSha256, selected.candidateSha256);
});
test("chunk boundaries exclude unrecovered pages but leave verified blank pages on the legacy path", () => {
const hole = selectPageContent({ method: "ocr", qualityOutcome: "blocked", nativeText: "" });
const blank = selectPageContent({ method: "blank", qualityOutcome: "accepted", nativeText: "" });
const pages = [{ candidateText: "Before gap" }, { candidateText: "", selection: hole }, { candidateText: "After gap" }];
const chunks = chunkSelectedPages("Fixture", pages);
assert.deepEqual(chunks.map(({ content }) => content), ["Before gap", "After gap"]);
assert.deepEqual(chunks.map(({ index }) => index), [0, 1]);
assert.deepEqual(chunks.map(({ startLine }) => startLine), [1, 3]);
assert.deepEqual(chunkSelectedPages("Fixture", [{ candidateText: "Before gap" }, { candidateText: "", selection: blank }, { candidateText: "After gap" }]),
chunkDocument("Fixture", normalizeContentForHash("Before gap\n\nAfter gap"), documentalChunkingPolicy));
assert.deepEqual(chunkSelectedPages("Fixture", pages), chunks);
});
test("gap line ranges follow normalized selected text across consecutive holes and whitespace", () => {
const hole = { candidateText: "", selection: selectPageContent({ method: "ocr", qualityOutcome: "blocked", nativeText: "" }) };
const pages = [hole, { candidateText: "\uFEFF\r\n Alpha\r\nTail \r\n " }, hole, hole,
{ candidateText: " \r\nBeta\r\nFinal\r\n " }, hole];
const chunks = chunkSelectedPages("Fixture", pages);
assert.deepEqual(chunks.map(({ content, index, startLine, endLine }) => ({ content, index, startLine, endLine })), [
{ content: "Alpha\nTail", index: 0, startLine: 1, endLine: 2 },
{ content: "Beta\nFinal", index: 1, startLine: 6, endLine: 7 }
]);
const selectedLines = normalizeContentForHash(pages.filter(({ candidateText }) => candidateText.trim())
.map(({ candidateText }) => candidateText).join("\n\n")).split("\n");
for (const chunk of chunks) assert.equal(selectedLines.slice(chunk.startLine - 1, chunk.endLine).join("\n").trim(), chunk.content);
assert.deepEqual(chunkSelectedPages("Fixture", [hole, hole]), []);
});
async function durableFixture(context: { after(callback: () => unknown): void }, unusable = false, companion = false) {
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-page-policy-"));
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
const versionId = "abababab-abab-4aba-8aba-abababababab";
const documentId = "doc:page-policy";
const original = Buffer.from("%PDF-synthetic-policy-fixture");
const nativeTexts = unusable ? [""] : ["Título", "", "", "", "Leyenda", ""];
const numbers = nativeTexts.map((_, index) => index + 1);
await stageOcrArtifacts({ rootDirectory, versionId, contentPolicyVersion: CONTENT_POLICY_VERSION,
createdAt: "2026-10-09T12:00:00.000Z", documents: [{ documentId, documentKey: "policy.pdf", bytes: original,
requestedPages: numbers, pages: nativeTexts.map((text, index) => ({ page: index + 1, text, rasterCoverage: 1, textSha256: sha256Hex(text) })) },
...(companion ? [{ documentId: "doc:native-companion", documentKey: "companion.pdf", bytes: Buffer.from("%PDF-native-companion"),
requestedPages: [], pages: [{ page: 1, text: "Native companion", rasterCoverage: 0, textSha256: sha256Hex("Native companion") }] }] : [])] });
const identity = buildOcrIdentity({ documentSha256: sha256Hex(original), pages: numbers, idempotencyKey: "policy-fixture" });
const pages: OcrResult["pages"] = numbers.map((page) => {
const blank = page >= 5;
const blocked = page <= 2;
const text = blank ? "" : blocked ? "garbled" : `Recognized text on page ${page} with enough meaningful characters for review`;
return { page, width: 100, height: 100, processingMs: 1, text,
metrics: { lineCount: blank ? 0 : 1, nonWhitespaceCharacters: text.replace(/\s/g, "").length,
inkCoverage: blank ? 0 : 0.4, medianConfidence: blocked ? 0.6 : 0.99,
p10Confidence: page === 3 ? 0.2 : 0.99, lowConfidenceLineRatio: blocked ? 1 : page === 3 ? 0.1 : 0 },
lines: blank ? [] : [{ lineId: `p${page}-l1`, text, confidence: blocked ? 0.6 : 0.99, bbox: [1, 2, 30, 10] }] };
});
await persistOcrResultArtifact({ rootDirectory, versionId, documentId, result: { schemaVersion: "1", jobId: "policy-job", ...identity,
engine: { name: "paddleocr", version: "3.4.0", runtime: "paddlepaddle-3.2.2", device: "cpu", configVersion: "ocr-v2", dpi: 200 }, pages } });
const png = Buffer.from("89504e470d0a1a0a01020304", "hex");
await persistReviewImageArtifacts({ rootDirectory, versionId, documentId, images: numbers.map((page) => ({ page, bytes: png, sha256: sha256Hex(png) })) });
return { rootDirectory, versionId, documentId, jobs: [{ documentId, remoteJobId: "policy-job", requestedPages: numbers, state: "succeeded" }] };
}
test("durable approval and restart retain native fallback, OCR evidence, gaps and blank discrepancies", async (context) => {
const fixture = await durableFixture(context);
const { candidate } = await persistComposedCandidateArtifact(fixture);
assert.equal(candidate.schemaVersion, "2");
const manifest = JSON.parse(await readFile(path.join(fixture.rootDirectory, fixture.versionId, "manifest.json"), "utf8"));
assert.equal(manifest.schemaVersion, "2");
assert.equal(manifest.contentPolicyVersion, CONTENT_POLICY_VERSION);
const lifecycle = { versionId: fixture.versionId, sourceId: "src:policy", state: "review_required",
baseActiveVersionId: null, currentActiveVersionId: null, activateRequested: false, processingFingerprint: "new-policy", metadataHash: "metadata",
pages: candidate.documents.flatMap(({ documentId, pages }) => pages.map((page) => ({ documentId, ...page }))) };
const reader = new DurableOcrReviewReader({ async loadOcrReviewContext() { return lifecycle; } }, fixture.rootDirectory);
const current = await reader.readCanonicalCandidate(fixture.versionId);
assert.equal(current.documents[0]!.pages[0]!.candidateText, "Título");
assert.ok(current.documents[0]!.pages[0]!.imageUrl);
assert.equal(current.documents[0]!.pages[1]!.selection!.contentUnrecovered, true);
assert.equal(current.documents[0]!.pages[4]!.candidateText, "Leyenda");
assert.equal(current.coverage!.pagesWithIssues, 4);
const query = async (sql: string) => {
if (sql.includes("FOR UPDATE OF v, s")) return { rowCount: 1, rows: [{ version_id: current.versionId, source_id: current.sourceId,
state: current.state, base_active_version_id: null, current_active_version_id: null, activate_requested: false,
processing_fingerprint: current.processingFingerprint, metadata_hash: current.metadataHash }] };
if (sql.includes("FROM rag_document_pages") && sql.includes("FOR UPDATE")) return { rowCount: lifecycle.pages.length, rows: lifecycle.pages.map((page) => ({
document_id: page.documentId, page_number: page.page, native_text_hash: page.nativeTextSha256, ocr_text_hash: page.ocrTextSha256,
candidate_text_hash: page.candidateTextSha256, risk_tokens: page.risks, quality_outcome: page.qualityOutcome,
quality_warnings: page.warnings, blocking_reasons: page.blockingReasons, primary_blocking_reason: page.primaryBlockingReason,
quality_report_sha256: page.qualityReportSha256, content_selection: page.selection })) };
return { rowCount: 1, rows: [] };
};
const pool = { async connect() { return { query, release() {} }; } };
const service = new OcrReviewService(new PostgresOcrReviewStore(pool as never, reader, fixture.rootDirectory));
await assert.rejects(service.approve(current.versionId, { candidateSha256: current.candidateSha256, expectedActiveVersionId: null,
reviewedBy: "reviewer", corrections: [{ documentId: fixture.documentId, page: 1, lineId: "p1-l1",
expectedLineSha256: sha256Hex("garbled"), replacementText: "Do not reintroduce rejected OCR" }] }), /Correction target/u);
const approved = await service.approve(current.versionId, { candidateSha256: current.candidateSha256,
expectedActiveVersionId: null, reviewedBy: "reviewer", corrections: [{ documentId: fixture.documentId, page: 3, lineId: "p3-l1",
expectedLineSha256: current.documents[0]!.pages[2]!.ocr.lines[0]!.lineSha256, replacementText: "Reviewed warning text" }] });
assert.doesNotMatch(approved.reviewedText, /garbled/u);
const recovered = await readReviewedPagesArtifactForRecovery({ ...fixture, candidateSha256: current.candidateSha256 });
assert.equal(recovered.schemaVersion, "2");
assert.deepEqual(recovered.documents[0]!.pages.map(({ candidateText }) => candidateText),
["Título", "", "Reviewed warning text", current.documents[0]!.pages[3]!.candidateText, "Leyenda", ""]);
assert.equal(recovered.documents[0]!.pages[0]!.ocr.lines[0]!.text, "garbled");
const chunks = chunkSelectedPages("Fixture", recovered.documents[0]!.pages);
assert.equal(chunks[0]!.content, "Título");
assert.ok(chunks.some(({ content }) => content.includes("Reviewed warning text")));
assert.ok(chunks.every(({ content }) => !content.includes("garbled")));
});
test("a completely unreadable document cannot publish a reviewable candidate", async (context) => {
const fixture = await durableFixture(context, true);
await assert.rejects(persistComposedCandidateArtifact(fixture), /OCR_NO_USABLE_CONTENT/u);
});
test("a useful companion document cannot silently hide an entirely unreadable document in a folder", async (context) => {
const fixture = await durableFixture(context, true, true);
await assert.rejects(persistComposedCandidateArtifact(fixture), /OCR_NO_USABLE_CONTENT/u);
});
test("rehashing a forged content selection cannot bypass immutable native and OCR evidence", async (context) => {
const fixture = await durableFixture(context);
const { candidate } = await persistComposedCandidateArtifact(fixture);
candidate.documents[0]!.pages[0]!.candidateText = "Forged fallback";
candidate.documents[0]!.pages[0]!.candidateTextSha256 = sha256Hex("Forged fallback");
candidate.candidateSha256 = sha256Hex(canonicalJson({ qualityReportSha256: candidate.qualityReportSha256, documents: candidate.documents }));
await writeFile(path.join(fixture.rootDirectory, fixture.versionId, "candidate-pages.json"), canonicalJson(candidate), { mode: 0o600 });
await assert.rejects(readComposedCandidateArtifact(fixture), /integrity validation failed/u);
});
test("reviewed selection tampering is rejected on recovery even if its text hash still matches", async (context) => {
const fixture = await durableFixture(context);
const { candidate } = await persistComposedCandidateArtifact(fixture);
const pages = candidate.documents[0]!.pages;
const review: OcrReviewCandidate = { versionId: fixture.versionId, sourceId: "src:policy", state: "review_required",
candidateSha256: candidate.candidateSha256, qualityReportSha256: candidate.qualityReportSha256,
baseActiveVersionId: null, currentActiveVersionId: null, activateRequested: false, processingFingerprint: "policy", metadataHash: "metadata",
documents: [{ documentId: fixture.documentId, pages: pages.map((page) => ({ ...page, imageUrl: "private", ocr: { text: page.rawOcrText, lines: page.lines }, differences: [] })) }] };
const { persistReviewedPagesArtifact } = await import("../../src/modules/ocr/artifacts.js");
const text = review.documents[0]!.pages.filter(({ candidateText }) => candidateText).map(({ candidateText }) => candidateText).join("\n\n");
await persistReviewedPagesArtifact({ ...fixture, sourceId: review.sourceId, candidateSha256: candidate.candidateSha256,
reviewedTextSha256: sha256Hex(text), reviewedBy: "reviewer", documents: review.documents });
const target = path.join(fixture.rootDirectory, fixture.versionId, "reviewed-pages.json");
const value = JSON.parse(await readFile(target, "utf8"));
value.documents[0].pages[1].selection.contentUnrecovered = false;
await writeFile(target, canonicalJson(value), { mode: 0o600 });
await assert.rejects(readReviewedPagesArtifactForRecovery({ ...fixture, candidateSha256: candidate.candidateSha256 }), /integrity validation failed/u);
});