fix(rag): make approved indexing transfers durable
This commit is contained in:
parent
b6bd69b762
commit
4241c82b88
22 changed files with 1500 additions and 105 deletions
|
|
@ -77,7 +77,7 @@ La API queda formada por las operaciones de descubrimiento, ingesta, retrieval,
|
|||
|
||||
## Seleccion e incidencias OCR por pagina (verificada localmente)
|
||||
|
||||
La politica `page-best-effort-v1` esta implementada, verificada localmente (suite `152/152`) y publicada en `4e30d8c`, pendiente de despliegue. Requiere `006_ocr_page_content_selection.sql`, validada solo en PostgreSQL local y pendiente en produccion; el contrato remoto OCR conserva `ocr-v2` y 200 DPI.
|
||||
La politica `page-best-effort-v1` esta desplegada en `b6bd69b7628e507c472b405e97e9337cfea5be80`, con migracion `006`. La prueba del libro completo supero OCR/revision/aprobacion y quedo bloqueada al escribir un payload Qdrant>32MiB. La transferencia durable posterior esta verificada solo en LOCAL (suite178/178), pendiente de publicacion/despliegue; apartados9-10 del plan. El contrato remoto OCR conserva `ocr-v2` y 200 DPI.
|
||||
|
||||
- El estado autenticado `GET /ingestions/{versionId}` expone `selection` por pagina y un resumen `coverage`, incluso despues de activar. `policyVersion: null` identifica cobertura historica no evaluada por esta politica; cero incidencias no garantiza exactitud semantica.
|
||||
- `selection` distingue `source` (`native`, `ocr`, `none`), `reason`, `contentUnrecovered` e `issue`, sin alterar `qualityOutcome`, `warnings` o `blockingReasons` del OCR. Los estados nuevos `native_fallback` y `content_unrecovered` no representan un fallo de ejecucion.
|
||||
|
|
@ -88,6 +88,8 @@ Esquemas en `src/api/openapi.ts`; decisiones, autorizaciones y gate de pruebas e
|
|||
|
||||
## Restaurar indexado OCR aprobado
|
||||
|
||||
**Transferencia durable LOCAL pendiente de despliegue (2026-10-10):** GET autenticado `/ingestions/{versionId}` añade `indexingTransfer` con señales nominales5s, etapa/fase, lote/intento, deadlines, puntos/bytes confirmados y ultima señal/avance. `signalStale` no equivale a permiso para ignorar el bloqueo de fuente. Una pausa devuelve fase `indexing_paused` y error no reintentable automaticamente, conservando los checkpoints; no repetir approve. Transporte maximo8MiB sin tope de puntos, tres intentos/lote, 180s/intento/540s total y reanudacion de aprobados desde cache durable. Contrato completo en apartado10 del plan; esto no cambia el CAS de la ruta historica siguiente ni constituye prueba de recuperacion productiva.
|
||||
|
||||
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:
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ Servicio RAG para ingesta, versionado y recuperacion de conocimiento. Incluye un
|
|||
- [x] En desarrollo
|
||||
- [x] En produccion
|
||||
|
||||
**Ultima sesion:** 2026-10-09
|
||||
**Ultima sesion:** 2026-10-10
|
||||
**Ultimo agente:** Agente RAG 3
|
||||
|
||||
### Ubicacion del proyecto
|
||||
|
|
@ -35,8 +35,9 @@ Servicio RAG para ingesta, versionado y recuperacion de conocimiento. Incluye un
|
|||
|
||||
### Notas rapidas
|
||||
|
||||
- Traspaso vigente al volver de compactar: COMMIT/PUSH autorizados tras retorno, entregar BUILD_REVISION real y versiones0.2.1 para despliegue manual del usuario en EasyPanel; esperar su aviso, verificar y ejecutar prueba integral NUEVA desde original421paginas. Fuente propuesta `libro:la-salud-prohibida:completo:prueba-integral`, nombre «La salud prohibida — libro completo (prueba integral)». Preservar anterior4e4a59ba como evidencia, sin purga. Leer apartado11 del plan: implementacion178/178 aun LOCAL; no probar codigo viejo. Scanner puede adoptar legacy: resolver tratamiento de anterior antes de deploy si debe quedar congelada.
|
||||
- `rag-service` es el unico proyecto Engram canonico; la sesion debe iniciarse desde la raiz de este worktree.
|
||||
- Politica `page-best-effort-v1` verificada localmente el 2026-10-09: suite `152/152`, check/build correctos, migracion `006` probada en PostgreSQL local real. Codigo publicado en `4e30d8c`; despliegue manual de RAG/OCR y nueva prueba del libro completo pendientes de su aviso. Version de ambas imagenes `0.2.1`; `BUILD_REVISION` debe coincidir con el HEAD completo real entregado tras publicar el registro documental.
|
||||
- Politica `page-best-effort-v1` desplegada en RAG/OCR `0.2.1`/`b6bd69b7628e507c472b405e97e9337cfea5be80`, migraciones001-006. Libro completo: fuente `libro:la-salud-prohibida:completo`, candidata aprobada `4e4a59ba-5516-495a-a885-c20234439371`, 421 paginas/fallback47/228/331; ultimo estado productivo indexing, 740 puntos esperados/0 almacenados por payload>32MiB, sin activar. Correccion LOCAL vigente: transferencia durable8MiB sin tope de puntos, tres intentos/lote180s/540s, señales5s, cache/reanudacion rapida; suite178/178, check/build correctos. Publicacion pausada. Scanner nuevo admite legacy aprobado, no reinicia pausas modernas; primera cache requiere vectores que codigo viejo no guardaba. No repetir OCR/aprobacion. Leer apartados9-10 del plan.
|
||||
- RAG y OCR `0.2.1` estan desplegados y verificados conjuntamente en revision `dcfb5c0ffbb9baf24966ac9f61b9c4f8b2428d09`; migraciones `001-005`, PostgreSQL, Qdrant, reconciliador y readiness OCR estan verificados.
|
||||
- El OCR queda aceptado para esta fase como servicio best-effort autonomo; la mejora de precision y la consola humana son evoluciones futuras no bloqueantes.
|
||||
- La version comparativa OCR `115506e6-ab0a-44e2-b46b-cf419d3b71b2` esta activa como version 2 de su fuente, con `13/13` puntos PostgreSQL/Qdrant y las correcciones auditadas `FAT07`, `NSAV06` y `DSAU04`.
|
||||
|
|
|
|||
|
|
@ -1540,7 +1540,7 @@ Aceptar el servicio no equivale a aceptar cualquier candidata ni elimina los est
|
|||
|
||||
### Politica objetivo best-effort por pagina
|
||||
|
||||
**Formalizada y verificada localmente el 2026-10-09; publicada en `4e30d8c`, pendiente de despliegue.** Verificacion personal tras compactar: suite `152/152`, check/build correctos y migracion `006` validada exclusivamente en PostgreSQL local real. Las reglas anteriores describen el comportamiento desplegado; esta seccion define el cambio publicado. Evidencia y limites de las pruebas en `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md`. La implementacion requiere la migracion aditiva `006_ocr_page_content_selection.sql`, todavia pendiente en produccion; no se modifica el contrato remoto `ocr-v2`.
|
||||
**Formalizada, verificada localmente y desplegada el 2026-10-09 en `b6bd69b7628e507c472b405e97e9337cfea5be80`.** Suite `152/152`, check/build y migracion `006` validados localmente. Prueba del libro completo2026-10-10: OCR/revision/aprobacion completados, indexacion bloqueada por payload Qdrant>32MiB, sin activacion. La transferencia durable posterior esta implementada/verificada solo en LOCAL con suite178/178; apartados9-10 del plan distinguen resultado productivo y correccion pendiente de despliegue. No se modifica el contrato remoto `ocr-v2`.
|
||||
|
||||
1. RAG decide el contenido; OCR conserva su contrato independiente de reconocimiento, estado, lineas, imagenes y metricas a 200 DPI. La clasificacion estadistica no prueba exactitud semantica ni relevancia de una imagen.
|
||||
2. Separar evidencia original, diagnostico OCR y decision de contenido. No convertir bloqueos OCR en aceptaciones artificiales ni eliminar su evidencia al elegir texto nativo.
|
||||
|
|
@ -1553,6 +1553,21 @@ Aceptar el servicio no equivale a aceptar cualquier candidata ni elimina los est
|
|||
9. Versionar la politica RAG y los formatos cuya semantica cambie, manteniendo evidencia historica inmutable y su lectura original. Cambiar esta politica no reactiva versiones fallidas ni elimina precondiciones de aprobacion/activacion.
|
||||
10. La fusion por regiones, mejora del reconocedor, segunda pasada a mayor DPI y exposicion de incidencias en respuestas LLM quedan fuera de esta unidad.
|
||||
|
||||
### Transferencia durable de indexacion aprobada (LOCAL verificado)
|
||||
|
||||
Contrato incorporado2026-10-10, pendiente de publicacion/despliegue; sustituye para la transferencia moderna el reintento grueso30min y el primer tope128 puntos.
|
||||
|
||||
1. Lotes de maximo8MiB de JSON UTF-8 real, sin limite de puntos adicional. No dividir vectores ni omitir contenido por capacidad.
|
||||
2. Vectores y checkpoints del indexado aprobado guardados antes de transferir, privados/atomicos y ligados a version, documento, proveedor/modelo, identidad y hashes. Reiniciar no vuelve a solicitar vectores ya cacheados.
|
||||
3. Tres intentos totales por lote, timeout maximo180s por intento y presupuesto persistente540s que incluye backoff/verificacion. Cancelar operaciones reales con AbortSignal; no abandonar solo la Promise mientras sigue escribiendo.
|
||||
4. Clasificar conexion/DNS/socket, timeout, cuota,5xx, rechazo de tamano, errores deterministas y desconocidos. Reintentar transitorios; respetar Retry-After; reducir lote rechazado por tamano heredando presupuesto; pausar datos invalidos/desconocidos y agotamiento.
|
||||
5. Verificar IDs y payload antes de reenviar y despues de enviar. Resolver respuestas ambiguas/reparar lotes pendientes con mismos IDs, sin duplicacion. Verificacion global exacta precede a ready/activacion; no inferir finalizacion por salud del servicio.
|
||||
6. Señales persistidas nominales cada5s: actividad separada de avance confirmado, sin inventar bytes en vuelo ni crear cola de I/O ilimitada. GET administrativo de estado expone indexingTransfer y fase indexing_paused cuando corresponde.
|
||||
7. Recuperacion de aprobados cada5s bajo bloqueo de fuente, elegibilidad de trabajo iniciado hace mas15s; no sustituye una transferencia viva. Pausa durable con motivo y marcador PostgreSQL, fuera de seleccion automatica, sin reinicio de contadores/deadline.
|
||||
8. Adopcion de aprobado legacy conserva OCR/revision/auditoria; puede crear su primera cache de vectores porque antes no existia. No usar esta compatibilidad para reaprobar, reinterpretar calidad o activar sin precondicion.
|
||||
|
||||
Detalle de estados, pruebas y operacion en apartado10 de `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md`. La pausa preserva evidencia; no se ha agregado un reset administrativo automatico del presupuesto. La precision OCR y la recuperacion semantica del libro se aceptan por evidencia separada, no por este gate de transporte.
|
||||
|
||||
### Revision de FacturaTech
|
||||
|
||||
Llegar a `review_required` no equivale a PASS. Antes de aprobar v8 o posterior:
|
||||
|
|
|
|||
|
|
@ -2,17 +2,18 @@
|
|||
|
||||
RAG dirige la ingesta y decide qué contenido se indexa. El servicio OCR reconoce páginas y devuelve evidencia; no decide la aceptación del documento ni su activación.
|
||||
|
||||
**Última revisión:** 2026-10-09. **Referencia de código:** `c60c225`.
|
||||
**Última revisión:** 2026-10-10. **Referencia del flujo base histórico:** `c60c225`.
|
||||
|
||||
| Sección | Estado |
|
||||
| --- | --- |
|
||||
| Flujo actual | Implementado en la revisión indicada. |
|
||||
| Tratamiento best-effort por página | Implementado y verificado localmente: suite `152/152`, check/build y migración 006 en PostgreSQL local. Publicado en `4e30d8c`, pendiente de despliegue. |
|
||||
| Flujo base histórico | Implementado en la revisión indicada; las extensiones vigentes se precisan en el contrato. |
|
||||
| Tratamiento best-effort por página | Desplegado en `b6bd69b`, migración006; libro completo llegó a revisión/aprobación con fallback47/228/331. Indexación productiva bloqueada por payload>32MiB. |
|
||||
| Transferencia durable del indexado aprobado | LOCAL verificado: 8MiB sin tope de puntos, tres intentos/lote180s/540s, señales5s, cache/checkpoints y reanudación rápida; suite178/178, pendiente publicación/despliegue. |
|
||||
| Segunda pasada a mayor resolución | Idea de mejora futura; no implementada. |
|
||||
|
||||
Este documento explica el recorrido y sirve como base para una futura composición visual. El [contrato](CONTRATO_CICLO_VIDA_Y_OCR.md) y el [backlog](PENDIENTES_RAG.md) siguen siendo las fuentes canónicas de requisitos y prioridades; esta explicación no los sustituye ni autoriza operaciones.
|
||||
|
||||
El «flujo actual» siguiente describe la revisión publicada `c60c225`. El worktree incorpora la política nueva con `selection`, incidencias persistidas, artefactos schema 2 y separación de fragmentos por huecos; requiere migración `006` y el gate pendiente del [plan ejecutable](PLAN_OCR_BEST_EFFORT_POR_PAGINA.md#traspaso-al-modelo-de-pruebas) antes de considerarse verificado.
|
||||
La descripción base siguiente corresponde a `c60c225`. La política `selection`, incidencias persistidas, artefactos schema2 y separación de fragmentos por huecos ya está desplegada y verificada; el contrato actual precisa su semántica. La transferencia durable posterior conserva contenido/IDs y agrega vectores cacheados, intentos/deadlines por lote y progreso persistente; su procedimiento LOCAL y siguiente verificación productiva están en el apartado10 del [plan ejecutable](PLAN_OCR_BEST_EFFORT_POR_PAGINA.md).
|
||||
|
||||
## 1. Responsabilidades
|
||||
|
||||
|
|
|
|||
|
|
@ -2,11 +2,95 @@
|
|||
|
||||
**Proyecto:** Workspace de tools IA para empresas
|
||||
**Modulo:** RAG
|
||||
**Ultima actualizacion:** 2026-10-09
|
||||
**Ultima actualizacion:** 2026-10-10
|
||||
**Ultima modificacion por:** Agente RAG 3
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Retorno y preparacion de publicacion durable
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** Compactacion completada; se retoma el commit/push expresamente autorizado. El usuario desplegara manualmente RAG/OCR y avisara antes de la prueba nueva.
|
||||
**Review:** Raiz/proyecto rag-service y plantilla1.2.7 confirmados. Status/diff/log/remoto revisados; unidad de transferencia durable con sus pruebas y contratos. Gate previo178/178/check/build se conserva, sin cambios de codigo durante este retorno. git diff --check se comprobara sobre la unidad staged. No se repite la suite por compactacion.
|
||||
**Scope:** Excluir docs/DESPLIEGUE_EASYPANEL.md ajeno y .ocr-test-artifacts/configuracion privada. Rollback y alcance del harness documentados en el bloque de transferencia durable. El registro de entrega posterior identificara el commit real publicado; no hay despliegue ni prueba productiva en este bloque.
|
||||
**Pending deployment:** Confirmar tratamiento de la candidata legacy preservada: el scanner puede reanudar su indexado automaticamente, sin repetir OCR/aprobacion. No declarar que queda congelada ni modificar su estado por SQL.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Publicacion autorizada despues de compactar
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** Usuario confirma secuencia al volver: commit/push, entrega de BUILD_REVISION real para despliegue manual suyo en EasyPanel y prueba integral despues de su aviso. La pausa para compactar sigue vigente; no publicar ahora.
|
||||
**Handoff:** Apartado11 actualizado. Gate178/178/check/build local ya registrado. Antes de commit revisar status/diff/log, stage solo codigo/pruebas/docs intencionados sin edicion ajena de despliegue ni PDFs/env privados; convencional sin atribucion AI. No inventar numero/hash de build antes del commit publicado; VERSION actual0.2.1 para RAG/OCR. Preservar candidata anterior y confirmar tratamiento del scanner antes del deploy si debe congelarse.
|
||||
**Side effects:** Solo continuidad documental/memoria; ningun commit/push/despliegue/prueba/remoto ejecutado en este bloque.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Nueva prueba integral acordada y pausa para compactar
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Instruction:** Usuario propone nueva ingesta completa para validar desde cero best-effort y transferencia durable; despues indica expresamente no eliminar la candidata anterior para conservar evidencia, autoriza nombre ligeramente distinto y pide compactar antes de empezar.
|
||||
**Handoff:** Apartado11 del plan con fuente nueva propuesta libro:la-salud-prohibida:completo:prueba-integral, nombre «La salud prohibida — libro completo (prueba integral)», sourceRef con extension.pdf y original421paginas/hash conocido. Flujo nuevo completo: upload/OCR/revision/aprobacion/indexingTransfer/verificacion/activacion/consultas del usuario. Candidata4e4a59ba-5516-495a-a885-c20234439371 preservada; ninguna purga/cancelacion/reaprobacion ni SQL manual.
|
||||
**Preconditions:** Codigo178/178/check/build solo LOCAL, sin autorizacion de publicacion posterior a la pausa, despliegue sigue ultima revision conocida b6bd69b. No iniciar prueba sobre codigo viejo; publicar/desplegar con aprobacion y verificar primero. Scanner nuevo puede adoptar el aprobado legacy automaticamente: confirmar tratamiento si se busca mantenerlo congelado antes de desplegar. La purga no admite indexing; rejection/recover solo review_required, por lo que no inventar una ruta de cierre.
|
||||
**Side effects:** Solo documentacion de traspaso/memoria. No nueva ingesta, llamada productiva, borrado, purga, cambio de estado, commit/push o despliegue. Pausa hasta retorno tras compactar.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Transferencia durable, señales y recuperacion por lote verificadas en LOCAL
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** El usuario pauso la publicacion del primer fix y solicito un unico limite por MiB, vigilancia frecuente, tres intentos maximos de hasta3min/lote, persistencia al fallar y reanudacion sin reconstruir vectores ya guardados. Implementacion/pruebas exclusivamente locales, sin subagentes.
|
||||
**Implementation:** Lotes de maximo8MiB JSON UTF-8 sin tope de puntos; plan/contador/deadline durable, tres intentos totales,180s/intento y540s/lote incluyendo esperas/verificacion. Clasificacion de conexion/DNS/socket/timeouts/408/5xx, cuota429/503+Retry-After, rechazo de tamano, errores deterministas y desconocidos. Reintentar transitorios con1s/2s o espera prescrita; dividir rechazo de tamano heredando presupuesto; pausar desconocidos/datos invalidos/agotamiento. Verificar IDs/payload antes de reenviar y despues de enviar; acknowledged/wait_timeout se comprueban hasta timeout, sin asumir finalizacion.
|
||||
**Persistence:** Vectores y estados del indexado aprobado en carpeta privada indexing de la version: identidad y SHA-256, ficheros600, temporales+fsync+rename. Reanudacion usa cache y verifica lotes confirmados/ambiguos; corrige puntos ausentes sin pedir nuevamente embeddings cacheados. Preparacion de vectores y comprobacion global tienen estado y presupuestos propios. No cambia IDs, seleccion, hashes revisados, fingerprints, migraciones ni actor/fecha de aprobacion.
|
||||
**Monitoring:** Señales nominales5s, ultima señal separada de ultimo avance, bytes/puntos confirmados y fase/lote/intento/deadline/proximo intento; GET administrativo expone indexingTransfer, signalStale y fase indexing_paused/error no reintentable automaticamente cuando procede. No hay SSE ni medicion ficticia de bytes en vuelo. Señales coalescidas para no crear cola ilimitada de I/O. Pausa marcada tambien en PostgreSQL INDEXING_TRANSFER_PAUSED; queda fuera de seleccion automatica para no monopolizar la cola.
|
||||
**Recovery:** Scanner5s, candidatas aprobadas iniciadas hace mas15s, sourceTryLock y un dren activo por instancia; bloqueo vivo impide duplicacion. Admite aprobado legacy aun con reintentos globales previos agotados, conservando aprobacion/auditoria. Pausas modernas no se reabren/resetear por scanner/restart. El codigo anterior del libro no guardo vectores: primera adopcion necesitara crear cache; futuras recuperaciones la reutilizan. Publicacion/despliegue y estado remoto pendientes; no repetir OCR/upload/aprobacion. No se agrego una ruta administrativa para resetear pausas modernas.
|
||||
**Transport discovery:** SDK Qdrant instalado toma solo primer caracter de Retry-After y reemplaza AbortSignal externo con su timeout. Transferencia/verificacion/recuento pasan a HTTP fetch cancelable con headers completos y redirect:error; SDK permanece para otras operaciones. Embeddings con signal usan maxRetries0 para que el presupuesto lo controle el proceso. Contratos actuales consultados y comportamiento confirmado tambien en dependencias instaladas.
|
||||
**Failures corrected:** Primeras focalizadas20/22: datos de dimensiones se trataban como5xx transitorio y expectativa antigua exigia reenvio de lote confirmado. Siguiente30/31: heartbeat acelerado5ms en disco mas lento acumulaba cola y agoto deadline; corregido coalescing, regresion dedicada y durabilidad con presupuestos de prueba apropiados. Siguiente41/42: expectativa contractual no incluia indexing_paused; actualizada y comprobada contra API real local. Todos comunicados al usuario. El log de conexion fallida de review.test.ts es simulacion esperada de prueba aprobada.
|
||||
**Verification:** Gate final npm test178/178, npm run check/build y git diff --check correctos. HTTP loopback con servidor Qdrant simulado:740 puntos/dim4096, tamano real de cuerpos,503, respuesta perdida, cancelacion real, Retry-After60 completo, ultimo lote, UTF-8, limites, confirmacion parcial/recuento global. Fs reales: cache/reinicio/corrupcion/progreso/disco lento. DoublesPG: adopcion legacy, pausa, auditoria y drenes concurrentes. Sin Qdrant/PostgreSQL/proveedores reales ni mutaciones productivas en este bloque.
|
||||
**Documentation/delivery:** Apartado10 del plan es contrato/procedimiento vigente; alineados contrato OCR, API, backlog, contexto, operativa1.13 e indice. Unidad codigo/pruebas/docs lista en local, sin commit/push/despliegue; DESPLIEGUE_EASYPANEL.md ajeno y artefactos privados preservados. Rollback de comportamiento: remover modulos transfer/indexing-checkpoint y sus conexiones en cliente/indexado/provider/API/scanner; no retirar artefactos revisados ni esquema/approval, ni reinstaurar migraciones viejas. Evidencia no implica prueba productiva ni aceptacion semantica del libro.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Escritura Qdrant por lotes implementada y verificada en local
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** Usuario autorizo implementar y probar en local la correccion del payload Qdrant. Sin subagentes, infraestructura ni operaciones productivas.
|
||||
**Fix:** QdrantVectorStoreClient.upsert planifica peticiones de hasta 8 MiB JSON UTF-8 (incluye sobre y separadores) y 128 puntos; rechaza punto individual demasiado grande antes de cualquier escritura. Envio secuencial, wait=true y resultado completed obligatorio por lote; fallo detiene lotes siguientes. IDs/vectores/payloads y verificacion global existentes se conservan. Cliente SDK inyectable opcional para probar el transporte; uso productivo predeterminado intacto. Sin migraciones, configuracion nueva, cambio de fingerprints o limitacion del libro.
|
||||
**Verification LOCAL:** Focalizadas 20/20: NODE_ENV=test npx tsx --test tests/vectorstore/upsert.test.ts tests/ocr/indexing-store.test.ts tests/ocr/approval-indexing-wiring.test.ts. Suite npm test 159/159; npm run check, npm run build y git diff --check correctos. Siete regresiones nuevas con SDK real contra HTTP simulado de loopback: 740 puntos/dim4096 superan limite viejo pero todas las peticiones quedan <=8 MiB; limite128/ultimo lote; texto UTF-8; punto oversized previo a toda escritura; vacio/dimensiones; estado acknowledged; fallo HTTP intermedio/reintento mismos IDs/recuento global incorrecto impide ready/active. No hubo prueba contra un Qdrant real ni proveedores. El log de fallo de conexion de review.test.ts es simulacion esperada de una prueba que paso.
|
||||
**Recovery:** Antes de retomar candidata 4e4a59ba-5516-495a-a885-c20234439371 en produccion, obtener estado/error_detail frescos: recuperacion automatica se detiene tras tres intentos y redeploy no reinicia presupuesto. No se verifico ahora si ya lo agoto ni se modifico esa politica. Ruta administrativa historica restaura aprobacion en review_required; no asumir que reabre un indexing con presupuesto agotado. No repetir upload/OCR/aprobacion ni editar SQL para recuperar.
|
||||
**Delivery:** Unidad revisable: src/modules/vectorstore/client.ts, tests/vectorstore/upsert.test.ts y documentacion de limite/continuidad. Rollback de codigo: revertir solo loteado del cliente y sus pruebas; restaura limitacion anterior de documentos grandes, no altera artefactos ni esquema. Codigo local sin commit/push/despliegue; cambios previos y DESPLIEGUE_EASYPANEL.md ajeno preservados. Publicacion/despliegue y recuperacion productiva pendientes de autorizacion.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Libro completo aprobado; indexacion bloqueada por tamano de payload Qdrant
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** El usuario autorizo crear fuente nueva con nombre «La salud prohibida — libro completo» e identificador libro:la-salud-prohibida:completo, completar revision/indexacion/activacion y explicar el conflicto anterior. Sin subagentes, modelos nuevos ni cambios de infraestructura.
|
||||
**Ingestion:** Preflight fresco correcto, original 421 paginas/hash/tamano esperados. Un upload aceptado con sourceRef «La salud prohibida — libro completo.pdf», activate=false; version 1 4e4a59ba-5516-495a-a885-c20234439371. Evidencia del intento previo rechazado conservada aparte. La candidata llego a review_required con 421/421 paginas, 46 OCR, sin error de procesamiento.
|
||||
**Review:** page-best-effort-v1: 375 native_only, 42 ocr_accepted, 3 native_fallback (47/228/331), una verified_blank (421); cero contentUnrecovered. Se verificaron consistencia texto/seleccion de las 421 paginas y las 46 imagenes PNG por SHA-256 autenticado. Motivos LOW_P10_CONFIDENCE en 47/228, LOW_MEDIAN_CONFIDENCE y EXCESS_LOW_CONFIDENCE_LINES en 331 conservados; visual_content_not_incorporated no implica fidelidad de imagen recuperada. Sin correcciones automaticas ni repeticion de diagnostico visual.
|
||||
**Identity:** candidateSha256 1f2a3858dc0fb4454291ca2008322721acb49cdf84758462626e82b885acc474; qualityReportSha256 d2a945855be09032f96579536aaf6d8e461a7e56178149bceaf29f80e81e9a73; processingFingerprint 0af9b7af4b3aafad50612cadcbfd952a3e0eee8373622d75e77f072946c95a1d; sourceContentHash aad249f758250e449805314d90df933a410e4acac17112b3b6cdb31bffb47a3e.
|
||||
**Failure:** Un POST approve con corrections=[] devolvio 500 OCR_REVIEW_UNEXPECTED. PostgreSQL READ ONLY confirma aprobacion durable reviewed_at 2026-10-10T00:46:44.118Z, reviewed_by opencode:page-best-effort-review:salud-prohibida-full-book, estado indexing, expectedPointCount=740, verifiedPointCount=0. Qdrant count exacto=0. Logs sanitizados: upsert HTTP 400, «JSON payload (67034666 bytes) is larger than allowed (limit: 33554432 bytes)». writeVersionedDocuments manda todos los chunks del documento a vectorStore.upsert; este hace una unica peticion sin lotes. No es un timeout OCR ni falta de tiempo.
|
||||
**Preservation:** Fuente nueva sin puntero activo; 12 fuentes previas conservan sus punteros (incluye fuente historica completa, corpus 22 paginas y FacturaTech). RAG health correcto, revision b6bd69b. No se activo, purgo, reaprobo, reingesto ni altero Qdrant/configuracion/SQL. Una lectura local a openrouter-provider.ts inexistente se corrigio a provider.ts sin efectos.
|
||||
**Next:** Informar bloqueo y proponer lotes acotados de upsert, con verificacion global de 740 puntos y recuperacion idempotente de la misma candidata aprobada. El reconciliador actual espera 1800000 ms y tiene tres reintentos; esos reintentos no solucionan un payload determinista demasiado grande. No prometer recuperacion ni modificar codigo/desplegar sin autorizacion. Preguntas del usuario pendientes hasta activacion real.
|
||||
**Evidence:** Helpers temporales rag-full-book.py/rag-full-book-diagnose.py y directorio separado /tmp/opencode/rag-full-book-new-source/ sin secretos; datos operativos y evidencia originales preservados. Codigo de aplicacion sin cambios; documentacion local actualizada.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-10 - Agente RAG 3 - Prueba completa autorizada; conflicto de identidad antes de OCR
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** Tras compactar, el usuario amplio el alcance hasta revision, aprobacion, indexacion, activacion y consultas posteriores con sus preguntas; exige tiempo suficiente para el PDF grande. Nombre humano acordado: «La salud prohibida — libro completo».
|
||||
**Preflight:** VPS2 PRODUCCION: contenedores redescubiertos, RAG/OCR 0.2.1/revision b6bd69b7628e507c472b405e97e9337cfea5be80, salud conjunta correcta, cola OCR vacia, migraciones 001-006/checksums/constraint verificados de solo lectura. Original: 421 paginas, 6.064.873 bytes, SHA-256 42d73fce9abbf2e5a75f2dbbfdb1683c41655ce2c82b85d8e7dc17363f9a7570. Fuente completa sin version activa, unica version historica v1 fallida; fuentes/punteros capturados.
|
||||
**Result:** Un POST upload con activate=false fue rechazado HTTP 409 SOURCE_IDENTITY_CONFLICT antes de crear el intento durable/OCR. El asistente intento conservar sourceId src:default:file:salud_prohibida_pdf_429ce2f2 pero cambiar sourceRef de «salud prohibida PDF.pdf» a «La salud prohibida — libro completo.pdf». repository.beginAttempt fija sourceType/sourceRef para cada sourceId: no son una etiqueta renombrable. Historial posterior confirma solo la v1 fallida 3559f1cb-71d8-47d0-a8ca-473b0bca175e, sin candidata nueva ni version activa.
|
||||
**Limits:** No se ejecuto OCR, aprobacion, indexacion, activacion, correccion o purga. No hubo reenvio automatico. El guard local impide repetir el upload sin resolver identidad y volver a consultar historial. Evidencia temporal sin secretos: /tmp/opencode/rag-full-book/ y helper /tmp/opencode/rag-full-book.py.
|
||||
**Next:** Detenerse e informar el error propio; confirmar con el usuario la identidad de la fuente antes de una nueva solicitud. Para el nombre nuevo se propone fuente nueva libro:la-salud-prohibida:completo; alternativa tecnica es conservar la referencia historica bajo el sourceId original. No modificar el catalogo manualmente.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-09 - Agente RAG 3 - Salud productiva y pausa antes de prueba para compactar
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Authorization:** El usuario anuncio despliegue completado y solicito verificaciones de salud, aviso antes de la prueba y ejecucion personal de la prueba tras compactar.
|
||||
**Verification:** VPS2 PRODUCCION solo lectura. RAG publico `ok=true`, `0.2.1`/`b6bd69b7628e507c472b405e97e9337cfea5be80`, PostgreSQL/Qdrant/reconciliador sanos sin inconsistencias/invariantes. OCR live/ready 200, ready/modelo/almacenamiento/worker/sweeper true, cola vacia e idle; Docker healthy. Etiquetas OCI de ambas imagenes coincidentes. PostgreSQL `db_rag`/`usr_rag` en transaccion READ ONLY: `001-006`, seis checksums coinciden con archivos desplegados, content_selection JSONB nullable y constraint validada. Flags OCR/lifecycle true. RAG sin HEALTHCHECK Docker; salud acreditada por endpoint.
|
||||
**Images:** RAG `sha256:5e2b210413e11a4514d464d30efdbc53ac6bfac1b9c8dfc8e59f388cdccd9e84`; OCR `sha256:4cff99d27a13abc2ff21058026426d201269007bc1d153fb41325d248dac9175` (IDs de imagen locales del VPS, no manifest digests de registry).
|
||||
**Continuity:** Apartado 9 del plan actualizado con secuencia post-compactacion: preflight fresco, original 421 paginas/hash conocido, fuente completa/historico, unica ingesta activate=false, seguimiento acotado y revision/incidencias preservando fuentes activas. Credenciales solo en memoria; askpass temporal sin valores embebidos. Helper local temporal `/tmp/opencode/rag-prod-health.py`; redescubrir contenedores si cambia despliegue. Engram emitio advertencia de portabilidad al guardar rutas tecnicas, pero persistio el resultado.
|
||||
**Limits:** No se hizo upload, prueba del libro, correccion, aprobacion, indexacion, activacion ni purga. No hubo cambio remoto ni nueva publicacion. El bloque termina para que el usuario compacte.
|
||||
**Next:** Tras retorno, el mismo asistente ejecuta personalmente la prueba de ingesta/revision y entrega resultado antes de solicitar cualquier aprobacion/activacion posterior.
|
||||
|
||||
---
|
||||
|
||||
### 2026-10-09 - Agente RAG 3 - Codigo OCR best-effort publicado para despliegue
|
||||
**Agent:** Agente RAG 3 · **Model:** openai/gpt-6.1-sol · **Session:** `ses_f358ccfe9ffeEzEVNuKo93aHyH`
|
||||
**Role:** Publicar la unidad verificada y dejar constancia de la entrega.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Indice de documentacion - RAG Service
|
||||
|
||||
**Ultima actualizacion:** 2026-10-09
|
||||
**Ultima actualizacion:** 2026-10-10
|
||||
**Ultima modificacion por:** Agente RAG 3
|
||||
**Version:** 1.0
|
||||
|
||||
|
|
@ -24,7 +24,7 @@ Este indice es un mapa de consulta. Leelo antes de crear, buscar o actualizar do
|
|||
| `API_RAG.md` | Contratos y uso de la API RAG. |
|
||||
| `INGESTA.md` | Flujo de ingesta. |
|
||||
| `FLUJO_INGESTA_RAG_Y_OCR.md` | Recorrido completo RAG/OCR, responsabilidades, errores, propuesta best-effort por página y futura segunda pasada selectiva a mayor resolución; base para composición visual. |
|
||||
| `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md` | Plan, evidencia de verificación local (suite 152/152 y migración 006) y paso productivo pendiente de instrucciones. |
|
||||
| `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md` | Resultado productivo del libro (apartado9) y contrato/procedimiento de transferencia durable LOCAL verificada (apartado10). |
|
||||
| `PROCESADO.md` | Procesamiento documental. |
|
||||
| `SALIDA.md` | Generacion y salida de respuestas. |
|
||||
| `SISTEMA_RAG_BASE.md` | Arquitectura base del servicio. |
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
# Operativa del servicio RAG
|
||||
|
||||
**Modulo:** RAG
|
||||
**Ultima actualizacion:** 2026-10-04
|
||||
**Version:** 1.9
|
||||
**Ultima actualizacion:** 2026-10-10
|
||||
**Version:** 1.13
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -24,6 +24,18 @@ Este documento registra los hechos operativos del servicio RAG: la configuracion
|
|||
- Fixture temporal eliminado y contenedor detenido al terminar; volumen e historial conservados. Este resultado no aplica `006` a produccion.
|
||||
- Para repetir, comprobar primero identidad/destino y arrancar solo este contenedor conforme a la autorizacion de pruebas; no cargar archivos de entorno productivos. `NODE_ENV=test` evita que la importacion del runner cargue `.env.local`; usar un pool explicito hacia el harness. La prueba SQL de este bloque esta en `/tmp/opencode/rag-verify-migration006.mts` como evidencia temporal local, no como script portable versionado.
|
||||
|
||||
## Estado productivo verificado (2026-10-09)
|
||||
|
||||
**Actualizacion 2026-10-10:** Salud/revision correctas durante prueba autorizada del libro completo. Fuente nueva `libro:la-salud-prohibida:completo`, candidata aprobada `4e4a59ba-5516-495a-a885-c20234439371` permanece en `indexing`, sin activar. Qdrant rechazo upsert HTTP 400 por payload 67.034.666 bytes frente a limite 33.554.432 bytes; 740 puntos esperados y cero almacenados/verificados. No es falta de tiempo OCR. Las 12 fuentes previas mantienen punteros. Reconciliador usa timeout stale 1.800.000 ms y reintentos existentes; esperar no corrige el tamano determinista. No reenviar upload ni aprobacion, no aumentar limite ni editar SQL. Correccion por lotes/publicacion/despliegue requieren autorizacion; evidencia en historial y apartado 9 del plan.
|
||||
|
||||
**Correccion LOCAL vigente:** Transferencia por unico limite8MiB sin tope de puntos, tres intentos/lote, 180s/intento/540s de deadline persistente, Retry-After integro, cancelacion real, vectores cacheados/checkpoints privados y señales5s en indexingTransfer. Scanner aprobado5s/sourceTryLock/eligibilidad15s adopta incluso legacy aprobado con reintentos globales agotados sin borrar auditoria; pausas modernas quedan excluidas y no reinician presupuesto. Codigo viejo no persistia vectores: primera adopcion crea esa cache; posteriores reintentos/reinicios la reutilizan. Gatefinal suite178/178, check/build correctos, HTTP loopback simulado/fs reales/doublesPG, sin contacto productivo. Pendiente publicacion/despliegue autorizado; apartado10 del plan es procedimiento vigente. La ruta historica recover-indexing para review_required no se usa como reset de una pausa moderna. No se ha verificado estado remoto desde la prueba productiva.
|
||||
|
||||
- RAG y OCR reportan `version=0.2.1`, `revision=b6bd69b7628e507c472b405e97e9337cfea5be80`; ambas etiquetas OCI coinciden. El usuario realizo el despliegue; el agente solo verifico.
|
||||
- RAG publico `/health`: `ok=true`, PostgreSQL/Qdrant sanos, reconciliador sano sin fuentes inconsistentes ni violaciones de invariantes; enforcement y escrituras habilitados.
|
||||
- OCR interno: `/health/live` y `/health/ready` HTTP 200, `ready=true`, modelo y almacenamiento disponibles, worker idle/operativo, sweeper operativo, todos los conteos de cola cero. Docker reporta OCR `healthy`; RAG no tiene HEALTHCHECK Docker y su salud se acredita mediante `/health`.
|
||||
- PostgreSQL identificado como `db_rag`, rol `usr_rag`: consulta en transaccion `READ ONLY` confirmo `001-006` y sus seis checksums contra los archivos desplegados. `content_selection` existe como JSONB nullable y su constraint esta validada. `OCR_INGEST_ENABLED=true` y `KNOWLEDGE_LIFECYCLE_ENFORCED=true` comprobados en el proceso.
|
||||
- Comprobaciones realizadas en VPS2 PRODUCCION solo de lectura: sin ingesta, correccion, aprobacion, indexacion, activacion ni purga. La prueba del libro se iniciara despues de compactar, conforme a la instruccion del usuario.
|
||||
|
||||
## Estado verificado (2026-10-04)
|
||||
|
||||
- RAG y OCR estan desplegados en VPS2 PRODUCCION con version `0.2.1` y revision `dcfb5c0ffbb9baf24966ac9f61b9c4f8b2428d09`; las etiquetas OCI coinciden. RAG confirma PostgreSQL, Qdrant y reconciliador sanos. OCR responde `live=ok` y `ready=true`, con cola vacia, worker/sweeper operativos y almacenamiento disponible.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Pendientes priorizados del RAG
|
||||
|
||||
**Ultima actualizacion:** 2026-10-09
|
||||
**Ultima actualizacion:** 2026-10-10
|
||||
**Responsable de la priorizacion:** Usuario
|
||||
**Estado:** Activo
|
||||
|
||||
|
|
@ -8,11 +8,15 @@ Este documento es la fuente canonica del orden de trabajo pendiente del modulo R
|
|||
|
||||
## Hoja de ruta OCR prioritaria
|
||||
|
||||
La politica best-effort por pagina quedo implementada, verificada localmente y publicada en `4e30d8c`, siguiendo `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md`. El siguiente paso es el despliegue manual del usuario y la validacion productiva tras su aviso. La correccion de orden canonico esta publicada en `c60c225`; la prueba anterior del libro completo fallo por calidad de la pagina 331. Las fases historicas siguientes conservan su evidencia, pero no definen el siguiente trabajo.
|
||||
La politica best-effort por pagina quedo implementada, verificada localmente y desplegada por el usuario. La prueba completa del 2026-10-10 supero OCR/revision y guardo aprobacion: fuente nueva `libro:la-salud-prohibida:completo`, version `4e4a59ba-5516-495a-a885-c20234439371`, 421 paginas, fallback nativo en 47/228/331 y cero contenido no recuperado. El bloqueo actual es indexacion: una unica peticion Qdrant de 67.034.666 bytes excede 33.554.432 bytes; 740 puntos esperados, cero almacenados, sin activacion. Leer apartado 9 de `PLAN_OCR_BEST_EFFORT_POR_PAGINA.md`. Las fases historicas siguientes conservan evidencia, pero no definen el siguiente trabajo.
|
||||
|
||||
### Bloque actual — Calidad por página sin fallo global del documento
|
||||
|
||||
**Estado:** Gate local verificado: focalizadas `77/77`, regresion adicional de huecos/rangos incluida en suite final `152/152`, check/build y diff-check correctos. Migracion `006` aplicada solo en PostgreSQL local reutilizable: dos filas preservadas, siete selecciones validas, once invalidas rechazadas, runner idempotente. Contenedor detenido y volumen intacto. Codigo publicado; despliegue y validacion del libro completo pendientes del aviso del usuario.
|
||||
**Estado:** RAG/OCR `0.2.1` desplegados en `b6bd69b`, migraciones001-006. Ultimo resultado productivo: candidata aprobada bloqueada en indexing por payload>32MiB, sin activar. Correccion LOCAL vigente: transferencia durable por bytes8MiB, tres intentos/lote180s/540s, progreso5s, cache/checkpoints y reanudacion rapida; suite178/178 y check/build correctos. Publicacion sigue pausada; leer apartado10 del plan antes de entregar/desplegar/recuperar.
|
||||
|
||||
- [x] Transferencia durable: unico limite8MiB, intentos acotados, clasificacion/recuperacion, confirmacion por lote, cache sin regeneracion, progreso nominal5s y scanner de aprobados bajo source lock; suite178/178, check/build correctos en LOCAL. Sustituye el primer fix8MiB/128 y gate159/159.
|
||||
- [ ] Tras compactar, ejecutar commit/push YA autorizados del codigo178/178 y entregar BUILD_REVISION real/versiones para deploy manual del usuario; resolver tratamiento del scanner respecto de candidata anterior preservada, sin SQL manual/purga/cierre inventado. Esperar confirmacion de deploy y verificar salud/revision antes de probar.
|
||||
- [ ] Ejecutar prueba NUEVA integral desde original421paginas con fuente/nombre distintos, preservando candidata anterior. Apartado11 del plan: upload/OCR/revision/aprobacion/transferencia/verificacion/activacion/consultas con scope nuevo; registrar IDs/recuentos reales.
|
||||
|
||||
- [x] P1: Representacion de evidencia, diagnostico y contenido elegido; identidad de politica y compatibilidad historica.
|
||||
- [x] P2: Seleccion por pagina y candidata con incidencias persistidas, conservando texto nativo utilizable.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# Plan ejecutable: ingesta OCR best-effort por página
|
||||
|
||||
**Fecha:** 2026-10-09. **Estado:** implementación y gate local verificados personalmente tras compactar: suite `152/152`, check/build correctos y migración `006` validada en PostgreSQL local real. Código publicado en `4e30d8c`; pendiente de despliegue manual del usuario.
|
||||
**Fecha:** 2026-10-09. **Estado:** gate local `152/152` y migración `006` verificados; RAG/OCR desplegados por el usuario y salud/revisión/migraciones productivas verificadas en `b6bd69b7628e507c472b405e97e9337cfea5be80`. Prueba del libro pendiente tras compactar.
|
||||
|
||||
## Objetivo y resultado esperado
|
||||
|
||||
|
|
@ -240,3 +240,97 @@ Este mapa identifica impactos; no obliga a editar todos los archivos ni autoriza
|
|||
Después de las pruebas locales y de la autorización de publicación: commit/push de la unidad, entregar `BUILD_REVISION` y versiones reales desde `VERSION`; el usuario despliega y avisa. Entonces verificar servicios y revisión antes de una nueva ingesta autorizada.
|
||||
|
||||
La versión fallida permanece histórica; no prometer reutilización administrativa de sus artefactos como parte de este cambio. La nueva ingesta se revisa, indexa y activa mediante el ciclo soportado. Solo después de verificar el libro completo se retira el corpus de 22 páginas mediante una operación soportada y autorizada. Esa retirada no se resuelve forzando la purga de una versión activa.
|
||||
|
||||
## 9. Traspaso a la prueba productiva tras compactar
|
||||
|
||||
**Correccion LOCAL vigente (2026-10-10):** Tras revisar el primer fix 8 MiB/128 puntos, el usuario exigio unico limite por bytes, recuperacion por lote y progreso persistente. Implementado y verificado: 8 MiB sin limite de puntos, tres intentos totales/lote, 180 s/intento y 540 s de presupuesto persistente, señales nominales cada5s, cache durable de vectores y checkpoints, clasificacion de fallos, verificacion de IDs/payload, reanudacion rapida bajo source lock. Suite178/178, check/build/diff-check correctos. Publicacion pausada; sin despliegue ni contacto productivo en este bloque. Contrato y procedimiento actuales en apartado10; los recuentos20/20 y159/159 del historial corresponden al primer fix, no al vigente.
|
||||
|
||||
**Ultimo resultado PRODUCTIVO (2026-10-10):** El usuario autorizo fuente nueva libro:la-salud-prohibida:completo, sourceRef «La salud prohibida — libro completo.pdf». Candidata v1 4e4a59ba-5516-495a-a885-c20234439371 creada y revisada: 421/421 paginas, 46 imagenes/hashes verificados, tres fallback nativos (47/228/331), cero contenido no recuperado y una pagina blank (421). Aprobacion durable realizada sin correcciones; POST approve devolvio 500 por upsert Qdrant 400: payload 67.034.666 bytes supera limite 33.554.432 bytes (32 MiB). Estado indexing, 740 puntos esperados, cero verificados/almacenados, sin activacion. Las 12 fuentes anteriores conservan sus punteros. Siguiente paso: publicar/desplegar correccion local verificada con autorizacion y consultar estado/reintentos para reanudar misma aprobacion. No repetir OCR/upload/aprobacion ni confundir espera con solucion de este rechazo determinista.
|
||||
|
||||
**Actualizacion tras el retorno (2026-10-10):** El usuario amplio y autorizo el flujo completo hasta aprobacion, indexacion, activacion y consultas limitadas al libro. Dar margen suficiente al PDF de 421 paginas; una ventana de seguimiento agotada no constituye un fallo y no autoriza reupload. El primer upload fue rechazado antes de OCR con SOURCE_IDENTITY_CONFLICT: el sourceId historico tiene sourceRef inmutable «salud prohibida PDF.pdf» y no admite el nombre nuevo «La salud prohibida — libro completo.pdf». Historial confirmado sin candidata nueva. Prueba detenida para resolver con el usuario si el nombre nuevo identifica una fuente nueva; no repetir upload sin esa decision. El alcance anterior de detenerse en revision que sigue debajo queda sustituido por esta autorizacion posterior.
|
||||
|
||||
**Instrucción vigente del usuario:** verificar salud ahora y avisar antes de hacer la prueba; tras compactar, el mismo asistente realizará personalmente la prueba, sin subagentes. Este bloque se detiene antes de upload. No repetir implementación, publicación ni despliegue por haber compactado.
|
||||
|
||||
**Precondiciones ya acreditadas:** RAG/OCR `0.2.1` en `b6bd69b7628e507c472b405e97e9337cfea5be80`, etiquetas OCI coincidentes; RAG/PostgreSQL/Qdrant/reconciliador sanos; OCR live/ready HTTP 200, modelo/worker/sweeper/almacenamiento operativos y cola vacía. En `db_rag`/`usr_rag` se verificaron migraciones `001-006`, los seis checksums y columna/constraint de selección. No hubo operaciones de corpus durante esas comprobaciones.
|
||||
|
||||
### Secuencia al volver
|
||||
|
||||
1. Confirmar raíz/proyecto `rag-service`, leer este apartado y `OPERATIVA.md`, comprobar status/diff y preservar las actualizaciones documentales locales, el cambio ajeno de despliegue y los artefactos privados. Confirmar salud/revisión fresca antes de subir el PDF; las comprobaciones anteriores no sustituyen ese preflight.
|
||||
2. Verificar el original `.ocr-test-artifacts/salud prohibida PDF.pdf`: SHA-256 esperado `42d73fce9abbf2e5a75f2dbbfdb1683c41655ce2c82b85d8e7dc17363f9a7570`, 6.064.873 bytes, 421 páginas; selección histórica de 46 páginas OCR, bajo límite de 100. No usar el derivado de 22 páginas ni repetir diagnóstico visual de 331/47/228.
|
||||
3. Cargar `.env.rag-tests.local` en memoria, sin volcarlo; comprobar destino HTTPS esperado `https://rag.por-correo.com` antes de enviar credencial. Leer fuente/historial de `src:default:file:salud_prohibida_pdf_429ce2f2`, recuperar sus metadatos y comprobar que no exista ya una candidata equivalente pendiente. La versión anterior `3559f1cb-71d8-47d0-a8ca-473b0bca175e` era v1 fallida por calidad, sin activar; mantenerla histórica. Capturar también los punteros de las fuentes activas a preservar antes de probar.
|
||||
4. Realizar **un solo** `POST /ingest/upload` multipart con el PDF original, `sourceId` completo explícito, `sourceRef`/tags coherentes con la fuente leída y `activate=false` como cadena. El handler de `src/app.ts:583-640` interpreta esa cadena; no omitirla ni suponer activación por defecto segura. No repetir un upload si la respuesta se pierde: consultar primero el historial/estado para localizar la candidata real.
|
||||
5. Guardar ID/versionNumber/fingerprint devueltos, sin inventarlos. Sondear con timeout y límite de intentos hasta `review_required` o fallo; reutilizar la identidad aceptada. Si falla, informar código e incidencias, sin reupload automático. Esperar candidata nueva bajo `page-best-effort-v1`, no reinterpretar la fallida anterior.
|
||||
6. Leer revisión autenticada y verificar las 421 páginas en orden canónico, `selection`/`coverage`, fallback nativo/contenido no recuperado, motivos OCR preservados y correspondencia de imágenes/hashes. Examinar especialmente 331/47/228 frente a la limitación anterior. Comparar punteros activos posteriores con el preflight y presentar resultado.
|
||||
7. Detenerse al completar el informe de ingesta/revisión. Aprobación, indexación, activación, retirada del corpus anterior y purga requieren instrucciones específicas posteriores. No corregir automáticamente texto descartado ni modificar fuentes activas para completar la prueba.
|
||||
|
||||
**Fuentes a preservar:** 22 páginas `src:default:file:salud_prohibida_first_22_pages_c712b8f4`, activa registrada `dbd208de-3e4a-4903-af78-87f5e48cd86b`; FacturaTech original `3fc78163-9cfb-4979-985c-1520a63327b0` y comparativa `115506e6-ab0a-44e2-b46b-cf419d3b71b2`. Confirmar punteros frescos; no tratarlos como comprobados en el bloque de salud.
|
||||
|
||||
Helper temporal de salud: `/tmp/opencode/rag-prod-health.py`, sin secretos embebidos. Los IDs de contenedor del modo verify son los observados en este bloque; redescubrirlos si se repite la consulta tras un redeploy. SSH sigue el procedimiento canónico de `OPERATIVA.md`, con askpass temporal y consultas remotas de solo lectura.
|
||||
|
||||
## 10. Transferencia durable del indexado aprobado
|
||||
|
||||
**Estado: implementada y verificada en LOCAL; publicacion/despliegue pendientes.** Sustituye el primer loteado de128 puntos y su dependencia del reintento global30min para el ciclo aprobado. No cambia contenido seleccionado, IDs, fingerprints, aprobacion ni politica OCR.
|
||||
|
||||
### Camino normal
|
||||
|
||||
1. Validar evidencia revisada y configuracion de embeddings bajo el bloqueo de fuente existente.
|
||||
2. Cargar vectores guardados del documento si su identidad y SHA-256 coinciden; si no existen, solicitarlos una vez y persistirlos de forma privada/atomica antes de transferir.
|
||||
3. Planificar lotes por el JSON UTF-8 real de `{points:[...]}`: maximo8MiB, incluyendo sobre y separadores, sin limite artificial de puntos. No dividir un punto ni descartar contenido para hacerlo caber.
|
||||
4. Antes de cada envio, comprobar IDs y payload ya presentes. Si se perdio una respuesta pero el lote esta aplicado, confirmarlo sin reenviar. Si faltan datos, enviar con wait=true y verificar su presencia/payload; no exigir igualdad bit a bit de vectores entre representaciones numericas.
|
||||
5. Persistir confirmacion por lote, avance y proxima accion. Al reiniciar, volver a comprobar lotes confirmados/ambiguos y enviar los pendientes, usando vectores cacheados y los mismos IDs. Reparar un lote cuyos puntos hayan desaparecido sin regenerar vectores.
|
||||
6. Verificar el recuento exacto global esperado antes de `ready`. La activacion mantiene su autorizacion/precondicion existentes; `activateRequested=false` no se convierte en activacion automatica.
|
||||
|
||||
### Fallos y limites
|
||||
|
||||
| Situacion | Salida implementada |
|
||||
| --- | --- |
|
||||
| Corte/DNS/socket, timeout, HTTP408 o5xx | Reintento del lote afectado; esperas progresivas iniciales1s/2s, no30min. |
|
||||
| HTTP429 o503 con Retry-After | Respetar segundos o fecha del encabezado completo dentro del presupuesto; si no cabe la espera, pausar con motivo de presupuesto. |
|
||||
| Respuesta perdida o timeout tras aplicar | Comprobar antes de reenviar; la existencia/payload correcto resuelve la ambiguedad sin duplicar. |
|
||||
| acknowledged/wait_timeout | Consultar confirmacion durante el mismo intento, hasta su timeout; no declarar el lote completo por mera aceptacion. |
|
||||
| Rechazo explicito de tamano | Dividir solo ese lote, heredando intentos y deadline. Punto individual que no cabe se pausa; no fragmentar su vector/semantica. |
|
||||
| 4xx determinista, evidencia/vector invalido o error desconocido | Guardar motivo y pausar; repetir una solicitud identica no constituye recuperacion. |
|
||||
| Tres intentos totales o540s agotados | Guardar progreso y pausar. Reinicio/scanner no reinician contadores ni deadline. |
|
||||
| Disco lento | Coalescing de heartbeat, sin cola ilimitada; confirmaciones criticas esperan persistencia. Fallo de persistencia impide continuar/activar. |
|
||||
|
||||
Cada intento abarca comprobacion, envio y verificacion; timeout maximo180s con AbortSignal que cancela la peticion/lectura real. Los540s/lote incluyen esperas y se conservan entre reinicios; son limites maximos, no tiempos de espera obligatorios. Preparacion de vectores y comprobacion final tienen tambien presupuestos acotados y estado propio.
|
||||
|
||||
### Observacion y reanudacion
|
||||
|
||||
- GET autenticado `/ingestions/{versionId}` incorpora `indexingTransfer`: fase/etapa, lote, intento, deadline/proximo intento, puntos/bytes confirmados, `lastSignalAt` y `lastProgressAt`. El observador puede consultar cada5s; no se ha agregado SSE ni una estimacion ficticia de bytes subidos en vuelo.
|
||||
- `signalStale` indica ausencia de señal persistida durante15s, no autoriza tomar trabajo que conserve un source lock activo. Las señales son nominales5s y se coalescen si el almacenamiento es lento.
|
||||
- Pausa: fase publica `indexing_paused`, error no reintentable automaticamente, checkpoint privado preservado y marcador PostgreSQL `INDEXING_TRANSFER_PAUSED`. Queda fuera del scanner; no puede monopolizar su primera pagina de resultados ni reiniciar infinitamente intentos.
|
||||
- Scanner de transferencias aprobadas cada5s, seleccion de trabajo iniciado hace mas15s y sourceTryLock; evita drenes superpuestos. El reconciliador global mantiene funciones previas, pero no reinicia transferencias modernas ni pausadas.
|
||||
- El scanner admite una candidata legacy aprobada aun si agoto los antiguos reintentos globales, conservando aprobacion/auditoria historica y sin repetir OCR/aprobacion. Como el codigo anterior no guardaba vectores, su primera adopcion necesitara generarlos y guardarlos; despues se reutilizan. Solo se adopta evidencia valida y version activa compatible.
|
||||
- Persistencia para este ciclo: `<artifactRoot>/<versionId>/indexing/`, puntos/estado/preparacion privados con identidad/hashes, escritura temporal+fsync+rename. La retencion/purga del directorio de version incluye estos artefactos. No subirlos a Git.
|
||||
- Tras una pausa definitiva se conserva evidencia para una decision operativa; este bloque no agrega una ruta que resetee automaticamente presupuestos ni permite SQL manual. No prometer recuperacion de una pausa sin inspeccionar su motivo.
|
||||
|
||||
### Evidencia y siguiente paso
|
||||
|
||||
Gatefinal: npm test178/178, npm run check/build y git diff --check correctos. Regresiones HTTP loopback reales con servidor simulado (740 puntos/dim4096, limites, HTTP503, respuesta perdida, cancelacion, Retry-After60), fs reales (reinicio/cache/corrupcion/disco lento) y doubles de PostgreSQL (scanner/pausa/auditoria). No se ejecuto esta revision contra Qdrant, PostgreSQL o proveedores reales.
|
||||
|
||||
El procedimiento siguiente de prueba productiva fue actualizado por el usuario: apartado11. La candidata anterior se conserva como evidencia; el ensayo principal sera una fuente nueva desde el PDF original. La correccion sigue solo en LOCAL y no hay resultado productivo de ella.
|
||||
|
||||
## 11. Traspaso para nueva prueba integral despues de compactar
|
||||
|
||||
**Instruccion vigente2026-10-10:** El usuario prefiere validar desde cero ambos cambios con el libro completo, decide no eliminar la candidata anterior para conservar evidencia y autoriza una fuente nueva con nombre ligeramente distinto. Pide compactar ANTES de iniciar y comenzar la prueba al volver cuando sus precondiciones esten cumplidas.
|
||||
|
||||
- Fuente propuesta para el ensayo: `libro:la-salud-prohibida:completo:prueba-integral`.
|
||||
- Nombre humano: «La salud prohibida — libro completo (prueba integral)»; sourceRef multipart: `La salud prohibida — libro completo (prueba integral).pdf`.
|
||||
- Original fisico intacto: `.ocr-test-artifacts/salud prohibida PDF.pdf`,421 paginas,6.064.873 bytes,SHA-256 `42d73fce9abbf2e5a75f2dbbfdb1683c41655ce2c82b85d8e7dc17363f9a7570`. No usar el derivado22paginas.
|
||||
- Preservar candidata anterior aprobada `4e4a59ba-5516-495a-a885-c20234439371` y su fuente `libro:la-salud-prohibida:completo`: no purgar, borrar, reaprobar ni editar SQL. Guardar evidencia del fallo anterior y sus originales/revision/aprobacion.
|
||||
|
||||
**Entrega autorizada al volver de compactar:** El usuario autoriza commit y push de la correccion y solicita el BUILD_REVISION real para desplegar personalmente en EasyPanel; despues de su aviso se verificara salud/revision y se probara. Implementacion actual solo local, suite178/178/check/build/diff-check correctos, HEAD publicado aun b6bd69b. No ejecutar commit/push antes del retorno. Revisar status/diff/log y stage solo unidad intencionada, excluyendo DESPLIEGUE_EASYPANEL.md ajeno, PDFs/env privados. Commit convencional sin atribucion AI; entregar hash completo realmente publicado como BUILD_REVISION y versiones desde VERSION (actual0.2.1 para RAG/OCR). No subir el libro a revision vieja ni antes del despliegue manual y su confirmacion.
|
||||
|
||||
**Aspecto a resolver antes del despliegue:** El scanner actual adopta legacy aprobado automaticamente; por tanto puede reanudar la candidata anterior al arrancar. La instruccion de preservar su evidencia no equivale a autorizar modificarla. Explicar/confirmar como se tratara esa adopcion si se requiere mantenerla congelada; no hacer exclusiones con UUID hardcodeado, SQL manual, purga ni cambio de estados sin operacion soportada/autorizacion. API actual no permite purgar indexing ni usar rejection/recover de review_required para cerrar este aprobado.
|
||||
|
||||
### Secuencia de la prueba nueva
|
||||
|
||||
1. Recuperar este traspaso y confirmar proyecto/identidad; conservar cambios locales y artefactos privados. Verificar entrega/deploy nuevo y tratamiento de candidata anterior antes de upload.
|
||||
2. Preflight fresco: salud/revision, original/hash/421paginas, fuente nueva ausente o historial compatible, captura de punteros previos. No asumir ausencia de colision sin consultar.
|
||||
3. Preparar cliente/evidencia NUEVOS, separados de los helpers/directorios anteriores. Un upload con sourceId/sourceRef nuevos explicitos y activate="false". Ante respuesta perdida, consultar historial antes de reenviar. Registrar versionId/versionNumber/fingerprint REALES.
|
||||
4. Seguir OCR con margen para documento grande hasta revision, revisar421paginas/seleccion/incidencias/imagenes y paginas47/228/331. No exigir recuentos de cobertura predeterminados: comparar contra evidencia anterior e informar resultado real.
|
||||
5. Aprobar la candidata NUEVA tras revision; seguir indexingTransfer en caliente cada5s hasta ready o pausa explicita. Verificar cache/checkpoints y recuento esperado/almacenado del ensayo;740 era recuento anterior, no inventar el nuevo. Preservar fuente anterior y demas punteros.
|
||||
6. Activar solo la version nueva con CAS y verificar retrieval limitado al sourceId nuevo. Despues ejecutar las preguntas que aporte el usuario mostrando las respuestas reales del RAG y referencias disponibles.
|
||||
|
||||
**Estado al compactar:** No hubo upload nuevo, cancelacion, purga, publicacion, despliegue o cambio remoto en este bloque. El codigo/transporte178/178 esta preparado en local; no repetir trabajo ya verificado por haber compactado.
|
||||
|
|
|
|||
|
|
@ -610,7 +610,7 @@ export const openApiDocument = {
|
|||
},
|
||||
OcrPhase: {
|
||||
type: "string",
|
||||
enum: ["native_extracting", "ocr_queued", "ocr_running", "review_required", "indexing", "ready", "active", "failed", "rejected"]
|
||||
enum: ["native_extracting", "ocr_queued", "ocr_running", "review_required", "indexing", "indexing_paused", "ready", "active", "failed", "rejected"]
|
||||
},
|
||||
OcrAccepted: {
|
||||
type: "object",
|
||||
|
|
@ -631,9 +631,34 @@ export const openApiDocument = {
|
|||
sourceId: { type: "string" }, versionId: { type: "string", format: "uuid" }, state: ref("SourceVersionState"), phase: ref("OcrPhase"), activated: { type: "boolean" },
|
||||
documents: { type: "array", items: ref("OcrProgressDocument") },
|
||||
coverage: ref("OcrCoverage"),
|
||||
indexingTransfer: ref("IndexingTransferProgress"),
|
||||
error: { oneOf: [ref("OcrStatusError"), { type: "null" }] }, statusUrl: { type: "string" }, reviewUrl: { type: ["string", "null"] }
|
||||
}
|
||||
},
|
||||
IndexingTransferProgress: {
|
||||
type: "object", description: "Durable transfer signals, not estimated network upload bytes. Completed batches are verified by point identity before their bytes/points count as confirmed.",
|
||||
required: ["heartbeatMs", "totalPoints", "confirmedPoints", "confirmedBytes", "paused", "documents"],
|
||||
properties: { heartbeatMs: { type: "integer", const: 5000 }, totalPoints: { type: "integer" },
|
||||
confirmedPoints: { type: "integer" }, confirmedBytes: { type: "integer" }, paused: { type: "boolean" },
|
||||
documents: { type: "array", items: ref("IndexingTransferDocument") } }
|
||||
},
|
||||
IndexingTransferDocument: {
|
||||
type: "object", required: ["documentId", "stage", "phase", "lastSignalAt", "lastProgressAt", "signalStale", "attempt", "confirmedPoints", "confirmedBytes"],
|
||||
properties: { documentId: { type: "string" }, stage: { type: "string", enum: ["preparation", "transfer", "verification"] },
|
||||
phase: { type: "string", enum: ["preparing_vectors", "verifying_version", "pending", "checking", "sending", "verifying", "retry_wait", "complete", "paused"] },
|
||||
lastSignalAt: { type: "integer", description: "Unix epoch milliseconds of the last persisted signal." },
|
||||
lastProgressAt: { type: "integer", description: "Changes on confirmed work, not on periodic activity signals." },
|
||||
signalStale: { type: "boolean", description: "No fresh persisted activity signal for 15 seconds; not proof that a live source lock can be bypassed." }, totalPoints: { type: "integer" }, totalSourcePoints: { type: "integer" },
|
||||
confirmedPoints: { type: "integer" }, confirmedBytes: { type: "integer" }, totalBytes: { type: "integer" },
|
||||
batch: { type: "integer" }, batchCount: { type: "integer" }, attempt: { type: "integer", minimum: 0, maximum: 3 },
|
||||
batchBytes: { type: "integer" }, deadlineAt: { type: ["integer", "null"] }, nextAttemptAt: { type: ["integer", "null"] },
|
||||
failure: { oneOf: [ref("IndexingTransferFailure"), { type: "null" }] } }
|
||||
},
|
||||
IndexingTransferFailure: {
|
||||
type: "object", required: ["kind", "code"], properties: {
|
||||
kind: { type: "string", enum: ["connection", "timeout", "overloaded", "server", "payload_size", "invalid", "unknown", "unconfirmed"] },
|
||||
code: { type: "string" }, httpStatus: { type: "integer" }, retryAfterMs: { type: "integer" } }
|
||||
},
|
||||
OcrProgressDocument: {
|
||||
type: "object", required: ["documentId", "state", "completedPages", "totalPages", "pages"],
|
||||
properties: {
|
||||
|
|
|
|||
13
src/app.ts
13
src/app.ts
|
|
@ -1,4 +1,5 @@
|
|||
import express from "express";
|
||||
import { readIndexingProgress } from "./modules/ingest/indexing-checkpoint.js";
|
||||
import multer from "multer";
|
||||
import type { Request } from "express";
|
||||
import { readFile, unlink, mkdtemp, rm } from "node:fs/promises";
|
||||
|
|
@ -121,6 +122,9 @@ export function createApp(options: AppOptions = {}) {
|
|||
if (options.startReconciler !== false) {
|
||||
ocrDispatcher?.start();
|
||||
reconciler.start();
|
||||
if (env.knowledgeLifecycleEnforced && env.ingestWritesEnabled && indexingService instanceof OcrIndexingService) {
|
||||
indexingService.startTransferRecovery();
|
||||
}
|
||||
}
|
||||
|
||||
function sendError(res: express.Response, error: unknown, fallback: string) {
|
||||
|
|
@ -137,7 +141,8 @@ export function createApp(options: AppOptions = {}) {
|
|||
function sendOcrReviewError(res: express.Response, error: unknown) {
|
||||
const classified = classifyOcrReviewError(error);
|
||||
if (classified.statusCode === 500) console.error("OCR review request failed", error);
|
||||
const action = classified.code === "OCR_CANDIDATE_NOT_FOUND" ? "verify_version_id"
|
||||
const action = classified.code.startsWith("INDEXING_") ? "inspect_indexing_transfer"
|
||||
: classified.code === "OCR_CANDIDATE_NOT_FOUND" ? "verify_version_id"
|
||||
: classified.code === "OCR_REVIEW_STATE_INVALID" ? "inspect_ingestion_status"
|
||||
: classified.statusCode === 409 || classified.statusCode === 422 ? "use_admin_recovery"
|
||||
: "retry_or_contact_support";
|
||||
|
|
@ -316,7 +321,11 @@ export function createApp(options: AppOptions = {}) {
|
|||
res.status(404).json({ ok: false, error: "Ingestion not found", code: "INGESTION_NOT_FOUND" });
|
||||
return;
|
||||
}
|
||||
res.json(status);
|
||||
const transfer = await readIndexingProgress(ocr.artifactRoot, String(req.params.versionId));
|
||||
const paused = transfer?.documents.find((document) => document.phase === "paused");
|
||||
res.json({ ...status, ...(transfer ? { indexingTransfer: transfer } : {}),
|
||||
...(paused ? { phase: "indexing_paused", error: { code: paused.failure?.code ?? "INDEXING_TRANSFER_PAUSED",
|
||||
message: "Indexing transfer is paused; inspect its persisted failure and checkpoint before resuming.", retryable: false } } : {}) });
|
||||
} catch (error) {
|
||||
sendOcrReviewError(res, error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -565,7 +565,8 @@ export class CatalogRepository {
|
|||
[versionId]
|
||||
);
|
||||
const row = version.rows[0];
|
||||
const phase = ingestionPhase(row.state, documents.rows.map(({ job_state }) => job_state));
|
||||
const phase = row.error_code === "INDEXING_TRANSFER_PAUSED" ? "indexing_paused"
|
||||
: ingestionPhase(row.state, documents.rows.map(({ job_state }) => job_state));
|
||||
const qualityError = row.error_code === "OCR_QUALITY_BLOCKED" ? parseQualityBlockedDetail(row.error_detail) : undefined;
|
||||
return {
|
||||
sourceId: row.source_id,
|
||||
|
|
@ -888,6 +889,24 @@ export class CatalogRepository {
|
|||
return result.rows.map(({ version_id, source_id }) => ({ versionId: version_id, sourceId: source_id }));
|
||||
}
|
||||
|
||||
async listInterruptedApprovedTransfers(): 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() - interval '15 seconds'
|
||||
AND (error_code IS NULL OR error_code = 'OCR_INDEX_RECOVERY_RETRY')
|
||||
ORDER BY indexing_started_at, version_id LIMIT 20`);
|
||||
return result.rows.map(({ version_id, source_id }) => ({ versionId: version_id, sourceId: source_id }));
|
||||
}
|
||||
|
||||
async markIndexingTransferPaused(versionId: string, code: string): Promise<void> {
|
||||
const result = await this.pool.query(
|
||||
`UPDATE rag_source_versions SET error_code = 'INDEXING_TRANSFER_PAUSED', error_detail = $2
|
||||
WHERE version_id = $1 AND state = 'indexing' AND reviewed_at IS NOT NULL`,
|
||||
[versionId, JSON.stringify({ code })]);
|
||||
if (result.rowCount !== 1) throw new CatalogError("Indexing transfer state changed while pausing", 409, "INVALID_VERSION_STATE");
|
||||
}
|
||||
|
||||
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 }>(
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export interface EmbeddingProvider {
|
|||
readonly providerName: string;
|
||||
readonly modelName: string;
|
||||
readonly dimensions?: number;
|
||||
embed(input: string[]): Promise<number[][]>;
|
||||
embed(input: string[], options?: { signal: AbortSignal }): Promise<number[][]>;
|
||||
}
|
||||
|
||||
export class OpenRouterEmbeddingProvider implements EmbeddingProvider {
|
||||
|
|
@ -23,7 +23,7 @@ export class OpenRouterEmbeddingProvider implements EmbeddingProvider {
|
|||
});
|
||||
}
|
||||
|
||||
async embed(input: string[]): Promise<number[][]> {
|
||||
async embed(input: string[], options?: { signal: AbortSignal }): Promise<number[][]> {
|
||||
if (!env.embeddingApiKey) {
|
||||
throw new Error("Missing EMBEDDING_API_KEY for embedding provider");
|
||||
}
|
||||
|
|
@ -32,7 +32,7 @@ export class OpenRouterEmbeddingProvider implements EmbeddingProvider {
|
|||
model: this.modelName,
|
||||
input,
|
||||
encoding_format: "float"
|
||||
});
|
||||
}, options ? { signal: options.signal, maxRetries: 0 } : undefined);
|
||||
|
||||
if (!Array.isArray(response.data)) {
|
||||
throw new Error("Embedding provider returned an invalid response without data array");
|
||||
|
|
|
|||
211
src/modules/ingest/indexing-checkpoint.ts
Normal file
211
src/modules/ingest/indexing-checkpoint.ts
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { lstat, mkdir, open, readFile, readdir, rename, unlink } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { sha256Hex } from "../../shared/utils/ids.js";
|
||||
import type { IngestedChunk } from "../../shared/types/rag.js";
|
||||
import type { TransferJournal, TransferState } from "../vectorstore/transfer.js";
|
||||
import { classifyTransferFailure, transferPolicy, TransferPausedError, type TransferFailure } from "../vectorstore/transfer.js";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
|
||||
interface PreparationState {
|
||||
identityHash: string; versionId: string; documentId: string;
|
||||
phase: "preparing_vectors" | "verifying_version" | "retry_wait" | "paused" | "complete";
|
||||
step?: "preparation" | "verification";
|
||||
attempts: number; deadlineAt: number; nextAttemptAt?: number; lastSignalAt: number; lastProgressAt?: number;
|
||||
totalPoints: number; totalSourcePoints: number; failure?: TransferFailure;
|
||||
}
|
||||
|
||||
function checkpointDirectory(root: string, versionId: string): string {
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(versionId)) {
|
||||
throw new Error("Indexing checkpoint version identity is invalid");
|
||||
}
|
||||
return path.join(path.resolve(root), versionId, "indexing");
|
||||
}
|
||||
|
||||
async function readPrivate(file: string): Promise<unknown | undefined> {
|
||||
const entry = await lstat(file).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
});
|
||||
if (!entry) return undefined;
|
||||
if (!entry.isFile() || (entry.mode & 0o777) !== 0o600) throw new Error("Indexing checkpoint is not a private regular file");
|
||||
return JSON.parse(await readFile(file, "utf8"));
|
||||
}
|
||||
|
||||
async function atomicWrite(file: string, data: unknown): Promise<void> {
|
||||
const directory = path.dirname(file);
|
||||
for (const parent of [path.dirname(directory), directory]) {
|
||||
await mkdir(parent, { recursive: true, mode: 0o700 });
|
||||
if (!(await lstat(parent)).isDirectory()) throw new Error("Indexing checkpoint directory is invalid");
|
||||
}
|
||||
const temporary = `${file}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
const handle = await open(temporary, "wx", 0o600);
|
||||
try { await handle.writeFile(JSON.stringify(data)); await handle.sync(); } finally { await handle.close(); }
|
||||
await rename(temporary, file);
|
||||
const parent = await open(directory, "r");
|
||||
try { await parent.sync(); } finally { await parent.close(); }
|
||||
} finally { await unlink(temporary).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; }); }
|
||||
}
|
||||
|
||||
export class IndexingCheckpoint implements TransferJournal {
|
||||
private readonly directory: string;
|
||||
private readonly prefix: string;
|
||||
constructor(root: string, readonly versionId: string, readonly documentId: string, private readonly identityHash: string) {
|
||||
this.directory = checkpointDirectory(root, versionId);
|
||||
this.prefix = path.join(this.directory, sha256Hex(documentId));
|
||||
}
|
||||
|
||||
async loadPoints(): Promise<IngestedChunk[] | undefined> {
|
||||
const value = await readPrivate(`${this.prefix}.points.json`) as {
|
||||
schemaVersion: string; identityHash: string; pointsSha256: string; points: IngestedChunk[]
|
||||
} | undefined;
|
||||
if (!value) return undefined;
|
||||
if (value.schemaVersion !== "1" || value.identityHash !== this.identityHash || !Array.isArray(value.points)
|
||||
|| sha256Hex(JSON.stringify(value.points)) !== value.pointsSha256) throw new Error("Indexing vector cache integrity mismatch");
|
||||
return value.points;
|
||||
}
|
||||
|
||||
async savePoints(points: IngestedChunk[]): Promise<void> {
|
||||
await atomicWrite(`${this.prefix}.points.json`, { schemaVersion: "1", identityHash: this.identityHash,
|
||||
pointsSha256: sha256Hex(JSON.stringify(points)), points });
|
||||
}
|
||||
|
||||
async preparePoints(build: (signal: AbortSignal) => Promise<IngestedChunk[]>, totalPoints: number,
|
||||
totalSourcePoints: number, policy = transferPolicy): Promise<IngestedChunk[]> {
|
||||
return this.runStep(build, totalPoints, totalSourcePoints, policy, true);
|
||||
}
|
||||
|
||||
async verifyFinal(check: (signal: AbortSignal) => Promise<void>, totalSourcePoints: number, policy = transferPolicy): Promise<void> {
|
||||
await this.runStep(async (signal) => { await check(signal); return []; }, 0, totalSourcePoints, policy, false);
|
||||
}
|
||||
|
||||
private async runStep(build: (signal: AbortSignal) => Promise<IngestedChunk[]>, totalPoints: number,
|
||||
totalSourcePoints: number, policy: typeof transferPolicy, cacheVectors: boolean): Promise<IngestedChunk[]> {
|
||||
const cached = cacheVectors ? await this.loadPoints() : undefined;
|
||||
if (cached) return cached;
|
||||
const file = `${this.prefix}.preparation.json`;
|
||||
const loaded = await readPrivate(file) as PreparationState | undefined;
|
||||
const state = (loaded && (cacheVectors || loaded.phase !== "complete") ? loaded : { identityHash: this.identityHash, versionId: this.versionId,
|
||||
documentId: this.documentId, phase: cacheVectors ? "preparing_vectors" : "verifying_version", step: cacheVectors ? "preparation" : "verification",
|
||||
attempts: 0, deadlineAt: Date.now() + policy.totalTimeoutMs,
|
||||
lastSignalAt: Date.now(), lastProgressAt: Date.now(), totalPoints, totalSourcePoints }) as PreparationState;
|
||||
if (state.identityHash !== this.identityHash || state.versionId !== this.versionId || state.documentId !== this.documentId
|
||||
|| !Number.isSafeInteger(state.attempts) || state.attempts < 0 || state.attempts > policy.maxAttempts
|
||||
|| !Number.isFinite(state.deadlineAt)) throw new Error("Indexing preparation checkpoint identity mismatch");
|
||||
if (state.phase === "paused") throw new TransferPausedError(state.failure!);
|
||||
let writes = Promise.resolve();
|
||||
let storageError: unknown;
|
||||
let controller: AbortController | undefined;
|
||||
const persist = async () => {
|
||||
state.lastSignalAt = Date.now();
|
||||
const snapshot = structuredClone(state);
|
||||
writes = writes.then(() => atomicWrite(file, snapshot));
|
||||
try { await writes; } catch (error) { storageError = error; controller?.abort(); throw error; }
|
||||
};
|
||||
const pause = async (failure: TransferFailure): Promise<never> => {
|
||||
state.phase = "paused"; state.failure = failure; await persist(); throw new TransferPausedError(failure);
|
||||
};
|
||||
let heartbeatPending = false;
|
||||
const timer = setInterval(() => {
|
||||
if (heartbeatPending || storageError) return;
|
||||
heartbeatPending = true;
|
||||
void persist().then(() => { heartbeatPending = false; }, () => { heartbeatPending = false; });
|
||||
}, policy.heartbeatMs);
|
||||
try {
|
||||
while (true) {
|
||||
if (storageError) throw storageError;
|
||||
if (state.attempts >= policy.maxAttempts || Date.now() >= state.deadlineAt) {
|
||||
return await pause({ kind: "timeout", code: "INDEXING_PREPARATION_RETRY_EXHAUSTED" });
|
||||
}
|
||||
if (state.nextAttemptAt && state.nextAttemptAt > Date.now()) {
|
||||
const delay = state.nextAttemptAt - Date.now();
|
||||
if (delay >= state.deadlineAt - Date.now()) return await pause({ kind: "timeout", code: "INDEXING_PREPARATION_BUDGET_EXHAUSTED" });
|
||||
await sleep(delay);
|
||||
}
|
||||
state.attempts += 1; state.phase = cacheVectors ? "preparing_vectors" : "verifying_version"; state.nextAttemptAt = undefined;
|
||||
controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller!.abort(), Math.min(policy.attemptTimeoutMs, state.deadlineAt - Date.now()));
|
||||
let failure: TransferFailure | undefined;
|
||||
try {
|
||||
await persist();
|
||||
const points = await build(controller.signal);
|
||||
if (storageError) throw storageError;
|
||||
if (controller.signal.aborted) throw controller.signal.reason;
|
||||
if (cacheVectors) await this.savePoints(points);
|
||||
state.phase = "complete"; state.failure = undefined; state.lastProgressAt = Date.now(); await persist();
|
||||
return points;
|
||||
} catch (error) {
|
||||
if (storageError) throw storageError;
|
||||
failure = controller.signal.aborted ? { kind: "timeout", code: "INDEXING_PREPARATION_TIMEOUT" } : classifyTransferFailure(error);
|
||||
} finally { clearTimeout(timeout); controller = undefined; }
|
||||
state.failure = failure;
|
||||
if (["unknown", "invalid", "payload_size"].includes(failure.kind)) return await pause(failure);
|
||||
state.phase = "retry_wait";
|
||||
state.nextAttemptAt = Date.now() + Math.max(failure.retryAfterMs ?? 0, policy.retryDelayMs * 2 ** (state.attempts - 1));
|
||||
await persist();
|
||||
}
|
||||
} finally { clearInterval(timer); await writes; }
|
||||
}
|
||||
|
||||
async load(): Promise<TransferState | undefined> {
|
||||
const value = await readPrivate(`${this.prefix}.state.json`) as {
|
||||
identityHash: string; versionId: string; documentId: string; transfer: TransferState
|
||||
} | undefined;
|
||||
if (!value) return undefined;
|
||||
if (value.identityHash !== this.identityHash || value.versionId !== this.versionId || value.documentId !== this.documentId) {
|
||||
throw new Error("Indexing transfer checkpoint identity mismatch");
|
||||
}
|
||||
return value.transfer;
|
||||
}
|
||||
|
||||
async save(transfer: TransferState): Promise<void> {
|
||||
await atomicWrite(`${this.prefix}.state.json`, { identityHash: this.identityHash, versionId: this.versionId,
|
||||
documentId: this.documentId, transfer });
|
||||
}
|
||||
}
|
||||
|
||||
export async function readIndexingProgress(root: string, versionId: string) {
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(versionId)) return undefined;
|
||||
const directory = checkpointDirectory(root, versionId);
|
||||
const entry = await lstat(directory).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === "ENOENT") return undefined;
|
||||
throw error;
|
||||
});
|
||||
if (!entry) return undefined;
|
||||
if (!entry.isDirectory()) throw new Error("Indexing checkpoint directory is invalid");
|
||||
const documents = [];
|
||||
for (const file of (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.state\.json$/u.test(name)).sort()) {
|
||||
const value = await readPrivate(path.join(directory, file)) as { versionId: string; documentId: string; transfer: TransferState };
|
||||
if (value.versionId !== versionId || !value.transfer || !Array.isArray(value.transfer.batches)) {
|
||||
throw new Error("Indexing progress identity mismatch");
|
||||
}
|
||||
const state = value.transfer;
|
||||
const active = state.batches[state.activeBatch];
|
||||
documents.push({ documentId: value.documentId, stage: "transfer" as const, phase: state.phase, lastSignalAt: state.updatedAt,
|
||||
lastProgressAt: state.lastProgressAt, signalStale: !["complete", "paused"].includes(state.phase) && Date.now() - state.updatedAt > 15_000,
|
||||
totalPoints: state.totalPoints, totalSourcePoints: state.totalSourcePoints,
|
||||
confirmedPoints: state.batches.filter(({ confirmed }) => confirmed).reduce((total, batch) => total + batch.end - batch.start, 0),
|
||||
confirmedBytes: state.batches.filter(({ confirmed }) => confirmed).reduce((total, batch) => total + batch.bytes, 0),
|
||||
totalBytes: state.batches.reduce((total, batch) => total + batch.bytes, 0),
|
||||
batch: state.activeBatch + 1, batchCount: state.batches.length,
|
||||
attempt: active?.attempts ?? 0, batchBytes: active?.bytes ?? 0,
|
||||
deadlineAt: active?.deadlineAt ?? null, nextAttemptAt: active?.nextAttemptAt ?? null,
|
||||
failure: state.failure ?? active?.failure ?? null });
|
||||
}
|
||||
for (const file of (await readdir(directory)).filter((name) => /^[0-9a-f]{64}\.preparation\.json$/u.test(name)).sort()) {
|
||||
const state = await readPrivate(path.join(directory, file)) as PreparationState;
|
||||
if (documents.some(({ documentId }) => documentId === state.documentId)) continue;
|
||||
if (state.versionId !== versionId) throw new Error("Indexing preparation progress identity mismatch");
|
||||
documents.push({ documentId: state.documentId, stage: state.step ?? "preparation", phase: state.phase, lastSignalAt: state.lastSignalAt,
|
||||
lastProgressAt: state.lastProgressAt ?? 0, signalStale: !["complete", "paused"].includes(state.phase) && Date.now() - state.lastSignalAt > 15_000,
|
||||
totalPoints: state.totalPoints, totalSourcePoints: state.totalSourcePoints, confirmedPoints: 0, confirmedBytes: 0,
|
||||
totalBytes: 0, batch: 0, batchCount: 0, attempt: state.attempts, batchBytes: 0,
|
||||
deadlineAt: state.deadlineAt, nextAttemptAt: state.nextAttemptAt ?? null, failure: state.failure ?? null });
|
||||
}
|
||||
if (!documents.length) return undefined;
|
||||
return { heartbeatMs: 5_000, totalPoints: documents[0].totalSourcePoints,
|
||||
confirmedPoints: documents.reduce((total, document) => total + document.confirmedPoints, 0),
|
||||
confirmedBytes: documents.reduce((total, document) => total + document.confirmedBytes, 0),
|
||||
paused: documents.some(({ phase }) => phase === "paused"), documents };
|
||||
}
|
||||
|
|
@ -2,7 +2,8 @@ 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";
|
||||
import { buildChunkId, buildVersionedQdrantPointId, canonicalJson, sha256Hex } from "../../shared/utils/ids.js";
|
||||
import { IndexingCheckpoint } from "./indexing-checkpoint.js";
|
||||
|
||||
export interface VersionedDocumentForIndexing {
|
||||
documentId: string;
|
||||
|
|
@ -30,51 +31,65 @@ export async function writeVersionedDocuments(input: {
|
|||
documents: VersionedDocumentForIndexing[];
|
||||
embeddingProvider: EmbeddingProvider;
|
||||
vectorStore: VectorStoreClient;
|
||||
checkpointRoot?: string;
|
||||
}): 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;
|
||||
const totalSourcePoints = input.documents.reduce((total, item) => total + item.chunks.length, 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);
|
||||
const checkpoint = input.checkpointRoot ? new IndexingCheckpoint(input.checkpointRoot, input.identity.versionId,
|
||||
document.documentId, sha256Hex(canonicalJson({ identity: input.identity, document,
|
||||
provider: input.embeddingProvider.providerName, model: input.embeddingProvider.modelName }))) : undefined;
|
||||
const build = async (signal?: AbortSignal): Promise<IngestedChunk[]> => {
|
||||
const embeddings = await input.embeddingProvider.embed(document.chunks.map(({ content }) => content), signal ? { signal } : undefined);
|
||||
if (embeddings.length !== document.chunks.length || embeddings.some((embedding) =>
|
||||
embedding.length !== input.identity.expectedEmbeddingDimensions || embedding.some((value) => !Number.isFinite(value)))) {
|
||||
throw new CatalogError("Embedding provider returned invalid dimensions", 503, "EMBEDDING_DIMENSIONS_INVALID");
|
||||
}
|
||||
return 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"
|
||||
}
|
||||
};
|
||||
});
|
||||
};
|
||||
const points = checkpoint ? await checkpoint.preparePoints(build, document.chunks.length, totalSourcePoints) : await build();
|
||||
if (points.length !== document.chunks.length || points.some((point, index) =>
|
||||
point.id !== buildVersionedQdrantPointId(input.identity.versionId, buildChunkId(document.documentId, document.chunkMode, document.chunks[index].index))
|
||||
|| point.vector.length !== input.identity.expectedEmbeddingDimensions || point.vector.some((value) => !Number.isFinite(value))
|
||||
|| point.payload.source_version_id !== input.identity.versionId || point.payload.document_id !== document.documentId
|
||||
|| point.payload.content !== document.chunks[index].content)) throw new Error("Indexing vector cache does not match the document");
|
||||
if (points.length) await input.vectorStore.upsert(points, { journal: checkpoint,
|
||||
totalSourcePoints });
|
||||
stored += points.length;
|
||||
}
|
||||
return stored;
|
||||
|
|
@ -85,8 +100,9 @@ export async function verifyVersionedDocuments(input: {
|
|||
expectedPointCount: number;
|
||||
chunksWritten: number;
|
||||
vectorStore: VectorStoreClient;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<number> {
|
||||
const actual = await input.vectorStore.countVersionPoints(input.versionId);
|
||||
const actual = await input.vectorStore.countVersionPoints(input.versionId, input.signal);
|
||||
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");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ import { readComposedCandidateArtifact, readReviewedPagesArtifact, readReviewedP
|
|||
import { CatalogRepository } from "../catalog/repository.js";
|
||||
import { verifyVersionedDocuments, writeVersionedDocuments, type VersionedDocumentForIndexing } from "../ingest/versioned-indexing.js";
|
||||
import { env } from "../../config/env.js";
|
||||
import { IndexingCheckpoint, readIndexingProgress } from "../ingest/indexing-checkpoint.js";
|
||||
import { TransferPausedError, classifyTransferFailure } from "../vectorstore/transfer.js";
|
||||
|
||||
export interface ApprovedOcrCandidate {
|
||||
versionId: string;
|
||||
|
|
@ -25,6 +27,8 @@ export interface ApprovedOcrCandidate {
|
|||
}
|
||||
|
||||
export interface OcrIndexingStore {
|
||||
markTransferPaused?(versionId: string, code: string): Promise<void>;
|
||||
recoverInterruptedTransfers?(indexLocked: (candidate: ApprovedOcrCandidate) => Promise<OcrIndexingResult>): Promise<number>;
|
||||
withSourceLock?<T>(sourceId: string, handler: () => Promise<T>): Promise<T>;
|
||||
recoverStaleApprovedVersions?(indexLocked: (candidate: ApprovedOcrCandidate) => Promise<OcrIndexingResult>): Promise<number>;
|
||||
restoreApprovedIndexing?(input: ApprovedOcrIndexingRecoveryRequest & { versionId: string }): Promise<ApprovedOcrIndexingRecoveryResult>;
|
||||
|
|
@ -80,8 +84,32 @@ function activeRace(error: unknown): never {
|
|||
}
|
||||
|
||||
export class OcrIndexingService {
|
||||
private transferRecoveryTimer?: NodeJS.Timeout;
|
||||
private transferRecoveryRun?: Promise<number>;
|
||||
constructor(private readonly store: OcrIndexingStore) {}
|
||||
|
||||
startTransferRecovery(): void {
|
||||
if (this.transferRecoveryTimer || !this.store.recoverInterruptedTransfers) return;
|
||||
const run = () => { void this.recoverInterruptedTransfers().catch(() => console.error("Indexing transfer recovery scan failed")); };
|
||||
this.transferRecoveryTimer = setInterval(run, 5_000);
|
||||
this.transferRecoveryTimer.unref();
|
||||
run();
|
||||
}
|
||||
|
||||
stopTransferRecovery(): void {
|
||||
if (this.transferRecoveryTimer) clearInterval(this.transferRecoveryTimer);
|
||||
this.transferRecoveryTimer = undefined;
|
||||
}
|
||||
|
||||
recoverInterruptedTransfers(): Promise<number> {
|
||||
if (this.transferRecoveryRun) return this.transferRecoveryRun;
|
||||
const run = this.store.recoverInterruptedTransfers?.((candidate) => this.indexLocked(candidate)) ?? Promise.resolve(0);
|
||||
this.transferRecoveryRun = run;
|
||||
const clear = () => { if (this.transferRecoveryRun === run) this.transferRecoveryRun = undefined; };
|
||||
void run.then(clear, clear);
|
||||
return run;
|
||||
}
|
||||
|
||||
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));
|
||||
|
|
@ -118,7 +146,12 @@ export class OcrIndexingService {
|
|||
};
|
||||
}
|
||||
|
||||
const verifiedPointCount = await this.store.indexReviewed(candidate);
|
||||
let verifiedPointCount: number;
|
||||
try { verifiedPointCount = await this.store.indexReviewed(candidate); }
|
||||
catch (error) {
|
||||
if (error instanceof TransferPausedError) await this.store.markTransferPaused?.(candidate.versionId, error.failure.code);
|
||||
throw error;
|
||||
}
|
||||
await this.store.markReady(candidate.versionId, verifiedPointCount);
|
||||
if (!candidate.activateRequested) return { versionId: candidate.versionId, state: "ready", activated: false };
|
||||
try {
|
||||
|
|
@ -212,9 +245,15 @@ export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
|||
processingFingerprint: candidate.processingFingerprint, expectedEmbeddingDimensions: Number(first.embedding_dimensions) },
|
||||
documents: prepared.documents,
|
||||
embeddingProvider: this.embeddingProvider,
|
||||
vectorStore: this.vectorStore
|
||||
vectorStore: this.vectorStore,
|
||||
checkpointRoot: this.rootDirectory
|
||||
});
|
||||
await verifyVersionedDocuments({ versionId: candidate.versionId, expectedPointCount, chunksWritten, vectorStore: this.vectorStore });
|
||||
const verification = new IndexingCheckpoint(this.rootDirectory, candidate.versionId, "__version_verification__",
|
||||
sha256Hex(canonicalJson({ sourceId: candidate.sourceId, sourceContentHash, expectedPointCount,
|
||||
fingerprint: candidate.processingFingerprint, metadataHash: candidate.metadataHash })));
|
||||
await verification.verifyFinal(async (signal) => {
|
||||
await verifyVersionedDocuments({ versionId: candidate.versionId, expectedPointCount, chunksWritten, vectorStore: this.vectorStore, signal });
|
||||
}, expectedPointCount);
|
||||
return chunksWritten;
|
||||
}
|
||||
|
||||
|
|
@ -222,6 +261,10 @@ export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
|||
await this.catalog.markReady(versionId, verifiedPointCount);
|
||||
}
|
||||
|
||||
async markTransferPaused(versionId: string, code: string): Promise<void> {
|
||||
await this.catalog.markIndexingTransferPaused(versionId, code);
|
||||
}
|
||||
|
||||
async settleReusable(candidate: ApprovedOcrCandidate, reusableVersionId: string, activate: boolean): Promise<boolean> {
|
||||
await this.catalog.markOcrDuplicate(candidate.versionId, reusableVersionId);
|
||||
if (!activate) return false;
|
||||
|
|
@ -236,6 +279,8 @@ export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
|||
let recovered = 0;
|
||||
for (const stale of candidates) {
|
||||
const result = await this.catalog.withSourceTryLock(stale.sourceId, async () => {
|
||||
const progress = await readIndexingProgress(this.rootDirectory, stale.versionId);
|
||||
if (progress?.paused || progress?.documents.some((document) => document.stage === "transfer")) return false;
|
||||
let approved: ApprovedOcrCandidate;
|
||||
try {
|
||||
approved = await this.loadApprovedCandidateForRecovery(stale.versionId, stale.sourceId);
|
||||
|
|
@ -257,6 +302,35 @@ export class PostgresOcrIndexingStore implements OcrIndexingStore {
|
|||
return recovered;
|
||||
}
|
||||
|
||||
async recoverInterruptedTransfers(indexLocked: (candidate: ApprovedOcrCandidate) => Promise<OcrIndexingResult>): Promise<number> {
|
||||
let recovered = 0;
|
||||
for (const candidate of await this.catalog.listInterruptedApprovedTransfers()) {
|
||||
const result = await this.catalog.withSourceTryLock(candidate.sourceId, async () => {
|
||||
const progress = await readIndexingProgress(this.rootDirectory, candidate.versionId);
|
||||
if (progress?.paused) {
|
||||
const code = progress.documents.find(({ phase }) => phase === "paused")?.failure?.code ?? "INDEXING_TRANSFER_PAUSED";
|
||||
await this.markTransferPaused(candidate.versionId, code);
|
||||
return false;
|
||||
}
|
||||
let approved: ApprovedOcrCandidate;
|
||||
try { approved = await this.loadApprovedCandidateForRecovery(candidate.versionId, candidate.sourceId); }
|
||||
catch (error) {
|
||||
await this.catalog.markApprovedOcrIndexRecoveryInvalid(candidate.versionId, this.recoveryErrorCode(error));
|
||||
return false;
|
||||
}
|
||||
try { await indexLocked(approved); return true; }
|
||||
catch (error) {
|
||||
if (!(error instanceof TransferPausedError) && ["unknown", "invalid"].includes(classifyTransferFailure(error).kind)) {
|
||||
await this.catalog.markApprovedOcrIndexRecoveryInvalid(candidate.versionId, "INDEXING_TRANSFER_EVIDENCE_OR_STATE_INVALID");
|
||||
}
|
||||
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 }>(
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import { QdrantClient } from "@qdrant/js-client-rest";
|
|||
import { env } from "../../config/env.js";
|
||||
import type { AvailableScope, IngestedChunk, RetrieveScope, RetrievedItem } from "../../shared/types/rag.js";
|
||||
import type { ActiveVersionScope } from "../catalog/repository.js";
|
||||
import { transferPoints, transferPolicy, type TransferOptions } from "./transfer.js";
|
||||
import { canonicalJson } from "../../shared/utils/ids.js";
|
||||
|
||||
export function buildQdrantClient(): QdrantClient {
|
||||
const url = new URL(env.qdrantUrl);
|
||||
|
|
@ -19,13 +21,13 @@ export interface VectorStoreClient {
|
|||
healthcheck(): Promise<{ ok: boolean; kind: string }>;
|
||||
ensureCollection(vectorSize: number): Promise<void>;
|
||||
ensurePayloadIndexes(): Promise<void>;
|
||||
upsert(chunks: IngestedChunk[]): Promise<void>;
|
||||
upsert(chunks: IngestedChunk[], options?: TransferOptions): Promise<void>;
|
||||
search(queryVector: number[], limit: number, mode?: string, scope?: RetrieveScope, activeVersions?: ActiveVersionScope[]): Promise<RetrievedItem[]>;
|
||||
listScopes(): Promise<AvailableScope[]>;
|
||||
browseScope(limit: number, mode?: string, scope?: RetrieveScope, activeVersions?: ActiveVersionScope[]): Promise<RetrievedItem[]>;
|
||||
deleteScope(scope: RetrieveScope): Promise<number>;
|
||||
validateCollectionDimensions(expectedDimensions: number): Promise<void>;
|
||||
countVersionPoints(sourceVersionId: string): Promise<number>;
|
||||
countVersionPoints(sourceVersionId: string, signal?: AbortSignal): Promise<number>;
|
||||
deleteVersionPoints(sourceVersionId: string): Promise<number>;
|
||||
}
|
||||
|
||||
|
|
@ -91,8 +93,28 @@ export class QdrantVectorStoreClient implements VectorStoreClient {
|
|||
private readonly client: QdrantClient;
|
||||
private collectionReady = false;
|
||||
|
||||
constructor() {
|
||||
this.client = buildQdrantClient();
|
||||
constructor(client: QdrantClient = buildQdrantClient(),
|
||||
private readonly transferConnection = { url: env.qdrantUrl, apiKey: env.qdrantApiKey },
|
||||
private readonly policy = transferPolicy) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
private async transferRequest<T>(suffix: string, method: string, body: unknown, signal: AbortSignal): Promise<T> {
|
||||
const url = new URL(this.transferConnection.url);
|
||||
if (!url.port && url.protocol === "http:") url.port = "6333";
|
||||
const headers: Record<string, string> = {};
|
||||
if (this.transferConnection.apiKey) headers["api-key"] = this.transferConnection.apiKey;
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
const response = await fetch(url.origin + suffix, { method, headers, signal, redirect: "error",
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
|
||||
const text = await response.text();
|
||||
let data: { result?: T } | undefined;
|
||||
try { data = JSON.parse(text); } catch { /* Non-JSON error bodies still retain their HTTP status. */ }
|
||||
if (!response.ok) throw Object.assign(new Error("Qdrant transfer request failed"), {
|
||||
status: response.status, headers: response.headers, data
|
||||
});
|
||||
if (data?.result === undefined) throw new Error("Qdrant transfer response was not confirmed");
|
||||
return data.result;
|
||||
}
|
||||
|
||||
async healthcheck(): Promise<{ ok: boolean; kind: string }> {
|
||||
|
|
@ -148,28 +170,54 @@ export class QdrantVectorStoreClient implements VectorStoreClient {
|
|||
}
|
||||
}
|
||||
|
||||
async upsert(chunks: IngestedChunk[]): Promise<void> {
|
||||
async upsert(chunks: IngestedChunk[], options?: TransferOptions): Promise<void> {
|
||||
if (chunks.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const vectorSize = chunks[0].vector.length;
|
||||
if (vectorSize === 0 || chunks.some((chunk) => chunk.vector.length !== vectorSize)) {
|
||||
throw new Error("Qdrant upsert rejected: vectors must be non-empty and have consistent dimensions");
|
||||
if (vectorSize === 0 || chunks.some((chunk) => chunk.vector.length !== vectorSize || chunk.vector.some((value) => !Number.isFinite(value)))) {
|
||||
throw new Error("Qdrant upsert rejected: vectors must be non-empty, finite, and have consistent dimensions");
|
||||
}
|
||||
|
||||
await this.ensureCollection(vectorSize);
|
||||
const result = await this.client.upsert(env.qdrantCollection, {
|
||||
wait: true,
|
||||
points: chunks.map((chunk) => ({
|
||||
id: chunk.id,
|
||||
vector: chunk.vector,
|
||||
payload: chunk.payload
|
||||
}))
|
||||
});
|
||||
if (result.status !== "completed") {
|
||||
throw new Error(`Qdrant upsert did not complete: ${result.status}`);
|
||||
}
|
||||
const points = chunks.map(({ id, vector, payload }) => ({ id, vector, payload }));
|
||||
const collectionPath = `/collections/${encodeURIComponent(env.qdrantCollection)}`;
|
||||
await transferPoints(points, {
|
||||
prepare: async (signal) => {
|
||||
if (this.collectionReady) return;
|
||||
const collections = await this.transferRequest<{ collections: Array<{ name: string }> }>("/collections", "GET", undefined, signal);
|
||||
const exists = collections.collections.some(({ name }) => name === env.qdrantCollection);
|
||||
if (!exists) {
|
||||
try { await this.transferRequest(collectionPath, "PUT", { vectors: { size: vectorSize, distance: "Cosine" } }, signal); }
|
||||
catch (error) { if ((error as { status?: number }).status !== 409) throw error; }
|
||||
}
|
||||
const info = await this.transferRequest<{ payload_schema?: Record<string, unknown> }>(collectionPath, "GET", undefined, signal);
|
||||
if (extractVectorSize(info) !== vectorSize) throw new Error("Qdrant collection dimension mismatch");
|
||||
for (const field of ["source_id", "source_version_id", "document_id", "chunk_mode", "tags"]) {
|
||||
if (info.payload_schema?.[field]) continue;
|
||||
const result = await this.transferRequest<{ status: string }>(collectionPath + "/index?wait=true", "PUT",
|
||||
{ field_name: field, field_schema: "keyword" }, signal);
|
||||
if (result.status !== "completed") throw new Error("Qdrant payload index not confirmed");
|
||||
}
|
||||
this.collectionReady = true;
|
||||
},
|
||||
send: async (batch, signal) => {
|
||||
const response = await this.transferRequest<{ status: string }>(collectionPath + "/points?wait=true", "PUT", { points: batch }, signal);
|
||||
return response.status;
|
||||
},
|
||||
verify: async (batch, signal) => {
|
||||
const response = await this.transferRequest<Array<{ id: string | number; payload?: Record<string, unknown> }>>(collectionPath + "/points", "POST",
|
||||
{ ids: batch.map(({ id }) => id), with_payload: true, with_vector: false }, signal);
|
||||
const found = new Map(response.map((point) => [String(point.id), point]));
|
||||
return batch.every((point) => {
|
||||
const stored = found.get(point.id);
|
||||
if (!stored?.payload) return false;
|
||||
const { indexed_at: _storedTimestamp, ...storedPayload } = stored.payload;
|
||||
const { indexed_at: _expectedTimestamp, ...expectedPayload } = point.payload;
|
||||
return canonicalJson(storedPayload) === canonicalJson(expectedPayload);
|
||||
});
|
||||
}
|
||||
}, options, this.policy);
|
||||
}
|
||||
|
||||
async search(queryVector: number[], limit: number, mode?: string, scope?: RetrieveScope, activeVersions?: ActiveVersionScope[]): Promise<RetrievedItem[]> {
|
||||
|
|
@ -323,19 +371,20 @@ export class QdrantVectorStoreClient implements VectorStoreClient {
|
|||
}
|
||||
}
|
||||
|
||||
async countVersionPoints(sourceVersionId: string): Promise<number> {
|
||||
const collections = await this.client.getCollections();
|
||||
async countVersionPoints(sourceVersionId: string, signal = AbortSignal.timeout(180_000)): Promise<number> {
|
||||
const collections = await this.transferRequest<{ collections: Array<{ name: string }> }>("/collections", "GET", undefined, signal);
|
||||
const exists = collections.collections.some((collection) => collection.name === env.qdrantCollection);
|
||||
if (!exists) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const result = await this.client.count(env.qdrantCollection, {
|
||||
const result = await this.transferRequest<{ count: number }>(`/collections/${encodeURIComponent(env.qdrantCollection)}/points/count`, "POST", {
|
||||
filter: {
|
||||
must: [{ key: "source_version_id", match: { value: sourceVersionId } }]
|
||||
},
|
||||
exact: true
|
||||
});
|
||||
}, signal);
|
||||
if (!Number.isSafeInteger(result.count) || result.count < 0) throw new Error("Qdrant count was not confirmed");
|
||||
return result.count;
|
||||
}
|
||||
|
||||
|
|
|
|||
243
src/modules/vectorstore/transfer.ts
Normal file
243
src/modules/vectorstore/transfer.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import { sha256Hex } from "../../shared/utils/ids.js";
|
||||
import type { IngestedChunk } from "../../shared/types/rag.js";
|
||||
import { CatalogError } from "../catalog/errors.js";
|
||||
|
||||
export type TransferPoint = Pick<IngestedChunk, "id" | "vector" | "payload">;
|
||||
export type TransferFailureKind = "connection" | "timeout" | "overloaded" | "server" | "payload_size" | "invalid" | "unknown" | "unconfirmed";
|
||||
export interface TransferFailure { kind: TransferFailureKind; code: string; httpStatus?: number; retryAfterMs?: number }
|
||||
export interface TransferBatch {
|
||||
start: number; end: number; bytes: number; attempts: number; confirmed: boolean;
|
||||
deadlineAt?: number; nextAttemptAt?: number; failure?: TransferFailure;
|
||||
}
|
||||
export interface TransferState {
|
||||
schemaVersion: "1"; pointsSha256: string; totalPoints: number; totalSourcePoints: number;
|
||||
phase: "pending" | "checking" | "sending" | "verifying" | "retry_wait" | "complete" | "paused";
|
||||
updatedAt: number; lastProgressAt: number; activeBatch: number; batches: TransferBatch[];
|
||||
failure?: TransferFailure;
|
||||
}
|
||||
export interface TransferJournal {
|
||||
load(): Promise<TransferState | undefined>;
|
||||
save(state: TransferState): Promise<void>;
|
||||
}
|
||||
export interface TransferOptions { journal?: TransferJournal; totalSourcePoints?: number }
|
||||
export interface TransferTransport {
|
||||
prepare?(signal: AbortSignal): Promise<void>;
|
||||
send(points: TransferPoint[], signal: AbortSignal): Promise<string>;
|
||||
verify(points: TransferPoint[], signal: AbortSignal): Promise<boolean>;
|
||||
}
|
||||
export const transferPolicy = {
|
||||
maxBytes: 8 * 1024 * 1024, maxAttempts: 3, attemptTimeoutMs: 180_000,
|
||||
totalTimeoutMs: 540_000, heartbeatMs: 5_000, retryDelayMs: 1_000, verificationIntervalMs: 1_000
|
||||
};
|
||||
export class TransferPausedError extends CatalogError {
|
||||
constructor(readonly failure: TransferFailure) {
|
||||
super(`Indexing transfer paused: ${failure.code}`, failure.kind === "invalid" ? 422 : 503, failure.code);
|
||||
}
|
||||
}
|
||||
|
||||
export function classifyTransferFailure(error: unknown): TransferFailure {
|
||||
const value = error as { status?: number; statusCode?: number; code?: string; name?: string; cause?: { code?: string }; data?: unknown; retry_after?: number; headers?: Headers | Record<string, string> };
|
||||
const status = value?.status ?? value?.statusCode;
|
||||
let code = value?.code;
|
||||
let cause: unknown = value?.cause;
|
||||
for (let depth = 0; !code && cause && depth < 5; depth += 1) {
|
||||
const nested = cause as { code?: string; cause?: unknown };
|
||||
code = nested.code;
|
||||
cause = nested.cause;
|
||||
}
|
||||
if (code && /^(EMBEDDING_(?:DIMENSIONS|CONFIGURATION)_INVALID|EMBEDDING_CONFIGURATION_MISMATCH|REVIEW_CONFLICT|SOURCE_VERSION_INCONSISTENT|INDEXING_CHECKPOINT_)/u.test(code)) {
|
||||
return { kind: "invalid", code };
|
||||
}
|
||||
const name = error instanceof Error ? error.constructor.name : value?.name;
|
||||
if (value?.name === "AbortError" || value?.name === "TimeoutError" || name === "APIConnectionTimeoutError" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT") {
|
||||
return { kind: "timeout", code: "INDEXING_TRANSFER_TIMEOUT" };
|
||||
}
|
||||
if (name === "APIConnectionError" || ["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "EPIPE", "UND_ERR_SOCKET"].includes(code ?? "")) {
|
||||
return { kind: "connection", code: "INDEXING_TRANSFER_CONNECTION" };
|
||||
}
|
||||
if (status === 413 || (status === 400 && /payload.*(?:larger|limit|size)|request.*too large/iu.test(JSON.stringify(value.data)))) {
|
||||
return { kind: "payload_size", code: "INDEXING_TRANSFER_PAYLOAD_SIZE", httpStatus: status };
|
||||
}
|
||||
const retryHeader = value?.headers instanceof Headers ? value.headers.get("retry-after") : value?.headers?.["retry-after"];
|
||||
if (status === 429 || typeof value?.retry_after === "number" || (status === 503 && retryHeader)) {
|
||||
const header = retryHeader;
|
||||
const seconds = value.retry_after ?? (header && Number.isFinite(Number(header)) ? Number(header) : undefined);
|
||||
const delay = seconds !== undefined ? seconds * 1000 : header ? Date.parse(header) - Date.now() : undefined;
|
||||
return { kind: "overloaded", code: "INDEXING_TRANSFER_OVERLOADED", httpStatus: status,
|
||||
...(delay !== undefined && Number.isFinite(delay) ? { retryAfterMs: Math.max(0, delay) } : {}) };
|
||||
}
|
||||
if (status === 408 || (status !== undefined && status >= 500 && status <= 599)) {
|
||||
return { kind: status === 408 ? "timeout" : "server", code: status === 408 ? "INDEXING_TRANSFER_TIMEOUT" : "INDEXING_TRANSFER_SERVER", httpStatus: status };
|
||||
}
|
||||
if (status !== undefined && status >= 400 && status < 500) return { kind: "invalid", code: "INDEXING_TRANSFER_REJECTED", httpStatus: status };
|
||||
return { kind: "unknown", code: "INDEXING_TRANSFER_UNKNOWN" };
|
||||
}
|
||||
|
||||
function byteSize(points: TransferPoint[]): number {
|
||||
return Buffer.byteLength(JSON.stringify({ points }), "utf8");
|
||||
}
|
||||
|
||||
function planBatches(points: TransferPoint[], maxBytes: number): TransferBatch[] {
|
||||
const envelope = byteSize([]);
|
||||
const batches: TransferBatch[] = [];
|
||||
let start = 0;
|
||||
let bytes = envelope;
|
||||
for (let index = 0; index < points.length; index += 1) {
|
||||
const pointBytes = Buffer.byteLength(JSON.stringify(points[index]), "utf8");
|
||||
if (envelope + pointBytes > maxBytes) throw new TransferPausedError({ kind: "invalid", code: "INDEXING_TRANSFER_POINT_TOO_LARGE" });
|
||||
if (bytes + (index > start ? 1 : 0) + pointBytes > maxBytes) {
|
||||
batches.push({ start, end: index, bytes, attempts: 0, confirmed: false });
|
||||
start = index;
|
||||
bytes = envelope;
|
||||
}
|
||||
bytes += (index > start ? 1 : 0) + pointBytes;
|
||||
}
|
||||
if (start < points.length) batches.push({ start, end: points.length, bytes, attempts: 0, confirmed: false });
|
||||
return batches;
|
||||
}
|
||||
|
||||
function validateState(state: TransferState, points: TransferPoint[], hash: string, policy: typeof transferPolicy): void {
|
||||
let end = 0;
|
||||
if (state.schemaVersion !== "1" || state.pointsSha256 !== hash || state.totalPoints !== points.length
|
||||
|| !Array.isArray(state.batches)) throw new Error("Indexing transfer checkpoint identity mismatch");
|
||||
for (const batch of state.batches) {
|
||||
if (batch.start !== end || !Number.isSafeInteger(batch.end) || batch.end <= batch.start || batch.end > points.length
|
||||
|| batch.bytes !== byteSize(points.slice(batch.start, batch.end)) || batch.bytes > policy.maxBytes
|
||||
|| !Number.isSafeInteger(batch.attempts) || batch.attempts < 0 || batch.attempts > policy.maxAttempts
|
||||
|| typeof batch.confirmed !== "boolean" || (batch.deadlineAt !== undefined && !Number.isFinite(batch.deadlineAt))) {
|
||||
throw new Error("Indexing transfer checkpoint is invalid");
|
||||
}
|
||||
end = batch.end;
|
||||
}
|
||||
if (end !== points.length) throw new Error("Indexing transfer checkpoint is incomplete");
|
||||
}
|
||||
|
||||
export async function transferPoints(points: TransferPoint[], transport: TransferTransport,
|
||||
options: TransferOptions = {}, policy = transferPolicy): Promise<void> {
|
||||
const now = Date.now();
|
||||
const hash = sha256Hex(JSON.stringify(points));
|
||||
const loaded = await options.journal?.load();
|
||||
let state: TransferState;
|
||||
try {
|
||||
state = loaded ?? { schemaVersion: "1", pointsSha256: hash, totalPoints: points.length,
|
||||
totalSourcePoints: options.totalSourcePoints ?? points.length, phase: "pending", updatedAt: now, lastProgressAt: now,
|
||||
activeBatch: 0, batches: planBatches(points, policy.maxBytes) };
|
||||
if (state.phase !== "paused") validateState(state, points, hash, policy);
|
||||
else if (state.pointsSha256 !== hash) throw new Error("Indexing transfer checkpoint identity mismatch");
|
||||
} catch (error) {
|
||||
if (error instanceof TransferPausedError) await options.journal?.save({ schemaVersion: "1", pointsSha256: hash,
|
||||
totalPoints: points.length, totalSourcePoints: options.totalSourcePoints ?? points.length, phase: "paused",
|
||||
updatedAt: now, lastProgressAt: now, activeBatch: 0, batches: [], failure: error.failure });
|
||||
throw error;
|
||||
}
|
||||
if (state.phase === "paused") throw new TransferPausedError(state.failure ?? { kind: "unknown", code: "INDEXING_TRANSFER_PAUSED" });
|
||||
|
||||
let writes = Promise.resolve();
|
||||
let persistenceError: unknown;
|
||||
let controller: AbortController | undefined;
|
||||
const persist = async () => {
|
||||
state.updatedAt = Date.now();
|
||||
const snapshot = structuredClone(state);
|
||||
writes = writes.then(() => options.journal?.save(snapshot));
|
||||
try { await writes; } catch (error) { persistenceError = error; controller?.abort(); throw error; }
|
||||
};
|
||||
const pause = async (failure: TransferFailure): Promise<never> => {
|
||||
state.phase = "paused";
|
||||
state.failure = failure;
|
||||
await persist();
|
||||
throw new TransferPausedError(failure);
|
||||
};
|
||||
let heartbeatPending = false;
|
||||
const heartbeat = setInterval(() => {
|
||||
if (heartbeatPending || persistenceError) return;
|
||||
heartbeatPending = true;
|
||||
void persist().then(() => { heartbeatPending = false; }, () => { heartbeatPending = false; });
|
||||
}, policy.heartbeatMs);
|
||||
try {
|
||||
await persist();
|
||||
for (let index = 0; index < state.batches.length; index += 1) {
|
||||
state.activeBatch = index;
|
||||
const batch = state.batches[index];
|
||||
const current = points.slice(batch.start, batch.end);
|
||||
// Recheck confirmed IDs after restart; resend only if Qdrant no longer has them.
|
||||
if (batch.confirmed) {
|
||||
batch.confirmed = false;
|
||||
batch.attempts = 0;
|
||||
batch.deadlineAt = undefined;
|
||||
batch.nextAttemptAt = undefined;
|
||||
batch.failure = undefined;
|
||||
}
|
||||
while (!batch.confirmed) {
|
||||
if (persistenceError) throw persistenceError;
|
||||
batch.deadlineAt ??= Date.now() + policy.totalTimeoutMs;
|
||||
if (batch.attempts >= policy.maxAttempts) await pause({ ...(batch.failure ?? { kind: "timeout" }), code: "INDEXING_TRANSFER_RETRY_EXHAUSTED" });
|
||||
if (Date.now() >= batch.deadlineAt) await pause({ kind: "timeout", code: "INDEXING_TRANSFER_BUDGET_EXHAUSTED" });
|
||||
if (batch.nextAttemptAt && batch.nextAttemptAt > Date.now()) {
|
||||
state.phase = "retry_wait";
|
||||
await persist();
|
||||
const remaining = batch.deadlineAt - Date.now();
|
||||
const delay = batch.nextAttemptAt - Date.now();
|
||||
if (delay >= remaining) await pause({ kind: "timeout", code: "INDEXING_TRANSFER_BUDGET_EXHAUSTED" });
|
||||
await sleep(delay);
|
||||
if (persistenceError) throw persistenceError;
|
||||
}
|
||||
batch.attempts += 1;
|
||||
batch.nextAttemptAt = undefined;
|
||||
controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller!.abort(), Math.min(policy.attemptTimeoutMs, batch.deadlineAt - Date.now()));
|
||||
let failure: TransferFailure | undefined;
|
||||
try {
|
||||
state.phase = "checking";
|
||||
await persist();
|
||||
await transport.prepare?.(controller.signal);
|
||||
let confirmed = await transport.verify(current, controller.signal);
|
||||
if (!confirmed) {
|
||||
state.phase = "sending";
|
||||
await persist();
|
||||
const status = await transport.send(current, controller.signal);
|
||||
if (!["completed", "acknowledged", "wait_timeout"].includes(status)) throw new Error("Unexpected Qdrant operation status");
|
||||
state.phase = "verifying";
|
||||
await persist();
|
||||
confirmed = await transport.verify(current, controller.signal);
|
||||
while (!confirmed && status !== "completed") {
|
||||
await sleep(policy.verificationIntervalMs, undefined, { signal: controller.signal });
|
||||
confirmed = await transport.verify(current, controller.signal);
|
||||
}
|
||||
}
|
||||
if (!confirmed) failure = { kind: "unconfirmed", code: "INDEXING_TRANSFER_NOT_CONFIRMED" };
|
||||
else {
|
||||
batch.confirmed = true;
|
||||
batch.failure = undefined;
|
||||
state.lastProgressAt = Date.now();
|
||||
await persist();
|
||||
}
|
||||
} catch (error) {
|
||||
if (persistenceError) throw persistenceError;
|
||||
failure = controller.signal.aborted ? { kind: "timeout", code: "INDEXING_TRANSFER_TIMEOUT" } : classifyTransferFailure(error);
|
||||
} finally { clearTimeout(timeout); controller = undefined; }
|
||||
if (!failure) continue;
|
||||
batch.failure = failure;
|
||||
if (failure.kind === "payload_size" && current.length > 1) {
|
||||
const middle = batch.start + Math.floor(current.length / 2);
|
||||
const children = [[batch.start, middle], [middle, batch.end]].map(([start, end]) => ({
|
||||
start, end, bytes: byteSize(points.slice(start, end)), attempts: batch.attempts, confirmed: false,
|
||||
deadlineAt: batch.deadlineAt, failure
|
||||
}));
|
||||
state.batches.splice(index, 1, ...children);
|
||||
await persist();
|
||||
index -= 1;
|
||||
break;
|
||||
}
|
||||
if (["invalid", "unknown", "payload_size"].includes(failure.kind)) await pause(failure);
|
||||
if (batch.attempts >= policy.maxAttempts) await pause({ ...failure, code: "INDEXING_TRANSFER_RETRY_EXHAUSTED" });
|
||||
batch.nextAttemptAt = Date.now() + Math.max(failure.retryAfterMs ?? 0, policy.retryDelayMs * 2 ** (batch.attempts - 1));
|
||||
state.phase = "retry_wait";
|
||||
await persist();
|
||||
}
|
||||
}
|
||||
state.phase = "complete";
|
||||
state.failure = undefined;
|
||||
await persist();
|
||||
} finally { clearInterval(heartbeat); await writes; }
|
||||
}
|
||||
|
|
@ -61,9 +61,13 @@ test("OpenAPI describes authenticated OCR ingestion, status, review, approval, a
|
|||
|
||||
test("OpenAPI OCR schemas preserve progress, review evidence, corrections, and decision states", () => {
|
||||
const schemas = api.components.schemas;
|
||||
assert.deepEqual(schemas.OcrPhase!.enum, ["native_extracting", "ocr_queued", "ocr_running", "review_required", "indexing", "ready", "active", "failed", "rejected"]);
|
||||
assert.deepEqual(schemas.OcrPhase!.enum, ["native_extracting", "ocr_queued", "ocr_running", "review_required", "indexing", "indexing_paused", "ready", "active", "failed", "rejected"]);
|
||||
assert.deepEqual(schemas.OcrAccepted!.required, ["accepted", "sourceId", "versionId", "versionNumber", "state", "phase", "statusUrl", "reviewUrl", "activated"]);
|
||||
assert.deepEqual(schemas.IngestionStatus!.required, ["sourceId", "versionId", "state", "phase", "activated", "documents", "error", "statusUrl", "reviewUrl"]);
|
||||
assert.deepEqual((schemas.IngestionStatus!.properties as Record<string, unknown>).indexingTransfer, { $ref: "#/components/schemas/IndexingTransferProgress" });
|
||||
assert.ok(schemas.IndexingTransferProgress!.required?.includes("confirmedBytes"));
|
||||
assert.ok(schemas.IndexingTransferDocument!.required?.includes("lastSignalAt"));
|
||||
assert.ok(schemas.IndexingTransferDocument!.required?.includes("lastProgressAt"));
|
||||
assert.deepEqual(schemas.OcrReview!.required, ["versionId", "sourceId", "state", "candidateSha256", "baseActiveVersionId", "currentActiveVersionId", "activateRequested", "processingFingerprint", "metadataHash", "documents"]);
|
||||
assert.deepEqual((schemas.OcrReviewPage!.properties as Record<string, unknown>).imageUrl, { type: ["string", "null"] });
|
||||
const approvalProperties = schemas.OcrApprovalRequest!.properties as Record<string, { items?: unknown }>;
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { CONTENT_POLICY_VERSION } from "../../src/modules/ocr/content-policy.js"
|
|||
import { chunkDocument, documentalChunkingPolicy } from "../../src/modules/process/chunking.js";
|
||||
import type { VectorStoreClient } from "../../src/modules/vectorstore/client.js";
|
||||
import { buildChunkId, buildVersionedQdrantPointId, normalizeContentForHash, sha256Hex } from "../../src/shared/utils/ids.js";
|
||||
import { IndexingCheckpoint } from "../../src/modules/ingest/indexing-checkpoint.js";
|
||||
|
||||
const versionId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
|
||||
const documentId = "doc:indexed-review";
|
||||
|
|
@ -100,7 +101,7 @@ function candidate(reviewedText: string): ApprovedOcrCandidate {
|
|||
reviewedText, reviewedTextSha256: sha256Hex(reviewedText), processingFingerprint: "fingerprint", metadataHash: "metadata" };
|
||||
}
|
||||
|
||||
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 } = {}) {
|
||||
function harness(pageCount: number, options: { initialRecoveryAttempts?: number; 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);
|
||||
|
|
@ -111,7 +112,7 @@ function harness(pageCount: number, options: { embeddingFailure?: boolean; embed
|
|||
let embedCalls = 0;
|
||||
let embeddingFailure = options.embeddingFailure ?? false;
|
||||
let countFailureOnce = options.countFailureOnce ?? false;
|
||||
let recoveryAttempts = 0;
|
||||
let recoveryAttempts = options.initialRecoveryAttempts ?? 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: options.versionState ?? "indexing", base_active_version_id: "active-1",
|
||||
|
|
@ -150,7 +151,7 @@ function harness(pageCount: number, options: { embeddingFailure?: boolean; embed
|
|||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("SELECT version_id, source_id FROM rag_source_versions")) {
|
||||
return rows[0]!.state === "indexing" && recoveryAttempts < 3
|
||||
return rows[0]!.state === "indexing" && (recoveryAttempts < 3 || statement.includes("interval '15 seconds'"))
|
||||
? { rowCount: 1, rows: [{ version_id: versionId, source_id: rows[0]!.source_id }] }
|
||||
: { rowCount: 0, rows: [] };
|
||||
}
|
||||
|
|
@ -173,6 +174,7 @@ function harness(pageCount: number, options: { embeddingFailure?: boolean; embed
|
|||
return { rowCount: 1, rows: [] };
|
||||
}
|
||||
if (statement.includes("SET error_code = 'OCR_INDEX_RECOVERY_INVALID'")) return { rowCount: 1, rows: [] };
|
||||
if (statement.includes("SET error_code = 'INDEXING_TRANSFER_PAUSED'")) 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() }] };
|
||||
}
|
||||
|
|
@ -208,7 +210,7 @@ function harness(pageCount: number, options: { embeddingFailure?: boolean; embed
|
|||
else points[existing] = chunk;
|
||||
}
|
||||
}, async countVersionPoints() {
|
||||
if (countFailureOnce) { countFailureOnce = false; throw new Error("simulated interruption after deterministic point upsert"); }
|
||||
if (countFailureOnce) { countFailureOnce = false; throw Object.assign(new Error("simulated connection interruption after deterministic point upsert"), { code: "ECONNRESET" }); }
|
||||
return points.length + (options.countOffset ?? 0);
|
||||
} };
|
||||
return { pool: pool as never, embeddings, vectors: vectors as VectorStoreClient, points, sql, rows, mutations,
|
||||
|
|
@ -261,6 +263,53 @@ test("reviewed artifact indexing survives restart and writes canonical versioned
|
|||
assert.doesNotMatch(runtime.sql.join("\n"), /active_version_id\s*=/u);
|
||||
});
|
||||
|
||||
test("fast transfer recovery adopts an approved legacy candidate without waiting thirty minutes or resetting its audit", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-fast-transfer-recovery-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { initialRecoveryAttempts: 3 });
|
||||
for (const [index, page] of pages.entries()) runtime.rows[index].reviewed_text_hash = sha256Hex(page.candidateText);
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
assert.equal(await service.recoverInterruptedTransfers(), 1);
|
||||
assert.equal(runtime.recoveryAttempts(), 3);
|
||||
assert.equal(runtime.embedCalls(), 1);
|
||||
assert.equal(runtime.rows[0].reviewed_by, "reviewer");
|
||||
assert.ok(runtime.sql.some((statement) => statement.includes("interval '15 seconds'")));
|
||||
assert.equal(await service.recoverInterruptedTransfers(), 0);
|
||||
});
|
||||
|
||||
test("a durable paused transfer is not automatically reopened by the fast recovery scan", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-paused-transfer-recovery-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { pages } = await fixture(rootDirectory);
|
||||
const runtime = harness(pages.length, { initialRecoveryAttempts: 3 });
|
||||
await new IndexingCheckpoint(rootDirectory, versionId, documentId, "paused-evidence").save({
|
||||
schemaVersion: "1", pointsSha256: "hash", totalPoints: 1, totalSourcePoints: 1,
|
||||
phase: "paused", updatedAt: Date.now(), lastProgressAt: Date.now(), activeBatch: 0, batches: [],
|
||||
failure: { kind: "connection", code: "INDEXING_TRANSFER_RETRY_EXHAUSTED" }
|
||||
});
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
assert.equal(await service.recoverInterruptedTransfers(), 0);
|
||||
assert.equal(runtime.embedCalls(), 0);
|
||||
assert.equal(runtime.points.length, 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 3);
|
||||
assert.ok(runtime.sql.some((statement) => statement.includes("SET error_code = 'INDEXING_TRANSFER_PAUSED'")));
|
||||
});
|
||||
|
||||
test("overlapping fast recovery scans share one in-flight drain", async () => {
|
||||
let calls = 0;
|
||||
let release!: (result: number) => void;
|
||||
const service = new OcrIndexingService({ recoverInterruptedTransfers() {
|
||||
calls += 1; return new Promise<number>((resolve) => { release = resolve; });
|
||||
} } as never);
|
||||
const first = service.recoverInterruptedTransfers();
|
||||
const second = service.recoverInterruptedTransfers();
|
||||
assert.equal(first, second);
|
||||
release(1);
|
||||
assert.equal(await second, 1);
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
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 }));
|
||||
|
|
@ -298,7 +347,7 @@ test("approved OCR indexing rebuilds every reviewed document with canonical per-
|
|||
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) => {
|
||||
test("approved indexing retries temporary final verification without regenerating vectors 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);
|
||||
|
|
@ -306,15 +355,16 @@ test("approved indexing recovery resumes after an upsert interruption, is idempo
|
|||
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(await service.recoverStaleApprovedVersions(), 1);
|
||||
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.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 1);
|
||||
assert.deepEqual(runtime.points.map(({ id }) => id).sort(), firstWrittenIds);
|
||||
assert.equal(await service.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.recoveryAttempts(), 2);
|
||||
assert.equal(runtime.recoveryAttempts(), 1);
|
||||
assert.equal(runtime.embedCalls(), 1);
|
||||
});
|
||||
|
||||
test("approved indexing recovery stops before claims or vector writes when correction audit differs from the immutable reviewed artifact", async (context) => {
|
||||
|
|
@ -422,7 +472,7 @@ test("administrative recovery rejects mismatched hashes, missing reviewer eviden
|
|||
assert.equal(raced.runtime.mutations.some(({ statement }) => statement.includes("INSERT INTO rag_ocr_recovery_audit")), false);
|
||||
});
|
||||
|
||||
test("best-effort indexing resumes identical points after a partial write without crossing the excluded page", async (context) => {
|
||||
test("best-effort indexing retries verification without rewriting points or crossing an excluded page", async (context) => {
|
||||
const rootDirectory = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-gap-recovery-"));
|
||||
context.after(() => rm(rootDirectory, { recursive: true, force: true }));
|
||||
const { reviewedText, pages } = await fixture(rootDirectory, true);
|
||||
|
|
@ -431,11 +481,12 @@ test("best-effort indexing resumes identical points after a partial write withou
|
|||
reviewed_text_hash: sha256Hex(page.candidateText), content_selection: page.selection
|
||||
});
|
||||
const service = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
await assert.rejects(service.index(candidate(reviewedText)), /simulated interruption/u);
|
||||
assert.equal((await service.index(candidate(reviewedText))).state, "ready");
|
||||
const stablePoints = () => runtime.points.map(({ payload: { indexed_at: _indexedAt, ...payload }, ...point }) => ({ ...point, payload }));
|
||||
const beforeRestart = structuredClone(stablePoints());
|
||||
const restarted = new OcrIndexingService(new PostgresOcrIndexingStore(runtime.pool, rootDirectory, runtime.embeddings, runtime.vectors));
|
||||
assert.equal(await restarted.recoverStaleApprovedVersions(), 1);
|
||||
assert.equal(await restarted.recoverStaleApprovedVersions(), 0);
|
||||
assert.equal(runtime.embedCalls(), 1);
|
||||
assert.deepEqual(stablePoints(), beforeRestart);
|
||||
assert.equal(new Set(runtime.points.map(({ id }) => id)).size, runtime.points.length);
|
||||
assert.ok(runtime.points.every(({ payload }) => !String(payload.content).includes("garbled")));
|
||||
|
|
@ -455,8 +506,11 @@ test("identity, corrupt artifact, embedding, and partial-write failures remain f
|
|||
{ name: "embedding", runtime: harness(pages.length, { embeddingFailure: true }), value: candidate(reviewedText) },
|
||||
{ name: "count", runtime: harness(pages.length, { countOffset: -1 }), value: candidate(reviewedText) }
|
||||
]) {
|
||||
const scenarioRoot = await mkdtemp(path.join(os.tmpdir(), "rag-reviewed-isolated-failure-"));
|
||||
context.after(() => rm(scenarioRoot, { recursive: true, force: true }));
|
||||
await fixture(scenarioRoot);
|
||||
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),
|
||||
await assert.rejects(new OcrIndexingService(new PostgresOcrIndexingStore(scenario.runtime.pool, scenarioRoot, 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);
|
||||
|
|
|
|||
248
tests/vectorstore/transfer.test.ts
Normal file
248
tests/vectorstore/transfer.test.ts
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
import { createApp } from "../../src/app.js";
|
||||
import { env } from "../../src/config/env.js";
|
||||
import { IndexingCheckpoint, readIndexingProgress } from "../../src/modules/ingest/indexing-checkpoint.js";
|
||||
import { classifyTransferFailure, transferPoints, transferPolicy, type TransferJournal, type TransferPoint,
|
||||
type TransferState, type TransferTransport } from "../../src/modules/vectorstore/transfer.js";
|
||||
import { sha256Hex } from "../../src/shared/utils/ids.js";
|
||||
|
||||
const versionId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
|
||||
const fastPolicy = { ...transferPolicy, maxBytes: 600, attemptTimeoutMs: 200, totalTimeoutMs: 2_000,
|
||||
heartbeatMs: 5, retryDelayMs: 1, verificationIntervalMs: 2 };
|
||||
|
||||
function points(count = 6): TransferPoint[] {
|
||||
return Array.from({ length: count }, (_, index) => ({ id: `point-${index}`, vector: [0.1, 0.2, 0.3],
|
||||
payload: { source_version_id: versionId, content: `Text ${index} ${"x".repeat(50)}` } }));
|
||||
}
|
||||
|
||||
function memoryJournal() {
|
||||
let state: TransferState | undefined;
|
||||
const snapshots: TransferState[] = [];
|
||||
const journal: TransferJournal = { async load() { return state && structuredClone(state); },
|
||||
async save(next) { state = structuredClone(next); snapshots.push(structuredClone(next)); } };
|
||||
return { journal, snapshots, state: () => state! };
|
||||
}
|
||||
|
||||
function transportHarness() {
|
||||
const stored = new Set<string>();
|
||||
const sent: string[][] = [];
|
||||
const transport: TransferTransport = { async verify(batch) { return batch.every(({ id }) => stored.has(id)); },
|
||||
async send(batch) { sent.push(batch.map(({ id }) => id)); for (const { id } of batch) stored.add(id); return "completed"; } };
|
||||
return { transport, stored, sent };
|
||||
}
|
||||
|
||||
test("expected connection, server, quota, payload and deterministic failures are classified", () => {
|
||||
assert.equal(classifyTransferFailure({ cause: { code: "ECONNRESET" } }).kind, "connection");
|
||||
assert.equal(classifyTransferFailure({ code: "ENOTFOUND" }).kind, "connection");
|
||||
assert.equal(classifyTransferFailure({ name: "AbortError" }).kind, "timeout");
|
||||
assert.equal(classifyTransferFailure({ status: 503 }).kind, "server");
|
||||
assert.deepEqual(classifyTransferFailure({ status: 429, headers: { "retry-after": "2" } }),
|
||||
{ kind: "overloaded", code: "INDEXING_TRANSFER_OVERLOADED", httpStatus: 429, retryAfterMs: 2000 });
|
||||
assert.equal(classifyTransferFailure({ status: 400, data: { error: "JSON payload is larger than allowed limit" } }).kind, "payload_size");
|
||||
assert.equal(classifyTransferFailure({ status: 401 }).kind, "invalid");
|
||||
assert.equal(classifyTransferFailure({ statusCode: 503, code: "EMBEDDING_DIMENSIONS_INVALID" }).kind, "invalid");
|
||||
assert.equal(classifyTransferFailure(new Error("unrecognized failure")).kind, "unknown");
|
||||
});
|
||||
|
||||
test("three failed attempts pause durably and a later invocation cannot reset the budget", async () => {
|
||||
const h = memoryJournal();
|
||||
let sends = 0;
|
||||
const transport: TransferTransport = { async verify() { return false; }, async send() { sends += 1; throw { status: 503 }; } };
|
||||
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /RETRY_EXHAUSTED/u);
|
||||
assert.equal(sends, 3);
|
||||
assert.equal(h.state().phase, "paused");
|
||||
assert.equal(h.state().batches[0].attempts, 3);
|
||||
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /RETRY_EXHAUSTED/u);
|
||||
assert.equal(sends, 3);
|
||||
});
|
||||
|
||||
test("timeouts abort the actual pending operation, rather than merely abandoning its promise", async () => {
|
||||
const h = memoryJournal();
|
||||
let aborts = 0;
|
||||
let pending = 0;
|
||||
const transport: TransferTransport = { async verify() { return false; }, send(_batch, signal) {
|
||||
pending += 1;
|
||||
return new Promise((_resolve, reject) => signal.addEventListener("abort", () => {
|
||||
pending -= 1; aborts += 1; reject(signal.reason);
|
||||
}, { once: true }));
|
||||
} };
|
||||
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, { ...fastPolicy, attemptTimeoutMs: 20 }), /RETRY_EXHAUSTED/u);
|
||||
assert.equal(aborts, 3);
|
||||
assert.equal(pending, 0);
|
||||
});
|
||||
|
||||
test("Retry-After is honored and cannot extend the total persisted deadline", async () => {
|
||||
const h = memoryJournal();
|
||||
let sends = 0;
|
||||
const transport: TransferTransport = { async verify() { return false; }, async send() {
|
||||
sends += 1; throw { status: 429, headers: new Headers({ "retry-after": "60" }) };
|
||||
} };
|
||||
await assert.rejects(transferPoints(points(1), transport, { journal: h.journal }, fastPolicy), /BUDGET_EXHAUSTED/u);
|
||||
assert.equal(sends, 1);
|
||||
assert.equal(h.state().phase, "paused");
|
||||
assert.ok(h.snapshots.some(({ phase }) => phase === "retry_wait"));
|
||||
});
|
||||
|
||||
test("an explicit smaller server payload limit splits the affected batch and retains deadlines and attempt counts", async () => {
|
||||
const h = memoryJournal();
|
||||
const stored = new Set<string>();
|
||||
const sizes: number[] = [];
|
||||
const transport: TransferTransport = { async verify(batch) { return batch.every(({ id }) => stored.has(id)); }, async send(batch) {
|
||||
sizes.push(batch.length);
|
||||
if (batch.length > 2) throw { status: 413 };
|
||||
for (const { id } of batch) stored.add(id);
|
||||
return "completed";
|
||||
} };
|
||||
await transferPoints(points(4), transport, { journal: h.journal }, { ...fastPolicy, maxBytes: 2000 });
|
||||
assert.deepEqual(sizes, [4, 2, 2]);
|
||||
assert.equal(stored.size, 4);
|
||||
assert.ok(h.state().batches.every(({ attempts }) => attempts === 2));
|
||||
assert.equal(new Set(h.state().batches.map(({ deadlineAt }) => deadlineAt)).size, 1);
|
||||
});
|
||||
|
||||
test("heartbeats persist activity during an in-flight operation without inventing confirmed progress", async () => {
|
||||
const h = memoryJournal();
|
||||
const base = transportHarness();
|
||||
let release: (() => void) | undefined;
|
||||
let sendingSignals = 0;
|
||||
const journal: TransferJournal = { load: h.journal.load, async save(state) {
|
||||
await h.journal.save(state);
|
||||
if (state.phase === "sending" && ++sendingSignals >= 3) release?.();
|
||||
} };
|
||||
const transport: TransferTransport = { verify: base.transport.verify, async send(batch, signal) {
|
||||
await new Promise<void>((resolve) => { release = resolve; });
|
||||
return base.transport.send(batch, signal);
|
||||
} };
|
||||
await transferPoints(points(1), transport, { journal }, fastPolicy);
|
||||
const sending = h.snapshots.filter(({ phase }) => phase === "sending");
|
||||
assert.ok(sending.length >= 3);
|
||||
assert.ok(sending.at(-1)!.updatedAt > sending[0].updatedAt);
|
||||
assert.ok(sending.every((state) => state.batches.every(({ confirmed }) => !confirmed)));
|
||||
assert.equal(h.state().phase, "complete");
|
||||
});
|
||||
|
||||
test("slow checkpoint storage coalesces periodic signals instead of accumulating an unbounded write queue", async () => {
|
||||
const h = memoryJournal();
|
||||
let writes = 0;
|
||||
const journal: TransferJournal = { load: h.journal.load, async save(state) {
|
||||
writes += 1; await sleep(10); await h.journal.save(state);
|
||||
} };
|
||||
await transferPoints(points(1), transportHarness().transport, { journal }, { ...fastPolicy, heartbeatMs: 1 });
|
||||
assert.equal(h.state().phase, "complete");
|
||||
assert.ok(writes < 25, `Unexpected write backlog: ${writes}`);
|
||||
});
|
||||
|
||||
test("vector preparation retries temporary failures and later processes reload the persisted result", async (t) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "rag-vector-preparation-retry-"));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
let calls = 0;
|
||||
const cached = await checkpoint.preparePoints(async () => {
|
||||
calls += 1;
|
||||
if (calls < 3) throw { status: 503 };
|
||||
return points(1);
|
||||
}, 1, 1, { ...fastPolicy, heartbeatMs: 20, attemptTimeoutMs: 2000, totalTimeoutMs: 10000 });
|
||||
assert.equal(calls, 3);
|
||||
const restarted = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
assert.deepEqual(await restarted.preparePoints(async () => { calls += 1; throw new Error("must not call provider again"); }, 1, 1), cached);
|
||||
assert.equal(calls, 3);
|
||||
});
|
||||
|
||||
test("a persisted deadline exhausted during downtime pauses before any new request", async () => {
|
||||
const h = memoryJournal();
|
||||
await transferPoints(points(1), { async verify() { return false; }, async send() { throw { status: 429, headers: { "retry-after": "60" } }; } },
|
||||
{ journal: h.journal }, fastPolicy).catch(() => {});
|
||||
const state = h.state();
|
||||
state.phase = "retry_wait"; state.failure = undefined;
|
||||
state.batches[0].deadlineAt = Date.now() - 1;
|
||||
await h.journal.save(state);
|
||||
const transport = transportHarness();
|
||||
await assert.rejects(transferPoints(points(1), transport.transport, { journal: h.journal }, fastPolicy), /BUDGET_EXHAUSTED/u);
|
||||
assert.equal(transport.sent.length, 0);
|
||||
});
|
||||
|
||||
test("a restart reloads cached vectors and verifies ambiguous/confirmed batches without retransmitting them", async (t) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "rag-transfer-restart-"));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
const durablePolicy = { ...fastPolicy, heartbeatMs: 20, attemptTimeoutMs: 5000, totalTimeoutMs: 20000 };
|
||||
let embeddingCalls = 0;
|
||||
const input = await checkpoint.preparePoints(async () => { embeddingCalls += 1; return points(); }, 6, 6, durablePolicy);
|
||||
const h = transportHarness();
|
||||
const crash: TransferJournal = { load: () => checkpoint.load(), async save(state) {
|
||||
await checkpoint.save(state);
|
||||
if (state.activeBatch === 1 && state.phase === "verifying") throw new Error("simulated process loss after durable checkpoint");
|
||||
} };
|
||||
await assert.rejects(transferPoints(input, h.transport, { journal: crash }, durablePolicy), /simulated process loss/u);
|
||||
const before = await readIndexingProgress(root, versionId);
|
||||
assert.ok(before!.confirmedPoints > 0 && before!.confirmedPoints < 6);
|
||||
const restarted = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
const cached = await restarted.preparePoints(async () => { embeddingCalls += 1; throw new Error("must not regenerate vectors"); }, 6, 6, durablePolicy);
|
||||
await transferPoints(cached, h.transport, { journal: restarted }, durablePolicy);
|
||||
assert.equal(embeddingCalls, 1);
|
||||
assert.equal(h.stored.size, 6);
|
||||
assert.equal(new Set(h.sent.flat()).size, h.sent.flat().length);
|
||||
const after = await readIndexingProgress(root, versionId);
|
||||
assert.equal(after!.confirmedPoints, 6);
|
||||
assert.equal(after!.paused, false);
|
||||
const missing = cached[0].id;
|
||||
h.stored.delete(missing);
|
||||
await transferPoints(cached, h.transport, { journal: restarted }, durablePolicy);
|
||||
assert.equal(h.stored.size, 6);
|
||||
assert.ok(h.sent.at(-1)!.includes(missing));
|
||||
assert.equal(embeddingCalls, 1);
|
||||
});
|
||||
|
||||
test("cached vector corruption fails before any new embedding request", async (t) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "rag-vector-cache-integrity-"));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
await checkpoint.preparePoints(async () => points(1), 1, 1, fastPolicy);
|
||||
const file = path.join(root, versionId, "indexing", `${sha256Hex("doc:book")}.points.json`);
|
||||
const value = JSON.parse(await readFile(file, "utf8"));
|
||||
value.points[0].vector[0] = 0.9;
|
||||
await writeFile(file, JSON.stringify(value), { mode: 0o600 });
|
||||
let calls = 0;
|
||||
await assert.rejects(checkpoint.preparePoints(async () => { calls += 1; return points(1); }, 1, 1, fastPolicy), /integrity mismatch/u);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test("authenticated ingestion status exposes progress without returning cached vectors", async (t) => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "rag-transfer-status-"));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const previous = { ocrIngestEnabled: env.ocrIngestEnabled, ocrArtifactRoot: env.ocrArtifactRoot, lifecycleAdminToken: env.lifecycleAdminToken };
|
||||
Object.assign(env, { ocrIngestEnabled: true, ocrArtifactRoot: root, lifecycleAdminToken: "local-transfer-status-token" });
|
||||
t.after(() => Object.assign(env, previous));
|
||||
const checkpoint = new IndexingCheckpoint(root, versionId, "doc:book", "identity");
|
||||
const h = transportHarness();
|
||||
await transferPoints(points(1), h.transport, { journal: checkpoint }, fastPolicy);
|
||||
const app = createApp({ startReconciler: false, catalog: { async getIngestionStatus() {
|
||||
return { versionId, state: "indexing", phase: "indexing", documents: [] };
|
||||
} } as never, vectorStore: {} as never });
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
t.after(() => { server.closeAllConnections(); server.close(); });
|
||||
await new Promise<void>((resolve) => server.once("listening", resolve));
|
||||
const address = server.address() as { port: number };
|
||||
const url = `http://127.0.0.1:${address.port}/ingestions/${versionId}`;
|
||||
assert.equal((await fetch(url)).status, 401);
|
||||
const response = await fetch(url, { headers: { Authorization: "Bearer local-transfer-status-token" } });
|
||||
assert.equal(response.status, 200);
|
||||
const body = await response.json();
|
||||
assert.equal(body.indexingTransfer.heartbeatMs, 5000);
|
||||
assert.equal(body.indexingTransfer.confirmedPoints, 1);
|
||||
assert.ok(!JSON.stringify(body).includes('"vector"'));
|
||||
const state = (await checkpoint.load())!;
|
||||
state.phase = "paused";
|
||||
state.failure = { kind: "connection", code: "INDEXING_TRANSFER_RETRY_EXHAUSTED" };
|
||||
await checkpoint.save(state);
|
||||
const paused = await (await fetch(url, { headers: { Authorization: "Bearer local-transfer-status-token" } })).json();
|
||||
assert.equal(paused.phase, "indexing_paused");
|
||||
assert.equal(paused.error.code, "INDEXING_TRANSFER_RETRY_EXHAUSTED");
|
||||
assert.equal(paused.error.retryable, false);
|
||||
assert.equal(paused.indexingTransfer.paused, true);
|
||||
});
|
||||
230
tests/vectorstore/upsert.test.ts
Normal file
230
tests/vectorstore/upsert.test.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { QdrantClient } from "@qdrant/js-client-rest";
|
||||
import { env } from "../../src/config/env.js";
|
||||
import { OcrIndexingService, type ApprovedOcrCandidate } from "../../src/modules/ocr/indexing.js";
|
||||
import { verifyVersionedDocuments, writeVersionedDocuments } from "../../src/modules/ingest/versioned-indexing.js";
|
||||
import { QdrantVectorStoreClient } from "../../src/modules/vectorstore/client.js";
|
||||
import type { IngestedChunk } from "../../src/shared/types/rag.js";
|
||||
import { transferPolicy } from "../../src/modules/vectorstore/transfer.js";
|
||||
|
||||
const requestBudget = 8 * 1024 * 1024;
|
||||
const versionId = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
|
||||
type Point = Pick<IngestedChunk, "id" | "vector" | "payload">;
|
||||
|
||||
async function httpHarness(t: TestContext, dimensions: number, policy = transferPolicy) {
|
||||
const requests: Array<{ bytes: number; ids: string[]; wait: string | null }> = [];
|
||||
const stored = new Map<string, Point>();
|
||||
const control = { failRequest: 0, failStatus: 400, retryAfter: "", dropResponse: 0, holdResponse: 0, abortedResponses: 0, responseStatus: "completed", countOffset: 0 };
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url!, "http://localhost");
|
||||
const respond = (result: unknown, status = 200) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ result, status: status === 200 ? "ok" : { error: "simulated batch failure" }, time: 0 }));
|
||||
};
|
||||
if (req.method === "GET") {
|
||||
respond(url.pathname === "/collections" ? { collections: [{ name: env.qdrantCollection }] } : {
|
||||
config: { params: { vectors: { size: dimensions } } },
|
||||
payload_schema: Object.fromEntries(["source_id", "source_version_id", "document_id", "chunk_mode", "tags"].map((key) => [key, {}]))
|
||||
});
|
||||
return;
|
||||
}
|
||||
const buffers: Buffer[] = [];
|
||||
for await (const buffer of req) buffers.push(Buffer.from(buffer));
|
||||
const raw = Buffer.concat(buffers);
|
||||
const body = JSON.parse(raw.toString("utf8"));
|
||||
if (url.pathname.endsWith("/points/count")) {
|
||||
assert.equal(body.exact, true);
|
||||
const id = body.filter.must[0].match.value;
|
||||
respond({ count: [...stored.values()].filter((point) => point.payload.source_version_id === id).length + control.countOffset });
|
||||
return;
|
||||
}
|
||||
if (req.method === "POST" && url.pathname.endsWith("/points")) {
|
||||
respond(body.ids.flatMap((id: string) => stored.has(id) ? [stored.get(id)] : []));
|
||||
return;
|
||||
}
|
||||
assert.equal(req.method, "PUT");
|
||||
assert.ok(url.pathname.endsWith("/points"));
|
||||
const points: Point[] = body.points;
|
||||
requests.push({ bytes: raw.length, ids: points.map(({ id }) => id), wait: url.searchParams.get("wait") });
|
||||
if (requests.length === control.failRequest || raw.length > 32 * 1024 * 1024) {
|
||||
if (control.retryAfter) res.setHeader("Retry-After", control.retryAfter);
|
||||
respond(null, control.failStatus);
|
||||
return;
|
||||
}
|
||||
if (control.responseStatus === "completed") {
|
||||
for (const point of points) stored.set(point.id, point);
|
||||
}
|
||||
if (requests.length === control.dropResponse) { res.destroy(); return; }
|
||||
if (requests.length === control.holdResponse) { res.on("close", () => { control.abortedResponses += 1; }); return; }
|
||||
respond({ status: control.responseStatus, operation_id: requests.length });
|
||||
} catch (error) {
|
||||
res.writeHead(500, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ status: { error: String(error) } }));
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
t.after(() => new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => error ? reject(error) : resolve());
|
||||
server.closeAllConnections();
|
||||
}));
|
||||
const client = new QdrantClient({ url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, checkCompatibility: false, timeout: Infinity });
|
||||
return { vectors: new QdrantVectorStoreClient(client, { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, apiKey: "" }, policy), requests, stored, control };
|
||||
}
|
||||
|
||||
function chunks(count: number, dimensions = 3): IngestedChunk[] {
|
||||
const vector = Array(dimensions).fill(0.12345678901234568);
|
||||
return Array.from({ length: count }, (_, index) => ({
|
||||
id: `00000000-0000-4000-8000-${index.toString(16).padStart(12, "0")}`, vector,
|
||||
payload: { source_id: "test:book", source_version_id: versionId, content: `Page content ${index}` }
|
||||
}));
|
||||
}
|
||||
|
||||
test("a 740-point, 4096-dimensional document crosses the old limit but all HTTP batches fit", async (t) => {
|
||||
const input = chunks(740, 4096);
|
||||
assert.ok(Buffer.byteLength(JSON.stringify({ points: input })) > 32 * 1024 * 1024);
|
||||
const h = await httpHarness(t, 4096);
|
||||
await h.vectors.upsert(input);
|
||||
assert.ok(h.requests.length > 1);
|
||||
assert.ok(h.requests.every((request) => request.bytes <= requestBudget && request.wait === "true"));
|
||||
assert.deepEqual(h.requests.flatMap(({ ids }) => ids), input.map(({ id }) => id));
|
||||
assert.equal(await h.vectors.countVersionPoints(versionId), 740);
|
||||
assert.deepEqual(h.stored.get(input[739]!.id), input[739]);
|
||||
});
|
||||
|
||||
test("a temporary server error retries only the affected batch", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, maxBytes: 15_000, retryDelayMs: 1 });
|
||||
h.control.failRequest = 2;
|
||||
h.control.failStatus = 503;
|
||||
const input = chunks(300);
|
||||
await h.vectors.upsert(input);
|
||||
assert.deepEqual(h.requests[1].ids, h.requests[2].ids);
|
||||
assert.equal(h.stored.size, input.length);
|
||||
assert.ok(!h.requests.slice(1).some(({ ids }) => ids.includes(input[0].id)));
|
||||
});
|
||||
|
||||
test("a lost response is resolved by verifying stored IDs before any resend", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, retryDelayMs: 1 });
|
||||
h.control.dropResponse = 1;
|
||||
await h.vectors.upsert(chunks(30));
|
||||
assert.equal(h.requests.length, 1);
|
||||
assert.equal(h.stored.size, 30);
|
||||
});
|
||||
|
||||
test("the HTTP request is actually cancelled on timeout and an applied batch is not resent", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, attemptTimeoutMs: 100, totalTimeoutMs: 2000, heartbeatMs: 10, retryDelayMs: 1 });
|
||||
h.control.holdResponse = 1;
|
||||
await h.vectors.upsert(chunks(10));
|
||||
assert.equal(h.requests.length, 1);
|
||||
assert.equal(h.control.abortedResponses, 1);
|
||||
assert.equal(h.stored.size, 10);
|
||||
});
|
||||
|
||||
test("HTTP Retry-After retains all digits and pauses when the prescribed delay exceeds the budget", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, totalTimeoutMs: 2000 });
|
||||
h.control.failRequest = 1; h.control.failStatus = 429; h.control.retryAfter = "60";
|
||||
let snapshot: import("../../src/modules/vectorstore/transfer.js").TransferState | undefined;
|
||||
await assert.rejects(h.vectors.upsert(chunks(10), { journal: {
|
||||
async load() { return undefined; }, async save(state) { snapshot = structuredClone(state); }
|
||||
} }), /BUDGET_EXHAUSTED/u);
|
||||
assert.equal(h.requests.length, 1);
|
||||
assert.equal(snapshot!.batches[0].failure?.retryAfterMs, 60000);
|
||||
});
|
||||
|
||||
test("small points are sized only by bytes, without an artificial point-count limit", async (t) => {
|
||||
const h = await httpHarness(t, 3);
|
||||
await h.vectors.upsert(chunks(257));
|
||||
assert.deepEqual(h.requests.map(({ ids }) => ids.length), [257]);
|
||||
assert.equal(h.stored.size, 257);
|
||||
});
|
||||
|
||||
test("UTF-8 payload bytes, rather than character count, bound requests", async (t) => {
|
||||
const h = await httpHarness(t, 3);
|
||||
const input = chunks(3);
|
||||
for (const point of input) point.payload.content = "é".repeat(1_500_000);
|
||||
await h.vectors.upsert(input);
|
||||
assert.deepEqual(h.requests.map(({ ids }) => ids.length), [2, 1]);
|
||||
assert.ok(h.requests.every(({ bytes }) => bytes <= requestBudget));
|
||||
assert.deepEqual(h.stored.get(input[2]!.id), input[2]);
|
||||
});
|
||||
|
||||
test("an oversized individual point is rejected before any batch is written", async (t) => {
|
||||
const h = await httpHarness(t, 3);
|
||||
const input = chunks(130);
|
||||
input[129]!.payload.content = "x".repeat(requestBudget);
|
||||
await assert.rejects(h.vectors.upsert(input), /INDEXING_TRANSFER_POINT_TOO_LARGE/u);
|
||||
assert.equal(h.requests.length, 0);
|
||||
assert.equal(h.stored.size, 0);
|
||||
});
|
||||
|
||||
test("empty input is a no-op and inconsistent dimensions fail before writes", async (t) => {
|
||||
const h = await httpHarness(t, 3);
|
||||
await h.vectors.upsert([]);
|
||||
const input = chunks(130);
|
||||
input[129]!.vector = [0.1];
|
||||
await assert.rejects(h.vectors.upsert(input), /consistent dimensions/u);
|
||||
assert.equal(h.requests.length, 0);
|
||||
});
|
||||
|
||||
test("an acknowledged batch is verified and bounded by three timed attempts", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, attemptTimeoutMs: 100, totalTimeoutMs: 400,
|
||||
heartbeatMs: 10, retryDelayMs: 1, verificationIntervalMs: 5 });
|
||||
h.control.responseStatus = "acknowledged";
|
||||
await assert.rejects(h.vectors.upsert(chunks(300)), /INDEXING_TRANSFER_RETRY_EXHAUSTED/u);
|
||||
assert.equal(h.requests.length, 3);
|
||||
assert.equal(h.stored.size, 0);
|
||||
});
|
||||
|
||||
test("partial HTTP failure retries the same IDs and activates only after the global count matches", async (t) => {
|
||||
const h = await httpHarness(t, 3, { ...transferPolicy, maxBytes: 80_000 });
|
||||
const document = { documentId: "doc:book", documentKey: "book.pdf", contentHash: "content-hash", title: "Book",
|
||||
mimeType: "application/pdf", chunkMode: "documental" as const,
|
||||
chunks: Array.from({ length: 300 }, (_, index) => ({ index, sectionTitle: "Book", startLine: index + 1, endLine: index + 1, content: `Text ${index}` })) };
|
||||
let readyCount = 0;
|
||||
let activated = false;
|
||||
const service = new OcrIndexingService({
|
||||
async findReusableVersion() { return undefined; },
|
||||
async indexReviewed() {
|
||||
const written = await writeVersionedDocuments({
|
||||
identity: { sourceId: "test:book", versionId, versionNumber: 1, sourceType: "file", sourceRef: "book.pdf", tags: [],
|
||||
processingFingerprint: "fingerprint", expectedEmbeddingDimensions: 3 },
|
||||
documents: [document], vectorStore: h.vectors,
|
||||
embeddingProvider: { providerName: "test", modelName: "test", dimensions: 3, async embed(input) { return input.map(() => [0.1, 0.2, 0.3]); } }
|
||||
});
|
||||
return verifyVersionedDocuments({ versionId, expectedPointCount: 300, chunksWritten: written, vectorStore: h.vectors });
|
||||
},
|
||||
async markReady(_id, count) { readyCount = count; },
|
||||
async activateVersion() { assert.equal(readyCount, 300); activated = true; return versionId; },
|
||||
async settleReusable() { throw new Error("Unexpected reuse"); }
|
||||
});
|
||||
const candidate: ApprovedOcrCandidate = { versionId, sourceId: "test:book", state: "indexing", activateRequested: true,
|
||||
expectedActiveVersionId: null, reviewedText: "reviewed", reviewedTextSha256: "hash", processingFingerprint: "fingerprint", metadataHash: "metadata" };
|
||||
h.control.failRequest = 2;
|
||||
await assert.rejects(service.index(candidate));
|
||||
assert.equal(h.requests.length, 2);
|
||||
assert.equal(h.stored.size, h.requests[0]!.ids.length);
|
||||
assert.ok(h.stored.size > 0 && h.stored.size < 300);
|
||||
const initialIds = [...h.stored.keys()];
|
||||
assert.equal(readyCount, 0);
|
||||
assert.equal(activated, false);
|
||||
|
||||
h.control.failRequest = 0;
|
||||
h.control.countOffset = -1;
|
||||
await assert.rejects(service.index(candidate), /expected catalog count/u);
|
||||
assert.equal(h.stored.size, 300);
|
||||
assert.equal(readyCount, 0);
|
||||
assert.equal(activated, false);
|
||||
|
||||
h.control.countOffset = 0;
|
||||
const result = await service.index(candidate);
|
||||
assert.equal(result.state, "active");
|
||||
assert.equal(result.activated, true);
|
||||
assert.equal(h.stored.size, 300);
|
||||
assert.deepEqual(h.requests[2]!.ids, h.requests[1]!.ids);
|
||||
assert.equal(h.requests.filter(({ ids }) => ids.includes(initialIds[0])).length, 1);
|
||||
assert.equal(readyCount, 300);
|
||||
assert.equal(activated, true);
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue