fix(ocr): preserve canonical page order

This commit is contained in:
Paco POR-CORREO 2026-10-08 15:59:58 +02:00
parent dcfb5c0ffb
commit c60c225126
2 changed files with 75 additions and 27 deletions

View file

@ -78,13 +78,13 @@ export interface OcrReviewContext {
qualityReportSha256: string }>;
}
type ReviewReader = Pick<DurableOcrReviewReader, "view">;
type ReviewReader = Pick<DurableOcrReviewReader, "readCanonicalCandidate">;
export class PostgresOcrReviewStore implements OcrReviewStore {
constructor(private readonly pool: PgPool, private readonly reader: ReviewReader, private readonly rootDirectory: string) {}
loadCandidate(versionId: string): Promise<OcrReviewCandidate | undefined> {
return this.reader.view(versionId);
return this.reader.readCanonicalCandidate(versionId);
}
async commitApproval(input: Parameters<OcrReviewStore["commitApproval"]>[0]): Promise<void> {
@ -183,7 +183,7 @@ export class PostgresOcrReviewStore implements OcrReviewStore {
`SELECT document_id, page_number, native_text_hash, ocr_text_hash, candidate_text_hash, risk_tokens,
quality_outcome, quality_warnings, blocking_reasons, primary_blocking_reason, quality_report_sha256
FROM rag_document_pages WHERE version_id = $1 ORDER BY document_id, page_number FOR UPDATE`, [versionId]);
const candidate = await this.reader.view(versionId);
const candidate = await this.reader.readCanonicalCandidate(versionId);
if (candidate.versionId !== row.version_id || candidate.sourceId !== row.source_id || candidate.state !== row.state
|| candidate.baseActiveVersionId !== row.base_active_version_id || candidate.currentActiveVersionId !== row.current_active_version_id
|| candidate.activateRequested !== row.activate_requested || candidate.processingFingerprint !== row.processing_fingerprint
@ -205,7 +205,7 @@ export class PostgresOcrReviewStore implements OcrReviewStore {
export class DurableOcrReviewReader {
constructor(private readonly catalog: { loadOcrReviewContext(versionId: string): Promise<OcrReviewContext | undefined> }, private readonly rootDirectory: string) {}
async view(versionId: string): Promise<OcrReviewCandidate> {
async readCanonicalCandidate(versionId: string): Promise<OcrReviewCandidate> {
const context = await this.catalog.loadOcrReviewContext(versionId);
if (!context) throw new CatalogError("OCR review candidate not found", 404, "REVIEW_NOT_FOUND");
if (context.versionId !== versionId) throw new Error("OCR review candidate identity validation failed");
@ -229,19 +229,23 @@ export class DurableOcrReviewReader {
}
const { pages: _lifecyclePages, ...identity } = context;
const documents = candidate.documents.map((document) => ({ documentId: document.documentId,
pages: prioritizeReviewPages(document.pages.map((page) => ({
pages: document.pages.map((page) => ({
page: page.page, imageUrl: page.method === "native" ? null : `/ingestions/${versionId}/documents/${encodeURIComponent(document.documentId)}/pages/${page.page}/image`,
nativeText: page.nativeText, ocr: { text: page.rawOcrText, lines: page.lines }, candidateText: page.candidateText,
differences: page.nativeText === page.rawOcrText ? [] : ["Native and OCR text differ"], risks: page.risks,
qualityOutcome: page.qualityOutcome, warnings: page.warnings, blockingReasons: page.blockingReasons,
primaryBlockingReason: page.primaryBlockingReason
}))) })).sort((left, right) => compareReviewPages(left.pages[0]!, right.pages[0]!));
})) }));
return { ...identity, state: "review_required", candidateSha256: candidate.candidateSha256,
qualityReportSha256: candidate.qualityReportSha256, documents };
}
async view(versionId: string): Promise<OcrReviewCandidate> {
return prioritizeReviewCandidate(await this.readCanonicalCandidate(versionId));
}
async image(versionId: string, documentId: string, page: number) {
const candidate = await this.view(versionId);
const candidate = await this.readCanonicalCandidate(versionId);
if (!candidate.documents.some((document) => document.documentId === documentId && document.pages.some((item) => item.page === page))) throw new CatalogError("OCR review image not found", 404, "REVIEW_IMAGE_NOT_FOUND");
return readReviewImageArtifact({ rootDirectory: this.rootDirectory, versionId, documentId, page });
}
@ -267,6 +271,10 @@ export class OcrReviewService {
constructor(private readonly store: OcrReviewStore) {}
async view(versionId: string): Promise<OcrReviewCandidate> {
return prioritizeReviewCandidate(await this.loadCanonicalCandidate(versionId));
}
private async loadCanonicalCandidate(versionId: string): Promise<OcrReviewCandidate> {
const candidate = await this.store.loadCandidate(versionId);
if (!candidate) throw new CatalogError("OCR review candidate not found", 404, "REVIEW_NOT_FOUND");
if (candidate.state !== "review_required") throw conflict("Version is not awaiting OCR review", "INVALID_VERSION_STATE");
@ -279,7 +287,7 @@ export class OcrReviewService {
reviewedBy: string;
corrections: OcrCorrection[];
}): Promise<ApprovedOcrReview> {
const candidate = await this.view(versionId);
const candidate = await this.loadCanonicalCandidate(versionId);
if (input.candidateSha256 !== candidate.candidateSha256) throw conflict("Candidate hash is stale");
if (input.expectedActiveVersionId !== candidate.baseActiveVersionId || input.expectedActiveVersionId !== candidate.currentActiveVersionId) {
throw conflict("Active version changed during review", "ACTIVE_VERSION_CHANGED");
@ -305,7 +313,7 @@ export class OcrReviewService {
const reviewedBy = input.reviewedBy?.trim();
const reason = input.reason?.trim();
if (!input.candidateSha256 || !reviewedBy || !reason) throw new CatalogError("Candidate hash, reviewer, and rejection reason are required", 400, "INVALID_REJECTION");
const candidate = await this.view(versionId);
const candidate = await this.loadCanonicalCandidate(versionId);
if (input.candidateSha256 !== candidate.candidateSha256) throw conflict("Candidate hash is stale");
await this.store.commitRejection({ candidate, candidateSha256: input.candidateSha256, reviewedBy, reason });
return { versionId, state: "rejected", activated: false };
@ -313,14 +321,14 @@ export class OcrReviewService {
}
export class OcrReviewRecoveryService {
constructor(private readonly reader: Pick<DurableOcrReviewReader, "view">, private readonly store: OcrReviewRecoveryStore) {}
constructor(private readonly reader: Pick<DurableOcrReviewReader, "readCanonicalCandidate">, private readonly store: OcrReviewRecoveryStore) {}
async recover(versionId: string, input: { recoveredBy: string; reason: string }): Promise<{ versionId: string; state: "failed"; outcome: "closed_failed" }> {
const recoveredBy = input?.recoveredBy?.trim();
const reason = input?.reason?.trim();
if (!recoveredBy || !reason) throw new CatalogError("Recovery actor and reason are required", 400, "OCR_RECOVERY_INVALID");
try {
await this.reader.view(versionId);
await this.reader.readCanonicalCandidate(versionId);
} catch (error) {
const classified = classifyOcrReviewError(error);
if (classified.statusCode !== 409 && classified.statusCode !== 422) throw classified;
@ -372,6 +380,15 @@ function reviewedText(candidate: OcrReviewCandidate): string {
return candidate.documents.flatMap(({ pages }) => pages.filter(({ candidateText }) => candidateText).map(({ candidateText }) => candidateText)).join("\n\n");
}
function prioritizeReviewCandidate(candidate: OcrReviewCandidate): OcrReviewCandidate {
const prioritized = structuredClone(candidate);
const documents = prioritized.documents.map((document) => ({
...document,
pages: prioritizeReviewPages(document.pages)
})).sort((left, right) => compareReviewPages(left.pages[0]!, right.pages[0]!));
return { ...prioritized, documents };
}
export function prioritizeReviewPages<T extends { page: number; qualityOutcome: OcrQualityOutcome; risks: string[] }>(pages: ReadonlyArray<T>): T[] {
return [...pages].sort(compareReviewPages);
}

View file

@ -27,6 +27,22 @@ function candidate(state: OcrReviewCandidate["state"] = "review_required"): OcrR
};
}
function priorityCandidate(): OcrReviewCandidate {
const value = candidate();
value.qualityReportSha256 = sha256Hex("quality-report");
value.documents[0]!.pages = [1, 2, 3].map((page) => {
const text = `Page ${page} original`;
const line = { lineId: `page-${page}-line`, text, confidence: 0.9,
bbox: [0, page * 10, 50, page * 10 + 8] as [number, number, number, number], lineSha256: sha256Hex(text) };
return {
page, imageUrl: `/private/page-${page}.png`, nativeText: "", ocr: { text, lines: [line] }, candidateText: text,
differences: [], risks: page === 3 ? ["MMS2"] : [], qualityOutcome: "accepted" as const,
warnings: [], blockingReasons: [], primaryBlockingReason: null
};
});
return value;
}
test("review HTTP rejects unauthorized and premature access without exposing artifacts", async (context) => {
const previous = { token: env.lifecycleAdminToken, enabled: env.ocrIngestEnabled };
Object.assign(env, { lifecycleAdminToken: "review-token", ocrIngestEnabled: true });
@ -303,12 +319,16 @@ function decisionPool(current: OcrReviewCandidate, state = "review_required", fa
current_active_version_id: current.currentActiveVersionId, activate_requested: current.activateRequested,
processing_fingerprint: current.processingFingerprint, metadata_hash: current.metadataHash
}] };
if (statement.includes("FROM rag_document_pages") && statement.includes("FOR UPDATE")) return { rowCount: 1, rows: [{
document_id: current.documents[0]!.documentId, page_number: 1,
native_text_hash: sha256Hex(current.documents[0]!.pages[0]!.nativeText),
ocr_text_hash: sha256Hex(current.documents[0]!.pages[0]!.ocr.text),
candidate_text_hash: sha256Hex(current.documents[0]!.pages[0]!.candidateText), risk_tokens: current.documents[0]!.pages[0]!.risks
}] };
if (statement.includes("FROM rag_document_pages") && statement.includes("FOR UPDATE")) {
const rows = current.documents.flatMap((document) => document.pages.map((page) => ({
document_id: document.documentId, page_number: page.page,
native_text_hash: sha256Hex(page.nativeText), ocr_text_hash: page.imageUrl === null ? null : sha256Hex(page.ocr.text),
candidate_text_hash: sha256Hex(page.candidateText), risk_tokens: page.risks,
quality_outcome: page.qualityOutcome, quality_warnings: page.warnings, blocking_reasons: page.blockingReasons,
primary_blocking_reason: page.primaryBlockingReason, quality_report_sha256: current.qualityReportSha256
})));
return { rowCount: rows.length, rows };
}
if (failReviewedPage && statement.includes("SET reviewed_text_hash")) return { rowCount: 0, rows: [] };
return { rowCount: 1, rows: [] };
},
@ -319,20 +339,31 @@ function decisionPool(current: OcrReviewCandidate, state = "review_required", fa
test("production decision store commits corrected reviewed pages and the indexing transition in one locked transaction", async (context) => {
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-review-decision-"));
const current = candidate();
const current = priorityCandidate();
current.versionId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
await mkdir(path.join(rootDirectory, current.versionId));
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
const { pool, sql } = decisionPool(current);
const store = new PostgresOcrReviewStore(pool, { async view() { return structuredClone(current); } }, rootDirectory);
const approved = await new OcrReviewService(store).approve(current.versionId, {
const store = new PostgresOcrReviewStore(pool, { async readCanonicalCandidate() { return current; } }, rootDirectory);
const service = new OcrReviewService(store);
const review = await service.view(current.versionId);
assert.deepEqual(review.documents[0]!.pages.map(({ page }) => page), [3, 1, 2]);
assert.deepEqual(current.documents[0]!.pages.map(({ page }) => page), [1, 2, 3]);
const approved = await service.approve(current.versionId, {
candidateSha256: current.candidateSha256, expectedActiveVersionId: current.baseActiveVersionId, reviewedBy: "admin",
corrections: [{ documentId: "document-1", page: 1, lineId: "line-1", expectedLineSha256: sha256Hex("CBGO4a"), replacementText: "CBG04a" }]
corrections: [{ documentId: "document-1", page: 3, lineId: "page-3-line", expectedLineSha256: sha256Hex("Page 3 original"), replacementText: "Page 3 corrected" }]
});
assert.equal(approved.reviewedText, "Page 1 original\n\nPage 2 original\n\nPage 3 corrected");
assert.equal(approved.reviewedTextSha256, sha256Hex(approved.reviewedText));
const reviewed = await readReviewedPagesArtifact({ rootDirectory, versionId: current.versionId,
candidateSha256: current.candidateSha256, reviewedTextSha256: approved.reviewedTextSha256 });
assert.equal(reviewed.documents[0]!.pages[0]!.candidateText, "CBG04a\nFATo7");
assert.deepEqual(reviewed.documents[0]!.pages.map(({ page }) => page), [1, 2, 3]);
assert.deepEqual(reviewed.documents[0]!.pages.map(({ candidateText }) => candidateText), [
"Page 1 original", "Page 2 original", "Page 3 corrected"
]);
assert.equal(reviewed.documents.flatMap(({ pages }) => pages.map(({ candidateText }) => candidateText)).join("\n\n"), approved.reviewedText);
assert.match(sql.join("\n"), /FOR UPDATE OF v, s/u);
assert.match(sql.join("\n"), /INSERT INTO rag_review_corrections/u);
assert.match(sql.join("\n"), /reviewed_text_hash/u);
@ -350,20 +381,20 @@ test("production decisions reject stale, replayed, and path-corrupt writes witho
for (const conflictState of ["indexing", "rejected"]) {
const { pool, sql } = decisionPool(current, conflictState);
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async view() { return structuredClone(current); } }, rootDirectory));
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async readCanonicalCandidate() { return structuredClone(current); } }, rootDirectory));
await assert.rejects(service.approve(current.versionId, input), (error) => error instanceof CatalogError && error.statusCode === 409);
assert.doesNotMatch(sql.join("\n"), /INSERT INTO rag_review_corrections|SET state = 'indexing'/u);
}
const { pool, sql } = decisionPool(current);
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async view() { return structuredClone(current); } }, rootDirectory));
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async readCanonicalCandidate() { return structuredClone(current); } }, rootDirectory));
await assert.rejects(service.approve(current.versionId, input), /ENOENT|artifact directory/u);
assert.doesNotMatch(sql.join("\n"), /INSERT INTO rag_review_corrections|SET state = 'indexing'/u);
await assert.rejects(access(path.join(rootDirectory, current.versionId, "reviewed-pages.json")));
await mkdir(path.join(rootDirectory, current.versionId));
const partial = decisionPool(current, "review_required", true);
const partialService = new OcrReviewService(new PostgresOcrReviewStore(partial.pool, { async view() { return structuredClone(current); } }, rootDirectory));
const partialService = new OcrReviewService(new PostgresOcrReviewStore(partial.pool, { async readCanonicalCandidate() { return structuredClone(current); } }, rootDirectory));
await assert.rejects(partialService.approve(current.versionId, input), /page evidence changed/u);
assert.equal(partial.sql.at(-1)?.trim(), "ROLLBACK");
await assert.rejects(access(path.join(rootDirectory, current.versionId, "reviewed-pages.json")));
@ -376,7 +407,7 @@ test("production rejection records the bound reason without reviewed, correction
await mkdir(path.join(rootDirectory, current.versionId));
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
const { pool, sql } = decisionPool(current);
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async view() { return structuredClone(current); } }, rootDirectory));
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async readCanonicalCandidate() { return structuredClone(current); } }, rootDirectory));
assert.deepEqual(await service.reject(current.versionId, { candidateSha256: current.candidateSha256, reviewedBy: " admin ", reason: " unreadable code " }),
{ versionId: current.versionId, state: "rejected", activated: false });
@ -396,7 +427,7 @@ test("production rejection accepts the persisted hash of an empty OCR page", asy
risks: []
});
const { pool, sql } = decisionPool(current);
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async view() { return structuredClone(current); } }, "/unused"));
const service = new OcrReviewService(new PostgresOcrReviewStore(pool, { async readCanonicalCandidate() { return structuredClone(current); } }, "/unused"));
assert.deepEqual(await service.reject(current.versionId, {
candidateSha256: current.candidateSha256,