fix(ocr): reuse native indexing and recover approved candidates
This commit is contained in:
parent
9f1b91dcf3
commit
ffd15589ec
20 changed files with 1393 additions and 172 deletions
|
|
@ -2,8 +2,8 @@
|
|||
|
||||
**Proyecto:** Workspace de tools IA para empresas
|
||||
**Modulo:** RAG
|
||||
**Ultima actualizacion:** 2026-09-21
|
||||
**Ultima modificacion por:** Agente RAG 2
|
||||
**Ultima actualizacion:** 2026-10-03
|
||||
**Ultima modificacion por:** Subagente integracion nativa OCR
|
||||
**Estado:** Produccion en `0.1.0`; version `0.2.0` preparada localmente
|
||||
|
||||
Esta guia explica como descubrir y consumir la API. El contrato tecnico completo y canonico se publica en OpenAPI 3.1.1; este documento prioriza el camino rapido, las decisiones de uso y los ejemplos habituales.
|
||||
|
|
@ -61,6 +61,8 @@ La API queda formada por las operaciones de descubrimiento, ingesta, retrieval,
|
|||
| `POST` | `/sources/{sourceId}/rollback` | Rollback administrativo sin recalcular embeddings |
|
||||
| `POST` | `/sources/{sourceId}/versions/{versionId}/retry` | Reintento explicito de version fallida o huerfana con fuente durable |
|
||||
| `DELETE` | `/sources/{sourceId}/versions/{versionId}` | Purga administrativa de una version no activa |
|
||||
| `GET` | `/ingestions/{versionId}/recover-indexing` | Obtener hashes/precondiciones CAS de una aprobacion OCR comprometida |
|
||||
| `POST` | `/ingestions/{versionId}/recover-indexing` | Restaurar una aprobacion OCR ya revisada que quedo en `review_required` |
|
||||
| `GET` | `/models/answer` | Modelo por defecto y modelos seleccionables |
|
||||
| `POST` | `/ingest` | Ingesta desde una ruta del servidor |
|
||||
| `POST` | `/ingest/upload` | Upload `multipart/form-data` |
|
||||
|
|
@ -73,6 +75,38 @@ La API queda formada por las operaciones de descubrimiento, ingesta, retrieval,
|
|||
| `POST` | `/logs/manual` | Registro manual de una evaluacion |
|
||||
| `PATCH` | `/logs/{id}` | Seguimiento y resolucion de un log |
|
||||
|
||||
## Restaurar indexado OCR aprobado
|
||||
|
||||
Este flujo administrativo recupera una version aprobada (`reviewed_at` y `reviewed_by` presentes) que, por un fallo de estado anterior, permanece en `review_required`. Es distinto de `POST /ingestions/{versionId}/recover`, que cierra como fallida una candidata sin evidencia recuperable.
|
||||
|
||||
Primero solicita el preflight autenticado, sin modificar datos:
|
||||
|
||||
```http
|
||||
GET /ingestions/{versionId}/recover-indexing
|
||||
Authorization: Bearer <LIFECYCLE_ADMIN_TOKEN>
|
||||
```
|
||||
|
||||
La respuesta incluye `candidateSha256`, `reviewedTextSha256`, `expectedReviewedAt`, `expectedReviewedBy` y `expectedActiveVersionId`. Envia esos valores sin alterarlos junto con el actor y el motivo:
|
||||
|
||||
```json
|
||||
{
|
||||
"expectedState": "review_required",
|
||||
"candidateSha256": "<candidate-sha256-del-preflight>",
|
||||
"reviewedTextSha256": "<reviewed-text-sha256-del-preflight>",
|
||||
"expectedReviewedAt": "<fecha-del-preflight>",
|
||||
"expectedReviewedBy": "<revisor-original>",
|
||||
"expectedActiveVersionId": "<uuid-activa-base-o-null>",
|
||||
"recoveredBy": "operator-id",
|
||||
"reason": "Resume previously approved OCR indexing"
|
||||
}
|
||||
```
|
||||
|
||||
`POST /ingestions/{versionId}/recover-indexing` responde `202` con `outcome: resumed_indexing` cuando confirma atomica y auditadamente `review_required -> indexing`; no declara que haya terminado el indexado ni la activacion. El reconciliador retomara el nucleo de indexacion desde el artefacto revisado validado, sin repetir OCR, aprobacion ni correcciones. Para una version que sigue en `indexing`, el reconciliador conserva su recuperacion automatica; esta ruta administrativa es solo para la regresion de estado `review_required` con aprobacion previa. La migracion `005_ocr_approved_indexing_recovery.sql` conserva los registros antiguos `closed_failed` y deduplica reintentos identicos mediante un fingerprint. El entrypoint RAG aplica las migraciones antes de iniciar HTTP; comprueba que `rag_schema_migrations` registra `005` antes de usar la ruta. El esquema ampliado es compatible con el codigo previo y los eventos `closed_failed`; no reviertas la restriccion mientras existan eventos `resumed_indexing`.
|
||||
|
||||
La restauracion reinicia el reloj stale y limpia el marcador de intentos anterior. El indexador automatico espera `LIFECYCLE_INDEXING_STALE_TIMEOUT_MS` (30 minutos por defecto) y dispone de hasta tres reintentos separados por ese intervalo. Sigue el contador del reconciliador `approvedIndexingRecovered` en `/health` y el estado/error de `GET /ingestions/{versionId}`. Si tras tres intentos sigue `indexing` con `OCR_INDEX_RECOVERY_RETRY`, conserva la evidencia y escala; no repitas aprobacion, OCR ni SQL manual.
|
||||
|
||||
La misma peticion puede repetirse: recibe el estado actual con `idempotent: true` y no crea una segunda fila de auditoria. `409 OCR_RECOVERY_CONFLICT` significa que cambio estado, hash, fecha/revisor de aprobacion o precondicion de version activa; no se modifica nada y debe consultarse de nuevo el preflight. Una evidencia invalida o una correccion que no coincide con su auditoria tambien falla sin cambiar estado, artefactos ni correcciones.
|
||||
|
||||
## Contratos comunes
|
||||
|
||||
### Scope
|
||||
|
|
|
|||
|
|
@ -984,6 +984,14 @@ Secuencia:
|
|||
|
||||
Si otra version se activo durante la revision, guardar el candidato aprobado como `ready`, devolver `409 ACTIVE_VERSION_CHANGED` y no activar. El operador puede activarlo despues con una nueva precondicion explicita; nunca se sobrescribe silenciosamente una version mas reciente.
|
||||
|
||||
### Recuperacion de una aprobacion cuyo indexado se interrumpio
|
||||
|
||||
Una version aprobada con `state = 'indexing'` y `reviewed_at IS NOT NULL` se reanuda automaticamente por el reconciliador existente. La recuperacion espera a que `indexing_started_at` supere `LIFECYCLE_INDEXING_STALE_TIMEOUT_MS` (por defecto 30 minutos), adquiere el lock de fuente usado por la ingesta sin bloquear una aprobacion sincronica y reconstruye todos los documentos exclusivamente desde `reviewed-pages.json`. Antes de escribir valida manifiesto/candidata, identidad de fuente/version, `reviewed_by`, hashes de pagina, auditoria de cada correccion, fingerprint, metadata, configuracion de embeddings y coleccion vectorial. No vuelve a ejecutar OCR, revision ni correcciones.
|
||||
|
||||
El reconciliador reclama como maximo tres intentos por version mediante `error_code`/`error_detail` y `indexing_started_at` ya existentes; cada intento fallido vuelve a esperar el umbral de stale. Los puntos se escriben con los mismos IDs versionados y upsert idempotente. La preparacion de hashes/conteos, `markReady` y la activacion usan los CAS canonicos: `activate_requested=false` termina `ready`; `true` activa solo si sigue vigente `base_active_version_id`, y la carrera devuelve `ACTIVE_VERSION_CHANGED` dejando la version `ready`. Si los tres intentos fallan, el candidato permanece `indexing` con `OCR_INDEX_RECOVERY_RETRY` y no se reintenta automaticamente; conservar evidencia y escalar sin forzar estado.
|
||||
|
||||
La corrupcion de estado separada `state = 'review_required' AND reviewed_at IS NOT NULL` no es una aprobacion pendiente ni entra en el reintento automatico. Con autorizacion administrativa, `GET /ingestions/:versionId/recover-indexing` valida y devuelve sus hashes/precondiciones; `POST` exige esos valores, `expectedState`, actor y motivo. Bajo el source advisory lock se vuelven a comprobar artefacto, hashes de pagina, correcciones auditadas, reviewer/fecha y precondicion activa; en una unica transaccion/CAS se restaura `indexing` y se inserta `outcome = 'resumed_indexing'`. No se modifican `reviewed_at`, `reviewed_by`, correcciones ni artefactos y no se vuelve a aprobar. La misma huella de peticion es idempotente; hashes o precondiciones desfasadas devuelven `409` sin mutaciones. `005_ocr_approved_indexing_recovery.sql` conserva `closed_failed`, anade el fingerprint unico y permite este nuevo outcome. El `202` confirma solo la restauracion/auditoria; el reconciliador existente completa despues el indexado normal.
|
||||
|
||||
Rechazar cambia a `rejected`, conserva auditoria temporal y no genera embeddings.
|
||||
|
||||
## Artefactos y retencion
|
||||
|
|
|
|||
|
|
@ -2,12 +2,23 @@
|
|||
|
||||
**Proyecto:** Workspace de tools IA para empresas
|
||||
**Modulo:** RAG
|
||||
**Ultima actualizacion:** 2026-09-25
|
||||
**Ultima modificacion por:** Agente RAG 3
|
||||
**Ultima actualizacion:** 2026-10-03
|
||||
**Ultima modificacion por:** Subagente integracion nativa OCR
|
||||
**Estado:** Activo
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-03 - Subagente integracion nativa OCR - Continuacion y restauracion auditada de indexado OCR
|
||||
**Agent:** Subagente integracion nativa OCR · **Model:** openai/gpt-6-luna · **Session:** `ses_efce04830ffea8Cl6myTBtwGyv`
|
||||
**Role:** Implementacion local de la integracion OCR con el ciclo canonico de versionado RAG.
|
||||
**Work:** Las ingestas nativas y OCR comparten el escritor/verificador versionado; OCR materializa hashes/conteos por documento y usa el CAS canonico de activacion. El reconciliador reanuda aprobaciones que siguen en `indexing` bajo source try-lock, tras 30 minutos stale y con un maximo de tres intentos espaciados. Se anadio ademas `GET/POST /ingestions/:versionId/recover-indexing` para la regresion administrativa distinta `review_required` + `reviewed_at`: inspeccion CAS de solo lectura seguida de restauracion `review_required -> indexing` bajo source lock, con validacion de hashes, correcciones auditadas, revisor, timestamp, configuracion y precondicion activa. Migration `005_ocr_approved_indexing_recovery.sql` incorpora outcome `resumed_indexing` y fingerprint idempotente sin reescribir eventos `closed_failed`; la transicion y el audit se confirman atomicamente, preservando aprobacion, correcciones y artefactos. El indexado posterior se realiza por el reconciliador, no se promete como parte del `202`. No se contacto produccion ni EasyPanel; `docs/DESPLIEGUE_EASYPANEL.md` permanece ajeno e intacto.
|
||||
**Validation:** TDD administrativo: `npx tsx --test tests/catalog/migration-005.test.ts tests/catalog/repository-ocr.test.ts tests/ocr/approval-indexing-wiring.test.ts` dio `18/21` (rojo: migration ausente, repositorio sin restauracion, ruta devolvio `404` en vez de `401`); tras implementar, el mismo comando dio `22/22`. Focalizadas `npm run check && npx tsx --test tests/catalog/repository-ocr.test.ts tests/ocr/indexing-store.test.ts tests/ocr/approval-indexing-wiring.test.ts tests/ocr/contracts-deploy.test.ts`: `32/32`. Gate final `npm run check && npm test && npm run build && git diff --check`: `140/140`, todo correcto. Se aplico `005` en el harness LOCAL existente `rag-r4-postgres` (loopback `127.0.0.1:55432`, volumen persistente, restart `no`): `runKnowledgeLifecycleMigrations` reporto `005`, preservo una fila fixture `closed_failed`, verifico check/index y la segunda ejecucion idempotente. En PostgreSQL real local tambien se restauro una fuente/version temporal con timestamp de microsegundos; CAS, `resumed_indexing`, replay idempotente, reviewer/timestamp preservados y una sola auditoria se comprobaron; se borraron los fixtures. El contenedor quedo detenido y su volumen intacto. Dos intentos iniciales del script inline de integracion fallaron por quoting y un nombre de variable (`ReferenceError`); el segundo limpio el fixture en `finally`; el script corregido completo paso. No se encontro normalizador configurado. Una consulta `pg_lsclusters` no pudo ejecutarse porque la utilidad no esta instalada; `pg_isready` y la inspeccion de Docker permitieron identificar el harness local aislado. Ninguna prueba o comando contacto produccion.
|
||||
**Next:** Desplegar solo tras autorizacion posterior. Antes de invocar la restauracion, consultar `GET /ingestions/{versionId}/recover-indexing`; enviar sin cambios sus valores en `POST`, y revisar el `202`/audit y luego el estado de ingesta. Verificar migration `005` en `rag_schema_migrations` antes de usar la nueva ruta. Las candidatas que fallen validacion permanecen sin cambios; no reaprobar ni forzar SQL.
|
||||
**Rollback:** Se puede revertir el codigo, pero se debe conservar `005` y su fingerprint/outcomes: no restaurar la antigua constraint mientras exista cualquier `resumed_indexing`. Un codigo anterior permanece compatible con auditorias `closed_failed` y el esquema extendido, pero no ofrece el endpoint administrativo. El contenedor LOCAL se detuvo; no borrar su volumen. Conservar completamente la modificacion previa de `docs/DESPLIEGUE_EASYPANEL.md`.
|
||||
**Files:** `migrations/005_ocr_approved_indexing_recovery.sql`, `src/modules/ocr/indexing.ts`, `src/modules/catalog/repository.ts`, `src/app.ts`, `src/api/openapi.ts`, `tests/catalog/{migration-005,repository-ocr}.test.ts`, `tests/ocr/{indexing-store,approval-indexing-wiring,contracts-deploy}.test.ts`, `docs/API_RAG.md`, `docs/CONTRATO_CICLO_VIDA_Y_OCR.md`, `docs/HISTORIAL_SESIONES.md`.
|
||||
|
||||
---
|
||||
|
||||
## Registro de sesion
|
||||
|
||||
### 2026-09-25 - Agente RAG 3 - Cierre productivo de limpieza OCR
|
||||
|
|
|
|||
20
migrations/005_ocr_approved_indexing_recovery.sql
Normal file
20
migrations/005_ocr_approved_indexing_recovery.sql
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
ALTER TABLE rag_ocr_recovery_audit
|
||||
ADD COLUMN IF NOT EXISTS recovery_fingerprint char(64) NULL;
|
||||
|
||||
ALTER TABLE rag_ocr_recovery_audit
|
||||
DROP CONSTRAINT IF EXISTS rag_ocr_recovery_audit_outcome_check;
|
||||
|
||||
ALTER TABLE rag_ocr_recovery_audit
|
||||
ADD CONSTRAINT rag_ocr_recovery_audit_outcome_check
|
||||
CHECK (outcome IN ('closed_failed', 'resumed_indexing'));
|
||||
|
||||
ALTER TABLE rag_ocr_recovery_audit
|
||||
DROP CONSTRAINT IF EXISTS rag_ocr_recovery_audit_fingerprint_check;
|
||||
|
||||
ALTER TABLE rag_ocr_recovery_audit
|
||||
ADD CONSTRAINT rag_ocr_recovery_audit_fingerprint_check
|
||||
CHECK ((outcome = 'resumed_indexing') = (recovery_fingerprint IS NOT NULL));
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS rag_ocr_recovery_audit_request_idx
|
||||
ON rag_ocr_recovery_audit(version_id, recovery_fingerprint)
|
||||
WHERE recovery_fingerprint IS NOT NULL;
|
||||
|
|
@ -298,6 +298,32 @@ export const openApiDocument = {
|
|||
}
|
||||
}
|
||||
},
|
||||
"/ingestions/{versionId}/recover-indexing": {
|
||||
get: {
|
||||
tags: ["OCR Review"], summary: "Inspect CAS values for an approved OCR indexing recovery", security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: "versionId", in: "path", required: true, schema: { type: "string", format: "uuid" } }],
|
||||
responses: {
|
||||
"200": jsonResponse("Validated recovery hashes and lifecycle preconditions; no state is changed.", ref("OcrApprovedIndexingRecoveryEvidence")),
|
||||
"401": jsonResponse("Missing or invalid lifecycle admin token.", ref("Error")),
|
||||
"404": jsonResponse("OCR candidate does not exist.", ref("Error")),
|
||||
"409": jsonResponse("Candidate is not awaiting approved-indexing recovery or evidence is invalid.", ref("Error")),
|
||||
"503": serverError
|
||||
}
|
||||
},
|
||||
post: {
|
||||
tags: ["OCR Review"], summary: "Restore an already-approved OCR candidate to its indexing coordinator", security: [{ bearerAuth: [] }],
|
||||
parameters: [{ name: "versionId", in: "path", required: true, schema: { type: "string", format: "uuid" } }],
|
||||
requestBody: { required: true, content: jsonContent(ref("OcrApprovedIndexingRecoveryRequest")) },
|
||||
responses: {
|
||||
"202": jsonResponse("Approval state restored and audited; the existing reconciler resumes indexing.", ref("OcrApprovedIndexingRecoveryResponse")),
|
||||
"400": jsonResponse("Recovery request fields are invalid.", ref("Error")),
|
||||
"401": jsonResponse("Missing or invalid lifecycle admin token.", ref("Error")),
|
||||
"404": jsonResponse("OCR candidate does not exist.", ref("Error")),
|
||||
"409": jsonResponse("Expected approval state, artifact identity, or active-version precondition changed.", ref("Error")),
|
||||
"503": serverError
|
||||
}
|
||||
}
|
||||
},
|
||||
"/ingestions/{versionId}/documents/{documentId}/pages/{page}/image": {
|
||||
get: {
|
||||
tags: ["OCR Review"], summary: "Get a private OCR review page image", security: [{ bearerAuth: [] }],
|
||||
|
|
@ -657,6 +683,32 @@ export const openApiDocument = {
|
|||
type: "object", required: ["versionId", "state", "outcome"],
|
||||
properties: { versionId: { type: "string", format: "uuid" }, state: { type: "string", const: "failed" }, outcome: { type: "string", const: "closed_failed" } }
|
||||
},
|
||||
OcrApprovedIndexingRecoveryRequest: {
|
||||
type: "object", required: ["expectedState", "candidateSha256", "reviewedTextSha256", "expectedReviewedAt", "expectedReviewedBy", "expectedActiveVersionId", "recoveredBy", "reason"],
|
||||
properties: {
|
||||
expectedState: { type: "string", const: "review_required" },
|
||||
candidateSha256: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
||||
reviewedTextSha256: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
||||
expectedReviewedAt: { type: "string", format: "date-time" },
|
||||
expectedReviewedBy: { type: "string", minLength: 1 },
|
||||
expectedActiveVersionId: { type: ["string", "null"], format: "uuid" },
|
||||
recoveredBy: { type: "string", minLength: 1 },
|
||||
reason: { type: "string", minLength: 1 }
|
||||
}
|
||||
},
|
||||
OcrApprovedIndexingRecoveryEvidence: {
|
||||
type: "object", required: ["versionId", "state", "candidateSha256", "reviewedTextSha256", "expectedReviewedAt", "expectedReviewedBy", "expectedActiveVersionId"],
|
||||
properties: {
|
||||
versionId: { type: "string", format: "uuid" }, state: { type: "string", const: "review_required" },
|
||||
candidateSha256: { type: "string", pattern: "^[a-f0-9]{64}$" }, reviewedTextSha256: { type: "string", pattern: "^[a-f0-9]{64}$" },
|
||||
expectedReviewedAt: { type: "string", format: "date-time" }, expectedReviewedBy: { type: "string" },
|
||||
expectedActiveVersionId: { type: ["string", "null"], format: "uuid" }
|
||||
}
|
||||
},
|
||||
OcrApprovedIndexingRecoveryResponse: {
|
||||
type: "object", required: ["versionId", "state", "outcome", "idempotent"],
|
||||
properties: { versionId: { type: "string", format: "uuid" }, state: { type: "string", enum: ["indexing", "ready", "active"] }, outcome: { type: "string", const: "resumed_indexing" }, idempotent: { type: "boolean" } }
|
||||
},
|
||||
OcrDecisionResponse: {
|
||||
type: "object", required: ["versionId", "state", "activated"],
|
||||
properties: { versionId: { type: "string", format: "uuid" }, state: { type: "string", enum: ["indexing", "rejected"] }, activated: { type: "boolean" } }
|
||||
|
|
|
|||
46
src/app.ts
46
src/app.ts
|
|
@ -24,8 +24,7 @@ import { OcrClient } from "./modules/ocr/client.js";
|
|||
import { OcrDispatcher } from "./modules/ocr/dispatcher.js";
|
||||
import { persistComposedCandidateArtifact, persistOcrResultArtifact, resolveArtifactPath, transferReviewImageArtifacts } from "./modules/ocr/artifacts.js";
|
||||
import { classifyOcrReviewError, DurableOcrReviewReader, OcrReviewRecoveryService, OcrReviewService, PostgresOcrReviewStore } from "./modules/ocr/review.js";
|
||||
import type { OcrIndexingService } from "./modules/ocr/indexing.js";
|
||||
import { OcrReadyIndexingService, PostgresOcrIndexingStore } from "./modules/ocr/indexing.js";
|
||||
import { OcrIndexingService, PostgresOcrIndexingStore } from "./modules/ocr/indexing.js";
|
||||
import { OcrRetentionService } from "./modules/ocr/retention.js";
|
||||
import type { ChatMessage, ChunkMode, RetrieveIntent, RetrieveScope } from "./shared/types/rag.js";
|
||||
import { sha256Hex } from "./shared/utils/ids.js";
|
||||
|
|
@ -40,7 +39,8 @@ interface AppOptions {
|
|||
ocrClient?: OcrClient;
|
||||
reviewService?: Pick<OcrReviewService, "view" | "approve" | "reject">;
|
||||
reviewRecoveryService?: Pick<OcrReviewRecoveryService, "recover">;
|
||||
indexingService?: Pick<OcrIndexingService, "index">;
|
||||
indexingService?: Pick<OcrIndexingService, "index"> & Partial<Pick<OcrIndexingService, "restoreApprovedIndexing" | "inspectApprovedIndexingRecovery">>;
|
||||
indexingRecoveryService?: Partial<Pick<OcrIndexingService, "inspectApprovedIndexingRecovery" | "restoreApprovedIndexing">>;
|
||||
vectorStore?: VectorStoreClient;
|
||||
startReconciler?: boolean;
|
||||
}
|
||||
|
|
@ -96,7 +96,6 @@ export function createApp(options: AppOptions = {}) {
|
|||
await catalog.persistOcrCandidate(versionId, candidate.documents.flatMap(({ documentId, pages }) => pages.map((page) => ({ documentId, ...page }))));
|
||||
}) : undefined;
|
||||
const retention = catalog ? new OcrRetentionService(catalog, ocr.artifactRoot) : undefined;
|
||||
const reconciler = new KnowledgeLifecycleReconciler(catalog, vectorStore, ocrDispatcher, retention);
|
||||
const evaluationLogs = new EvaluationLogService(embeddingProvider);
|
||||
const ingestService = options.ingestService ?? new IngestService(embeddingProvider, vectorStore, catalog, ocr);
|
||||
const durableReview = catalog ? new DurableOcrReviewReader(catalog, ocr.artifactRoot) : undefined;
|
||||
|
|
@ -108,8 +107,17 @@ export function createApp(options: AppOptions = {}) {
|
|||
const retrieveService = new RetrieveService(embeddingProvider, vectorStore, catalog);
|
||||
const answerService = new AnswerService(retrieveService);
|
||||
const indexingService = options.indexingService ?? (catalogPool
|
||||
? new OcrReadyIndexingService(new PostgresOcrIndexingStore(catalogPool, ocr.artifactRoot, embeddingProvider, vectorStore))
|
||||
? new OcrIndexingService(new PostgresOcrIndexingStore(catalogPool, ocr.artifactRoot, embeddingProvider, vectorStore))
|
||||
: undefined);
|
||||
const indexingRecoveryService = options.indexingRecoveryService ?? (indexingService
|
||||
&& typeof indexingService.restoreApprovedIndexing === "function" && typeof indexingService.inspectApprovedIndexingRecovery === "function"
|
||||
? indexingService as Pick<OcrIndexingService, "inspectApprovedIndexingRecovery" | "restoreApprovedIndexing">
|
||||
: undefined);
|
||||
const approvedOcrIndexer = indexingService
|
||||
&& typeof (indexingService as Partial<Pick<OcrIndexingService, "recoverStaleApprovedVersions">>).recoverStaleApprovedVersions === "function"
|
||||
? indexingService as Partial<Pick<OcrIndexingService, "recoverStaleApprovedVersions">>
|
||||
: undefined;
|
||||
const reconciler = new KnowledgeLifecycleReconciler(catalog, vectorStore, ocrDispatcher, retention, approvedOcrIndexer);
|
||||
if (options.startReconciler !== false) {
|
||||
ocrDispatcher?.start();
|
||||
reconciler.start();
|
||||
|
|
@ -343,6 +351,34 @@ export function createApp(options: AppOptions = {}) {
|
|||
}
|
||||
});
|
||||
|
||||
app.get("/ingestions/:versionId/recover-indexing", async (req, res) => {
|
||||
if (!requireOcrEnabled(res)) return;
|
||||
if (!requireLifecycleAdmin(req, res)) return;
|
||||
if (!indexingRecoveryService?.inspectApprovedIndexingRecovery) {
|
||||
res.status(503).json({ ok: false, error: "Approved OCR indexing recovery is not configured", code: "OCR_RECOVERY_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.json(await indexingRecoveryService.inspectApprovedIndexingRecovery(String(req.params.versionId)));
|
||||
} catch (error) {
|
||||
sendOcrReviewError(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/ingestions/:versionId/recover-indexing", async (req, res) => {
|
||||
if (!requireOcrEnabled(res)) return;
|
||||
if (!requireLifecycleAdmin(req, res)) return;
|
||||
if (!indexingRecoveryService?.restoreApprovedIndexing) {
|
||||
res.status(503).json({ ok: false, error: "Approved OCR indexing recovery is not configured", code: "OCR_RECOVERY_UNAVAILABLE" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
res.status(202).json(await indexingRecoveryService.restoreApprovedIndexing(String(req.params.versionId), req.body));
|
||||
} catch (error) {
|
||||
sendOcrReviewError(res, error);
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/ingestions/:versionId/documents/:documentId/pages/:page/image", async (req, res) => {
|
||||
if (!requireOcrEnabled(res)) return;
|
||||
if (!requireLifecycleAdmin(req, res)) return;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { VectorStoreClient } from "../vectorstore/client.js";
|
|||
import type { CatalogRepository } from "./repository.js";
|
||||
import type { OcrDispatcher } from "../ocr/dispatcher.js";
|
||||
import type { OcrRetentionService } from "../ocr/retention.js";
|
||||
import type { OcrIndexingService } from "../ocr/indexing.js";
|
||||
|
||||
export interface ReconcilerStatus {
|
||||
ok: boolean;
|
||||
|
|
@ -13,6 +14,7 @@ export interface ReconcilerStatus {
|
|||
orphanedVersionsFailed?: number;
|
||||
ocrLeasesRecovered?: number;
|
||||
ocrCandidatesRecovered?: number;
|
||||
approvedIndexingRecovered?: number;
|
||||
ocrRetentionDeleted?: number;
|
||||
invariantViolations?: string[];
|
||||
}
|
||||
|
|
@ -25,7 +27,8 @@ export class KnowledgeLifecycleReconciler {
|
|||
private readonly catalog: CatalogRepository | undefined,
|
||||
private readonly vectorStore: VectorStoreClient,
|
||||
private readonly ocrDispatcher?: Pick<OcrDispatcher, "recoverExpiredLeases" | "dispatchAvailable" | "recoverCompletedCandidates">,
|
||||
private readonly ocrRetention?: Pick<OcrRetentionService, "runOnce">
|
||||
private readonly ocrRetention?: Pick<OcrRetentionService, "runOnce">,
|
||||
private readonly approvedOcrIndexer?: Partial<Pick<OcrIndexingService, "recoverStaleApprovedVersions">>
|
||||
) {}
|
||||
|
||||
getStatus(): ReconcilerStatus {
|
||||
|
|
@ -61,6 +64,9 @@ export class KnowledgeLifecycleReconciler {
|
|||
const ocrCandidatesRecovered = this.ocrDispatcher?.recoverCompletedCandidates
|
||||
? await this.ocrDispatcher.recoverCompletedCandidates()
|
||||
: 0;
|
||||
const approvedIndexingRecovered = this.approvedOcrIndexer?.recoverStaleApprovedVersions
|
||||
? await this.approvedOcrIndexer.recoverStaleApprovedVersions()
|
||||
: 0;
|
||||
const retention = await this.ocrRetention?.runOnce();
|
||||
const orphanRecovery = await this.recoverOrphanedVersions(catalog);
|
||||
|
||||
|
|
@ -86,6 +92,7 @@ export class KnowledgeLifecycleReconciler {
|
|||
orphanedVersionsFailed: orphanRecovery.failed,
|
||||
ocrLeasesRecovered,
|
||||
ocrCandidatesRecovered,
|
||||
approvedIndexingRecovered,
|
||||
ocrRetentionDeleted: (retention?.deleted ?? 0) + (retention?.resumed ?? 0),
|
||||
invariantViolations
|
||||
};
|
||||
|
|
|
|||
|
|
@ -94,6 +94,11 @@ export interface OrphanedVersionCandidate {
|
|||
qdrantCollection: string;
|
||||
}
|
||||
|
||||
export interface ApprovedOcrIndexingCandidate {
|
||||
versionId: string;
|
||||
sourceId: string;
|
||||
}
|
||||
|
||||
export interface PendingOcrIdentity {
|
||||
sourceId: string;
|
||||
originalManifestHash: string;
|
||||
|
|
@ -418,7 +423,8 @@ export class CatalogRepository {
|
|||
async listOcrVersionsAwaitingCandidate(): Promise<string[]> {
|
||||
const result = await this.pool.query<{ version_id: string }>(
|
||||
`SELECT DISTINCT v.version_id FROM rag_source_versions v
|
||||
WHERE v.state = 'indexing' AND EXISTS (SELECT 1 FROM rag_ocr_jobs j WHERE j.version_id = v.version_id)
|
||||
WHERE v.state = 'indexing' AND v.reviewed_at IS NULL
|
||||
AND EXISTS (SELECT 1 FROM rag_ocr_jobs j WHERE j.version_id = v.version_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM rag_ocr_jobs j WHERE j.version_id = v.version_id AND j.state <> 'succeeded')
|
||||
ORDER BY v.version_id`
|
||||
);
|
||||
|
|
@ -648,7 +654,7 @@ export class CatalogRepository {
|
|||
async markReviewRequired(versionId: string): Promise<void> {
|
||||
const result = await this.pool.query(
|
||||
`UPDATE rag_source_versions SET state = 'review_required'
|
||||
WHERE version_id = $1 AND state = 'indexing'
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NULL
|
||||
AND EXISTS (SELECT 1 FROM rag_ocr_jobs WHERE version_id = $1)
|
||||
AND NOT EXISTS (SELECT 1 FROM rag_ocr_jobs WHERE version_id = $1 AND state <> 'succeeded')
|
||||
AND NOT EXISTS (
|
||||
|
|
@ -803,7 +809,7 @@ export class CatalogRepository {
|
|||
await client.query("UPDATE rag_version_documents SET index_state = 'ready' WHERE version_id = $1", [versionId]);
|
||||
const result = await client.query<VersionDbRow>(
|
||||
`UPDATE rag_source_versions
|
||||
SET state = 'ready', verified_point_count = $2, ready_at = now()
|
||||
SET state = 'ready', verified_point_count = $2, ready_at = now(), error_code = NULL, error_detail = NULL
|
||||
WHERE version_id = $1 AND state = 'indexing' AND expected_point_count = $2
|
||||
RETURNING *`,
|
||||
[versionId, verifiedPointCount]
|
||||
|
|
@ -815,6 +821,145 @@ export class CatalogRepository {
|
|||
});
|
||||
}
|
||||
|
||||
async materializeReviewedOcrIndex(versionId: string, input: {
|
||||
sourceContentHash: string;
|
||||
expectedPointCount: number;
|
||||
documents: Array<{ documentId: string; contentHash: string; chunkCount: number }>;
|
||||
}): Promise<void> {
|
||||
await withTransaction(this.pool, async (client) => {
|
||||
const version = await client.query<{ expected_document_count: string | number; state: string; reviewed_at: Date | null }>(
|
||||
`SELECT expected_document_count, state, reviewed_at FROM rag_source_versions
|
||||
WHERE version_id = $1 FOR UPDATE`, [versionId]);
|
||||
if (!version.rowCount || version.rows[0]!.state !== "indexing" || !version.rows[0]!.reviewed_at
|
||||
|| Number(version.rows[0]!.expected_document_count) !== input.documents.length) {
|
||||
throw new CatalogError("Approved OCR version is not eligible for indexing", 409, "INVALID_VERSION_STATE");
|
||||
}
|
||||
for (const document of input.documents) {
|
||||
const result = await client.query(
|
||||
`UPDATE rag_version_documents SET content_hash = $3, chunk_count = $4, index_state = 'indexing'
|
||||
WHERE version_id = $1 AND document_id = $2`,
|
||||
[versionId, document.documentId, document.contentHash, document.chunkCount]);
|
||||
if (result.rowCount !== 1) throw new CatalogError("Approved OCR document set changed", 409, "REVIEW_CONFLICT");
|
||||
}
|
||||
const updated = await client.query(
|
||||
`UPDATE rag_source_versions SET source_content_hash = $2, expected_point_count = $3, indexing_started_at = now()
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NOT NULL`,
|
||||
[versionId, input.sourceContentHash, input.expectedPointCount]);
|
||||
if (updated.rowCount !== 1) throw new CatalogError("Approved OCR version changed during indexing", 409, "INVALID_VERSION_STATE");
|
||||
});
|
||||
}
|
||||
|
||||
async markOcrDuplicate(versionId: string, reusableVersionId: string): Promise<void> {
|
||||
const result = await this.pool.query(
|
||||
`UPDATE rag_source_versions SET state = 'rejected', error_code = 'DUPLICATE_REUSABLE_VERSION',
|
||||
error_detail = $2, retention_due_at = now() + interval '7 days'
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NOT NULL`,
|
||||
[versionId, `Reusable version ${reusableVersionId} has the same reviewed content and processing identity`]);
|
||||
if (result.rowCount !== 1) throw new CatalogError("Approved OCR version changed during duplicate settlement", 409, "INVALID_VERSION_STATE");
|
||||
}
|
||||
|
||||
async listApprovedOcrIndexingCandidates(staleAfterMs = 1800000, limit = 20): Promise<ApprovedOcrIndexingCandidate[]> {
|
||||
const result = await this.pool.query<{ version_id: string; source_id: string }>(
|
||||
`SELECT version_id, source_id FROM rag_source_versions
|
||||
WHERE state = 'indexing' AND reviewed_at IS NOT NULL AND reviewed_by IS NOT NULL
|
||||
AND artifact_state = 'present'
|
||||
AND indexing_started_at < now() - ($1::text || ' milliseconds')::interval
|
||||
AND (error_code IS NULL OR (error_code = 'OCR_INDEX_RECOVERY_RETRY'
|
||||
AND COALESCE((error_detail::jsonb ->> 'attempt')::integer, 0) < 3))
|
||||
ORDER BY indexing_started_at, version_id LIMIT $2`,
|
||||
[String(staleAfterMs), limit]);
|
||||
return result.rows.map(({ version_id, source_id }) => ({ versionId: version_id, sourceId: source_id }));
|
||||
}
|
||||
|
||||
async claimApprovedOcrIndexingRecovery(versionId: string, staleAfterMs = 1800000): Promise<number | undefined> {
|
||||
return withTransaction(this.pool, async (client) => {
|
||||
const result = await client.query<{ error_code: string | null; error_detail: string | null; source_id: string }>(
|
||||
`SELECT source_id, error_code, error_detail FROM rag_source_versions
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NOT NULL AND reviewed_by IS NOT NULL
|
||||
AND artifact_state = 'present'
|
||||
AND indexing_started_at < now() - ($2::text || ' milliseconds')::interval
|
||||
FOR UPDATE`, [versionId, String(staleAfterMs)]);
|
||||
if (!result.rowCount) return undefined;
|
||||
const row = result.rows[0]!;
|
||||
let previousAttempts = 0;
|
||||
if (row.error_code === "OCR_INDEX_RECOVERY_RETRY") {
|
||||
try {
|
||||
const evidence = JSON.parse(row.error_detail ?? "null") as { attempt?: unknown };
|
||||
if (!Number.isInteger(evidence.attempt) || Number(evidence.attempt) < 1 || Number(evidence.attempt) >= 3) return undefined;
|
||||
previousAttempts = Number(evidence.attempt);
|
||||
} catch { return undefined; }
|
||||
} else if (row.error_code !== null) return undefined;
|
||||
const attempt = previousAttempts + 1;
|
||||
const updated = await client.query(
|
||||
`UPDATE rag_source_versions SET indexing_started_at = now(), error_code = 'OCR_INDEX_RECOVERY_RETRY', error_detail = $2
|
||||
WHERE version_id = $1 AND source_id = $3 AND state = 'indexing' AND reviewed_at IS NOT NULL AND reviewed_by IS NOT NULL
|
||||
AND artifact_state = 'present'`,
|
||||
[versionId, JSON.stringify({ attempt }), row.source_id]);
|
||||
return updated.rowCount === 1 ? attempt : undefined;
|
||||
});
|
||||
}
|
||||
|
||||
async markApprovedOcrIndexRecoveryInvalid(versionId: string, code: string): Promise<void> {
|
||||
await this.pool.query(
|
||||
`UPDATE rag_source_versions SET error_code = 'OCR_INDEX_RECOVERY_INVALID', error_detail = $2
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NOT NULL AND reviewed_by IS NOT NULL`,
|
||||
[versionId, JSON.stringify({ code })]);
|
||||
}
|
||||
|
||||
async restoreApprovedOcrIndexing(input: {
|
||||
versionId: string;
|
||||
sourceId: string;
|
||||
expectedState: "review_required";
|
||||
expectedReviewedAt: string;
|
||||
expectedReviewedBy: string;
|
||||
expectedActiveVersionId: string | null;
|
||||
recoveredBy: string;
|
||||
reason: string;
|
||||
recoveryFingerprint: string;
|
||||
}): Promise<{ versionId: string; state: "indexing" | "ready" | "active"; outcome: "resumed_indexing"; idempotent: boolean }> {
|
||||
return withTransaction(this.pool, async (client) => {
|
||||
const current = await client.query<{
|
||||
state: string; reviewed_at: string | null; reviewed_by: string | null; base_active_version_id: string | null;
|
||||
active_version_id: string | null;
|
||||
}>(`SELECT v.state, to_char(v.reviewed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS reviewed_at,
|
||||
v.reviewed_by, v.base_active_version_id, s.active_version_id
|
||||
FROM rag_source_versions v JOIN rag_sources s ON s.source_id = v.source_id
|
||||
WHERE v.version_id = $1 AND v.source_id = $2 FOR UPDATE OF v, s`, [input.versionId, input.sourceId]);
|
||||
if (!current.rowCount) throw new CatalogError("OCR recovery candidate was not found", 404, "OCR_CANDIDATE_NOT_FOUND");
|
||||
const audit = await client.query<{ outcome: string }>(
|
||||
`SELECT outcome FROM rag_ocr_recovery_audit
|
||||
WHERE version_id = $1 AND recovery_fingerprint = $2`, [input.versionId, input.recoveryFingerprint]);
|
||||
const state = current.rows[0]!;
|
||||
if (audit.rowCount) {
|
||||
if (audit.rows[0]!.outcome !== "resumed_indexing" || !["indexing", "ready", "active"].includes(state.state)) {
|
||||
throw new CatalogError("Recovery idempotency key conflicts with the current candidate", 409, "OCR_RECOVERY_CONFLICT");
|
||||
}
|
||||
return { versionId: input.versionId, state: state.state as "indexing" | "ready" | "active", outcome: "resumed_indexing", idempotent: true };
|
||||
}
|
||||
if (state.state !== input.expectedState || !state.reviewed_at || !state.reviewed_by
|
||||
|| state.reviewed_at !== input.expectedReviewedAt || state.reviewed_by !== input.expectedReviewedBy
|
||||
|| state.base_active_version_id !== input.expectedActiveVersionId || state.active_version_id !== input.expectedActiveVersionId) {
|
||||
throw new CatalogError("Approved OCR recovery preconditions changed", 409, "OCR_RECOVERY_CONFLICT");
|
||||
}
|
||||
const updated = await client.query(
|
||||
`UPDATE rag_source_versions v SET state = 'indexing', indexing_started_at = now(), error_code = NULL, error_detail = NULL
|
||||
FROM rag_sources s
|
||||
WHERE v.version_id = $1 AND v.source_id = $2 AND s.source_id = v.source_id
|
||||
AND v.state = $3
|
||||
AND to_char(v.reviewed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') = $4
|
||||
AND v.reviewed_by = $5
|
||||
AND v.base_active_version_id IS NOT DISTINCT FROM $6
|
||||
AND s.active_version_id IS NOT DISTINCT FROM $6`,
|
||||
[input.versionId, input.sourceId, input.expectedState, input.expectedReviewedAt, input.expectedReviewedBy, input.expectedActiveVersionId]);
|
||||
if (updated.rowCount !== 1) throw new CatalogError("Approved OCR recovery preconditions changed", 409, "OCR_RECOVERY_CONFLICT");
|
||||
await client.query(
|
||||
`INSERT INTO rag_ocr_recovery_audit(version_id, recovered_by, reason, outcome, error_code, recovery_fingerprint)
|
||||
VALUES ($1, $2, $3, 'resumed_indexing', 'APPROVED_INDEXING_RESUMED', $4)`,
|
||||
[input.versionId, input.recoveredBy, input.reason.slice(0, 2000), input.recoveryFingerprint]);
|
||||
return { versionId: input.versionId, state: "indexing", outcome: "resumed_indexing", idempotent: false };
|
||||
});
|
||||
}
|
||||
|
||||
async markFailed(versionId: string | undefined, code: string, detail: string): Promise<void> {
|
||||
if (!versionId) {
|
||||
return;
|
||||
|
|
@ -826,7 +971,7 @@ export class CatalogRepository {
|
|||
const result = await this.pool.query(
|
||||
`UPDATE rag_source_versions
|
||||
SET state = 'failed', error_code = $2, error_detail = $3, retention_due_at = now() + interval '7 days'
|
||||
WHERE version_id = $1 AND state IN ('pending', 'indexing')`,
|
||||
WHERE version_id = $1 AND state IN ('pending', 'indexing') AND reviewed_at IS NULL`,
|
||||
[versionId, code, detail.slice(0, 2000)]
|
||||
);
|
||||
if (result.rowCount === 1) {
|
||||
|
|
@ -1151,14 +1296,15 @@ export class CatalogRepository {
|
|||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM rag_ocr_jobs j
|
||||
WHERE j.version_id = rag_source_versions.version_id AND j.state IN ('queued', 'running')
|
||||
) AND (
|
||||
) AND ((
|
||||
state = 'pending'
|
||||
AND created_at < now() - ($1::text || ' milliseconds')::interval
|
||||
) OR (
|
||||
state = 'indexing'
|
||||
AND reviewed_at IS NULL
|
||||
AND indexing_started_at IS NOT NULL
|
||||
AND indexing_started_at < now() - ($1::text || ' milliseconds')::interval
|
||||
)`,
|
||||
))`,
|
||||
[String(maxAgeMs)]
|
||||
);
|
||||
return result.rows.map((row) => ({
|
||||
|
|
@ -1196,7 +1342,7 @@ export class CatalogRepository {
|
|||
const result = await client.query(
|
||||
`UPDATE rag_source_versions
|
||||
SET state = 'ready', verified_point_count = $2, ready_at = now(), error_code = NULL, error_detail = NULL
|
||||
WHERE version_id = $1 AND state IN ('pending', 'indexing') AND expected_point_count = $2`,
|
||||
WHERE version_id = $1 AND state IN ('pending', 'indexing') AND reviewed_at IS NULL AND expected_point_count = $2`,
|
||||
[versionId, verifiedPointCount]
|
||||
);
|
||||
return result.rowCount === 1;
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import { CatalogError, type CatalogDocumentInput, type CatalogRepository } from
|
|||
import { DETECTION_POLICY_VERSION, selectPdfPagesForOcr } from "../ocr/detection.js";
|
||||
import { OCR_CONFIG, buildOcrIdempotencyKey } from "../ocr/client.js";
|
||||
import { stageOcrArtifacts } from "../ocr/artifacts.js";
|
||||
import { verifyVersionedDocuments, writeVersionedDocuments } from "./versioned-indexing.js";
|
||||
|
||||
type PreparedDocument = CatalogDocumentInput & {
|
||||
chunks: ReturnType<typeof chunkDocument>;
|
||||
|
|
@ -306,10 +307,7 @@ export class IngestService {
|
|||
await catalog.markIndexing(versionId);
|
||||
|
||||
const chunksStored = await this.writeVersionedChunks(source, sourceId, created.versionId, created.versionNumber, preparedDocuments, processingFingerprint, tags, embeddingDimensions);
|
||||
const verifiedPointCount = await this.vectorStore.countVersionPoints(created.versionId);
|
||||
if (verifiedPointCount !== expectedPointCount || chunksStored !== expectedPointCount) {
|
||||
throw new CatalogError("Indexed point count does not match the expected catalog count", 503, "SOURCE_VERSION_INCONSISTENT");
|
||||
}
|
||||
const verifiedPointCount = await verifyVersionedDocuments({ versionId: created.versionId, expectedPointCount, chunksWritten: chunksStored, vectorStore: this.vectorStore });
|
||||
|
||||
const ready = await catalog.markReady(created.versionId, verifiedPointCount);
|
||||
canMarkVersionFailed = false;
|
||||
|
|
@ -555,49 +553,16 @@ export class IngestService {
|
|||
tags: string[],
|
||||
expectedEmbeddingDimensions: number
|
||||
): Promise<number> {
|
||||
let chunksStored = 0;
|
||||
for (const document of documents) {
|
||||
const embeddings = await this.embeddingProvider.embed(document.chunks.map((chunk) => chunk.content));
|
||||
if (embeddings.length !== document.chunks.length || embeddings.some((embedding) => embedding.length !== expectedEmbeddingDimensions)) {
|
||||
throw new CatalogError("Embedding provider returned invalid dimensions", 503, "EMBEDDING_DIMENSIONS_INVALID");
|
||||
}
|
||||
const qdrantChunks: IngestedChunk[] = document.chunks.map((chunk, index) => {
|
||||
const chunkId = buildChunkId(document.documentId, document.chunkMode, chunk.index);
|
||||
return {
|
||||
id: buildVersionedQdrantPointId(versionId, chunkId),
|
||||
vector: embeddings[index],
|
||||
payload: {
|
||||
chunk_id: chunkId,
|
||||
source_id: sourceId,
|
||||
source_version_id: versionId,
|
||||
source_version_number: versionNumber,
|
||||
source_type: source.sourceType,
|
||||
source_ref: source.sourceRef,
|
||||
document_id: document.documentId,
|
||||
document_key: document.documentKey,
|
||||
document_content_hash: document.contentHash,
|
||||
title: document.title,
|
||||
mime_type: document.mimeType,
|
||||
section_title: chunk.sectionTitle,
|
||||
chunk_mode: document.chunkMode,
|
||||
chunk_index: chunk.index,
|
||||
start_line: chunk.startLine,
|
||||
end_line: chunk.endLine,
|
||||
content: chunk.content,
|
||||
tags,
|
||||
embedding_provider: this.embeddingProvider.providerName,
|
||||
embedding_model: this.embeddingProvider.modelName,
|
||||
embedding_dimensions: embeddings[index]?.length ?? 0,
|
||||
processing_fingerprint: processingFingerprint,
|
||||
indexed_at: new Date().toISOString(),
|
||||
write_state: "staged"
|
||||
}
|
||||
};
|
||||
return writeVersionedDocuments({
|
||||
identity: { sourceId, versionId, versionNumber, sourceType: source.sourceType, sourceRef: source.sourceRef, tags,
|
||||
processingFingerprint, expectedEmbeddingDimensions },
|
||||
documents: documents.map(({ documentId, documentKey, contentHash, title, mimeType, chunkMode, chunks }) => {
|
||||
if (!contentHash) throw new CatalogError("Prepared document is missing its content hash", 500, "SOURCE_CONTENT_HASH_UNAVAILABLE");
|
||||
return { documentId, documentKey, contentHash, title, mimeType, chunkMode, chunks };
|
||||
}),
|
||||
embeddingProvider: this.embeddingProvider,
|
||||
vectorStore: this.vectorStore
|
||||
});
|
||||
await this.vectorStore.upsert(qdrantChunks);
|
||||
chunksStored += qdrantChunks.length;
|
||||
}
|
||||
return chunksStored;
|
||||
}
|
||||
|
||||
private async resolveInputFiles(source: IngestSourceInput): Promise<string[]> {
|
||||
|
|
|
|||
94
src/modules/ingest/versioned-indexing.ts
Normal file
94
src/modules/ingest/versioned-indexing.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import type { EmbeddingProvider } from "../embeddings/provider.js";
|
||||
import { CatalogError } from "../catalog/errors.js";
|
||||
import type { VectorStoreClient } from "../vectorstore/client.js";
|
||||
import type { IngestedChunk, SourceType } from "../../shared/types/rag.js";
|
||||
import { buildChunkId, buildVersionedQdrantPointId } from "../../shared/utils/ids.js";
|
||||
|
||||
export interface VersionedDocumentForIndexing {
|
||||
documentId: string;
|
||||
documentKey: string;
|
||||
contentHash: string;
|
||||
title: string;
|
||||
mimeType: string;
|
||||
chunkMode: "documental" | "codigo";
|
||||
chunks: Array<{ index: number; sectionTitle: string; startLine: number; endLine: number; content: string }>;
|
||||
}
|
||||
|
||||
export interface VersionedIndexingIdentity {
|
||||
sourceId: string;
|
||||
versionId: string;
|
||||
versionNumber: number;
|
||||
sourceType: SourceType;
|
||||
sourceRef: string;
|
||||
tags: string[];
|
||||
processingFingerprint: string;
|
||||
expectedEmbeddingDimensions: number;
|
||||
}
|
||||
|
||||
export async function writeVersionedDocuments(input: {
|
||||
identity: VersionedIndexingIdentity;
|
||||
documents: VersionedDocumentForIndexing[];
|
||||
embeddingProvider: EmbeddingProvider;
|
||||
vectorStore: VectorStoreClient;
|
||||
}): Promise<number> {
|
||||
if (!Number.isSafeInteger(input.identity.expectedEmbeddingDimensions) || input.identity.expectedEmbeddingDimensions <= 0) {
|
||||
throw new CatalogError("Embedding dimensions are not configured", 503, "EMBEDDING_CONFIGURATION_INVALID");
|
||||
}
|
||||
let stored = 0;
|
||||
for (const document of input.documents) {
|
||||
const embeddings = await input.embeddingProvider.embed(document.chunks.map(({ content }) => content));
|
||||
if (embeddings.length !== document.chunks.length || embeddings.some((embedding) =>
|
||||
embedding.length !== input.identity.expectedEmbeddingDimensions)) {
|
||||
throw new CatalogError("Embedding provider returned invalid dimensions", 503, "EMBEDDING_DIMENSIONS_INVALID");
|
||||
}
|
||||
const points: IngestedChunk[] = document.chunks.map((chunk, index) => {
|
||||
const chunkId = buildChunkId(document.documentId, document.chunkMode, chunk.index);
|
||||
return {
|
||||
id: buildVersionedQdrantPointId(input.identity.versionId, chunkId),
|
||||
vector: embeddings[index]!,
|
||||
payload: {
|
||||
chunk_id: chunkId,
|
||||
source_id: input.identity.sourceId,
|
||||
source_version_id: input.identity.versionId,
|
||||
source_version_number: input.identity.versionNumber,
|
||||
source_type: input.identity.sourceType,
|
||||
source_ref: input.identity.sourceRef,
|
||||
document_id: document.documentId,
|
||||
document_key: document.documentKey,
|
||||
document_content_hash: document.contentHash,
|
||||
title: document.title,
|
||||
mime_type: document.mimeType,
|
||||
section_title: chunk.sectionTitle,
|
||||
chunk_mode: document.chunkMode,
|
||||
chunk_index: chunk.index,
|
||||
start_line: chunk.startLine,
|
||||
end_line: chunk.endLine,
|
||||
content: chunk.content,
|
||||
tags: input.identity.tags,
|
||||
embedding_provider: input.embeddingProvider.providerName,
|
||||
embedding_model: input.embeddingProvider.modelName,
|
||||
embedding_dimensions: embeddings[index]!.length,
|
||||
processing_fingerprint: input.identity.processingFingerprint,
|
||||
indexed_at: new Date().toISOString(),
|
||||
write_state: "staged"
|
||||
}
|
||||
};
|
||||
});
|
||||
if (points.length) await input.vectorStore.upsert(points);
|
||||
stored += points.length;
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
export async function verifyVersionedDocuments(input: {
|
||||
versionId: string;
|
||||
expectedPointCount: number;
|
||||
chunksWritten: number;
|
||||
vectorStore: VectorStoreClient;
|
||||
}): Promise<number> {
|
||||
const actual = await input.vectorStore.countVersionPoints(input.versionId);
|
||||
if (actual !== input.expectedPointCount || input.chunksWritten !== input.expectedPointCount) {
|
||||
throw new CatalogError("Indexed point count does not match the expected catalog count", 503, "SOURCE_VERSION_INCONSISTENT");
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
|
|
@ -406,6 +406,18 @@ export async function readReviewedPagesArtifact(input: ReviewedPagesIdentity): P
|
|||
return value as ReviewedPagesArtifact;
|
||||
}
|
||||
|
||||
export async function readReviewedPagesArtifactForRecovery(input: {
|
||||
rootDirectory: string; versionId: string; candidateSha256: string;
|
||||
}): Promise<ReviewedPagesArtifact> {
|
||||
assertUuid(input.versionId);
|
||||
const artifactPath = path.join(path.resolve(input.rootDirectory), input.versionId, "reviewed-pages.json");
|
||||
const value = await readPrivateJson(artifactPath, undefined, "OCR reviewed artifact integrity validation failed");
|
||||
if (!isRecord(value) || typeof value.reviewedTextSha256 !== "string") {
|
||||
throw new OcrArtifactError("OCR reviewed artifact identity validation failed", 422, "OCR_ARTIFACT_INTEGRITY_FAILED");
|
||||
}
|
||||
return readReviewedPagesArtifact({ ...input, reviewedTextSha256: value.reviewedTextSha256 });
|
||||
}
|
||||
|
||||
export async function removeReviewedPagesArtifact(rootDirectory: string, versionId: string): Promise<void> {
|
||||
assertUuid(versionId);
|
||||
const target = path.join(path.resolve(rootDirectory), versionId, "reviewed-pages.json");
|
||||
|
|
|
|||
|
|
@ -1,11 +1,14 @@
|
|||
import { CatalogError } from "../catalog/errors.js";
|
||||
import { withTransaction, type PgPool } from "../catalog/client.js";
|
||||
import type { PgPool } from "../catalog/client.js";
|
||||
import type { EmbeddingProvider } from "../embeddings/provider.js";
|
||||
import type { VectorStoreClient } from "../vectorstore/client.js";
|
||||
import type { IngestedChunk } from "../../shared/types/rag.js";
|
||||
import { buildChunkId, buildVersionedQdrantPointId, normalizeContentForHash, sha256Hex } from "../../shared/utils/ids.js";
|
||||
import { canonicalJson, hashOrderedPairs, normalizeContentForHash, sha256Hex } from "../../shared/utils/ids.js";
|
||||
import { chunkDocument, documentalChunkingPolicy } from "../process/chunking.js";
|
||||
import { readComposedCandidateArtifact, readReviewedPagesArtifact, type ReviewedPagesArtifact } from "./artifacts.js";
|
||||
import { readComposedCandidateArtifact, readReviewedPagesArtifact, readReviewedPagesArtifactForRecovery,
|
||||
type ComposedCandidateArtifact, type ReviewedPagesArtifact } from "./artifacts.js";
|
||||
import { CatalogRepository } from "../catalog/repository.js";
|
||||
import { verifyVersionedDocuments, writeVersionedDocuments, type VersionedDocumentForIndexing } from "../ingest/versioned-indexing.js";
|
||||
import { env } from "../../config/env.js";
|
||||
|
||||
export interface ApprovedOcrCandidate {
|
||||
versionId: string;
|
||||
|
|
@ -20,6 +23,10 @@ export interface ApprovedOcrCandidate {
|
|||
}
|
||||
|
||||
export interface OcrIndexingStore {
|
||||
withSourceLock?<T>(sourceId: string, handler: () => Promise<T>): Promise<T>;
|
||||
recoverStaleApprovedVersions?(indexLocked: (candidate: ApprovedOcrCandidate) => Promise<OcrIndexingResult>): Promise<number>;
|
||||
restoreApprovedIndexing?(input: ApprovedOcrIndexingRecoveryRequest & { versionId: string }): Promise<ApprovedOcrIndexingRecoveryResult>;
|
||||
inspectApprovedIndexingRecovery?(versionId: string): Promise<ApprovedOcrIndexingRecoveryEvidence>;
|
||||
findReusableVersion(candidate: ApprovedOcrCandidate): Promise<{ versionId: string } | undefined>;
|
||||
indexReviewed(candidate: ApprovedOcrCandidate): Promise<number>;
|
||||
markReady(versionId: string, verifiedPointCount: number): Promise<void>;
|
||||
|
|
@ -27,6 +34,34 @@ export interface OcrIndexingStore {
|
|||
activateVersion(sourceId: string, versionId: string, expectedActiveVersionId: string | null): Promise<string>;
|
||||
}
|
||||
|
||||
export interface ApprovedOcrIndexingRecoveryRequest {
|
||||
expectedState: "review_required";
|
||||
candidateSha256: string;
|
||||
reviewedTextSha256: string;
|
||||
expectedReviewedAt: string;
|
||||
expectedReviewedBy: string;
|
||||
expectedActiveVersionId: string | null;
|
||||
recoveredBy: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface ApprovedOcrIndexingRecoveryResult {
|
||||
versionId: string;
|
||||
state: "indexing" | "ready" | "active";
|
||||
outcome: "resumed_indexing";
|
||||
idempotent: boolean;
|
||||
}
|
||||
|
||||
export interface ApprovedOcrIndexingRecoveryEvidence {
|
||||
versionId: string;
|
||||
state: "review_required";
|
||||
candidateSha256: string;
|
||||
reviewedTextSha256: string;
|
||||
expectedReviewedAt: string;
|
||||
expectedReviewedBy: string;
|
||||
expectedActiveVersionId: string | null;
|
||||
}
|
||||
|
||||
export type OcrIndexingResult = {
|
||||
versionId: string;
|
||||
state: "ready" | "active" | "rejected";
|
||||
|
|
@ -47,6 +82,26 @@ export class OcrIndexingService {
|
|||
|
||||
async index(candidate: ApprovedOcrCandidate): Promise<OcrIndexingResult> {
|
||||
if (candidate.state !== "indexing") throw new CatalogError("Only approved OCR candidates can be indexed", 409, "INVALID_VERSION_STATE");
|
||||
if (this.store.withSourceLock) return this.store.withSourceLock(candidate.sourceId, () => this.indexLocked(candidate));
|
||||
return this.indexLocked(candidate);
|
||||
}
|
||||
|
||||
async recoverStaleApprovedVersions(): Promise<number> {
|
||||
if (!this.store.recoverStaleApprovedVersions) return 0;
|
||||
return this.store.recoverStaleApprovedVersions((candidate) => this.indexLocked(candidate));
|
||||
}
|
||||
|
||||
async restoreApprovedIndexing(versionId: string, input: ApprovedOcrIndexingRecoveryRequest): Promise<ApprovedOcrIndexingRecoveryResult> {
|
||||
if (!this.store.restoreApprovedIndexing) throw new CatalogError("OCR indexing recovery is not configured", 503, "OCR_RECOVERY_UNAVAILABLE");
|
||||
return this.store.restoreApprovedIndexing({ versionId, ...input });
|
||||
}
|
||||
|
||||
async inspectApprovedIndexingRecovery(versionId: string): Promise<ApprovedOcrIndexingRecoveryEvidence> {
|
||||
if (!this.store.inspectApprovedIndexingRecovery) throw new CatalogError("OCR indexing recovery is not configured", 503, "OCR_RECOVERY_UNAVAILABLE");
|
||||
return this.store.inspectApprovedIndexingRecovery(versionId);
|
||||
}
|
||||
|
||||
private async indexLocked(candidate: ApprovedOcrCandidate): Promise<OcrIndexingResult> {
|
||||
const reusable = await this.store.findReusableVersion(candidate);
|
||||
if (reusable) {
|
||||
let activated: boolean;
|
||||
|
|
@ -79,6 +134,9 @@ interface IndexingLifecycleRow {
|
|||
state: string;
|
||||
base_active_version_id: string | null;
|
||||
current_active_version_id: string | null;
|
||||
activate_requested: boolean;
|
||||
reviewed_by: string | null;
|
||||
reviewed_at: string | Date | null;
|
||||
processing_fingerprint: string;
|
||||
metadata_hash: string;
|
||||
tags: string[];
|
||||
|
|
@ -87,33 +145,34 @@ interface IndexingLifecycleRow {
|
|||
embedding_dimensions: number;
|
||||
qdrant_collection: string;
|
||||
expected_document_count: number;
|
||||
version_number: number | string;
|
||||
source_type: "file" | "folder";
|
||||
source_ref: string;
|
||||
document_id: string;
|
||||
page_number: number | string | null;
|
||||
document_key: string;
|
||||
title: string;
|
||||
mime_type: string;
|
||||
page_number: number;
|
||||
reviewed_text_hash: string;
|
||||
}
|
||||
|
||||
function versionedPoints(versionId: string, documentId: string, reviewedText: string, fingerprint: string, embedding: number[], index: number, base: Omit<IngestedChunk, "id" | "vector">): IngestedChunk {
|
||||
return {
|
||||
id: buildVersionedQdrantPointId(versionId, buildChunkId(documentId, "documental", index)),
|
||||
vector: embedding,
|
||||
...base,
|
||||
payload: { ...base.payload, chunk_id: buildChunkId(documentId, "documental", index), source_version_id: versionId, processing_fingerprint: fingerprint }
|
||||
};
|
||||
reviewed_text_hash: string | null;
|
||||
}
|
||||
|
||||
export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
||||
private readonly catalog: CatalogRepository;
|
||||
constructor(
|
||||
private readonly pool: PgPool,
|
||||
private readonly rootDirectory: string,
|
||||
private readonly embeddingProvider: EmbeddingProvider,
|
||||
private readonly vectorStore: VectorStoreClient
|
||||
) {}
|
||||
) { this.catalog = new CatalogRepository(pool); }
|
||||
|
||||
async findReusableVersion(): Promise<{ versionId: string } | undefined> {
|
||||
return undefined;
|
||||
async findReusableVersion(candidate: ApprovedOcrCandidate): Promise<{ versionId: string } | undefined> {
|
||||
const rows = await this.loadLifecycleRows(candidate);
|
||||
if (!rows.length) throw new CatalogError("OCR indexing lifecycle identity validation failed", 409, "REVIEW_CONFLICT");
|
||||
const prepared = await this.prepareReviewedDocuments(candidate, rows);
|
||||
const sourceContentHash = hashOrderedPairs(prepared.documents.map(({ documentKey, contentHash }) => [documentKey, contentHash]));
|
||||
const reusable = await this.catalog.findReusableVersion({ sourceId: candidate.sourceId, sourceContentHash,
|
||||
processingFingerprint: candidate.processingFingerprint, metadataHash: candidate.metadataHash });
|
||||
return reusable ? { versionId: reusable.versionId } : undefined;
|
||||
}
|
||||
|
||||
async indexReviewed(candidate: ApprovedOcrCandidate): Promise<number> {
|
||||
|
|
@ -127,75 +186,282 @@ export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
|||
}
|
||||
const rows = await this.loadLifecycleRows(candidate);
|
||||
if (rows.length === 0 || rows.some((row) => row.version_id !== candidate.versionId || row.processing_fingerprint !== candidate.processingFingerprint
|
||||
|| row.metadata_hash !== candidate.metadataHash)) throw new CatalogError("OCR indexing lifecycle identity validation failed", 409, "REVIEW_CONFLICT");
|
||||
|| row.metadata_hash !== candidate.metadataHash || row.source_id !== candidate.sourceId)) throw new CatalogError("OCR indexing lifecycle identity validation failed", 409, "REVIEW_CONFLICT");
|
||||
const configured = rows[0]!;
|
||||
if (configured.embedding_provider !== this.embeddingProvider.providerName || configured.embedding_model !== this.embeddingProvider.modelName
|
||||
|| Number(configured.embedding_dimensions) !== (this.embeddingProvider.dimensions ?? 4096)) {
|
||||
throw new CatalogError("Configured embedding provider does not match the approved version", 409, "EMBEDDING_CONFIGURATION_MISMATCH");
|
||||
}
|
||||
|
||||
const normalized = normalizeContentForHash(candidate.reviewedText);
|
||||
const chunks = chunkDocument(rows[0]!.title, normalized, documentalChunkingPolicy);
|
||||
const embeddings = await this.embeddingProvider.embed(chunks.map((chunk) => chunk.content));
|
||||
if (embeddings.length !== chunks.length || embeddings.some((embedding) => embedding.length !== rows[0]!.embedding_dimensions)) {
|
||||
throw new CatalogError("Embedding provider returned invalid dimensions", 503, "EMBEDDING_DIMENSIONS_INVALID");
|
||||
}
|
||||
const points = chunks.map((chunk, index) => versionedPoints(candidate.versionId, reviewed.documents[0]!.documentId, candidate.reviewedText,
|
||||
candidate.processingFingerprint, embeddings[index]!, index, {
|
||||
payload: {
|
||||
chunk_id: "", source_id: candidate.sourceId, source_version_id: candidate.versionId, source_version_number: 0,
|
||||
source_type: "file", source_ref: reviewed.documents[0]!.documentId, document_id: reviewed.documents[0]!.documentId,
|
||||
document_key: rows[0]!.document_key, document_content_hash: sha256Hex(normalized), title: rows[0]!.title,
|
||||
mime_type: rows[0]!.mime_type, section_title: chunk.sectionTitle, chunk_mode: documentalChunkingPolicy.mode,
|
||||
chunk_index: chunk.index, start_line: chunk.startLine, end_line: chunk.endLine, content: chunk.content,
|
||||
tags: rows[0]!.tags, embedding_provider: rows[0]!.embedding_provider, embedding_model: rows[0]!.embedding_model,
|
||||
embedding_dimensions: rows[0]!.embedding_dimensions, processing_fingerprint: candidate.processingFingerprint,
|
||||
indexed_at: new Date().toISOString(), write_state: "staged"
|
||||
}
|
||||
}));
|
||||
await this.vectorStore.upsert(points);
|
||||
const stored = await this.vectorStore.countVersionPoints(candidate.versionId);
|
||||
if (stored !== points.length) throw new CatalogError("Indexed point count does not match the expected catalog count", 503, "SOURCE_VERSION_INCONSISTENT");
|
||||
return points.length;
|
||||
const prepared = await this.prepareReviewedDocuments(candidate, rows, reviewed);
|
||||
const sourceContentHash = hashOrderedPairs(prepared.documents.map(({ documentKey, contentHash }) => [documentKey, contentHash]));
|
||||
if (!sourceContentHash) throw new CatalogError("Reviewed source content hash could not be calculated", 409, "REVIEW_CONFLICT");
|
||||
const expectedPointCount = prepared.documents.reduce((total, document) => total + document.chunks.length, 0);
|
||||
await this.catalog.materializeReviewedOcrIndex(candidate.versionId, {
|
||||
sourceContentHash,
|
||||
expectedPointCount,
|
||||
documents: prepared.documents.map(({ documentId, contentHash, chunks }) => ({ documentId, contentHash, chunkCount: chunks.length }))
|
||||
});
|
||||
const first = rows[0]!;
|
||||
const chunksWritten = await writeVersionedDocuments({
|
||||
identity: { sourceId: candidate.sourceId, versionId: candidate.versionId, versionNumber: Number(first.version_number),
|
||||
sourceType: first.source_type, sourceRef: first.source_ref, tags: first.tags,
|
||||
processingFingerprint: candidate.processingFingerprint, expectedEmbeddingDimensions: Number(first.embedding_dimensions) },
|
||||
documents: prepared.documents,
|
||||
embeddingProvider: this.embeddingProvider,
|
||||
vectorStore: this.vectorStore
|
||||
});
|
||||
await verifyVersionedDocuments({ versionId: candidate.versionId, expectedPointCount, chunksWritten, vectorStore: this.vectorStore });
|
||||
return chunksWritten;
|
||||
}
|
||||
|
||||
async markReady(versionId: string, verifiedPointCount: number): Promise<void> {
|
||||
await withTransaction(this.pool, async (client) => {
|
||||
const documents = await client.query("UPDATE rag_version_documents SET indexed_chunk_count = $2, indexed_at = now() WHERE version_id = $1",
|
||||
[versionId, verifiedPointCount]);
|
||||
if (documents.rowCount !== 1) throw new CatalogError("OCR indexing target documents not found", 409, "REVIEW_CONFLICT");
|
||||
const version = await client.query(
|
||||
"UPDATE rag_source_versions SET state = 'ready', indexed_at = now(), indexed_chunk_count = $2 WHERE version_id = $1 AND state = 'indexing'",
|
||||
[versionId, verifiedPointCount]);
|
||||
if (version.rowCount !== 1) throw new CatalogError("Version is not in OCR indexing state", 409, "INVALID_VERSION_STATE");
|
||||
await this.catalog.markReady(versionId, verifiedPointCount);
|
||||
}
|
||||
|
||||
async settleReusable(candidate: ApprovedOcrCandidate, reusableVersionId: string, activate: boolean): Promise<boolean> {
|
||||
await this.catalog.markOcrDuplicate(candidate.versionId, reusableVersionId);
|
||||
if (!activate) return false;
|
||||
await this.catalog.activateVersion(candidate.sourceId, reusableVersionId, candidate.expectedActiveVersionId);
|
||||
return true;
|
||||
}
|
||||
|
||||
withSourceLock<T>(sourceId: string, handler: () => Promise<T>): Promise<T> { return this.catalog.withSourceLock(sourceId, handler); }
|
||||
|
||||
async recoverStaleApprovedVersions(indexLocked: (candidate: ApprovedOcrCandidate) => Promise<OcrIndexingResult>): Promise<number> {
|
||||
const candidates = await this.catalog.listApprovedOcrIndexingCandidates(env.lifecycleIndexingStaleTimeoutMs, 20);
|
||||
let recovered = 0;
|
||||
for (const stale of candidates) {
|
||||
const result = await this.catalog.withSourceTryLock(stale.sourceId, async () => {
|
||||
let approved: ApprovedOcrCandidate;
|
||||
try {
|
||||
approved = await this.loadApprovedCandidateForRecovery(stale.versionId, stale.sourceId);
|
||||
} catch (error) {
|
||||
await this.catalog.markApprovedOcrIndexRecoveryInvalid(stale.versionId, this.recoveryErrorCode(error));
|
||||
return false;
|
||||
}
|
||||
const attempt = await this.catalog.claimApprovedOcrIndexingRecovery(stale.versionId, env.lifecycleIndexingStaleTimeoutMs);
|
||||
if (!attempt) return false;
|
||||
try {
|
||||
await indexLocked(approved);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (result) recovered += 1;
|
||||
}
|
||||
return recovered;
|
||||
}
|
||||
|
||||
async restoreApprovedIndexing(input: ApprovedOcrIndexingRecoveryRequest & { versionId: string }): Promise<ApprovedOcrIndexingRecoveryResult> {
|
||||
if (!input || typeof input !== "object") throw new CatalogError("Approved OCR recovery fields are required", 400, "OCR_RECOVERY_INVALID");
|
||||
const identity = await this.pool.query<{ source_id: string }>(
|
||||
"SELECT source_id FROM rag_source_versions WHERE version_id = $1", [input.versionId]);
|
||||
const sourceId = identity.rows[0]?.source_id;
|
||||
if (!sourceId) throw new CatalogError("OCR recovery candidate was not found", 404, "OCR_CANDIDATE_NOT_FOUND");
|
||||
const recoveredBy = input.recoveredBy?.trim();
|
||||
const reason = input.reason?.trim();
|
||||
const expectedReviewedBy = input.expectedReviewedBy;
|
||||
const expectedReviewedAt = new Date(input.expectedReviewedAt);
|
||||
if (input.expectedState !== "review_required" || !/^[0-9a-f]{64}$/u.test(input.candidateSha256)
|
||||
|| !/^[0-9a-f]{64}$/u.test(input.reviewedTextSha256) || Number.isNaN(expectedReviewedAt.getTime())
|
||||
|| !expectedReviewedBy?.trim() || !recoveredBy || !reason || recoveredBy.length > 200 || reason.length > 2000) {
|
||||
throw new CatalogError("Approved OCR recovery fields are invalid", 400, "OCR_RECOVERY_INVALID");
|
||||
}
|
||||
|
||||
return this.catalog.withSourceLock(sourceId, async () => {
|
||||
const state = await this.pool.query<{ state: string }>(
|
||||
"SELECT state FROM rag_source_versions WHERE version_id = $1 AND source_id = $2", [input.versionId, sourceId]);
|
||||
const currentState = state.rows[0]?.state;
|
||||
if (!currentState || !["review_required", "indexing", "ready", "active"].includes(currentState)) {
|
||||
throw new CatalogError("Approved OCR recovery is not permitted for this version state", 409, "OCR_RECOVERY_CONFLICT");
|
||||
}
|
||||
const candidate = await this.loadApprovedCandidateForRecovery(input.versionId, sourceId, currentState);
|
||||
const rows = await this.loadLifecycleRows(candidate, currentState);
|
||||
const first = rows[0]!;
|
||||
const composed = await readComposedCandidateArtifact({ rootDirectory: this.rootDirectory, versionId: input.versionId });
|
||||
const reviewed = await readReviewedPagesArtifactForRecovery({ rootDirectory: this.rootDirectory, versionId: input.versionId,
|
||||
candidateSha256: composed.candidateSha256 });
|
||||
if (composed.candidateSha256 !== input.candidateSha256 || reviewed.reviewedTextSha256 !== input.reviewedTextSha256
|
||||
|| reviewed.sourceId !== sourceId || reviewed.reviewedBy !== expectedReviewedBy || first.reviewed_by !== expectedReviewedBy
|
||||
|| !first.reviewed_at || new Date(first.reviewed_at).getTime() !== expectedReviewedAt.getTime()
|
||||
|| first.base_active_version_id !== input.expectedActiveVersionId
|
||||
|| (currentState === "review_required" && first.current_active_version_id !== input.expectedActiveVersionId)) {
|
||||
throw new CatalogError("Approved OCR recovery evidence or compare-and-swap precondition changed", 409, "OCR_RECOVERY_CONFLICT");
|
||||
}
|
||||
const verifiedCandidate: ApprovedOcrCandidate = { ...candidate, reviewedTextSha256: reviewed.reviewedTextSha256 };
|
||||
await this.verifyPersistedCorrections(input.versionId, composed, reviewed);
|
||||
await this.prepareReviewedDocuments(verifiedCandidate, rows, reviewed);
|
||||
if (currentState === "review_required" && (first.embedding_provider !== this.embeddingProvider.providerName
|
||||
|| first.embedding_model !== this.embeddingProvider.modelName
|
||||
|| Number(first.embedding_dimensions) !== (this.embeddingProvider.dimensions ?? 4096)
|
||||
|| first.qdrant_collection !== env.qdrantCollection)) {
|
||||
throw new CatalogError("Approved OCR embedding configuration no longer matches", 409, "OCR_INDEX_RECOVERY_CONFIG_MISMATCH");
|
||||
}
|
||||
const recoveryFingerprint = sha256Hex(canonicalJson({
|
||||
versionId: input.versionId, sourceId, expectedState: input.expectedState,
|
||||
candidateSha256: input.candidateSha256, reviewedTextSha256: input.reviewedTextSha256,
|
||||
expectedReviewedAt: input.expectedReviewedAt, expectedReviewedBy,
|
||||
expectedActiveVersionId: input.expectedActiveVersionId, recoveredBy, reason
|
||||
}));
|
||||
return this.catalog.restoreApprovedOcrIndexing({
|
||||
versionId: input.versionId, sourceId, expectedState: input.expectedState, expectedReviewedAt: input.expectedReviewedAt,
|
||||
expectedReviewedBy, expectedActiveVersionId: input.expectedActiveVersionId, recoveredBy, reason, recoveryFingerprint
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async settleReusable(): Promise<boolean> {
|
||||
throw new CatalogError("Reusable version settlement is not available for OCR indexing", 409, "REVIEW_CONFLICT");
|
||||
async inspectApprovedIndexingRecovery(versionId: string): Promise<ApprovedOcrIndexingRecoveryEvidence> {
|
||||
const identity = await this.pool.query<{ source_id: string }>("SELECT source_id FROM rag_source_versions WHERE version_id = $1", [versionId]);
|
||||
const sourceId = identity.rows[0]?.source_id;
|
||||
if (!sourceId) throw new CatalogError("OCR recovery candidate was not found", 404, "OCR_CANDIDATE_NOT_FOUND");
|
||||
return this.catalog.withSourceLock(sourceId, async () => {
|
||||
const candidate = await this.loadApprovedCandidateForRecovery(versionId, sourceId, "review_required");
|
||||
const rows = await this.loadLifecycleRows(candidate, "review_required");
|
||||
const first = rows[0];
|
||||
if (!first?.reviewed_at || first.base_active_version_id !== first.current_active_version_id) {
|
||||
throw new CatalogError("Approved OCR recovery evidence or active-version precondition changed", 409, "OCR_RECOVERY_CONFLICT");
|
||||
}
|
||||
const composed = await readComposedCandidateArtifact({ rootDirectory: this.rootDirectory, versionId });
|
||||
return { versionId, state: "review_required", candidateSha256: composed.candidateSha256,
|
||||
reviewedTextSha256: candidate.reviewedTextSha256,
|
||||
expectedReviewedAt: typeof first.reviewed_at === "string" ? first.reviewed_at : first.reviewed_at.toISOString(),
|
||||
expectedReviewedBy: first.reviewed_by!, expectedActiveVersionId: first.base_active_version_id };
|
||||
});
|
||||
}
|
||||
|
||||
async activateVersion(): Promise<string> {
|
||||
throw new CatalogError("OCR activation requires a separately authorized activation unit", 409, "INVALID_VERSION_STATE");
|
||||
async activateVersion(sourceId: string, versionId: string, expectedActiveVersionId: string | null): Promise<string> {
|
||||
return (await this.catalog.activateVersion(sourceId, versionId, expectedActiveVersionId)).versionId;
|
||||
}
|
||||
|
||||
private async loadLifecycleRows(candidate: ApprovedOcrCandidate): Promise<IndexingLifecycleRow[]> {
|
||||
private async prepareReviewedDocuments(candidate: ApprovedOcrCandidate, rows: IndexingLifecycleRow[], reviewed?: ReviewedPagesArtifact): Promise<{ documents: VersionedDocumentForIndexing[] }> {
|
||||
if (!reviewed) {
|
||||
const composed = await readComposedCandidateArtifact({ rootDirectory: this.rootDirectory, versionId: candidate.versionId });
|
||||
reviewed = await readReviewedPagesArtifact({ rootDirectory: this.rootDirectory, versionId: candidate.versionId,
|
||||
candidateSha256: composed.candidateSha256, reviewedTextSha256: candidate.reviewedTextSha256 });
|
||||
}
|
||||
if (reviewed.documents.length !== Number(rows[0]?.expected_document_count)) throw new CatalogError("Reviewed document set is incomplete", 409, "REVIEW_CONFLICT");
|
||||
const dbById = new Map(rows.map((row) => [row.document_id, row]));
|
||||
const documents: VersionedDocumentForIndexing[] = [];
|
||||
for (const artifact of reviewed.documents) {
|
||||
const row = dbById.get(artifact.documentId);
|
||||
if (!row) throw new CatalogError("Reviewed artifact contains an unknown document", 409, "REVIEW_CONFLICT");
|
||||
const pageText = artifact.pages.filter(({ candidateText }) => candidateText.trim()).map(({ candidateText }) => candidateText).join("\n\n");
|
||||
const normalized = normalizeContentForHash(pageText);
|
||||
if (!normalized || artifact.pages.some(({ page, candidateText }) => {
|
||||
const lifecycle = rows.find((entry) => entry.document_id === artifact.documentId && Number(entry.page_number) === page);
|
||||
return !lifecycle || lifecycle.reviewed_text_hash !== sha256Hex(candidateText);
|
||||
})) throw new CatalogError("Reviewed page evidence does not match the approved artifact", 409, "REVIEW_CONFLICT");
|
||||
const chunks = chunkDocument(row.title, normalized, documentalChunkingPolicy);
|
||||
documents.push({ documentId: row.document_id, documentKey: row.document_key, contentHash: sha256Hex(normalized),
|
||||
title: row.title, mimeType: row.mime_type, chunkMode: documentalChunkingPolicy.mode, chunks });
|
||||
}
|
||||
const ordered = documents.sort((left, right) => Buffer.compare(Buffer.from(left.documentKey), Buffer.from(right.documentKey)));
|
||||
if (ordered.map(({ documentId }) => documentId).join("\0") !== rows.filter((row, index) => rows.findIndex((item) => item.document_id === row.document_id) === index)
|
||||
.map(({ document_id }) => document_id).sort().join("\0")) {
|
||||
throw new CatalogError("Reviewed artifact document identity is inconsistent", 409, "REVIEW_CONFLICT");
|
||||
}
|
||||
const reconstructedText = reviewed.documents.flatMap(({ pages }) => pages.filter(({ candidateText }) => candidateText).map(({ candidateText }) => candidateText)).join("\n\n");
|
||||
if (sha256Hex(reconstructedText) !== candidate.reviewedTextSha256 || reconstructedText !== candidate.reviewedText) {
|
||||
throw new CatalogError("Reviewed text does not match its durable artifact", 409, "REVIEW_CONFLICT");
|
||||
}
|
||||
return { documents: ordered };
|
||||
}
|
||||
|
||||
private async loadLifecycleRows(candidate: ApprovedOcrCandidate, state = "indexing"): Promise<IndexingLifecycleRow[]> {
|
||||
const result = await this.pool.query(
|
||||
`SELECT v.version_id, v.source_id, v.state, v.base_active_version_id, s.active_version_id AS current_active_version_id,
|
||||
v.processing_fingerprint, v.metadata_hash, v.tags, e.embedding_provider, e.embedding_model, e.embedding_dimensions,
|
||||
e.qdrant_collection, v.expected_document_count, d.document_id, d.document_key, d.title, d.mime_type, p.page_number, p.reviewed_text_hash
|
||||
v.activate_requested, v.reviewed_by,
|
||||
to_char(v.reviewed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS reviewed_at,
|
||||
v.processing_fingerprint, v.metadata_hash, v.tags, v.embedding_provider, v.embedding_model, v.embedding_dimensions,
|
||||
v.qdrant_collection, v.expected_document_count, v.version_number, s.source_type, s.source_ref,
|
||||
d.document_id, d.document_key, d.title, d.mime_type, p.page_number, p.reviewed_text_hash
|
||||
FROM rag_source_versions v
|
||||
JOIN rag_sources s ON s.source_id = v.source_id
|
||||
LEFT JOIN rag_version_documents d ON d.version_id = v.version_id
|
||||
LEFT JOIN rag_document_pages p ON p.version_id = v.version_id
|
||||
LEFT JOIN LATERAL (SELECT 'pending' AS embedding_provider, 'pending' AS embedding_model, 0 AS embedding_dimensions, 'rag_documents' AS qdrant_collection) e ON true
|
||||
WHERE v.version_id = $1 AND v.state = 'indexing'`,
|
||||
[candidate.versionId]);
|
||||
LEFT JOIN rag_document_pages p ON p.version_id = v.version_id AND p.document_id = d.document_id
|
||||
WHERE v.version_id = $1 AND v.state = $2 AND v.reviewed_at IS NOT NULL
|
||||
ORDER BY d.document_key, p.page_number`,
|
||||
[candidate.versionId, state]);
|
||||
return result.rows as IndexingLifecycleRow[];
|
||||
}
|
||||
|
||||
private async loadApprovedCandidateForRecovery(versionId: string, expectedSourceId: string, expectedState = "indexing"): Promise<ApprovedOcrCandidate> {
|
||||
const rows = await this.loadLifecycleRows({ versionId } as ApprovedOcrCandidate, expectedState);
|
||||
if (!rows.length || rows[0]!.source_id !== expectedSourceId || rows.some((row) => row.version_id !== versionId
|
||||
|| row.source_id !== expectedSourceId || row.state !== expectedState || !row.reviewed_by
|
||||
|| row.processing_fingerprint !== rows[0]!.processing_fingerprint || row.metadata_hash !== rows[0]!.metadata_hash)) {
|
||||
throw new CatalogError("Approved OCR lifecycle identity is incomplete", 409, "OCR_INDEX_RECOVERY_IDENTITY_INVALID");
|
||||
}
|
||||
const composed = await readComposedCandidateArtifact({ rootDirectory: this.rootDirectory, versionId });
|
||||
const reviewed = await readReviewedPagesArtifactForRecovery({ rootDirectory: this.rootDirectory, versionId,
|
||||
candidateSha256: composed.candidateSha256 });
|
||||
const reconstructedText = reviewed.documents.flatMap(({ pages }) => pages.filter(({ candidateText }) => candidateText)
|
||||
.map(({ candidateText }) => candidateText)).join("\n\n");
|
||||
if (reviewed.sourceId !== expectedSourceId || reviewed.reviewedBy !== rows[0]!.reviewed_by || !reconstructedText) {
|
||||
throw new CatalogError("Approved OCR artifact identity is incomplete", 409, "OCR_INDEX_RECOVERY_ARTIFACT_INVALID");
|
||||
}
|
||||
await this.verifyPersistedCorrections(versionId, composed, reviewed);
|
||||
const candidate: ApprovedOcrCandidate = {
|
||||
versionId, sourceId: expectedSourceId, state: "indexing", activateRequested: rows[0]!.activate_requested,
|
||||
expectedActiveVersionId: rows[0]!.base_active_version_id, reviewedText: reconstructedText,
|
||||
reviewedTextSha256: reviewed.reviewedTextSha256, processingFingerprint: rows[0]!.processing_fingerprint,
|
||||
metadataHash: rows[0]!.metadata_hash
|
||||
};
|
||||
const first = rows[0]!;
|
||||
if (expectedState !== "ready" && expectedState !== "active"
|
||||
&& (first.embedding_provider !== this.embeddingProvider.providerName || first.embedding_model !== this.embeddingProvider.modelName
|
||||
|| Number(first.embedding_dimensions) !== (this.embeddingProvider.dimensions ?? 4096)
|
||||
|| first.qdrant_collection !== env.qdrantCollection)) {
|
||||
throw new CatalogError("Approved OCR embedding configuration no longer matches", 409, "OCR_INDEX_RECOVERY_CONFIG_MISMATCH");
|
||||
}
|
||||
await this.prepareReviewedDocuments(candidate, rows, reviewed);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
export class OcrReadyIndexingService {
|
||||
constructor(private readonly store: OcrIndexingStore) {}
|
||||
private async verifyPersistedCorrections(versionId: string, composed: ComposedCandidateArtifact, reviewed: ReviewedPagesArtifact): Promise<void> {
|
||||
const result = await this.pool.query<{
|
||||
document_id: string; page_number: number | string; line_id: string; expected_line_hash: string;
|
||||
replacement_text: string; reviewed_by: string;
|
||||
}>(`SELECT document_id, page_number, line_id, expected_line_hash, replacement_text, reviewed_by
|
||||
FROM rag_review_corrections WHERE version_id = $1 ORDER BY document_id, page_number, line_id`, [versionId]);
|
||||
const pending = new Map(result.rows.map((row) => [`${row.document_id}:${Number(row.page_number)}:${row.line_id}`, row]));
|
||||
let matched = 0;
|
||||
const reviewedByDocument = new Map(reviewed.documents.map((document) => [document.documentId, document]));
|
||||
for (const document of composed.documents) {
|
||||
const reviewedDocument = reviewedByDocument.get(document.documentId);
|
||||
if (!reviewedDocument) throw new CatalogError("Reviewed correction document set changed", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
for (const page of document.pages) {
|
||||
const reviewedPage = reviewedDocument.pages.find(({ page: number }) => number === page.page);
|
||||
if (!reviewedPage) throw new CatalogError("Reviewed correction page set changed", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
const reviewedLines = new Map(reviewedPage.ocr.lines.map((line) => [line.lineId, line]));
|
||||
if (reviewedLines.size !== page.lines.length) throw new CatalogError("Reviewed correction line set changed", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
for (const original of page.lines) {
|
||||
const replacement = reviewedLines.get(original.lineId);
|
||||
if (!replacement) throw new CatalogError("Reviewed correction line identity changed", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
const key = `${document.documentId}:${page.page}:${original.lineId}`;
|
||||
const persisted = pending.get(key);
|
||||
if (persisted) {
|
||||
if (persisted.expected_line_hash !== original.lineSha256 || persisted.replacement_text !== replacement.text
|
||||
|| persisted.reviewed_by !== reviewed.reviewedBy) {
|
||||
throw new CatalogError("Reviewed correction audit does not match its artifact", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
}
|
||||
pending.delete(key);
|
||||
matched += 1;
|
||||
} else if (replacement.text !== original.text || replacement.lineSha256 !== original.lineSha256) {
|
||||
throw new CatalogError("Reviewed artifact contains an unaudited correction", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pending.size || matched !== result.rows.length) {
|
||||
throw new CatalogError("Reviewed correction audit contains unmatched records", 409, "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
async index(candidate: ApprovedOcrCandidate): Promise<OcrIndexingResult> {
|
||||
const verifiedPointCount = await this.store.indexReviewed(candidate);
|
||||
await this.store.markReady(candidate.versionId, verifiedPointCount);
|
||||
return { versionId: candidate.versionId, state: "ready", activated: false };
|
||||
private recoveryErrorCode(error: unknown): string {
|
||||
if (error instanceof CatalogError) return error.code;
|
||||
return "OCR_INDEX_RECOVERY_ARTIFACT_INVALID";
|
||||
}
|
||||
}
|
||||
|
|
|
|||
13
tests/catalog/migration-005.test.ts
Normal file
13
tests/catalog/migration-005.test.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import test from "node:test";
|
||||
|
||||
test("migration 005 adds approved-indexing recovery audit while preserving historical close outcomes", async () => {
|
||||
const sql = await readFile(new URL("../../migrations/005_ocr_approved_indexing_recovery.sql", import.meta.url), "utf8");
|
||||
assert.match(sql, /DROP CONSTRAINT IF EXISTS rag_ocr_recovery_audit_outcome_check/i);
|
||||
assert.match(sql, /outcome IN \('closed_failed', 'resumed_indexing'\)/i);
|
||||
assert.match(sql, /ADD COLUMN IF NOT EXISTS recovery_fingerprint char\(64\)/i);
|
||||
assert.match(sql, /WHERE recovery_fingerprint IS NOT NULL/i);
|
||||
assert.match(sql, /UNIQUE INDEX IF NOT EXISTS/i);
|
||||
assert.doesNotMatch(sql, /DELETE FROM rag_ocr_recovery_audit|UPDATE rag_ocr_recovery_audit/i);
|
||||
});
|
||||
|
|
@ -165,6 +165,7 @@ test("candidate lifecycle persistence requires exact native, OCR, and metrics ev
|
|||
assert.equal(await repository.completeOcrJob("job-1", { pages: [{ page: 1, text: "OCR", metrics: { inkCoverage: 0.4 } }] } as never), true);
|
||||
assert.doesNotMatch(calls[2]!.sql, /candidate_text_hash/);
|
||||
assert.deepEqual(await repository.listOcrVersionsAwaitingCandidate(), ["version-1"]);
|
||||
assert.match(calls.find(({ sql }) => sql.includes("SELECT DISTINCT v.version_id"))!.sql, /v\.reviewed_at IS NULL/u);
|
||||
await repository.persistOcrCandidate("version-1", [{
|
||||
documentId: "document-1", page: 1, method: "ocr", nativeTextSha256: "a".repeat(64),
|
||||
ocrTextSha256: "b".repeat(64), candidateTextSha256: "b".repeat(64), metrics: { inkCoverage: 0.4 }, risks: ["CBGO4a"],
|
||||
|
|
@ -187,6 +188,7 @@ test("review transitions enforce indexing, approval, and rejection state guards"
|
|||
await success.markOcrReviewIndexing("version-1", "reviewer-1");
|
||||
await success.rejectOcrVersion("version-1", "reviewer-1", "Unreadable code");
|
||||
assert.match(successfulSql[0], /state = 'indexing'.*NOT EXISTS/s);
|
||||
assert.match(successfulSql[0], /reviewed_at IS NULL/u);
|
||||
assert.match(successfulSql[0], /FROM rag_version_documents/);
|
||||
assert.match(successfulSql[0], /rag_ocr_jobs WHERE version_id = \$1 AND state <> 'succeeded'/);
|
||||
assert.match(successfulSql[1], /state = 'review_required'/);
|
||||
|
|
@ -199,6 +201,140 @@ test("review transitions enforce indexing, approval, and rejection state guards"
|
|||
);
|
||||
});
|
||||
|
||||
test("approved OCR recovery candidates are stale indexing approvals only and stop after the bounded retry budget", async () => {
|
||||
let observedSql = "";
|
||||
const repository = new CatalogRepository(poolFor(async (sql, params) => {
|
||||
observedSql = sql;
|
||||
assert.deepEqual(params, ["1800000", 3]);
|
||||
return { rowCount: 1, rows: [{ version_id: "version-approved", source_id: "source-1" }] };
|
||||
}) as never);
|
||||
|
||||
assert.deepEqual(await repository.listApprovedOcrIndexingCandidates(1_800_000, 3), [
|
||||
{ versionId: "version-approved", sourceId: "source-1" }
|
||||
]);
|
||||
assert.match(observedSql, /state = 'indexing'/u);
|
||||
assert.match(observedSql, /reviewed_at IS NOT NULL/u);
|
||||
assert.match(observedSql, /indexing_started_at/u);
|
||||
assert.match(observedSql, /OCR_INDEX_RECOVERY_RETRY/u);
|
||||
assert.doesNotMatch(observedSql, /state = 'review_required'/u);
|
||||
});
|
||||
|
||||
test("approved OCR recovery CAS allows no more than three recorded attempts", async () => {
|
||||
let attempts = 2;
|
||||
let updateCount = 0;
|
||||
const repository = new CatalogRepository(poolFor(async (sql, params) => {
|
||||
if (sql.startsWith("SELECT source_id, error_code")) {
|
||||
assert.deepEqual(params, ["version-approved", "1800000"]);
|
||||
return { rowCount: 1, rows: [{ source_id: "source-1",
|
||||
error_code: attempts ? "OCR_INDEX_RECOVERY_RETRY" : null, error_detail: attempts ? JSON.stringify({ attempt: attempts }) : null }] };
|
||||
}
|
||||
if (sql.includes("SET indexing_started_at = now(), error_code = 'OCR_INDEX_RECOVERY_RETRY'")) {
|
||||
assert.deepEqual(params?.slice(0, 1), ["version-approved"]);
|
||||
assert.match(sql, /state = 'indexing' AND reviewed_at IS NOT NULL/u);
|
||||
attempts = Number(JSON.parse(String(params?.[1])).attempt);
|
||||
updateCount += 1;
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
throw new Error(`Unexpected recovery SQL: ${sql}`);
|
||||
}) as never);
|
||||
|
||||
assert.equal(await repository.claimApprovedOcrIndexingRecovery("version-approved", 1_800_000), 3);
|
||||
assert.equal(await repository.claimApprovedOcrIndexingRecovery("version-approved", 1_800_000), undefined);
|
||||
assert.equal(updateCount, 1);
|
||||
});
|
||||
|
||||
test("generic orphan recovery query only selects unreviewed pending/indexing versions", async () => {
|
||||
let observedSql = "";
|
||||
const repository = new CatalogRepository(poolFor(async (sql) => {
|
||||
observedSql = sql;
|
||||
return { rowCount: 0, rows: [] };
|
||||
}) as never);
|
||||
|
||||
assert.deepEqual(await repository.listOrphanedIndexingCandidates(1_800_000), []);
|
||||
assert.match(observedSql, /reviewed_at IS NULL/u);
|
||||
assert.match(observedSql, /state = 'pending'/u);
|
||||
assert.match(observedSql, /state = 'indexing'/u);
|
||||
});
|
||||
|
||||
test("approved-indexing restoration is CAS-protected, audited atomically, and idempotent for the same fingerprint", async () => {
|
||||
const calls: string[] = [];
|
||||
const state = { state: "review_required", activeVersionId: "active-1", reviewedAt: "2026-10-01T10:00:00.000000Z", reviewer: "original-reviewer" };
|
||||
const audits = new Map<string, { outcome: string; versionId: string }>();
|
||||
const client = {
|
||||
async query(sql: string, params?: unknown[]) {
|
||||
calls.push(sql);
|
||||
if (/^(BEGIN|COMMIT|ROLLBACK|SET CONSTRAINTS)/u.test(sql.trim())) return { rowCount: 0, rows: [] };
|
||||
if (sql.includes("FROM rag_source_versions v JOIN rag_sources")) return { rowCount: 1, rows: [{ state: state.state,
|
||||
reviewed_at: state.reviewedAt, reviewed_by: state.reviewer, base_active_version_id: "active-1", active_version_id: state.activeVersionId }] };
|
||||
if (sql.includes("FROM rag_ocr_recovery_audit")) {
|
||||
const audit = audits.get(String(params?.[1]));
|
||||
return { rowCount: audit ? 1 : 0, rows: audit ? [audit] : [] };
|
||||
}
|
||||
if (sql.includes("UPDATE rag_source_versions") && sql.includes("SET state = 'indexing'")) {
|
||||
assert.match(sql, /v\.state = \$3/u);
|
||||
assert.match(sql, /to_char\(v\.reviewed_at AT TIME ZONE 'UTC'/u);
|
||||
assert.match(sql, /\) = \$4/u);
|
||||
assert.match(sql, /reviewed_by = \$5/u);
|
||||
assert.match(sql, /active_version_id IS NOT DISTINCT FROM \$6/u);
|
||||
assert.match(sql, /indexing_started_at = now\(\), error_code = NULL, error_detail = NULL/u);
|
||||
state.state = "indexing";
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (sql.includes("INSERT INTO rag_ocr_recovery_audit")) {
|
||||
const audit = { outcome: "resumed_indexing", versionId: String(params?.[0]) };
|
||||
audits.set(String(params?.[3]), audit);
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
throw new Error(`Unexpected recovery transaction SQL: ${sql} ${String(params)}`);
|
||||
}, release() {}
|
||||
};
|
||||
const repository = new CatalogRepository({ connect: async () => client } as never);
|
||||
const request = { versionId: "version-approved", sourceId: "source-1", expectedState: "review_required" as const,
|
||||
expectedReviewedAt: state.reviewedAt, expectedReviewedBy: "original-reviewer", expectedActiveVersionId: "active-1",
|
||||
recoveredBy: "admin", reason: "Resume interrupted approved indexing", recoveryFingerprint: "a".repeat(64) };
|
||||
|
||||
assert.deepEqual(await repository.restoreApprovedOcrIndexing(request), {
|
||||
versionId: "version-approved", state: "indexing", outcome: "resumed_indexing", idempotent: false
|
||||
});
|
||||
assert.equal(state.state, "indexing");
|
||||
assert.equal(audits.size, 1);
|
||||
assert.equal(calls.at(-1)?.trim(), "COMMIT");
|
||||
assert.doesNotMatch(calls.join("\n"), /rag_review_corrections|reviewed_text_hash|SET reviewed_by|reviewed_at = now\(\)/u);
|
||||
|
||||
assert.deepEqual(await repository.restoreApprovedOcrIndexing(request), {
|
||||
versionId: "version-approved", state: "indexing", outcome: "resumed_indexing", idempotent: true
|
||||
});
|
||||
assert.equal(audits.size, 1);
|
||||
});
|
||||
|
||||
test("approved-indexing recovery rejects a changed state, reviewer timestamp, reviewer, or active version without writes", async () => {
|
||||
const expectedReviewedAt = "2026-10-01T10:00:00.000000Z";
|
||||
const request = { versionId: "version-approved", sourceId: "source-1", expectedState: "review_required" as const,
|
||||
expectedReviewedAt, expectedReviewedBy: "original-reviewer", expectedActiveVersionId: "active-1",
|
||||
recoveredBy: "admin", reason: "Recovery test", recoveryFingerprint: "b".repeat(64) };
|
||||
for (const changed of [
|
||||
{ state: "indexing", reviewedAt: expectedReviewedAt, reviewer: "original-reviewer", active: "active-1" },
|
||||
{ state: "review_required", reviewedAt: "2026-10-01T10:00:00.000001Z", reviewer: "original-reviewer", active: "active-1" },
|
||||
{ state: "review_required", reviewedAt: expectedReviewedAt, reviewer: null, active: "active-1" },
|
||||
{ state: "review_required", reviewedAt: expectedReviewedAt, reviewer: "original-reviewer", active: "active-2" }
|
||||
]) {
|
||||
const calls: string[] = [];
|
||||
const client = { async query(sql: string) {
|
||||
calls.push(sql);
|
||||
if (/^(BEGIN|COMMIT|ROLLBACK|SET CONSTRAINTS)/u.test(sql.trim())) return { rowCount: 0, rows: [] };
|
||||
if (sql.includes("FROM rag_source_versions v JOIN rag_sources")) return { rowCount: 1, rows: [{ state: changed.state,
|
||||
reviewed_at: changed.reviewedAt, reviewed_by: changed.reviewer, base_active_version_id: "active-1", active_version_id: changed.active }] };
|
||||
if (sql.includes("FROM rag_ocr_recovery_audit")) return { rowCount: 0, rows: [] };
|
||||
throw new Error(`Unexpected recovery SQL: ${sql}`);
|
||||
}, release() {} };
|
||||
const repository = new CatalogRepository({ connect: async () => client } as never);
|
||||
await assert.rejects(repository.restoreApprovedOcrIndexing(request),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_RECOVERY_CONFLICT");
|
||||
assert.doesNotMatch(calls.join("\n"), /UPDATE rag_source_versions|INSERT INTO rag_ocr_recovery_audit/u);
|
||||
assert.equal(calls.at(-1)?.trim(), "ROLLBACK");
|
||||
}
|
||||
});
|
||||
|
||||
test("blocked candidate diagnostics commit before signaling the terminal quality outcome", async () => {
|
||||
const calls: Array<{ sql: string; params?: unknown[] }> = [];
|
||||
const client = { async query(sql: string, params?: unknown[]) {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { IngestService } from "../src/modules/ingest/service.js";
|
|||
import { RetrieveService } from "../src/modules/retrieve/service.js";
|
||||
import type { EmbeddingProvider } from "../src/modules/embeddings/provider.js";
|
||||
import type { VectorStoreClient } from "../src/modules/vectorstore/client.js";
|
||||
import { sha256Hex } from "../src/shared/utils/ids.js";
|
||||
|
||||
function setEnvFlag(name: keyof typeof env, value: unknown) {
|
||||
(env as unknown as Record<string, unknown>)[name] = value;
|
||||
|
|
@ -120,6 +121,38 @@ test("activation failure leaves a newly indexed version ready instead of failed"
|
|||
}));
|
||||
});
|
||||
|
||||
test("fresh native lifecycle ingest persists document/source hashes and canonical versioned payload before ready", async () => {
|
||||
await withEnvFlags({ knowledgeLifecycleEnforced: true }, async () => withTempMarkdown("# Fresh native source\n\nA newly ingested document verifies the complete native lifecycle indexing contract.", async (filePath) => {
|
||||
const points: Array<{ payload: Record<string, unknown>; vector: number[] }> = [];
|
||||
let created: Record<string, unknown> | undefined;
|
||||
const vectorStore = {
|
||||
kind: "fake",
|
||||
async upsert(values: Array<{ payload: Record<string, unknown>; vector: number[] }>) { points.push(...values); },
|
||||
async countVersionPoints() { return points.length; }
|
||||
};
|
||||
const catalog = {
|
||||
async beginAttempt() { return "fresh-attempt"; }, async updateAttempt() {},
|
||||
async withSourceLock(_sourceId: string, handler: () => Promise<unknown>) { return handler(); },
|
||||
async findReusableVersion() { return undefined; },
|
||||
async createPendingVersion(input: Record<string, unknown>) { created = input; return { versionId: "fresh-version", versionNumber: 7 }; },
|
||||
async markIndexing() {},
|
||||
async markReady(_versionId: string, verifiedPointCount: number) { assert.equal(verifiedPointCount, points.length); return { versionId: "fresh-version", versionNumber: 7, state: "ready", previousVersionId: null }; }
|
||||
};
|
||||
const result = await new IngestService(fakeEmbeddingProvider(), vectorStore as never, catalog as never).ingest({
|
||||
sourceType: "file", sourceRef: "fresh.md", readPath: filePath, activate: false
|
||||
});
|
||||
const prepared = (created?.documents as Array<{ contentHash: string }>)[0]!;
|
||||
const sourceContentHash = created?.sourceContentHash;
|
||||
assert.equal(result.state, "ready");
|
||||
assert.equal((created?.expectedPointCount as number), points.length);
|
||||
assert.ok(typeof sourceContentHash === "string" && sourceContentHash.length === 64);
|
||||
assert.equal(prepared.contentHash, sha256Hex("# Fresh native source\n\nA newly ingested document verifies the complete native lifecycle indexing contract.\n"));
|
||||
assert.ok(points.every(({ payload }) => payload.source_version_id === "fresh-version" && payload.source_version_number === 7
|
||||
&& payload.document_content_hash === prepared.contentHash && payload.embedding_dimensions === 3
|
||||
&& payload.embedding_provider === "test-provider" && payload.embedding_model === "test-model"));
|
||||
}));
|
||||
});
|
||||
|
||||
test("active no-op validates the expected active version precondition", async () => {
|
||||
await withEnvFlags({ knowledgeLifecycleEnforced: true }, async () => withTempMarkdown("# Title\n\nUseful content", async (filePath) => {
|
||||
const { vectorStore, chunks } = fakeVectorStore();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
|||
import test from "node:test";
|
||||
import { createApp } from "../../src/app.js";
|
||||
import { env } from "../../src/config/env.js";
|
||||
import { OcrReadyIndexingService } from "../../src/modules/ocr/indexing.js";
|
||||
import { OcrIndexingService } from "../../src/modules/ocr/indexing.js";
|
||||
import { OcrReviewService } from "../../src/modules/ocr/review.js";
|
||||
import type { OcrReviewCandidate } from "../../src/modules/ocr/review.js";
|
||||
|
||||
|
|
@ -11,7 +11,7 @@ const token = "admin-token";
|
|||
function candidate(state: string): OcrReviewCandidate {
|
||||
return {
|
||||
versionId: "11111111-2222-4333-8444-555555555555", sourceId: "src:scan.pdf", state: state as OcrReviewCandidate["state"],
|
||||
baseActiveVersionId: "active-1", currentActiveVersionId: "active-1", activateRequested: true, processingFingerprint: "fp", metadataHash: "mh",
|
||||
baseActiveVersionId: "active-1", currentActiveVersionId: "active-1", activateRequested: false, processingFingerprint: "fp", metadataHash: "mh",
|
||||
candidateSha256: "candidate-hash",
|
||||
documents: [{ documentId: "doc:scan", pages: [{ page: 1, imageUrl: "/img", nativeText: "", ocr: { text: "CBGO4a", lines: [{ lineId: "line-1", text: "CBGO4a", confidence: 0.9, bbox: [0, 0, 1, 1], lineSha256: "hash" }] }, candidateText: "CBGO4a", differences: [], risks: [] }] }]
|
||||
} as OcrReviewCandidate;
|
||||
|
|
@ -28,7 +28,7 @@ test("production approval triggers durable indexing and reports ready", async (c
|
|||
async commitApproval(input) { reviewed = input.reviewedText; },
|
||||
async commitRejection() { throw new Error("rejection is out of scope"); }
|
||||
});
|
||||
const indexing = new OcrReadyIndexingService({
|
||||
const indexing = new OcrIndexingService({
|
||||
async findReusableVersion() { return undefined; },
|
||||
async indexReviewed(value) { indexedCandidate = value.reviewedText; return 1; },
|
||||
async markReady() { /* ready marker */ },
|
||||
|
|
@ -79,3 +79,44 @@ test("approval without a configured indexing service stays at the indexing bound
|
|||
assert.equal(approval.status, 503);
|
||||
assert.equal(((await approval.json()) as { code?: string }).code, "OCR_INDEXING_UNAVAILABLE");
|
||||
});
|
||||
|
||||
test("approved indexing administrative recovery is authenticated and idempotency is delegated without reapproval", async (context) => {
|
||||
const previous = { lifecycle: env.knowledgeLifecycleEnforced, enabled: env.ocrIngestEnabled, admin: env.lifecycleAdminToken };
|
||||
Object.assign(env, { knowledgeLifecycleEnforced: true, ocrIngestEnabled: true, lifecycleAdminToken: token });
|
||||
context.after(() => Object.assign(env, previous));
|
||||
const requestBody = {
|
||||
expectedState: "review_required", candidateSha256: "a".repeat(64), reviewedTextSha256: "b".repeat(64),
|
||||
expectedReviewedAt: "2026-10-01T10:00:00.000Z", expectedReviewedBy: "original-reviewer",
|
||||
expectedActiveVersionId: "22222222-2222-4222-8222-222222222222", recoveredBy: "admin", reason: "Resume the previously approved indexing operation"
|
||||
};
|
||||
const calls: unknown[] = [];
|
||||
const evidence = {
|
||||
versionId: "11111111-2222-4333-8444-555555555555", state: "review_required", candidateSha256: requestBody.candidateSha256,
|
||||
reviewedTextSha256: requestBody.reviewedTextSha256, expectedReviewedAt: requestBody.expectedReviewedAt,
|
||||
expectedReviewedBy: requestBody.expectedReviewedBy, expectedActiveVersionId: requestBody.expectedActiveVersionId
|
||||
};
|
||||
const server = createApp({
|
||||
indexingRecoveryService: {
|
||||
async inspectApprovedIndexingRecovery(versionId: string) { calls.push({ inspect: versionId }); return evidence; },
|
||||
async restoreApprovedIndexing(versionId: string, input: typeof requestBody) {
|
||||
calls.push({ versionId, input });
|
||||
return { versionId, state: "indexing", outcome: "resumed_indexing", idempotent: false };
|
||||
}
|
||||
}, startReconciler: false
|
||||
}).listen(0);
|
||||
context.after(() => server.close());
|
||||
const address = server.address();
|
||||
assert.ok(address && typeof address === "object");
|
||||
const url = `http://127.0.0.1:${address.port}/ingestions/11111111-2222-4333-8444-555555555555/recover-indexing`;
|
||||
|
||||
assert.equal((await fetch(url)).status, 401);
|
||||
const preflight = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
|
||||
assert.equal(preflight.status, 200);
|
||||
assert.deepEqual(await preflight.json(), evidence);
|
||||
assert.equal((await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(requestBody) })).status, 401);
|
||||
const response = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(requestBody) });
|
||||
assert.equal(response.status, 202);
|
||||
assert.deepEqual(await response.json(), { versionId: "11111111-2222-4333-8444-555555555555", state: "indexing", outcome: "resumed_indexing", idempotent: false });
|
||||
assert.deepEqual(calls, [{ inspect: "11111111-2222-4333-8444-555555555555" },
|
||||
{ versionId: "11111111-2222-4333-8444-555555555555", input: requestBody }]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -25,6 +25,8 @@ test("OpenAPI describes authenticated OCR ingestion, status, review, approval, a
|
|||
["/ingestions/{versionId}", "get"],
|
||||
["/ingestions/{versionId}/review", "get"],
|
||||
["/ingestions/{versionId}/recover", "post"],
|
||||
["/ingestions/{versionId}/recover-indexing", "get"],
|
||||
["/ingestions/{versionId}/recover-indexing", "post"],
|
||||
["/ingestions/{versionId}/documents/{documentId}/pages/{page}/image", "get"],
|
||||
["/ingestions/{versionId}/approve", "post"],
|
||||
["/ingestions/{versionId}/reject", "post"]
|
||||
|
|
@ -32,7 +34,8 @@ test("OpenAPI describes authenticated OCR ingestion, status, review, approval, a
|
|||
const operation = api.paths[path]![method]!;
|
||||
assert.deepEqual(operation.security, [{ bearerAuth: [] }], `${method.toUpperCase()} ${path} must require bearer auth`);
|
||||
const responses = operation.responses as Record<string, unknown>;
|
||||
assert.ok("200" in responses && "401" in responses && "404" in responses && "503" in responses);
|
||||
assert.ok((path.endsWith("recover-indexing") && method === "post" ? "202" in responses : "200" in responses)
|
||||
&& "401" in responses && "404" in responses && "503" in responses);
|
||||
}
|
||||
|
||||
const approve = api.paths["/ingestions/{versionId}/approve"]!.post!;
|
||||
|
|
@ -48,6 +51,11 @@ test("OpenAPI describes authenticated OCR ingestion, status, review, approval, a
|
|||
{ $ref: "#/components/schemas/OcrRejectionRequest" });
|
||||
assert.deepEqual((recover.requestBody as { content: Record<string, { schema: unknown }> }).content["application/json"]!.schema,
|
||||
{ $ref: "#/components/schemas/OcrRecoveryRequest" });
|
||||
const indexingRecovery = api.paths["/ingestions/{versionId}/recover-indexing"]!;
|
||||
assert.deepEqual((indexingRecovery.post!.requestBody as { content: Record<string, { schema: unknown }> }).content["application/json"]!.schema,
|
||||
{ $ref: "#/components/schemas/OcrApprovedIndexingRecoveryRequest" });
|
||||
assert.deepEqual(((indexingRecovery.get!.responses as Record<string, { content: Record<string, { schema: unknown }> }>)["200"]!
|
||||
.content["application/json"]!.schema), { $ref: "#/components/schemas/OcrApprovedIndexingRecoveryEvidence" });
|
||||
assert.match(buildApiHelp().authentication, /Bearer.*OCR/u);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -713,6 +713,29 @@ test("reconciler restart completes durable OCR work without resubmitting OCR", a
|
|||
assert.deepEqual(calls, ["ocr-recovery", "ocr-dispatch", "candidate-recovery", "ocr-recovery", "ocr-dispatch", "candidate-recovery"]);
|
||||
});
|
||||
|
||||
test("reconciler delegates stale approved indexing to the serialized OCR recovery coordinator", async () => {
|
||||
const calls: string[] = [];
|
||||
const catalog = {
|
||||
async withGlobalTryLock(_name: string, handler: () => Promise<unknown>) { calls.push("global-lock"); return handler(); },
|
||||
async resolveActiveVersions() { return []; },
|
||||
async validateActiveInvariant() { return []; },
|
||||
async listOrphanedIndexingCandidates() { return []; }
|
||||
};
|
||||
const dispatcher = {
|
||||
async recoverExpiredLeases() { calls.push("ocr-leases"); return 0; },
|
||||
async dispatchAvailable() { calls.push("ocr-dispatch"); return 0; },
|
||||
async recoverCompletedCandidates() { calls.push("ocr-finalization"); return 0; }
|
||||
};
|
||||
const approvedIndexer = { async recoverStaleApprovedVersions() { calls.push("approved-indexing"); return 1; } };
|
||||
const reconciler = new KnowledgeLifecycleReconciler(catalog as never, vectorStore(), dispatcher as never,
|
||||
undefined, approvedIndexer);
|
||||
|
||||
const status = await reconciler.runOnce();
|
||||
|
||||
assert.equal(status.approvedIndexingRecovered, 1);
|
||||
assert.deepEqual(calls, ["global-lock", "ocr-leases", "ocr-dispatch", "ocr-finalization", "approved-indexing"]);
|
||||
});
|
||||
|
||||
test("runtime HTTP routing returns native 201, OCR 202/status, and catalog-down 503", async () => {
|
||||
const previous = { knowledgeLifecycleEnforced: env.knowledgeLifecycleEnforced, lifecycleAdminToken: env.lifecycleAdminToken, ocrIngestEnabled: env.ocrIngestEnabled };
|
||||
setEnvFlag("knowledgeLifecycleEnforced", true);
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import test from "node:test";
|
|||
import { createApp } from "../../src/app.js";
|
||||
import { env } from "../../src/config/env.js";
|
||||
import { OcrDispatcher } from "../../src/modules/ocr/dispatcher.js";
|
||||
import { OcrReadyIndexingService } from "../../src/modules/ocr/indexing.js";
|
||||
import { OcrIndexingService } from "../../src/modules/ocr/indexing.js";
|
||||
import { OcrReviewService, type OcrReviewCandidate } from "../../src/modules/ocr/review.js";
|
||||
import { sha256Hex } from "../../src/shared/utils/ids.js";
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ function candidate(): OcrReviewCandidate {
|
|||
candidateSha256: "candidate-hash",
|
||||
baseActiveVersionId: "previous-active",
|
||||
currentActiveVersionId: "previous-active",
|
||||
activateRequested: true,
|
||||
activateRequested: false,
|
||||
processingFingerprint: "fingerprint",
|
||||
metadataHash: "metadata",
|
||||
documents: [{
|
||||
|
|
@ -91,7 +91,7 @@ test("local HTTP flow keeps native ingestion synchronous and stops approved OCR
|
|||
async commitRejection() { throw new Error("rejection is outside this flow"); }
|
||||
});
|
||||
let indexingCalls = 0;
|
||||
const indexing = new OcrReadyIndexingService({
|
||||
const indexing = new OcrIndexingService({
|
||||
async findReusableVersion() { return undefined; },
|
||||
async indexReviewed(value) { indexingCalls += 1; assert.equal(value.reviewedText, "CBG04a"); return 1; },
|
||||
async markReady(versionId) { states.set(versionId, "ready"); },
|
||||
|
|
|
|||
|
|
@ -3,9 +3,10 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { env } from "../../src/config/env.js";
|
||||
import { CatalogError } from "../../src/modules/catalog/errors.js";
|
||||
import type { EmbeddingProvider } from "../../src/modules/embeddings/provider.js";
|
||||
import { PostgresOcrIndexingStore, OcrReadyIndexingService, type ApprovedOcrCandidate } from "../../src/modules/ocr/indexing.js";
|
||||
import { OcrIndexingService, PostgresOcrIndexingStore, type ApprovedOcrCandidate } from "../../src/modules/ocr/indexing.js";
|
||||
import { persistComposedCandidateArtifact, persistOcrResultArtifact, persistReviewedPagesArtifact, persistReviewImageArtifacts,
|
||||
stageOcrArtifacts } from "../../src/modules/ocr/artifacts.js";
|
||||
import { buildOcrIdentity } from "../../src/modules/ocr/client.js";
|
||||
|
|
@ -50,39 +51,183 @@ async function fixture(rootDirectory: string) {
|
|||
await persistReviewedPagesArtifact({ rootDirectory, versionId, sourceId, candidateSha256: candidate.candidateSha256,
|
||||
reviewedTextSha256: sha256Hex(reviewedText), reviewedBy: "reviewer",
|
||||
documents: [{ documentId, pages: pages.map(({ page, candidateText, lines }) => ({ page, candidateText, ocr: { lines } })) }] });
|
||||
return { reviewedText, pages };
|
||||
return { reviewedText, pages, candidateSha256: candidate.candidateSha256 };
|
||||
}
|
||||
|
||||
async function multiDocumentFixture(rootDirectory: string) {
|
||||
const sourceId = "src:reviewed-folder";
|
||||
const inputs = [
|
||||
{ documentId: "doc:folder-alpha", documentKey: "a-scanned.pdf", bytes: Buffer.from("%PDF-alpha"), pages: [1, 2], texts: ["Alpha reviewed text. ".repeat(90).trim(), "Alpha page two reviewed text. ".repeat(30).trim()], requestedPages: [1, 2] },
|
||||
{ documentId: "doc:folder-beta", documentKey: "b-native.pdf", bytes: Buffer.from("%PDF-beta"), pages: [1], texts: ["Native companion reviewed content. ".repeat(50).trim()], requestedPages: [] }
|
||||
];
|
||||
await stageOcrArtifacts({ rootDirectory, versionId, createdAt: "2026-09-22T12:00:00.000Z", documents: inputs.map((item) => ({
|
||||
documentId: item.documentId, documentKey: item.documentKey, bytes: item.bytes, requestedPages: item.requestedPages,
|
||||
pages: item.pages.map((page, index) => ({ page, text: item.requestedPages.length ? "" : item.texts[index]!, rasterCoverage: item.requestedPages.length ? 1 : 0,
|
||||
textSha256: sha256Hex(item.requestedPages.length ? "" : item.texts[index]!) }))
|
||||
})) });
|
||||
const jobs = [];
|
||||
for (const item of inputs.filter(({ requestedPages }) => requestedPages.length)) {
|
||||
const remoteJobId = `remote-${item.documentId}`;
|
||||
const identity = buildOcrIdentity({ documentSha256: sha256Hex(item.bytes), pages: item.requestedPages, idempotencyKey: `key-${item.documentId}` });
|
||||
await persistOcrResultArtifact({ rootDirectory, versionId, documentId: item.documentId, result: {
|
||||
schemaVersion: "1", jobId: remoteJobId, ...identity,
|
||||
engine: { name: "paddleocr", version: "3.4.0", runtime: "paddlepaddle-3.2.2", device: "cpu", configVersion: "ocr-v2", dpi: 200 },
|
||||
pages: item.pages.map((page, index) => ocrPage(page, item.texts[index]!))
|
||||
} });
|
||||
await persistReviewImageArtifacts({ rootDirectory, versionId, documentId: item.documentId,
|
||||
images: item.pages.map((page) => ({ page, bytes: png, sha256: sha256Hex(png) })) });
|
||||
jobs.push({ documentId: item.documentId, remoteJobId, requestedPages: item.requestedPages, state: "succeeded" });
|
||||
}
|
||||
const { candidate: composedCandidate } = await persistComposedCandidateArtifact({ rootDirectory, versionId, jobs });
|
||||
const reviewedText = composedCandidate.documents.flatMap(({ pages }) => pages.filter(({ candidateText }) => candidateText)
|
||||
.map(({ candidateText }) => candidateText)).join("\n\n");
|
||||
const reviewedDocuments = composedCandidate.documents.map(({ documentId, pages }) => ({ documentId,
|
||||
pages: pages.map(({ page, candidateText, lines }) => ({ page, candidateText, ocr: { lines } })) }));
|
||||
await persistReviewedPagesArtifact({ rootDirectory, versionId, sourceId, candidateSha256: composedCandidate.candidateSha256,
|
||||
reviewedTextSha256: sha256Hex(reviewedText), reviewedBy: "reviewer", documents: reviewedDocuments });
|
||||
return { sourceId, reviewedText, candidate: { ...candidate(reviewedText), sourceId }, pages: composedCandidate.documents.flatMap(({ documentId, pages }) =>
|
||||
pages.map(({ page, candidateText }) => ({ documentId, page, candidateText }))), docs: inputs.map(({ documentId, documentKey, texts }) => ({
|
||||
documentId, documentKey, text: texts.join("\n\n")
|
||||
})) };
|
||||
}
|
||||
|
||||
function candidate(reviewedText: string): ApprovedOcrCandidate {
|
||||
return { versionId, sourceId, state: "indexing", activateRequested: true, expectedActiveVersionId: "active-1",
|
||||
return { versionId, sourceId, state: "indexing", activateRequested: false, expectedActiveVersionId: "active-1",
|
||||
reviewedText, reviewedTextSha256: sha256Hex(reviewedText), processingFingerprint: "fingerprint", metadataHash: "metadata" };
|
||||
}
|
||||
|
||||
function harness(pageCount: number, options: { embeddingFailure?: boolean; countOffset?: number } = {}) {
|
||||
function harness(pageCount: number, options: { embeddingFailure?: boolean; embeddingModel?: string; embeddingOutputDimensions?: number; countOffset?: number; countFailureOnce?: boolean; sourceLockBusy?: boolean; documentCount?: number; sourceId?: string; sourceType?: "file" | "folder"; sourceRef?: string; docKeys?: string[]; correctionRows?: Array<Record<string, unknown>>; versionState?: string } = {}) {
|
||||
const documentCount = options.documentCount ?? 1;
|
||||
const sourceId = options.sourceId ?? "src:reviewed";
|
||||
const pagesPerDocument = Math.ceil(pageCount / documentCount);
|
||||
const documentIds = Array.from({ length: documentCount }, (_, index) => documentCount === 1 ? documentId : `doc:folder-${index === 0 ? "alpha" : "beta"}`);
|
||||
const sql: string[] = [];
|
||||
const mutations: Array<{ statement: string; params?: unknown[] }> = [];
|
||||
const points: Array<{ id: string; vector: number[]; payload: Record<string, unknown> }> = [];
|
||||
let embedCalls = 0;
|
||||
let embeddingFailure = options.embeddingFailure ?? false;
|
||||
let countFailureOnce = options.countFailureOnce ?? false;
|
||||
let recoveryAttempts = 0;
|
||||
const recoveryAudits = new Map<string, { outcome: string; version_id: string }>();
|
||||
const rows = Array.from({ length: pageCount }, (_, index) => ({
|
||||
version_id: versionId, source_id: sourceId, version_number: 4, state: "indexing", base_active_version_id: "active-1",
|
||||
version_id: versionId, source_id: sourceId, version_number: 4, state: options.versionState ?? "indexing", base_active_version_id: "active-1",
|
||||
current_active_version_id: "active-1", processing_fingerprint: "fingerprint", metadata_hash: "metadata", tags: ["reviewed"],
|
||||
embedding_provider: "test-provider", embedding_model: "test-model", embedding_dimensions: 3, qdrant_collection: "rag_documents",
|
||||
expected_document_count: 1, document_id: documentId, document_key: "review.pdf", title: "review.pdf", mime_type: "application/pdf",
|
||||
page_number: index + 1, reviewed_text_hash: "pending"
|
||||
embedding_provider: "test-provider", embedding_model: options.embeddingModel ?? "test-model", embedding_dimensions: 3, qdrant_collection: env.qdrantCollection,
|
||||
expected_document_count: documentCount, source_type: options.sourceType ?? "file", source_ref: options.sourceRef ?? "review.pdf",
|
||||
activate_requested: false, reviewed_by: "reviewer", document_id: documentIds[Math.floor(index / pagesPerDocument)]!,
|
||||
document_key: options.docKeys?.[Math.floor(index / pagesPerDocument)] ?? "review.pdf",
|
||||
title: options.docKeys?.[Math.floor(index / pagesPerDocument)] ?? "review.pdf", mime_type: "application/pdf",
|
||||
page_number: index % pagesPerDocument + 1, reviewed_text_hash: "pending", reviewed_at: new Date()
|
||||
}));
|
||||
const query = async (statement: string, params?: unknown[]) => {
|
||||
sql.push(statement);
|
||||
if (/^(UPDATE|INSERT|DELETE)/u.test(statement.trim())) mutations.push({ statement, params });
|
||||
if (/^(BEGIN|COMMIT|ROLLBACK|SET CONSTRAINTS)/u.test(statement.trim())) return { rowCount: 0, rows: [] };
|
||||
if (statement.includes("FROM rag_source_versions v")) return { rowCount: rows.length, rows };
|
||||
if (statement.includes("UPDATE rag_version_documents")) return { rowCount: 1, rows: [] };
|
||||
if (statement.includes("UPDATE rag_source_versions")) return { rowCount: 1, rows: [{ version_id: versionId }] };
|
||||
if (/^SELECT pg_(?:try_)?advisory_(?:lock|unlock)\(/u.test(statement.trim())) return { rowCount: 1, rows: [{ locked: !options.sourceLockBusy }] };
|
||||
if (statement.includes("FROM rag_review_corrections")) return { rowCount: options.correctionRows?.length ?? 0, rows: options.correctionRows ?? [] };
|
||||
if (statement.startsWith("SELECT source_id FROM rag_source_versions")) return { rowCount: 1, rows: [{ source_id: rows[0]!.source_id }] };
|
||||
if (statement.startsWith("SELECT state FROM rag_source_versions")) return { rowCount: 1, rows: [{ state: rows[0]!.state }] };
|
||||
if (statement.includes("to_char(v.reviewed_at AT TIME ZONE") && statement.includes("FROM rag_source_versions v JOIN rag_sources")) return { rowCount: 1, rows: [{
|
||||
state: rows[0]!.state, reviewed_at: rows[0]!.reviewed_at instanceof Date ? rows[0]!.reviewed_at.toISOString() : rows[0]!.reviewed_at,
|
||||
reviewed_by: rows[0]!.reviewed_by,
|
||||
base_active_version_id: rows[0]!.base_active_version_id, active_version_id: rows[0]!.current_active_version_id
|
||||
}] };
|
||||
if (statement.includes("FROM rag_ocr_recovery_audit")) {
|
||||
const audit = recoveryAudits.get(String(params?.[1]));
|
||||
return { rowCount: audit ? 1 : 0, rows: audit ? [audit] : [] };
|
||||
}
|
||||
if (statement.includes("UPDATE rag_source_versions v SET state = 'indexing'")) {
|
||||
if (rows[0]!.state !== "review_required") return { rowCount: 0, rows: [] };
|
||||
for (const row of rows) row.state = "indexing";
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("INSERT INTO rag_ocr_recovery_audit")) {
|
||||
recoveryAudits.set(String(params?.[3]), { outcome: "resumed_indexing", version_id: versionId });
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("SELECT version_id, source_id FROM rag_source_versions")) {
|
||||
return rows[0]!.state === "indexing" && recoveryAttempts < 3
|
||||
? { rowCount: 1, rows: [{ version_id: versionId, source_id: rows[0]!.source_id }] }
|
||||
: { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (statement.includes("SELECT source_id, error_code, error_detail FROM rag_source_versions")) {
|
||||
return { rowCount: 1, rows: [{ source_id: rows[0]!.source_id, error_code: recoveryAttempts ? "OCR_INDEX_RECOVERY_RETRY" : null,
|
||||
error_detail: recoveryAttempts ? JSON.stringify({ attempt: recoveryAttempts }) : null }] };
|
||||
}
|
||||
if (statement.includes("SET indexing_started_at = now(), error_code = 'OCR_INDEX_RECOVERY_RETRY'")) {
|
||||
recoveryAttempts = Number(JSON.parse(String(params?.[1])).attempt);
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("FROM rag_source_versions v")) {
|
||||
assert.match(statement, /v\.embedding_provider, v\.embedding_model, v\.embedding_dimensions/u);
|
||||
assert.match(statement, /d\.document_id, d\.document_key, d\.title, d\.mime_type/u);
|
||||
assert.doesNotMatch(statement, /indexed_chunk_count|indexed_at/u);
|
||||
return { rowCount: rows.length, rows };
|
||||
}
|
||||
if (statement.includes("UPDATE rag_source_versions SET source_content_hash")) {
|
||||
assert.match(statement, /source_content_hash = \$2/u);
|
||||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("SET error_code = 'OCR_INDEX_RECOVERY_INVALID'")) return { rowCount: 1, rows: [] };
|
||||
if (statement.includes("SELECT expected_document_count, state, reviewed_at FROM rag_source_versions")) {
|
||||
return { rowCount: 1, rows: [{ expected_document_count: documentCount, state: "indexing", reviewed_at: new Date() }] };
|
||||
}
|
||||
if (statement.includes("FROM rag_source_versions")) {
|
||||
assert.match(statement, /source_content_hash = \$2/u);
|
||||
assert.match(statement, /processing_fingerprint = \$3/u);
|
||||
assert.match(statement, /metadata_hash = \$4/u);
|
||||
return { rowCount: 0, rows: [] };
|
||||
}
|
||||
if (statement.includes("UPDATE rag_version_documents SET content_hash")) {
|
||||
assert.match(statement, /content_hash = \$3, chunk_count = \$4/u);
|
||||
return { rowCount: documentIds.includes(String(params?.[1])) ? 1 : 0, rows: [] };
|
||||
}
|
||||
if (statement.includes("UPDATE rag_version_documents SET index_state = 'ready'")) return { rowCount: documentCount, rows: [] };
|
||||
if (statement.includes("UPDATE rag_source_versions") && statement.includes("SET state = 'ready'")) {
|
||||
for (const row of rows) row.state = "ready";
|
||||
return { rowCount: 1, rows: [{
|
||||
version_id: versionId, source_id: sourceId, version_number: 4, previous_version_id: "active-1", state: "ready", tags: ["reviewed"],
|
||||
source_content_hash: "hash", processing_fingerprint: "fingerprint", metadata_hash: "metadata", embedding_provider: "test-provider",
|
||||
embedding_model: "test-model", embedding_dimensions: 3, expected_document_count: documentCount, expected_point_count: points.length,
|
||||
verified_point_count: points.length, qdrant_collection: "rag_documents"
|
||||
}] };
|
||||
}
|
||||
throw new Error(`Unexpected SQL: ${statement} ${String(params)}`);
|
||||
};
|
||||
const pool = { query, async connect() { return { query, release() {} }; } };
|
||||
const embeddings: EmbeddingProvider = { providerName: "test-provider", modelName: "test-model", dimensions: 3,
|
||||
async embed(input) { embedCalls += 1; if (options.embeddingFailure) throw new Error("embedding unavailable"); return input.map(() => [0.1, 0.2, 0.3]); } };
|
||||
const vectors: Partial<VectorStoreClient> = { kind: "fake", async upsert(chunks) { points.push(...chunks); },
|
||||
async countVersionPoints() { return points.length + (options.countOffset ?? 0); } };
|
||||
return { pool: pool as never, embeddings, vectors: vectors as VectorStoreClient, points, sql, embedCalls: () => embedCalls };
|
||||
async embed(input) { embedCalls += 1; if (embeddingFailure) throw new Error("embedding unavailable"); return input.map(() => Array(options.embeddingOutputDimensions ?? 3).fill(0.1)); } };
|
||||
const vectors: Partial<VectorStoreClient> = { kind: "fake", async upsert(chunks) {
|
||||
for (const chunk of chunks) {
|
||||
const existing = points.findIndex(({ id }) => id === chunk.id);
|
||||
if (existing < 0) points.push(chunk);
|
||||
else points[existing] = chunk;
|
||||
}
|
||||
}, async countVersionPoints() {
|
||||
if (countFailureOnce) { countFailureOnce = false; throw new Error("simulated interruption after deterministic point upsert"); }
|
||||
return points.length + (options.countOffset ?? 0);
|
||||
} };
|
||||
return { pool: pool as never, embeddings, vectors: vectors as VectorStoreClient, points, sql, rows, mutations,
|
||||
embedCalls: () => embedCalls, setEmbeddingFailure(value: boolean) { embeddingFailure = value; }, recoveryAttempts: () => recoveryAttempts, recoveryAudits };
|
||||
}
|
||||
|
||||
async function approvedRecoveryFixture(context: { after(callback: () => void): void }, options: { state?: string; reviewer?: string | null; active?: string | null; correctionRows?: Array<Record<string, unknown>> } = {}) {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-approved-admin-recovery-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages, candidateSha256 } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { versionState: options.state ?? "review_required", correctionRows: options.correctionRows });
|
||||
const activeVersionId = "11111111-1111-4111-8111-111111111111";
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
runtime.rows[index]!.base_active_version_id = activeVersionId;
|
||||
runtime.rows[index]!.current_active_version_id = options.active === undefined ? activeVersionId : options.active;
|
||||
if (options.reviewer !== undefined) runtime.rows[index]!.reviewed_by = options.reviewer;
|
||||
}
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
const request = { expectedState: "review_required" as const, candidateSha256, reviewedTextSha256: sha256Hex(reviewedText),
|
||||
expectedReviewedAt: runtime.rows[0]!.reviewed_at.toISOString(), expectedReviewedBy: "reviewer", expectedActiveVersionId: activeVersionId,
|
||||
recoveredBy: "admin", reason: "Resume interrupted approved indexing" };
|
||||
return { runtime, service, request };
|
||||
}
|
||||
|
||||
test("reviewed artifact indexing survives restart and writes canonical versioned chunks before ready", async (context) => {
|
||||
|
|
@ -90,40 +235,211 @@ test("reviewed artifact indexing survives restart and writes canonical versioned
|
|||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length);
|
||||
const originalQuery = (runtime.pool as { query: (sql: string, params?: unknown[]) => Promise<{ rowCount: number; rows: Array<Record<string, unknown>> }> }).query;
|
||||
for (let index = 0; index < pages.length; index += 1) {
|
||||
const row = (await originalQuery("SELECT * FROM rag_source_versions v", [])).rows[index]!;
|
||||
row.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
}
|
||||
const restarted = new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors);
|
||||
const result = await new OcrReadyIndexingService(restarted).index(candidate(reviewedText));
|
||||
const result = await new OcrIndexingService(restarted).index(candidate(reviewedText));
|
||||
|
||||
const expected = chunkDocument("review.pdf", normalizeContentForHash(reviewedText), documentalChunkingPolicy);
|
||||
assert.deepEqual(result, { versionId, state: "ready", activated: false });
|
||||
assert.equal(runtime.points.length, expected.length);
|
||||
assert.deepEqual(runtime.points.map(({ id }) => id), expected.map((chunk) => buildVersionedQdrantPointId(versionId, buildChunkId(documentId, "documental", chunk.index))));
|
||||
assert.ok(runtime.points.every(({ payload }) => payload.processing_fingerprint === "fingerprint" && payload.source_version_id === versionId));
|
||||
assert.ok(runtime.points.every(({ payload }) => payload.source_version_number === 4 && payload.source_type === "file"
|
||||
&& payload.source_ref === "review.pdf" && payload.embedding_provider === "test-provider"
|
||||
&& payload.embedding_model === "test-model" && payload.embedding_dimensions === 3));
|
||||
const contentHash = sha256Hex(normalizeContentForHash(reviewedText));
|
||||
assert.ok(runtime.points.every(({ payload }) => payload.document_content_hash === contentHash));
|
||||
assert.ok(runtime.mutations.some(({ statement, params }) => statement.includes("SET source_content_hash")
|
||||
&& params?.[2] === expected.length));
|
||||
assert.match(runtime.sql.join("\n"), /SET state = 'ready'/u);
|
||||
assert.doesNotMatch(runtime.sql.join("\n"), /active_version_id\s*=/u);
|
||||
});
|
||||
|
||||
test("approved OCR indexing rebuilds every reviewed document with canonical per-document hashes and payload identity", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-multi-index-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const multi = await multiDocumentFixture(rootDirectory);
|
||||
const runtime = harness(3, { documentCount: 2, sourceId: multi.sourceId, sourceType: "folder", sourceRef: "bundle",
|
||||
docKeys: ["a-scanned.pdf", "b-native.pdf"] });
|
||||
for (const page of multi.pages) {
|
||||
const row = runtime.rows.find((entry) => entry.document_id === page.documentId && entry.page_number === page.page);
|
||||
assert.ok(row);
|
||||
row.reviewed_text_hash = sha256Hex(page.candidateText);
|
||||
}
|
||||
|
||||
const result = await new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors))
|
||||
.index(multi.candidate);
|
||||
|
||||
const expectedByDocument = new Map(multi.docs.map(({ documentId, documentKey, text }) => [documentId, {
|
||||
documentKey, contentHash: sha256Hex(normalizeContentForHash(text)),
|
||||
chunks: chunkDocument(documentKey, normalizeContentForHash(text), documentalChunkingPolicy)
|
||||
}]));
|
||||
assert.deepEqual(result, { versionId, state: "ready", activated: false });
|
||||
assert.deepEqual(new Set(runtime.points.map(({ payload }) => payload.document_id)), new Set(multi.docs.map(({ documentId }) => documentId)));
|
||||
for (const point of runtime.points) {
|
||||
const expected = expectedByDocument.get(String(point.payload.document_id));
|
||||
assert.ok(expected);
|
||||
assert.equal(point.payload.document_content_hash, expected.contentHash);
|
||||
assert.equal(point.payload.document_key, expected.documentKey);
|
||||
assert.equal(point.payload.source_type, "folder");
|
||||
assert.equal(point.payload.source_ref, "bundle");
|
||||
assert.equal(point.payload.source_version_number, 4);
|
||||
assert.equal(point.payload.embedding_dimensions, 3);
|
||||
}
|
||||
assert.equal(runtime.points.length, [...expectedByDocument.values()].reduce((total, doc) => total + doc.chunks.length, 0));
|
||||
const documentWrites = runtime.mutations.filter(({ statement }) => statement.includes("UPDATE rag_version_documents SET content_hash"));
|
||||
assert.equal(documentWrites.length, 2);
|
||||
assert.deepEqual(documentWrites.map(({ params }) => params?.[1]).sort(), multi.docs.map(({ documentId }) => documentId).sort());
|
||||
});
|
||||
|
||||
test("approved indexing recovery resumes after an upsert interruption, is idempotent, and stops after ready", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-recovery-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { countFailureOnce: true });
|
||||
for (let index = 0; index < pages.length; index += 1) runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 1);
|
||||
const firstWrittenIds = runtime.points.map(({ id }) => id).sort();
|
||||
assert.ok(firstWrittenIds.length > 0);
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 1);
|
||||
assert.equal(runtime.recoveryAttempts(), 2);
|
||||
assert.deepEqual(runtime.points.map(({ id }) => id).sort(), firstWrittenIds);
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 2);
|
||||
});
|
||||
|
||||
test("approved indexing recovery stops before claims or vector writes when correction audit differs from the immutable reviewed artifact", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-recovery-correction-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { correctionRows: [{ document_id: documentId, page_number: 1, line_id: "p1-l1",
|
||||
expected_line_hash: "f".repeat(64), replacement_text: "forged replacement", reviewed_by: "reviewer" }] });
|
||||
for (let index = 0; index < pages.length; index += 1) runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 0);
|
||||
assert.equal(runtime.points.length, 0);
|
||||
assert.ok(runtime.sql.some((statement) => statement.includes("UPDATE rag_source_versions SET error_code = 'OCR_INDEX_RECOVERY_INVALID'")));
|
||||
});
|
||||
|
||||
test("approved indexing recovery skips a source while synchronous indexing holds its advisory lock", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-recovery-lock-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { sourceLockBusy: true });
|
||||
for (let index = 0; index < pages.length; index += 1) runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 0);
|
||||
assert.equal(runtime.embedCalls(), 0);
|
||||
assert.equal(runtime.points.length, 0);
|
||||
});
|
||||
|
||||
test("authenticated recovery validates evidence, preserves approval records, and treats an identical retry idempotently", async (context) => {
|
||||
const { runtime, service, request } = await approvedRecoveryFixture(context);
|
||||
|
||||
const first = await service.restoreApprovedIndexing(versionId, request);
|
||||
const replay = await service.restoreApprovedIndexing(versionId, request);
|
||||
|
||||
assert.deepEqual(first, { versionId, state: "indexing", outcome: "resumed_indexing", idempotent: false });
|
||||
assert.deepEqual(replay, { versionId, state: "indexing", outcome: "resumed_indexing", idempotent: true });
|
||||
assert.equal(runtime.rows[0]!.state, "indexing");
|
||||
assert.equal(runtime.rows[0]!.reviewed_by, "reviewer");
|
||||
assert.ok(runtime.recoveryAudits.size === 1);
|
||||
assert.equal(runtime.mutations.filter(({ statement }) => statement.includes("INSERT INTO rag_ocr_recovery_audit")).length, 1);
|
||||
assert.doesNotMatch(runtime.sql.join("\n"), /INSERT INTO rag_review_corrections|SET reviewed_by|reviewed_at = now\(\)/u);
|
||||
});
|
||||
|
||||
test("approved recovery preflight returns exact artifact hashes and CAS values without changing the candidate", async (context) => {
|
||||
const { runtime, service, request } = await approvedRecoveryFixture(context);
|
||||
|
||||
const evidence = await service.inspectApprovedIndexingRecovery(versionId);
|
||||
|
||||
assert.deepEqual(evidence, { versionId, state: "review_required", candidateSha256: request.candidateSha256,
|
||||
reviewedTextSha256: request.reviewedTextSha256, expectedReviewedAt: request.expectedReviewedAt,
|
||||
expectedReviewedBy: request.expectedReviewedBy, expectedActiveVersionId: request.expectedActiveVersionId });
|
||||
assert.equal(runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(runtime.recoveryAudits.size, 0);
|
||||
assert.equal(runtime.mutations.length, 0);
|
||||
});
|
||||
|
||||
test("administrative recovery rejects mismatched hashes, missing reviewer evidence, and concurrent state changes without mutation", async (context) => {
|
||||
const invalidHash = await approvedRecoveryFixture(context);
|
||||
await assert.rejects(invalidHash.service.restoreApprovedIndexing(versionId, { ...invalidHash.request, candidateSha256: "f".repeat(64) }),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_RECOVERY_CONFLICT");
|
||||
assert.equal(invalidHash.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(invalidHash.runtime.recoveryAudits.size, 0);
|
||||
assert.equal(invalidHash.runtime.mutations.some(({ statement }) => statement.includes("SET state = 'indexing'")), false);
|
||||
|
||||
const invalidReviewedHash = await approvedRecoveryFixture(context);
|
||||
await assert.rejects(invalidReviewedHash.service.restoreApprovedIndexing(versionId,
|
||||
{ ...invalidReviewedHash.request, reviewedTextSha256: "e".repeat(64) }),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_RECOVERY_CONFLICT");
|
||||
assert.equal(invalidReviewedHash.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(invalidReviewedHash.runtime.recoveryAudits.size, 0);
|
||||
|
||||
const invalidPageEvidence = await approvedRecoveryFixture(context);
|
||||
invalidPageEvidence.runtime.rows[0]!.reviewed_text_hash = "f".repeat(64);
|
||||
await assert.rejects(invalidPageEvidence.service.restoreApprovedIndexing(versionId, invalidPageEvidence.request),
|
||||
(error) => error instanceof CatalogError && error.statusCode === 409);
|
||||
assert.equal(invalidPageEvidence.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(invalidPageEvidence.runtime.recoveryAudits.size, 0);
|
||||
|
||||
const invalidCorrectionAudit = await approvedRecoveryFixture(context, { correctionRows: [{ document_id: documentId, page_number: 1,
|
||||
line_id: "p1-l1", expected_line_hash: "f".repeat(64), replacement_text: "forged text", reviewed_by: "reviewer" }] });
|
||||
await assert.rejects(invalidCorrectionAudit.service.restoreApprovedIndexing(versionId, invalidCorrectionAudit.request),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_INDEX_RECOVERY_EVIDENCE_INVALID");
|
||||
assert.equal(invalidCorrectionAudit.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(invalidCorrectionAudit.runtime.recoveryAudits.size, 0);
|
||||
|
||||
const missingReviewer = await approvedRecoveryFixture(context, { reviewer: null });
|
||||
await assert.rejects(missingReviewer.service.restoreApprovedIndexing(versionId, missingReviewer.request),
|
||||
(error) => error instanceof CatalogError && error.statusCode === 409);
|
||||
assert.equal(missingReviewer.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(missingReviewer.runtime.recoveryAudits.size, 0);
|
||||
|
||||
const activeChanged = await approvedRecoveryFixture(context, { active: "22222222-2222-4222-8222-222222222222" });
|
||||
await assert.rejects(activeChanged.service.restoreApprovedIndexing(versionId, activeChanged.request),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_RECOVERY_CONFLICT");
|
||||
assert.equal(activeChanged.runtime.rows[0]!.state, "review_required");
|
||||
assert.equal(activeChanged.runtime.recoveryAudits.size, 0);
|
||||
|
||||
const raced = await approvedRecoveryFixture(context, { state: "indexing" });
|
||||
await assert.rejects(raced.service.restoreApprovedIndexing(versionId, raced.request),
|
||||
(error) => error instanceof CatalogError && error.code === "OCR_RECOVERY_CONFLICT");
|
||||
assert.equal(raced.runtime.recoveryAudits.size, 0);
|
||||
assert.equal(raced.runtime.mutations.some(({ statement }) => statement.includes("INSERT INTO rag_ocr_recovery_audit")), false);
|
||||
});
|
||||
|
||||
test("identity, corrupt artifact, embedding, and partial-write failures remain fail closed", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-index-fail-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
for (const scenario of [
|
||||
{ name: "identity", runtime: harness(pages.length), value: { ...candidate(reviewedText), processingFingerprint: "wrong" } },
|
||||
{ name: "configuration", runtime: harness(pages.length, { embeddingModel: "different-model" }), value: candidate(reviewedText) },
|
||||
{ name: "dimensions", runtime: harness(pages.length, { embeddingOutputDimensions: 2 }), value: candidate(reviewedText) },
|
||||
{ name: "embedding", runtime: harness(pages.length, { embeddingFailure: true }), value: candidate(reviewedText) },
|
||||
{ name: "count", runtime: harness(pages.length, { countOffset: -1 }), value: candidate(reviewedText) }
|
||||
]) {
|
||||
await assert.rejects(new OcrReadyIndexingService(new PostgresOcrIndexingStore(scenario.runtime.pool, rootDirectory, scenario.runtime.embeddings, scenario.runtime.vectors)).index(scenario.value),
|
||||
scenario.name === "count" ? (error) => error instanceof CatalogError && error.code === "SOURCE_VERSION_INCONSISTENT" : Error);
|
||||
for (let index = 0; index < pages.length; index += 1) scenario.runtime.rows[index]!.reviewed_text_hash = sha256Hex(pages[index]!.candidateText);
|
||||
await assert.rejects(new OcrIndexingService(new PostgresOcrIndexingStore(scenario.runtime.pool, rootDirectory, scenario.runtime.embeddings, scenario.runtime.vectors)).index(scenario.value),
|
||||
scenario.name === "count" ? (error) => error instanceof CatalogError && error.code === "SOURCE_VERSION_INCONSISTENT"
|
||||
: scenario.name === "configuration" ? (error) => error instanceof CatalogError && error.code === "EMBEDDING_CONFIGURATION_MISMATCH"
|
||||
: scenario.name === "dimensions" ? (error) => error instanceof CatalogError && error.code === "EMBEDDING_DIMENSIONS_INVALID" : Error);
|
||||
assert.doesNotMatch(scenario.runtime.sql.join("\n"), /SET state = 'ready'/u);
|
||||
if (scenario.name === "identity") assert.equal(scenario.runtime.embedCalls(), 0);
|
||||
}
|
||||
await writeFile(path.join(rootDirectory, versionId, "reviewed-pages.json"), "corrupt", { mode: 0o600 });
|
||||
const corrupt = harness(pages.length);
|
||||
await assert.rejects(new OcrReadyIndexingService(new PostgresOcrIndexingStore(corrupt.pool, rootDirectory, corrupt.embeddings, corrupt.vectors)).index(candidate(reviewedText)), /integrity validation failed/u);
|
||||
await assert.rejects(new OcrIndexingService(new PostgresOcrIndexingStore(corrupt.pool, rootDirectory, corrupt.embeddings, corrupt.vectors)).index(candidate(reviewedText)), /integrity validation failed/u);
|
||||
assert.equal(corrupt.embedCalls(), 0);
|
||||
assert.equal(corrupt.points.length, 0);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue