docling-studio/document-parser/services/ingestion_service.py
Pier-Jean Malandrino efc27932dd refactor(audit): remediate 0.5.0 audit findings — clean architecture, security, DRY, SOLID, perf
Closes the 12 MAJ raised by the release/0.5.0 audit pipeline (cf.
docs/audit/reports/release-0.5.0/summary.md → summary-reaudit.md).

Volet 1 — Reasoning architecture (audits 01/02/06/07 strengthening)
  * Domain ports: LLMProvider, ReasoningRunner, ReasoningParseError
  * Domain DTOs: LLMProviderType, ReasoningResult, ReasoningIteration
  * infra/llm/ollama_provider.py — OllamaProvider with health_check
  * infra/docling_agent_reasoning.py — runner adapter, encapsulates the
    private _rag_loop call (tracked at docling-project/docling-agent#26),
    commits OLLAMA_HOST once at boot (eliminates the per-request env race),
    translates upstream IndexError into ReasoningParseError
  * api/reasoning.py — zero coupling to docling-agent / mellea / docling-core,
    consumes app.state.reasoning_runner via the port
  * main.py — DI wires OllamaProvider + DoclingAgentReasoningRunner at boot
    when REASONING_ENABLED=true and deps are importable
  * Rename RAG_* env vars → REASONING_*, endpoint /rag → /reasoning,
    type RAGResult → ReasoningResult, frontend feature flag wiring,
    i18n strings, tests, docs (BREAKING — pre-1.0 surface, no external
    consumers in production)
  * 17 new tests: adapter unit tests with sys.modules stubs, OllamaProvider
    httpx tests, R3 concurrent-host isolation, R6 multi-iteration trace
    serialization, R13 Protocol conformance via isinstance
  * E2E Karate scenario: nav-reasoning hidden when REASONING_ENABLED=false
  * README — Live Reasoning section (env vars, archi, link to issue #26)

Bloc B — Security (audit 08, dev-only context)
  * docker-compose.yml — DEV DEFAULTS header, OpenSearch DISABLE_SECURITY_PLUGIN
    flagged as dev-only with link to OpenSearch security docs
  * main.py — boot warning if NEO4J_URI is set with the default 'changeme'
    password, so prod operators can't silently inherit it

Bloc C — DRY frontend (audit 05)
  * shared/storage/keys.ts — STORAGE_KEYS centralised (theme, locale)
  * features/settings/store.ts — dead apiUrl ref + orphan i18n keys removed
  * api/schemas.py — DOCUMENT_STATUS_UPLOADED constant

Bloc D — Quality (audits 02/06/07/09/10/12)
  * domain/ports.py — DocumentConverter.supports_page_batching property
    (LSP fix, replaces isinstance(ServeConverter) check)
  * domain/ports.py — VectorStore.ping() (encapsulation, replaces
    _vector_store._client.info() reach-around)
  * api/analyses.py + api/ingestion.py — path params {job_id} → {analysis_id}
    aligned with the user-facing terminology (URLs unchanged)
  * api/documents.py — Path.read_bytes() + generate_preview() wrapped in
    asyncio.to_thread, unblocks the FastAPI event loop on /preview
  * infra/docling_tree.py — PEP 604 union for isinstance (Ruff UP038)
  * src/__tests__/integration/ — cross-feature integration test relocated
    out of features/history/ so feature folders stay self-contained
  * Tightened terminal `assert X is not None` checks (isinstance(.., datetime),
    exact value comparisons)

Validation
  * 446 backend pytest, 202 frontend vitest — all green
  * ruff + ruff format + ESLint + Prettier + vue-tsc clean
  * Re-audit verdict: 0 CRIT / 0 MAJ, score ~94/100, GO

Closes #200
2026-04-29 14:00:00 +02:00

200 lines
6.6 KiB
Python

"""Ingestion service — orchestrates Docling → embedding → OpenSearch.
Chains the full ingestion pipeline:
1. Convert document via Docling (reuse existing analysis)
2. Chunk with selected strategy
3. Embed all chunk texts via EmbeddingService
4. Index into OpenSearch via VectorStore
Idempotent: re-ingesting a document deletes old chunks before re-indexing.
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING
from domain.vector_schema import (
ChunkBboxEntry,
ChunkOrigin,
IndexedChunk,
build_index_mapping,
)
if TYPE_CHECKING:
from domain.ports import EmbeddingService, VectorStore
logger = logging.getLogger(__name__)
@dataclass
class IngestionConfig:
"""Configuration for the ingestion pipeline."""
index_name: str = "docling-studio-chunks"
embedding_dimension: int = 384
@dataclass
class IngestionResult:
"""Result of an ingestion pipeline run."""
doc_id: str
chunks_indexed: int
embedding_dimension: int
class IngestionService:
"""Orchestrates the embedding + indexing pipeline."""
def __init__(
self,
embedding_service: EmbeddingService,
vector_store: VectorStore,
config: IngestionConfig | None = None,
neo4j_driver=None,
) -> None:
self._embedding = embedding_service
self._vector_store = vector_store
self._config = config or IngestionConfig()
self._neo4j = neo4j_driver
async def ensure_index(self) -> None:
"""Ensure the vector index exists with the correct mapping."""
mapping = build_index_mapping(self._config.embedding_dimension)
await self._vector_store.ensure_index(self._config.index_name, mapping)
async def ingest(
self,
doc_id: str,
filename: str,
chunks_json: str,
*,
binary_hash: str | None = None,
) -> IngestionResult:
"""Run the embedding + indexing pipeline on pre-chunked data.
This method is idempotent: it deletes any existing chunks for the
document before re-indexing.
Args:
doc_id: Unique document identifier.
filename: Original filename.
chunks_json: JSON-serialized list of chunk dicts (from analysis).
binary_hash: Optional hash of the source file for provenance.
Returns:
IngestionResult with the number of chunks indexed.
"""
await self.ensure_index()
chunks_data: list[dict] = json.loads(chunks_json)
active_chunks = [c for c in chunks_data if not c.get("deleted")]
if not active_chunks:
logger.info("No active chunks for doc %s — skipping ingestion", doc_id)
return IngestionResult(doc_id=doc_id, chunks_indexed=0, embedding_dimension=0)
# 1. Embed all chunk texts
texts = [c["text"] for c in active_chunks]
logger.info("Embedding %d chunks for doc %s", len(texts), doc_id)
embeddings = await self._embedding.embed(texts)
# 2. Build IndexedChunk domain objects
origin = (
ChunkOrigin(binary_hash=binary_hash or "", filename=filename) if binary_hash else None
)
indexed_chunks: list[IndexedChunk] = []
for i, (chunk_data, embedding) in enumerate(zip(active_chunks, embeddings, strict=True)):
bboxes = [
ChunkBboxEntry(
page=b["page"],
x=b["bbox"][0] if b.get("bbox") else 0,
y=b["bbox"][1] if b.get("bbox") else 0,
w=(b["bbox"][2] - b["bbox"][0]) if b.get("bbox") and len(b["bbox"]) >= 4 else 0,
h=(b["bbox"][3] - b["bbox"][1]) if b.get("bbox") and len(b["bbox"]) >= 4 else 0,
)
for b in chunk_data.get("bboxes", [])
]
indexed_chunks.append(
IndexedChunk(
doc_id=doc_id,
filename=filename,
content=chunk_data["text"],
embedding=embedding,
chunk_index=i,
chunk_type=chunk_data.get("chunkType", "text"),
page_number=chunk_data.get("sourcePage", 0) or 0,
bboxes=bboxes,
headings=chunk_data.get("headings", []),
origin=origin,
)
)
# 3. Delete old chunks (idempotent re-indexing)
deleted = await self._vector_store.delete_document(self._config.index_name, doc_id)
if deleted:
logger.info("Deleted %d old chunks for doc %s", deleted, doc_id)
# 4. Index new chunks
indexed = await self._vector_store.index_chunks(self._config.index_name, indexed_chunks)
logger.info("Indexed %d/%d chunks for doc %s", indexed, len(indexed_chunks), doc_id)
# 5. Mirror chunks in Neo4j if configured (with DERIVED_FROM edges).
if self._neo4j is not None:
try:
from infra.neo4j import write_chunks
await write_chunks(self._neo4j, doc_id=doc_id, chunks_json=chunks_json)
except Exception:
logger.exception("Neo4j ChunkWriter failed for doc %s", doc_id)
return IngestionResult(
doc_id=doc_id,
chunks_indexed=indexed,
embedding_dimension=len(embeddings[0]) if embeddings else 0,
)
async def delete_document(self, doc_id: str) -> int:
"""Remove all indexed chunks for a document."""
return await self._vector_store.delete_document(self._config.index_name, doc_id)
async def search(
self,
query: str,
*,
k: int = 10,
doc_id: str | None = None,
) -> list:
"""Semantic search: embed the query then find nearest chunks."""
embeddings = await self._embedding.embed([query])
return await self._vector_store.search_similar(
self._config.index_name,
embeddings[0],
k=k,
doc_id=doc_id,
)
async def search_fulltext(
self,
query: str,
*,
k: int = 20,
doc_id: str | None = None,
) -> list:
"""Full-text keyword search in indexed chunks."""
return await self._vector_store.search_fulltext(
self._config.index_name,
query,
k=k,
doc_id=doc_id,
)
async def ping(self) -> bool:
"""Check if the underlying vector store is reachable."""
try:
return await self._vector_store.ping()
except Exception:
logger.debug("Vector store ping failed", exc_info=True)
return False