Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(lightrag): preserve partially accepted ingress

Codexcefc3471f2f8
diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.py
index d59990887..f84ad2069 100644
--- a/deeptutor/services/rag/pipelines/lightrag/engine.py
+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py
@@ -230,6 +230,33 @@ async def enqueue(rag: Any, staged: list[StagedDocument]) -> str:
)
+def _document_id(canonical_name: str) -> str:
+ from lightrag.utils import compute_mdhash_id
+ from lightrag.utils_pipeline import (
+ has_known_document_source,
+ normalize_document_file_path,
+ )
+
+ source = normalize_document_file_path(canonical_name)
+ if not has_known_document_source(source):
+ raise LightRagContractError(
+ f"LightRAG cannot derive a stable document ID for {canonical_name!r}"
+ )
+ return compute_mdhash_id(source, prefix="doc-")
+
+
+async def confirmed_unaccepted(rag: Any, staged: list[StagedDocument]) -> list[StagedDocument]:
+ """Return documents whose missing doc_status row was strictly confirmed."""
+ ids_by_name = {item.canonical_name: _document_id(item.canonical_name) for item in staged}
+ rows = await rag.doc_status.get_docs_by_ids(
+ list(ids_by_name.values()),
+ strict=True,
+ )
+ if not isinstance(rows, dict):
+ raise LightRagContractError("doc_status.get_docs_by_ids must return an object")
+ return [item for item in staged if ids_by_name[item.canonical_name] not in rows]
+
+
def _managed_queue_funcs(rag: Any) -> Iterable[Callable[..., Any]]:
role_funcs = getattr(rag, "role_llm_funcs", {})
candidates: list[object] = list(role_funcs.values()) if isinstance(role_funcs, Mapping) else []
@@ -418,6 +445,7 @@ __all__ = [
"LightRagContractError",
"PARSER_ENGINE",
"build_rag",
+ "confirmed_unaccepted",
"enqueue",
"finalize",
"initialize",
diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
index cbe2c90aa..087c70480 100644
--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py
+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
@@ -285,8 +285,11 @@ class LightRagPipeline:
raise
failed = True
accepted = False
+ enqueue_started = False
+ cleanup: list[ingress.StagedDocument] = []
try:
await engine.initialize(rag)
+ enqueue_started = True
track_id = await engine.enqueue(rag, staged)
if not isinstance(track_id, str) or not track_id.strip():
raise engine.LightRagContractError(
@@ -306,6 +309,18 @@ class LightRagPipeline:
raise LightRagBatchError(outcome)
failed = False
return outcome
+ except BaseException:
+ if not enqueue_started:
+ cleanup = staged
+ elif not accepted:
+ try:
+ cleanup = await engine.confirmed_unaccepted(rag, staged)
+ except BaseException:
+ self.logger.exception(
+ "Could not confirm which LightRAG documents were rejected; "
+ "retaining all staged ingress"
+ )
+ raise
finally:
try:
await engine.finalize(rag, cancel_pending=failed)
@@ -314,9 +329,8 @@ class LightRagPipeline:
raise
self.logger.exception("LightRAG cleanup failed while indexing was aborting")
finally:
- if failed and not accepted:
- for item in staged:
- ingress.remove_unaccepted(item)
+ for item in cleanup:
+ ingress.remove_unaccepted(item)
return await run_in_worker_loop(job)
diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.py
index 83bb5a04f..5e96acca2 100644
--- a/tests/services/rag/test_lightrag_pipeline.py
+++ b/tests/services/rag/test_lightrag_pipeline.py
@@ -573,6 +573,13 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(
class Rag:
working_dir = str(working)
+ class DocStatus:
+ async def get_docs_by_ids(self, _doc_ids, *, strict):
+ assert strict is True
+ return {}
+
+ doc_status = DocStatus()
+
async def apipeline_process_enqueue_documents(self):
return None
@@ -617,6 +624,105 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(
assert outcome.complete is True
+def test_enqueue_partial_commit_removes_only_confirmed_unaccepted_ingress(
+ tmp_path: Path, monkeypatch
+) -> None:
+ sources = [tmp_path / "source" / name for name in ("accepted.md", "rejected.md")]
+ sources[0].parent.mkdir()
+ for source in sources:
+ source.write_text(source.stem, encoding="utf-8")
+ working = tmp_path / "version-1"
+ status_reads: list[tuple[list[str], bool]] = []
+
+ class DocStatus:
+ async def get_docs_by_ids(self, doc_ids, *, strict):
+ status_reads.append((doc_ids, strict))
+ return {doc_ids[0]: types.SimpleNamespace(status="pending")}
+
+ class Rag:
+ working_dir = str(working)
+ doc_status = DocStatus()
+
+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))
+
+ def stage(_working, paths):
+ return [
+ freeze_document(
+ working,
+ Path(path),
+ ParsedDocument(markdown=Path(path).stem, engine="text_only"),
+ )
+ for path in paths
+ ], {}
+
+ async def enqueue(_rag, _staged):
+ raise RuntimeError("doc_status partially committed")
+
+ async def no_op(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(pipeline, "_stage_documents", stage)
+ monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: Rag())
+ monkeypatch.setattr(engine, "initialize", no_op)
+ monkeypatch.setattr(engine, "enqueue", enqueue)
+ monkeypatch.setattr(engine, "finalize", no_op)
+
+ with pytest.raises(RuntimeError, match="partially committed"):
+ asyncio.run(pipeline._run_indexing(working, [str(path) for path in sources], None))
+
+ assert len(status_reads) == 1
+ assert status_reads[0][1] is True
+ assert (pending_root(working) / "accepted.md").is_file()
+ assert (bundles_root(working) / "accepted.md.bundle").is_dir()
+ assert not (pending_root(working) / "rejected.md").exists()
+ assert not (bundles_root(working) / "rejected.md.bundle").exists()
+
+
+def test_enqueue_status_read_failure_retains_all_ingress(tmp_path: Path, monkeypatch) -> None:
+ source = tmp_path / "source" / "doc.md"
+ source.parent.mkdir()
+ source.write_text("body", encoding="utf-8")
+ working = tmp_path / "version-1"
+
+ class DocStatus:
+ async def get_docs_by_ids(self, _doc_ids, *, strict):
+ assert strict is True
+ raise RuntimeError("status unavailable")
+
+ class Rag:
+ working_dir = str(working)
+ doc_status = DocStatus()
+
+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))
+
+ def stage(_working, paths):
+ return [
+ freeze_document(
+ working,
+ Path(paths[0]),
+ ParsedDocument(markdown="body", engine="text_only"),
+ )
+ ], {}
+
+ async def enqueue(_rag, _staged):
+ raise ValueError("enqueue failed")
+
+ async def no_op(*_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(pipeline, "_stage_documents", stage)
+ monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: Rag())
+ monkeypatch.setattr(engine, "initialize", no_op)
+ monkeypatch.setattr(engine, "enqueue", enqueue)
+ monkeypatch.setattr(engine, "finalize", no_op)
+
+ with pytest.raises(ValueError, match="enqueue failed"):
+ asyncio.run(pipeline._run_indexing(working, [str(source)], None))
+
+ assert (pending_root(working) / "doc.md").is_file()
+ assert (bundles_root(working) / "doc.md.bundle").is_dir()
+
+
def test_append_rejects_corrupt_or_unpublished_existing_version(
tmp_path: Path, monkeypatch
) -> None: