2026-09-29 08:42:31 +00:00
|
|
|
"""Document indexing phases and their application-owned persistence and execution ports."""
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
|
import time
|
|
|
|
|
from collections.abc import Callable, Mapping, Sequence
|
|
|
|
|
from dataclasses import dataclass
|
2026-11-19 17:53:51 +08:00
|
|
|
from enum import StrEnum
|
|
|
|
|
from typing import Protocol
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
from core.credit_usage import CreditUsageCreatedBy
|
|
|
|
|
from core.model_context import with_credit_usage_created_by
|
|
|
|
|
from core.rag.models.document import Document
|
2026-10-30 16:13:53 +08:00
|
|
|
from services.extraction.contracts import ExtractionResult
|
|
|
|
|
from services.knowledge.entities.resource_scope import DocumentRef
|
|
|
|
|
from services.knowledge.indexing.contracts import IndexingDocument
|
2026-09-29 08:42:31 +00:00
|
|
|
from services.knowledge.indexing.errors import DocumentIsDeletedPausedError, DocumentIsPausedError
|
2026-10-30 16:13:53 +08:00
|
|
|
from services.knowledge.indexing.locks import (
|
|
|
|
|
KnowledgeIndexingLease,
|
|
|
|
|
KnowledgeIndexingLeaseLostError,
|
|
|
|
|
KnowledgeIndexingLock,
|
|
|
|
|
document_index_lock_name,
|
|
|
|
|
)
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
2026-10-30 16:13:53 +08:00
|
|
|
class IndexingTransformResult:
|
|
|
|
|
chunks: list[Document]
|
|
|
|
|
created_upload_file_ids: tuple[str, ...] = ()
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class IndexingDocumentStore(Protocol):
|
|
|
|
|
def get_indexing_document(self, ref: DocumentRef) -> IndexingDocument | None: ...
|
|
|
|
|
|
2026-10-30 16:13:53 +08:00
|
|
|
def mark_splitting(self, ref: DocumentRef, *, source_version: str | None = None) -> None: ...
|
2026-09-29 08:42:31 +00:00
|
|
|
|
2026-10-30 16:13:53 +08:00
|
|
|
def complete_indexing(
|
|
|
|
|
self,
|
|
|
|
|
ref: DocumentRef,
|
|
|
|
|
*,
|
|
|
|
|
tokens: int,
|
|
|
|
|
latency: float,
|
|
|
|
|
) -> None: ...
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
def fail_indexing(self, ref: DocumentRef, error: str) -> None: ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class IndexingSegmentStore(Protocol):
|
|
|
|
|
def save_for_indexing(
|
2026-10-30 16:13:53 +08:00
|
|
|
self,
|
|
|
|
|
document: IndexingDocument,
|
|
|
|
|
chunks: list[Document],
|
|
|
|
|
token_counts: list[int],
|
|
|
|
|
) -> tuple[str, ...]: ...
|
|
|
|
|
|
|
|
|
|
def get_pending_upload_cleanup_ids(self, document: IndexingDocument) -> tuple[str, ...]: ...
|
|
|
|
|
|
|
|
|
|
def acknowledge_upload_cleanup(self, document: IndexingDocument, processed_file_ids: Sequence[str]) -> None: ...
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
def resume_indexing(self, document: IndexingDocument) -> tuple[list[Document], int]: ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class IndexingBackend(Protocol):
|
|
|
|
|
def describe_error(self, error: Exception) -> str:
|
|
|
|
|
"""Translate backend-specific exceptions into the persisted error message."""
|
|
|
|
|
...
|
|
|
|
|
|
|
|
|
|
def check_paused(self, ref: DocumentRef) -> None: ...
|
|
|
|
|
|
2026-10-30 16:13:53 +08:00
|
|
|
def extract(self, document: IndexingDocument) -> ExtractionResult[Document]: ...
|
2026-09-29 08:42:31 +00:00
|
|
|
|
2026-10-30 16:13:53 +08:00
|
|
|
def cleanup_created_upload_files(self, document: IndexingDocument, file_ids: Sequence[str]) -> None: ...
|
|
|
|
|
|
|
|
|
|
def reclaim_upload_files(self, document: IndexingDocument, file_ids: Sequence[str]) -> None: ...
|
|
|
|
|
|
|
|
|
|
def transform(self, document: IndexingDocument, texts: list[Document]) -> IndexingTransformResult: ...
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
def ensure_admission(self, document: IndexingDocument, chunks: list[Document]) -> None: ...
|
|
|
|
|
|
|
|
|
|
def count_tokens(self, document: IndexingDocument, chunks: list[Document]) -> list[int]: ...
|
|
|
|
|
|
|
|
|
|
def load(self, document: IndexingDocument, chunks: list[Document]) -> None: ...
|
|
|
|
|
|
2026-10-26 05:24:08 +00:00
|
|
|
def discard(self, document: IndexingDocument, chunks: list[Document]) -> None:
|
|
|
|
|
"""Remove index entries that ``load`` may have written for a document deleted meanwhile."""
|
|
|
|
|
...
|
|
|
|
|
|
2026-09-29 08:42:31 +00:00
|
|
|
|
2026-11-19 17:53:51 +08:00
|
|
|
class _IndexingPhase(StrEnum):
|
|
|
|
|
PARSING = "parsing"
|
|
|
|
|
SPLITTING = "splitting"
|
|
|
|
|
INDEXING = "indexing"
|
|
|
|
|
|
|
|
|
|
|
2026-09-29 08:42:31 +00:00
|
|
|
class DocumentIndexingService:
|
|
|
|
|
"""Coordinate committed phases; no caller session is held across execution."""
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
*,
|
|
|
|
|
documents: IndexingDocumentStore,
|
|
|
|
|
segments: IndexingSegmentStore,
|
|
|
|
|
backend: IndexingBackend,
|
2026-10-30 16:13:53 +08:00
|
|
|
indexing_locks: KnowledgeIndexingLock,
|
2026-09-29 08:42:31 +00:00
|
|
|
enforce_vector_space_admission: bool = False,
|
|
|
|
|
clock: Callable[[], float] = time.perf_counter,
|
|
|
|
|
) -> None:
|
|
|
|
|
self._documents = documents
|
|
|
|
|
self._segments = segments
|
|
|
|
|
self._backend = backend
|
2026-10-30 16:13:53 +08:00
|
|
|
self._indexing_locks = indexing_locks
|
2026-09-29 08:42:31 +00:00
|
|
|
self._enforce_vector_space_admission = enforce_vector_space_admission
|
|
|
|
|
self._clock = clock
|
|
|
|
|
|
|
|
|
|
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
|
2026-10-30 16:13:53 +08:00
|
|
|
def run(
|
|
|
|
|
self,
|
|
|
|
|
document_refs: Sequence[DocumentRef],
|
|
|
|
|
*,
|
|
|
|
|
owned_leases: Mapping[str, KnowledgeIndexingLease] | None = None,
|
|
|
|
|
) -> None:
|
2026-09-29 08:42:31 +00:00
|
|
|
for ref in document_refs:
|
2026-10-30 16:13:53 +08:00
|
|
|
self._run_guarded(
|
|
|
|
|
ref,
|
2026-11-19 17:53:51 +08:00
|
|
|
start=_IndexingPhase.PARSING,
|
2026-10-30 16:13:53 +08:00
|
|
|
owned_lease=owned_leases.get(ref.document_id) if owned_leases is not None else None,
|
|
|
|
|
)
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
|
2026-10-30 16:13:53 +08:00
|
|
|
def run_in_splitting_status(
|
|
|
|
|
self,
|
|
|
|
|
ref: DocumentRef,
|
|
|
|
|
*,
|
|
|
|
|
owned_lease: KnowledgeIndexingLease | None = None,
|
|
|
|
|
) -> None:
|
2026-11-19 17:53:51 +08:00
|
|
|
self._run_guarded(ref, start=_IndexingPhase.SPLITTING, owned_lease=owned_lease)
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
|
2026-10-30 16:13:53 +08:00
|
|
|
def run_in_indexing_status(
|
|
|
|
|
self,
|
|
|
|
|
ref: DocumentRef,
|
|
|
|
|
*,
|
|
|
|
|
owned_lease: KnowledgeIndexingLease | None = None,
|
|
|
|
|
) -> None:
|
2026-11-19 17:53:51 +08:00
|
|
|
self._run_guarded(ref, start=_IndexingPhase.INDEXING, owned_lease=owned_lease)
|
2026-09-29 08:42:31 +00:00
|
|
|
|
2026-10-30 16:13:53 +08:00
|
|
|
def _run_guarded(
|
|
|
|
|
self,
|
|
|
|
|
ref: DocumentRef,
|
|
|
|
|
*,
|
2026-11-19 17:53:51 +08:00
|
|
|
start: _IndexingPhase,
|
2026-10-30 16:13:53 +08:00
|
|
|
owned_lease: KnowledgeIndexingLease | None,
|
|
|
|
|
) -> None:
|
|
|
|
|
if owned_lease is not None:
|
|
|
|
|
owned_lease.assert_owned()
|
|
|
|
|
self._run(ref, start=start, lease=owned_lease)
|
|
|
|
|
owned_lease.assert_owned()
|
|
|
|
|
return
|
|
|
|
|
with self._indexing_locks.hold(
|
|
|
|
|
document_index_lock_name(ref.document_id),
|
|
|
|
|
timeout=600,
|
|
|
|
|
blocking_timeout=600,
|
|
|
|
|
) as lease:
|
|
|
|
|
self._run(ref, start=start, lease=lease)
|
|
|
|
|
|
|
|
|
|
def _run(
|
|
|
|
|
self,
|
|
|
|
|
ref: DocumentRef,
|
|
|
|
|
*,
|
2026-11-19 17:53:51 +08:00
|
|
|
start: _IndexingPhase,
|
2026-10-30 16:13:53 +08:00
|
|
|
lease: KnowledgeIndexingLease,
|
|
|
|
|
) -> None:
|
|
|
|
|
document: IndexingDocument | None = None
|
|
|
|
|
created_upload_file_ids: tuple[str, ...] = ()
|
2026-10-26 05:24:08 +00:00
|
|
|
# None: no index write has started, so a deletion leaves nothing behind.
|
|
|
|
|
# Set: load may have written these chunks; document cleanup snapshots segment
|
|
|
|
|
# node ids before deleting them and cannot see entries written after its snapshot,
|
|
|
|
|
# so whichever way this run stops, the entries are discarded if the document is gone.
|
|
|
|
|
loading: tuple[IndexingDocument, list[Document]] | None = None
|
2026-09-29 08:42:31 +00:00
|
|
|
try:
|
|
|
|
|
document = self._documents.get_indexing_document(ref)
|
|
|
|
|
if document is None:
|
|
|
|
|
logger.info("Document not found, skipping indexing: %s", ref)
|
|
|
|
|
return
|
|
|
|
|
self._backend.check_paused(ref)
|
2026-11-19 17:53:51 +08:00
|
|
|
if start == _IndexingPhase.INDEXING:
|
2026-10-30 16:13:53 +08:00
|
|
|
pending_upload_cleanup_ids = self._segments.get_pending_upload_cleanup_ids(document)
|
|
|
|
|
self._reconcile_pending_upload_cleanup(document, pending_upload_cleanup_ids, lease=lease)
|
2026-09-29 08:42:31 +00:00
|
|
|
chunks, total_tokens = self._segments.resume_indexing(document)
|
|
|
|
|
else:
|
2026-10-30 16:13:53 +08:00
|
|
|
extraction = self._backend.extract(document)
|
|
|
|
|
created_upload_file_ids = tuple(artifact.id for artifact in extraction.created_upload_artifacts)
|
|
|
|
|
lease.assert_owned()
|
|
|
|
|
self._documents.mark_splitting(ref, source_version=extraction.source_version)
|
|
|
|
|
transformation = self._backend.transform(document, extraction.documents)
|
|
|
|
|
created_upload_file_ids += transformation.created_upload_file_ids
|
|
|
|
|
chunks = transformation.chunks
|
2026-09-29 08:42:31 +00:00
|
|
|
# Recovery retains its existing admission policy; only normal
|
|
|
|
|
# indexing callers that explicitly opt in reserve vector space.
|
2026-11-19 17:53:51 +08:00
|
|
|
if start == _IndexingPhase.PARSING and self._enforce_vector_space_admission:
|
2026-09-29 08:42:31 +00:00
|
|
|
self._backend.ensure_admission(document, chunks)
|
|
|
|
|
token_counts = self._backend.count_tokens(document, chunks)
|
|
|
|
|
total_tokens = sum(token_counts)
|
2026-10-30 16:13:53 +08:00
|
|
|
lease.assert_owned()
|
|
|
|
|
pending_upload_cleanup_ids = self._segments.save_for_indexing(document, chunks, token_counts)
|
|
|
|
|
self._reconcile_pending_upload_cleanup(document, pending_upload_cleanup_ids, lease=lease)
|
2026-09-29 08:42:31 +00:00
|
|
|
|
|
|
|
|
started = self._clock()
|
|
|
|
|
self._backend.check_paused(ref)
|
2026-10-30 16:13:53 +08:00
|
|
|
lease.assert_owned()
|
2026-10-26 05:24:08 +00:00
|
|
|
loading = (document, chunks)
|
2026-09-29 08:42:31 +00:00
|
|
|
self._backend.load(document, chunks)
|
|
|
|
|
self._backend.check_paused(ref)
|
2026-10-30 16:13:53 +08:00
|
|
|
lease.assert_owned()
|
|
|
|
|
self._documents.complete_indexing(
|
|
|
|
|
ref,
|
|
|
|
|
tokens=total_tokens,
|
|
|
|
|
latency=self._clock() - started,
|
|
|
|
|
)
|
2026-09-29 08:42:31 +00:00
|
|
|
except DocumentIsPausedError:
|
2026-10-30 16:13:53 +08:00
|
|
|
self._cleanup_created_upload_files(document, created_upload_file_ids)
|
2026-10-26 05:24:08 +00:00
|
|
|
# The pause flag is checked before document existence, so a paused document
|
|
|
|
|
# deleted mid-write surfaces here rather than as a deletion.
|
|
|
|
|
self._discard_if_deleted(ref, loading)
|
2026-09-29 08:42:31 +00:00
|
|
|
raise
|
|
|
|
|
except DocumentIsDeletedPausedError:
|
2026-10-30 16:13:53 +08:00
|
|
|
self._cleanup_created_upload_files(document, created_upload_file_ids)
|
2026-09-29 08:42:31 +00:00
|
|
|
logger.info("Document deleted during indexing: %s", ref)
|
2026-10-26 05:24:08 +00:00
|
|
|
self._discard(ref, loading)
|
2026-10-30 16:13:53 +08:00
|
|
|
except KnowledgeIndexingLeaseLostError:
|
|
|
|
|
self._cleanup_created_upload_files(document, created_upload_file_ids)
|
|
|
|
|
raise
|
2026-09-29 08:42:31 +00:00
|
|
|
except Exception as error:
|
2026-10-30 16:13:53 +08:00
|
|
|
self._cleanup_created_upload_files(document, created_upload_file_ids)
|
2026-09-29 08:42:31 +00:00
|
|
|
logger.exception("Document indexing failed: %s", ref)
|
2026-10-30 16:13:53 +08:00
|
|
|
lease.assert_owned()
|
2026-10-30 16:48:14 +08:00
|
|
|
try:
|
|
|
|
|
self._documents.fail_indexing(ref, self._backend.describe_error(error))
|
|
|
|
|
finally:
|
|
|
|
|
# A concurrent deletion can make the failure transition itself
|
|
|
|
|
# raise. It must not suppress compensation for vectors that the
|
|
|
|
|
# preceding load may already have published.
|
|
|
|
|
self._discard_if_deleted(ref, loading)
|
2026-10-30 16:13:53 +08:00
|
|
|
|
|
|
|
|
def _reconcile_pending_upload_cleanup(
|
|
|
|
|
self,
|
|
|
|
|
document: IndexingDocument,
|
|
|
|
|
pending_file_ids: Sequence[str],
|
|
|
|
|
*,
|
|
|
|
|
lease: KnowledgeIndexingLease,
|
|
|
|
|
) -> None:
|
|
|
|
|
if not pending_file_ids:
|
|
|
|
|
return
|
|
|
|
|
lease.assert_owned()
|
|
|
|
|
self._backend.reclaim_upload_files(document, pending_file_ids)
|
|
|
|
|
lease.assert_owned()
|
|
|
|
|
self._segments.acknowledge_upload_cleanup(document, pending_file_ids)
|
|
|
|
|
|
|
|
|
|
def _cleanup_created_upload_files(
|
|
|
|
|
self,
|
|
|
|
|
document: IndexingDocument | None,
|
|
|
|
|
file_ids: Sequence[str],
|
|
|
|
|
) -> None:
|
|
|
|
|
if document is None or not file_ids:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
self._backend.cleanup_created_upload_files(document, file_ids)
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.exception("Failed to clean extraction files after document indexing stopped: %s", document.ref)
|
2026-10-26 05:24:08 +00:00
|
|
|
|
|
|
|
|
def _discard(self, ref: DocumentRef, loading: tuple[IndexingDocument, list[Document]] | None) -> None:
|
|
|
|
|
"""Best-effort removal of entries ``load`` may have written; failures never mask the outcome."""
|
|
|
|
|
if loading is None:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
self._backend.discard(*loading)
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.exception("Failed to discard index entries of document deleted during indexing: %s", ref)
|
|
|
|
|
|
|
|
|
|
def _discard_if_deleted(self, ref: DocumentRef, loading: tuple[IndexingDocument, list[Document]] | None) -> None:
|
|
|
|
|
"""Discard written entries when indexing stopped for another reason and the document is gone."""
|
|
|
|
|
if loading is None:
|
|
|
|
|
return
|
|
|
|
|
try:
|
|
|
|
|
self._documents.get_indexing_document(ref)
|
|
|
|
|
except DocumentIsDeletedPausedError:
|
|
|
|
|
logger.info("Document deleted during indexing: %s", ref)
|
|
|
|
|
self._discard(ref, loading)
|
|
|
|
|
except DocumentIsPausedError:
|
|
|
|
|
return
|
|
|
|
|
except Exception:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Could not check whether document still exists after indexing stopped: %s", ref, exc_info=True
|
|
|
|
|
)
|