DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Replace RAG-Anything with native LightRAG pipeline
Codex6d02ff929961
diff --git a/README.md b/README.mdindex e5f80e89c..64c3dec67 100644--- a/README.md+++ b/README.md@@ -277,9 +277,11 @@ python -m pip install --upgrade pip</details><details>-<summary><b>Optional install extras</b> — dev / partners / matrix / math-animator</summary>+<summary><b>Optional install extras</b> — RAG engines / dev / partners / matrix / math-animator</summary>```bash+pip install -e ".[rag-lightrag]" # Built-in LightRAG engine (exact supported SDK)+pip install -e ".[graphrag]" # Microsoft GraphRAG enginepip install -e ".[dev]" # tests/lint toolspip install -e ".[partners]" # Partner IM channel SDKspip install -e ".[matrix]" # Matrix channel without E2EE/libolm@@ -602,6 +604,8 @@ Knowledge bases are the document collections behind RAG — they ground Chat turCreating a KB, you either **create new** (upload documents and build a fresh index) or **link existing** (reuse an index built elsewhere, read in place with no re-index). A KB can also track **GitHub repositories** (repo, branch, glob) or **documentation-site URLs** (bounded crawl depth and page count); on-demand sync hash-diffs added, changed, and removed content so followed documentation stays current without re-uploading. Re-indexing writes a new flat `version-N` directory and keeps prior ones, so a working index is never destroyed mid-rebuild. A single document can be removed even from an **error**-state base — dropping a file that failed to parse without a full delete-and-rebuild. Document parsing — Text-only, MinerU, Docling, Tika, markitdown, PyMuPDF4LLM, or LiteParse — is chosen in **Settings → Knowledge Base**, with local model downloads off by default. Docling can also run in **remote** mode against a Docling Serve server (no local install or models needed), configured via **Settings → Document Parsing** (`mode=remote`, a server base URL, and an optional API key) or the `DOCLING_MODE` / `DOCLING_API_BASE_URL` / `DOCLING_API_TOKEN` environment variables. Tika is remote-only and points at an Apache Tika server (`TIKA_SERVER_URL`). The CLI mirrors the lifecycle with `list/info/create/add/search/set-default/delete`, source add/remove commands, `list-sources`, and `sync`.+The built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its local CLI when structured PDF parsing is wanted; text-only and the other parsing engines do not require MinerU.+</details><details>diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex f6815c48a..15205015d 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -289,13 +289,11 @@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, Any] = {"dynamic_community_selection": False,}-# LightRAG retrieval + indexing knobs (HKUDS/LightRAG via RAG-Anything). ``top_k``+# LightRAG retrieval + indexing knobs (HKUDS/LightRAG native SDK). ``top_k``# is the number of entities/relations the query pulls; ``response_type`` mirrors-# GraphRAG's. These ride into ``QueryParam`` via the engine's aquery() call;-# wiring is defensive (an older RAG-Anything that rejects a kwarg degrades to a-# mode-only query). ``max_concurrent_files`` maps to RAGAnythingConfig's batch-# knob; ``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride into-# LightRAG's own constructor via RAGAnything's ``lightrag_kwargs`` passthrough.+# GraphRAG's. These ride into ``QueryParam`` and the pinned SDK constructor.+# ``max_concurrent_files`` sizes the native parser worker pool after DeepTutor+# has frozen each ParseService result; pre-parsing itself remains serial.DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {"version": 1,"top_k": 60,diff --git a/deeptutor/services/parsing/cache.py b/deeptutor/services/parsing/cache.pyindex eda764a39..94bea9574 100644--- a/deeptutor/services/parsing/cache.py+++ b/deeptutor/services/parsing/cache.py@@ -127,7 +127,7 @@ def _absolutize_img_paths(blocks: list[dict], content_dir: Path) -> list[dict]:"""Anchor relative ``img_path`` entries at ``content_dir``.Engines (MinerU especially) emit ``img_path`` values like ``images/x.png``- relative to the content-list file. Consumers such as RAG-Anything resolve+ relative to the content-list file. Consumers such as LightRAG resolvethem against their own working directory instead, so the images are neverfound (issue #624). The cached JSON stays relative — paths are rewrittenonly on load, keeping the cache dir relocatable.diff --git a/deeptutor/services/rag/factory.py b/deeptutor/services/rag/factory.pyindex fbf4d90c8..db9fc2ec4 100644--- a/deeptutor/services/rag/factory.py+++ b/deeptutor/services/rag/factory.py@@ -9,7 +9,7 @@ today:* ``graphrag`` — local knowledge-graph retrieval (microsoft/graphrag);optional dependency, ``pip install 'deeptutor[graphrag]'``.* ``lightrag`` — graph + vector retrieval (HKUDS/LightRAG, multimodal- via RAG-Anything); optional dependency,+ via the LightRAG native pipeline); optional dependency,``pip install 'deeptutor[rag-lightrag]'``.* ``lightrag-server`` — retrieval offloaded to an external, standaloneLightRAG server the user runs. No local index: eachdiff --git a/deeptutor/services/rag/index_versioning.py b/deeptutor/services/rag/index_versioning.pyindex b6d24606a..632755861 100644--- a/deeptutor/services/rag/index_versioning.py+++ b/deeptutor/services/rag/index_versioning.py@@ -113,11 +113,50 @@ def _next_flat_version_dir(kb_dir: Path) -> Path:return kb_dir / f"{VERSION_PREFIX}{(max(existing) if existing else 0) + 1}"+def _native_lightrag_output_ready(version_dir: Path, meta: dict[str, Any]) -> bool:+ workspace = str(meta.get("workspace") or "").strip()+ if workspace:+ workspace_path = Path(workspace)+ if workspace_path.is_absolute() or workspace_path.name != workspace:+ return False+ status_path = version_dir / workspace / "kv_store_doc_status.json"+ else:+ # Transitional/test layouts may still keep the status store flat.+ status_path = version_dir / "kv_store_doc_status.json"+ payload = _read_json(status_path)+ if not payload:+ return False+ return any(+ isinstance(row, dict)+ and (str(row.get("status") or "").lower() == "processed" or bool(row.get("chunks_list")))+ for row in payload.values()+ )++def _entry_from_flat_version(version_dir: Path) -> dict[str, Any]:- meta = _read_json(version_dir / META_FILENAME) or {}+ stored_meta = _read_json(version_dir / META_FILENAME)+ meta = dict(stored_meta or {})meta.setdefault("version", version_dir.name)meta.setdefault("signature", meta.get("signature") or version_dir.name)- meta["ready"] = _is_storage_ready(version_dir)+ has_provider_output = _is_storage_ready(version_dir)+ # Legacy flat stores from other providers predate metadata, so their+ # established readiness rule remains output-based. A native LightRAG+ # candidate is identifiable before publication by its doc-status/ingress+ # files and must fail closed until schema-2 metadata is atomically written.+ is_unpublished_lightrag_candidate = stored_meta is None and (+ (version_dir / "kv_store_doc_status.json").exists()+ or (version_dir / "deeptutor_ingress").exists()+ )+ ready = has_provider_output and not is_unpublished_lightrag_candidate+ if stored_meta is not None and stored_meta.get("provider") == "lightrag":+ adapter_schema = stored_meta.get("lightrag_adapter_schema")+ if adapter_schema is not None:+ ready = bool(+ adapter_schema == 2+ and stored_meta.get("state") == "published"+ and _native_lightrag_output_ready(version_dir, stored_meta)+ )+ meta["ready"] = readymeta["storage_path"] = str(version_dir)meta["version_path"] = str(version_dir)meta["layout"] = "flat"diff --git a/deeptutor/services/rag/pipelines/lightrag/__init__.py b/deeptutor/services/rag/pipelines/lightrag/__init__.pyindex 0e4443a2b..f531ee960 100644--- a/deeptutor/services/rag/pipelines/lightrag/__init__.py+++ b/deeptutor/services/rag/pipelines/lightrag/__init__.py@@ -1,15 +1,15 @@-"""LightRAG / RAG-Anything knowledge-base engine.+"""Native LightRAG knowledge-base engine.-A graph-based RAG provider built on HKUDS/LightRAG (multimodal via-HKUDS/RAG-Anything). It consumes DeepTutor's shared parse layer for document-parsing and exposes LightRAG's native query modes (naive/local/global/hybrid/mix)-through the per-KB ``search_mode``.+A graph-based RAG provider built directly on HKUDS/LightRAG. It consumes+DeepTutor's shared parse layer for document parsing and exposes LightRAG's+native query modes (naive/local/global/hybrid/mix) through the per-KB+``search_mode``.Modules:* ``block_policy`` — versioned MinerU block classification before indexing.* ``config`` — availability + mode helpers + the LLM/vision/embedding adapters.* ``storage`` — per-KB version-dir layout + readiness marker.-* ``engine`` — the ONLY module importing ``raganything``/``lightrag``.+* ``engine`` — constructs the exact supported LightRAG SDK version.* ``pipeline`` — :class:`LightRagPipeline` implementing the ``RAGPipeline`` contract."""diff --git a/deeptutor/services/rag/pipelines/lightrag/block_policy.py b/deeptutor/services/rag/pipelines/lightrag/block_policy.pyindex 048ee8c9a..dbbaf4cb2 100644--- a/deeptutor/services/rag/pipelines/lightrag/block_policy.py+++ b/deeptutor/services/rag/pipelines/lightrag/block_policy.py@@ -1,9 +1,9 @@"""Versioned MinerU block policy for LightRAG indexing.MinerU's legacy ``content_list.json`` mixes semantic document content with-page-layout helpers. DeepTutor retains the raw parser cache for audit and-derives an independent, deep-copied list for indexing so RAG-Anything never-needs to decide which parser blocks are semantic.+page-layout helpers. DeepTutor retains the raw parser cache for audit and+derives an independent, deep-copied list before the native LightRAG Sidecar+bridge decides which parser blocks are semantic."""from __future__ import annotationsdiff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 049e30763..4c215948c 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -1,16 +1,9 @@-"""Bridge DeepTutor's runtime config into LightRAG / RAG-Anything.--LightRAG (HKUDS/LightRAG) is a text knowledge-graph RAG engine; its multimodal-story is RAG-Anything (HKUDS/RAG-Anything), built on top of LightRAG. The-``lightrag`` provider uses RAG-Anything so multimodal content (the parse layer's-``content_list``) becomes graph entities, while text-only documents fall back to-a plain text insert.+"""Bridge DeepTutor runtime configuration into the LightRAG 1.5 native SDK.This module is the decoupling seam: it exposes availability + mode helpers and-builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM /-embedding clients. It imports neither RAG-Anything nor LightRAG at module load —-the adapter builders import ``lightrag.utils`` lazily (only the embedding wrapper-needs it), and engine construction lives in ``engine.py``.+builds the three adapters LightRAG needs from DeepTutor's already-resolved LLM,+vision, and embedding clients. LightRAG imports remain lazy so every other RAG+provider can import without the optional extra installed.Decoupling notes:* ``llm_model_func`` / ``vision_model_func`` wrap DeepTutor's unified model@@ -45,7 +38,7 @@ DEFAULT_MODE = "hybrid"# Conservative cap for the embedding wrapper when the model doesn't advertise one._DEFAULT_MAX_TOKEN_SIZE = 8192-# Keep retries at the LightRAG adapter boundary so RAG-Anything receives one+# Keep retries at the LightRAG adapter boundary so the SDK receives one# predictable policy for both text and vision calls. Provider retries are disabled# on every attempt to prevent the two retry layers from multiplying._ADAPTER_MAX_ATTEMPTS = 3@@ -59,7 +52,7 @@ _HTTP_STATUS_PATTERN = re.compile(class LightRagNotAvailableError(RuntimeError):- """Raised when the optional ``raganything`` dependency is not installed."""+ """Raised when the optional ``lightrag-hku`` dependency is not installed."""class LightRagNotConfiguredError(RuntimeError):@@ -138,12 +131,12 @@ async def _run_adapter_with_retry(def is_lightrag_available() -> bool:- """True when RAG-Anything (which bundles LightRAG) can be imported.+ """True when the native LightRAG SDK can be imported.Opt-in extra: ``pip install 'deeptutor[rag-lightrag]'``. Until installed theprovider is hidden / blocked in the UI."""- return importlib.util.find_spec("raganything") is not None+ return importlib.util.find_spec("lightrag") is not Nonedef normalize_mode(mode: str | None) -> str:@@ -157,12 +150,7 @@ def normalize_mode(mode: str | None) -> str:def query_kwargs_from_settings() -> dict:- """Extra ``aquery`` kwargs (top_k, response_type) from runtime settings.-- Returned as a dict so the engine can pass them through to LightRAG's- ``QueryParam`` and gracefully drop them if an older RAG-Anything rejects a- kwarg. Empty on any read error.- """+ """``QueryParam`` values from runtime settings."""try:from deeptutor.services.config import load_lightrag_settings@@ -176,34 +164,18 @@ def query_kwargs_from_settings() -> dict:def indexing_kwargs_from_settings() -> dict:- """``RAGAnythingConfig`` batch-processing knobs from runtime settings.-- Only ``max_concurrent_files`` is exposed for now (issue #640); the config- object accepts several other batch/context knobs we deliberately leave on- RAG-Anything's own defaults. Empty on any read error, so a bad settings- file falls back to RAG-Anything's built-in default of 1.- """+ """Native parser-pool knobs from runtime settings."""try:from deeptutor.services.config import load_lightrag_settingssettings = load_lightrag_settings()- return {"max_concurrent_files": int(settings.get("max_concurrent_files", 1))}+ return {"max_parallel_parse_native": int(settings.get("max_concurrent_files", 1))}except Exception:return {}-def lightrag_kwargs_from_settings() -> dict:- """Extra kwargs forwarded to LightRAG's own constructor via RAG-Anything's- ``lightrag_kwargs`` passthrough.-- ``llm_model_max_async`` bounds how many concurrent LLM calls LightRAG's- internal priority queue issues (covers both query and entity-extraction- traffic, since both ride the same wrapped ``llm_model_func``).- ``entity_extract_max_gleaning`` controls how many extra extraction passes- LightRAG runs per chunk to recover entities/relations the first pass- missed. Empty on any read error, so a bad settings file falls back to- LightRAG's own built-in defaults.- """+def constructor_kwargs_from_settings() -> dict:+ """Direct LightRAG constructor knobs from runtime settings."""try:from deeptutor.services.config import load_lightrag_settings@@ -248,7 +220,7 @@ def build_llm_model_func(*, io_bridge: OwnerLoopBridge | None = None):def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):- """Wrap DeepTutor's vision-capable callable for RAG-Anything's image step."""+ """Map rc2 ``image_inputs`` to DeepTutor's vision callable."""from deeptutor.services.llm import get_llm_clientbase = get_llm_client().get_vision_model_func()@@ -257,10 +229,19 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):prompt="",system_prompt=None,history_messages=None,- image_data=None,+ image_inputs=None,messages=None,**_ignored,):+ if not isinstance(image_inputs, list) or len(image_inputs) != 1:+ raise ValueError("LightRAG vision requests must contain exactly one image input")+ payload = image_inputs[0]+ if not isinstance(payload, dict):+ raise ValueError("LightRAG vision image input must be an object")+ image_data = payload.get("base64")+ if not isinstance(image_data, str) or not image_data.strip():+ raise ValueError("LightRAG vision image input requires a non-empty base64 value")+async def request():return await base(prompt or "",@@ -269,12 +250,6 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):image_data=image_data,messages=messages,max_retries=0,- # Never strip the image and answer anyway. The provider's- # stage-2 fallback exists to salvage a text answer from a model- # that turns out not to take images, but here the *whole point*- # of the call is the image: a description produced without it is- # invented, and it would be indexed as fact. Fail the image- # instead, and let the caller log and skip it.allow_image_fallback=False,)@@ -283,6 +258,16 @@ def build_vision_model_func(*, io_bridge: OwnerLoopBridge | None = None):return vision_model_func+def vision_model_available() -> bool:+ """Return whether the active DeepTutor model is explicitly vision-capable."""+ try:+ from deeptutor.services.llm import get_llm_client++ return bool(get_llm_client().supports_multimodal_images())+ except Exception:+ return False++def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):"""Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""from lightrag.utils import EmbeddingFunc@@ -334,8 +319,9 @@ __all__ = ["normalize_mode","query_kwargs_from_settings","indexing_kwargs_from_settings",- "lightrag_kwargs_from_settings",+ "constructor_kwargs_from_settings","build_llm_model_func","build_vision_model_func",+ "vision_model_available","build_embedding_func",]diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex d2e4758a6..d59990887 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -1,23 +1,12 @@-"""Thin adapter over the RAG-Anything / LightRAG Python API.--This is the ONLY module that imports ``raganything`` / ``lightrag``. Everything-version-sensitive lives here, so an API shift between releases is a one-file-fix. All imports are lazy so DeepTutor runs fine without the optional dependency-installed.--A RAG-Anything instance is built from DeepTutor's LLM/vision/embedding adapters-(see ``config.py``) over a per-KB ``working_dir``. Documents are inserted as a-MinerU-style ``content_list`` (produced upstream by the parse layer), so the-multimodal step never re-parses anything; retrieval delegates to LightRAG's-native query modes.-"""+"""Exact-version adapter over the LightRAG 1.5 native Python SDK."""from __future__ import annotationsimport asynciofrom collections.abc import Awaitable, Callable, Iterable, Mapping+import hashlib+from importlib.metadata import PackageNotFoundError, versionimport inspect-import loggingfrom pathlib import Pathfrom typing import Any@@ -26,335 +15,413 @@ from .config import (build_embedding_func,build_llm_model_func,build_vision_model_func,+ constructor_kwargs_from_settings,indexing_kwargs_from_settings,- lightrag_kwargs_from_settings,normalize_mode,query_kwargs_from_settings,)+from .ingress import IngressError, StagedDocument, pending_rootfrom .worker import OwnerLoopBridge-logger = logging.getLogger(__name__)+LIGHTRAG_DISTRIBUTION = "lightrag-hku"+LIGHTRAG_VERSION = "1.5.7rc2"+PARSER_ENGINE = "deeptutor"-def _accepts(target: Any, name: str) -> bool:- """Whether ``target``'s constructor takes a keyword called *name*.+class LightRagContractError(RuntimeError):+ """Raised when the pinned SDK returns a shape DeepTutor cannot trust."""- The settings knobs below ride on RAG-Anything parameters that arrived in- different releases — ``lightrag_kwargs`` only exists from ~1.2.5, while the- supported range starts at 1.0.1. Asking first keeps an older install- working on RAG-Anything's own defaults instead of dying with a TypeError- that takes the whole LightRAG engine down. Same defensive posture the query- path already takes for ``QueryParam`` kwargs.- """- import inspect+def installed_version() -> str:try:- return name in inspect.signature(target).parameters- except (TypeError, ValueError):- return False---def _drop_unsupported(target: Any, kwargs: dict[str, Any], *, what: str) -> dict[str, Any]:- supported = {key: value for key, value in kwargs.items() if _accepts(target, key)}- for key in kwargs.keys() - supported.keys():- logger.warning(- "Installed RAG-Anything does not accept %s=%r on %s; leaving it at "- "the library default. Upgrade raganything to use this setting.",- key,- kwargs[key],- what,+ return version(LIGHTRAG_DISTRIBUTION)+ except PackageNotFoundError as exc:+ raise LightRagContractError(+ "LightRAG is not installed. Install `deeptutor[rag-lightrag]`."+ ) from exc+++def _require_exact_version() -> None:+ current = installed_version()+ if current != LIGHTRAG_VERSION:+ raise LightRagContractError(+ f"DeepTutor requires {LIGHTRAG_DISTRIBUTION}=={LIGHTRAG_VERSION}; found {current}")- return supported-def _build_config(config_cls: Any, working_dir: Path) -> Any:- knobs = _drop_unsupported(config_cls, indexing_kwargs_from_settings(), what="RAGAnythingConfig")- return config_cls(working_dir=str(working_dir), **knobs)+def _validate_component(value: str, *, label: str) -> str:+ path = Path(str(value or ""))+ if path.is_absolute() or ".." in path.parts or path.name != str(value):+ raise IngressError(f"{label} must be a canonical basename: {value!r}")+ if not path.name or path.name in {".", ".."}:+ raise IngressError(f"{label} is empty or invalid")+ return path.name+++def _safe_candidate(root: Path, candidate: Path) -> Path | None:+ if candidate.is_symlink() or not candidate.is_file():+ return None+ resolved_root = root.resolve(strict=True)+ resolved = candidate.resolve(strict=True)+ try:+ resolved.relative_to(resolved_root)+ except ValueError as exc:+ raise IngressError(+ f"LightRAG source resolver escaped version ingress: {candidate}"+ ) from exc+ return resolved+++def _controlled_class():+ from lightrag import LightRAG++ class DeepTutorLightRAG(LightRAG):+ def _resolve_source_file_for_parser(+ self,+ file_path: str,+ *,+ source_file: str | None = None,+ parser_engine: str | None = None,+ ) -> str:+ if parser_engine not in (None, PARSER_ENGINE):+ raise IngressError(+ f"Unsupported parser engine for DeepTutor ingress: {parser_engine}"+ )+ name = _validate_component(file_path, label="file_path")+ if source_file is not None:+ source_name = _validate_component(source_file, label="source_file")+ if source_name != name:+ raise IngressError(+ f"LightRAG source hints disagree: {name!r} != {source_name!r}"+ )+ root = pending_root(Path(self.working_dir))+ root.mkdir(parents=True, exist_ok=True)+ matches = [+ resolved+ for candidate in (root / name, root / "__parsed__" / name)+ if (resolved := _safe_candidate(root, candidate)) is not None+ ]+ if len(matches) != 1:+ reason = "missing" if not matches else "ambiguous"+ raise IngressError(f"Version-local LightRAG source is {reason}: {name}")+ return str(matches[0])++ return DeepTutorLightRAG+++_SUFFIXES = frozenset(+ {+ "txt",+ "md",+ "mdx",+ "pdf",+ "doc",+ "docx",+ "ppt",+ "pptx",+ "xls",+ "xlsx",+ "rtf",+ "odt",+ "tex",+ "epub",+ "html",+ "htm",+ "csv",+ "json",+ "xml",+ "yaml",+ "yml",+ "log",+ "conf",+ "ini",+ "properties",+ "sql",+ "sh",+ "c",+ "h",+ "cpp",+ "hpp",+ "py",+ "java",+ "js",+ "ts",+ "swift",+ "go",+ "rb",+ "php",+ "css",+ "scss",+ "less",+ "png",+ "jpg",+ "jpeg",+ "webp",+ "gif",+ "bmp",+ "tiff",+ }+)++def _register_parser() -> None:+ from lightrag.parser.registry import ParserSpec, register_parser-def _construct(rag_cls: Any, **kwargs: Any) -> Any:- extra = lightrag_kwargs_from_settings()- if extra and _accepts(rag_cls, "lightrag_kwargs"):- kwargs["lightrag_kwargs"] = extra- elif extra:- logger.warning(- "Installed RAG-Anything has no lightrag_kwargs passthrough; %s stay "- "at LightRAG's defaults. Upgrade raganything to use these settings.",- ", ".join(sorted(extra)),+ register_parser(+ ParserSpec(+ engine_name=PARSER_ENGINE,+ impl="deeptutor.services.rag.pipelines.lightrag.parser:DeepTutorParser",+ suffixes=_SUFFIXES,+ queue_group="native",)- return rag_cls(**kwargs)+ )++def workspace_for(working_dir: Path) -> str:+ identity = str(Path(working_dir).resolve()).encode("utf-8")+ return f"deeptutor_{hashlib.sha256(identity).hexdigest()[:16]}"-def build_rag(working_dir: Path, *, io_bridge: OwnerLoopBridge | None = None) -> Any:- """Construct a RAG-Anything instance rooted at ``working_dir``.- Pinned to RAG-Anything's config-based constructor; this is the single spot- to touch if its API changes between releases.- """- from raganything import RAGAnything, RAGAnythingConfig+def build_rag(+ working_dir: Path,+ *,+ io_bridge: OwnerLoopBridge | None = None,+ enable_vlm: bool = False,+) -> Any:+ """Construct one exact-version, version-isolated LightRAG instance."""+ _require_exact_version()+ _register_parser()+ from lightrag.llm_roles import RoleLLMConfig- config = _build_config(RAGAnythingConfig, working_dir)adapter_kwargs = {"io_bridge": io_bridge} if io_bridge is not None else {}- funcs = {+ constructor = {+ "working_dir": str(Path(working_dir)),+ "workspace": workspace_for(working_dir),"llm_model_func": build_llm_model_func(**adapter_kwargs),- "vision_model_func": build_vision_model_func(**adapter_kwargs),"embedding_func": build_embedding_func(**adapter_kwargs),+ "auto_manage_storages_states": False,+ "vlm_process_enable": bool(enable_vlm),+ **indexing_kwargs_from_settings(),+ **constructor_kwargs_from_settings(),}- rag = _construct(RAGAnything, config=config, **funcs)- # DeepTutor always feeds RAG-Anything a pre-parsed ``content_list`` (the- # parse layer runs upstream via DeepTutor's own ParseService), so- # RAG-Anything's bundled document parser is never invoked. Its LightRAG init- # nevertheless runs a one-time installation check on its *default* parser- # (``mineru``); when MinerU isn't installed that check hard-fails indexing- # with "Parser 'mineru' is not properly installed" — even though the user- # picked an entirely different parse engine (see issue #594). Marking the- # check as already satisfied skips that spurious gate for a parser we don't- # use, while leaving the real pre-parsed insert path untouched.- rag._parser_installation_checked = True- return rag---async def insert(rag: Any, content_list: list[dict], *, file_name: str, doc_id: str) -> None:- """Insert a pre-parsed ``content_list`` (multimodal-aware, no re-parsing)."""- await rag.insert_content_list(- content_list=content_list,- file_path=file_name,- doc_id=doc_id,- )+ if enable_vlm:+ constructor["role_llm_configs"] = {+ "vlm": RoleLLMConfig(func=build_vision_model_func(**adapter_kwargs))+ }+ return _controlled_class()(**constructor)-def _managed_queue_funcs(lightrag: Any) -> Iterable[Callable[..., Any]]:- """Yield each current LightRAG queue wrapper exactly once."""- role_funcs = getattr(lightrag, "role_llm_funcs", {})- candidates: list[object] = []- if isinstance(role_funcs, Mapping):- candidates.extend(role_funcs.values())+async def initialize(rag: Any) -> None:+ result = rag.initialize_storages()+ if inspect.isawaitable(result):+ await result+++async def enqueue(rag: Any, staged: list[StagedDocument]) -> str:+ if not staged:+ raise ValueError("Cannot enqueue an empty LightRAG batch")+ return await rag.apipeline_enqueue_documents(+ [""] * len(staged),+ file_paths=[item.canonical_name for item in staged],+ docs_format="pending_parse",+ parse_engine=PARSER_ENGINE,+ process_options=[item.process_options for item in staged],+ chunk_options=[item.chunk_options for item in staged],+ )- embedding = getattr(lightrag, "embedding_func", None)- candidates.append(getattr(embedding, "func", None))- candidates.append(getattr(lightrag, "rerank_model_func", None))+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 []+ embedding = getattr(rag, "embedding_func", None)+ candidates.append(getattr(embedding, "func", None))+ candidates.append(getattr(rag, "rerank_model_func", None))seen: set[int] = set()for candidate in candidates:- if not callable(candidate) or id(candidate) in seen:- continue- seen.add(id(candidate))- yield candidate+ if callable(candidate) and id(candidate) not in seen:+ seen.add(id(candidate))+ yield candidate-async def _shutdown_queues(lightrag: Any, *, cancel_pending: bool) -> None:- """Bound cleanup of LightRAG's role, embedding, and rerank queues."""+async def _shutdown_queues(rag: Any, *, cancel_pending: bool) -> None:shutdowns: list[Awaitable[Any]] = []- for func in _managed_queue_funcs(lightrag):+ for func in _managed_queue_funcs(rag):shutdown = getattr(func, "shutdown", None)if callable(shutdown):result = shutdown(graceful=not cancel_pending, timeout=5.0)if inspect.isawaitable(result):shutdowns.append(result)- if not shutdowns:- return-- results = await asyncio.gather(*shutdowns, return_exceptions=True)- failures = [result for result in results if isinstance(result, BaseException)]- if failures:- raise RuntimeError(- f"Failed to shut down {len(failures)} LightRAG managed queue(s)"- ) from failures[0]+ if shutdowns:+ results = await asyncio.gather(*shutdowns, return_exceptions=True)+ failures = [item for item in results if isinstance(item, BaseException)]+ if failures:+ raise RuntimeError(+ f"Failed to shut down {len(failures)} LightRAG queue(s)"+ ) from failures[0]async def finalize(rag: Any, *, cancel_pending: bool) -> None:- """Stop managed work before finalizing RAG-Anything storage resources."""- lightrag = getattr(rag, "lightrag", None)- if lightrag is not None:- await _shutdown_queues(lightrag, cancel_pending=cancel_pending)-- finalizer = getattr(rag, "finalize_storages", None)- if not callable(finalizer):- return- result = finalizer()+ await _shutdown_queues(rag, cancel_pending=cancel_pending)+ result = rag.finalize_storages()if inspect.isawaitable(result):await result-async def ensure_ready(rag: Any) -> None:- """Ensure RAG-Anything has an initialized LightRAG instance."""- if getattr(rag, "lightrag", None) is not None:- return+def _string(value: Any, *, label: str) -> str:+ if not isinstance(value, str):+ raise LightRagContractError(f"LightRAG query {label} must be a string")+ return value- initializer = getattr(rag, "_ensure_lightrag_initialized", None)- if initializer is None:- return- result = await initializer()- if isinstance(result, dict) and result.get("success") is False:- raise RuntimeError(result.get("error") or "Failed to initialize LightRAG")---async def query(rag: Any, question: str, mode: str | None = None) -> str:- """Run a LightRAG query and return the synthesized answer string.-- Extra knobs (top_k, response_type) from the lightrag.json slice ride into- LightRAG's ``QueryParam`` via aquery's ``**kwargs``. Wiring is defensive: an- older RAG-Anything that rejects one of these kwargs falls back to a- mode-only query rather than failing the search.- """- resolved = normalize_mode(mode) or DEFAULT_MODE- extra = query_kwargs_from_settings()- await ensure_ready(rag)- try:- result = await rag.aquery(question, mode=resolved, **extra)- except TypeError:- if extra:- logger.debug("RAG-Anything rejected extra query kwargs; retrying mode-only.")- result = await rag.aquery(question, mode=resolved)- else:- raise- return result if isinstance(result, str) else str(result)---async def query_with_sources(- rag: Any, question: str, mode: str | None = None-) -> tuple[str, list[dict[str, Any]]]:- """Return a LightRAG answer together with its structured provenance.-- ``RAGAnything.aquery`` owns the answer path, including its optional VLM- enhancement. LightRAG exposes the records used for retrieval separately via- ``aquery_data``. Keeping those calls separate preserves the existing answer- behavior while allowing DeepTutor to surface citation metadata.- """- answer = await query(rag, question, mode)- return answer, await query_sources(rag, question, mode)---async def query_sources(rag: Any, question: str, mode: str | None = None) -> list[dict[str, Any]]:- """Fetch and normalize the structured records used by a LightRAG query.-- ``aquery_data`` was added by LightRAG after some supported RAG-Anything- releases. Missing or failed provenance must not turn a successful answer- into a failed user request, so older installations gracefully return no- citations.- """- await ensure_ready(rag)- lightrag = getattr(rag, "lightrag", None)- aquery_data = getattr(lightrag, "aquery_data", None)- if not callable(aquery_data):- logger.debug("Installed LightRAG has no structured query data API.")- return []-- resolved = normalize_mode(mode) or DEFAULT_MODE- extra = query_kwargs_from_settings()- try:- from lightrag import QueryParam+def _records(data: dict[str, Any], key: str) -> list[dict[str, Any]]:+ value = data.get(key)+ if not isinstance(value, list) or not all(isinstance(item, dict) for item in value):+ raise LightRagContractError(f"LightRAG query data.{key} must be an object array")+ return value- try:- result = await aquery_data(question, param=QueryParam(mode=resolved, **extra))- except TypeError:- if not extra:- raise- logger.debug("LightRAG rejected extra provenance query kwargs; retrying mode-only.")- result = await aquery_data(question, param=QueryParam(mode=resolved))- except Exception as exc:- logger.warning("LightRAG provenance lookup failed; omitting citations: %s", exc)- return []- return _query_data_to_sources(result)---def _query_data_to_sources(result: Any) -> list[dict[str, Any]]:- """Map LightRAG's structured retrieval result to DeepTutor citations."""- if not isinstance(result, dict):- return []- data = result.get("data")- if not isinstance(data, dict):- return []-- reference_paths = {- str(record.get("reference_id")): str(record.get("file_path"))- for record in data.get("references", [])- if isinstance(record, dict) and record.get("reference_id") and record.get("file_path")+def _query_sources(data: dict[str, Any], metadata: dict[str, Any]) -> list[dict[str, Any]]:+ references = _records(data, "references")+ ref_paths = {+ str(item.get("reference_id")): str(item.get("file_path") or item.get("source") or "")+ for item in references+ if item.get("reference_id") is not None}sources: list[dict[str, Any]] = []- def source_path(record: dict[str, Any]) -> str:- return str(- record.get("file_path") or reference_paths.get(str(record.get("reference_id")), "")- )-- def source_title(path: str, fallback: str) -> str:- return Path(path).name if path else fallback-- for record in data.get("chunks", []):- if not isinstance(record, dict):- continue- path = source_path(record)- content = str(record.get("content") or "")- chunk_id = str(record.get("chunk_id") or "")- if not (path or content or chunk_id):- continue+ def add(kind: str, record: dict[str, Any], rank: int) -> None:+ ref = str(record.get("reference_id") or "")+ path = str(record.get("file_path") or ref_paths.get(ref, ""))+ if kind == "chunk":+ stable_id = str(record.get("chunk_id") or "")+ title = Path(path).name if path else "LightRAG chunk"+ content = _string(record.get("content", ""), label="chunk content")+ elif kind == "entity":+ stable_id = str(record.get("entity_name") or record.get("entity_id") or "")+ title = stable_id or "LightRAG entity"+ content = _string(record.get("description", ""), label="entity description")+ else:+ src_id = str(record.get("src_id") or "")+ tgt_id = str(record.get("tgt_id") or "")+ stable_id = str(record.get("relation_id") or f"{src_id}->{tgt_id}")+ title = stable_id or "LightRAG relationship"+ content = _string(record.get("description", ""), label="relationship description")+ item = {+ "kind": kind,+ "title": title,+ "content": content,+ "source": path,+ "page": str(record.get("page") or ""),+ "reference_id": ref,+ "rank": rank,+ }+ if kind == "chunk":+ item["chunk_id"] = stable_id+ elif kind == "entity":+ item.update(+ {+ "entity_id": stable_id,+ "entity_name": str(record.get("entity_name") or ""),+ "entity_type": str(record.get("entity_type") or ""),+ "source_id": str(record.get("source_id") or ""),+ }+ )+ else:+ item.update(+ {+ "relation_id": stable_id,+ "src_id": str(record.get("src_id") or ""),+ "tgt_id": str(record.get("tgt_id") or ""),+ "keywords": record.get("keywords"),+ "weight": record.get("weight"),+ "source_id": str(record.get("source_id") or ""),+ }+ )+ sources.append(item)++ for kind, key in (+ ("chunk", "chunks"),+ ("entity", "entities"),+ ("relationship", "relationships"),+ ):+ for record in _records(data, key):+ add(kind, record, len(sources) + 1)+ for reference in references:+ reference_id = str(reference.get("reference_id") or "")+ path = str(reference.get("file_path") or reference.get("source") or "")sources.append({- "title": source_title(path, "LightRAG chunk"),- "content": content[:200],+ "kind": "reference",+ "title": Path(path).name if path else reference_id or "LightRAG reference",+ "content": "","source": path,- "page": str(record.get("page") or ""),- "chunk_id": chunk_id,- "reference_id": str(record.get("reference_id") or ""),+ "page": str(reference.get("page") or ""),+ "reference_id": reference_id,+ "rank": len(sources) + 1,+ "reference": reference,})+ sources.append(+ {+ "kind": "query_metadata",+ "title": "LightRAG query metadata",+ "content": "",+ "source": "",+ "page": "",+ "reference_id": "",+ "rank": len(sources) + 1,+ "metadata": metadata,+ }+ )+ return sources- for record in data.get("entities", []):- if not isinstance(record, dict):- continue- path = source_path(record)- entity_id = str(record.get("entity_name") or record.get("entity_id") or "")- description = str(record.get("description") or "")- if not (path or entity_id or description):- continue- sources.append(- {- "title": entity_id or source_title(path, "LightRAG entity"),- "content": description[:200],- "source": path,- "page": str(record.get("page") or ""),- "entity_id": entity_id,- "entity_type": str(record.get("entity_type") or ""),- "source_id": str(record.get("source_id") or ""),- "reference_id": str(record.get("reference_id") or ""),- }- )- for record in data.get("relationships", []):- if not isinstance(record, dict):- continue- path = source_path(record)- source_id = str(record.get("src_id") or "")- target_id = str(record.get("tgt_id") or "")- relation_id = str(record.get("relation_id") or f"{source_id}->{target_id}")- description = str(record.get("description") or "")- if not (path or relation_id or description):- continue- sources.append(- {- "title": relation_id or source_title(path, "LightRAG relationship"),- "content": description[:200],- "source": path,- "page": str(record.get("page") or ""),- "relation_id": relation_id,- "source_entity_id": source_id,- "target_entity_id": target_id,- "source_id": str(record.get("source_id") or ""),- "reference_id": str(record.get("reference_id") or ""),- }- )+async def query_with_sources(+ rag: Any, question: str, mode: str | None = None+) -> tuple[str, list[dict[str, Any]]]:+ from lightrag import QueryParam- return sources+ param = QueryParam(+ mode=normalize_mode(mode) or DEFAULT_MODE,+ stream=False,+ include_references=True,+ **query_kwargs_from_settings(),+ )+ result = await rag.aquery_llm(question, param=param)+ if not isinstance(result, dict):+ raise LightRagContractError("LightRAG query response must be an object")+ if result.get("status") != "success":+ message = result.get("message")+ raise LightRagContractError(+ str(message).strip()+ if isinstance(message, str) and message.strip()+ else "LightRAG retrieval failed"+ )+ response = result.get("llm_response")+ data = result.get("data")+ metadata = result.get("metadata")+ if (+ not isinstance(response, dict)+ or not isinstance(data, dict)+ or not isinstance(metadata, dict)+ ):+ raise LightRagContractError("LightRAG query response is missing structured fields")+ if response.get("is_streaming") is not False:+ raise LightRagContractError("LightRAG returned streaming output for a non-streaming query")+ content = _string(response.get("content"), label="llm_response.content")+ return content, _query_sources(data, metadata)__all__ = [+ "LIGHTRAG_DISTRIBUTION",+ "LIGHTRAG_VERSION",+ "LightRagContractError",+ "PARSER_ENGINE","build_rag",- "ensure_ready",+ "enqueue","finalize",- "insert",- "query",+ "initialize",+ "installed_version","query_with_sources",+ "workspace_for",]diff --git a/deeptutor/services/rag/pipelines/lightrag/ingress.py b/deeptutor/services/rag/pipelines/lightrag/ingress.pynew file mode 100644index 000000000..6c410e499--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/ingress.py@@ -0,0 +1,364 @@+"""Freeze DeepTutor parse results into version-local LightRAG ingress bundles."""++from __future__ import annotations++from copy import deepcopy+from dataclasses import dataclass+import hashlib+import json+import os+from pathlib import Path+import shutil+from typing import Any+import uuid++from deeptutor.services.file_io import atomic_write_json+from deeptutor.services.parsing.types import ParsedDocument++from . import block_policy++PARSER_BRIDGE_SCHEMA = 1+INGRESS_DIRNAME = "deeptutor_ingress"+PENDING_DIRNAME = "pending"+BUNDLES_DIRNAME = "bundles"+MANIFEST_FILENAME = "manifest.json"+++class IngressError(RuntimeError):+ """Raised when an ingress bundle crosses or violates its trust boundary."""+++@dataclass(frozen=True)+class StagedDocument:+ canonical_name: str+ source_path: Path+ bundle_dir: Path+ manifest_path: Path+ process_options: str+ chunk_options: dict[str, Any]+ audit_ledger: dict[str, Any] | None+++def ingress_root(working_dir: Path) -> Path:+ return Path(working_dir) / INGRESS_DIRNAME+++def pending_root(working_dir: Path) -> Path:+ return ingress_root(working_dir) / PENDING_DIRNAME+++def bundles_root(working_dir: Path) -> Path:+ return ingress_root(working_dir) / BUNDLES_DIRNAME+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _contained_regular_file(root: Path, path: Path, *, label: str) -> Path:+ if root.is_symlink() or not root.is_dir():+ raise IngressError(f"Bundle root must be an ordinary directory: {root}")+ try:+ relative = path.relative_to(root)+ except ValueError as exc:+ raise IngressError(f"{label} escapes its bundle root: {path}") from exc+ current = root+ for part in relative.parts:+ current = current / part+ if current.is_symlink():+ raise IngressError(f"{label} must not traverse a symbolic link: {current}")+ if path.is_symlink():+ raise IngressError(f"{label} must not be a symbolic link: {path}")+ try:+ resolved_root = root.resolve(strict=True)+ resolved = path.resolve(strict=True)+ resolved.relative_to(resolved_root)+ except (FileNotFoundError, ValueError) as exc:+ raise IngressError(f"{label} escapes its bundle root: {path}") from exc+ stat = resolved.stat()+ if not resolved.is_file() or stat.st_nlink != 1:+ raise IngressError(f"{label} must be an ordinary, unlinked file: {path}")+ return resolved+++def _copy_regular(source: Path, target: Path, *, allowed_root: Path | None = None) -> str:+ if source.is_symlink() or not source.is_file():+ raise IngressError(f"Source is not an ordinary file: {source}")+ resolved_source = source.resolve(strict=True)+ if resolved_source.stat().st_nlink != 1:+ raise IngressError(f"Source must not be hard-linked: {source}")+ if allowed_root is not None:+ try:+ resolved_source.relative_to(allowed_root.resolve(strict=True))+ except ValueError as exc:+ raise IngressError(f"Source escapes allowed root: {source}") from exc+ source_digest = _sha256(resolved_source)+ target.parent.mkdir(parents=True, exist_ok=True)+ with resolved_source.open("rb") as src, target.open("xb") as dst:+ shutil.copyfileobj(src, dst, length=1024 * 1024)+ if target.is_symlink() or os.path.samefile(resolved_source, target):+ raise IngressError(f"Frozen copy must not share the source file: {target}")+ target_digest = _sha256(target)+ if target_digest != source_digest:+ raise IngressError(f"Digest drift while freezing {source.name}")+ if target.stat().st_nlink != 1:+ raise IngressError(f"Frozen copy has unexpected hard links: {target}")+ return target_digest+++def _write_new_bytes(path: Path, data: bytes) -> str:+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("xb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+ return hashlib.sha256(data).hexdigest()+++def _asset_files(asset_dir: Path | None) -> list[tuple[Path, Path]]:+ if asset_dir is None:+ return []+ root = Path(asset_dir)+ if root.is_symlink() or not root.is_dir():+ raise IngressError(f"Parser asset directory is not an ordinary directory: {root}")+ files: list[tuple[Path, Path]] = []+ for path in sorted(root.rglob("*")):+ if path.is_symlink():+ raise IngressError(f"Parser asset is a symbolic link: {path}")+ if path.is_dir():+ continue+ if not path.is_file():+ raise IngressError(f"Parser asset is not an ordinary file: {path}")+ files.append((path, path.relative_to(root)))+ return files+++def _freeze_asset_paths(+ blocks: list[dict[str, Any]],+ asset_dir: Path | None,+ asset_files: list[tuple[Path, Path]],+) -> list[dict[str, Any]]:+ """Rewrite parser-owned asset paths to bundle-relative copied paths."""+ frozen = deepcopy(blocks)+ if asset_dir is None:+ return frozen+ root = Path(asset_dir).resolve(strict=True)+ by_source = {source.resolve(strict=True): relative for source, relative in asset_files}+ by_relative = {relative: relative for _, relative in asset_files}+ for index, block in enumerate(frozen):+ if not isinstance(block, dict):+ continue+ kind = str(block.get("type") or block.get("label") or "").lower()+ if kind not in {"image", "picture", "drawing", "chart"}:+ continue+ for key in ("img_path", "path"):+ raw = block.get(key)+ if not isinstance(raw, str) or not raw.strip():+ continue+ path = Path(raw)+ relative: Path | None = None+ if path.is_absolute():+ try:+ resolved = path.resolve(strict=True)+ except FileNotFoundError as exc:+ raise IngressError(f"Block {index} asset does not exist: {raw}") from exc+ relative = by_source.get(resolved)+ elif ".." not in path.parts:+ relative = by_relative.get(path)+ if relative is None:+ candidate = root / path+ try:+ relative = by_source.get(candidate.resolve(strict=True))+ except FileNotFoundError:+ relative = None+ if relative is None:+ raise IngressError(f"Block {index} asset is outside the frozen asset set: {raw}")+ block[key] = relative.as_posix()+ return frozen+++def freeze_document(working_dir: Path, source: Path, parsed: ParsedDocument) -> StagedDocument:+ """Copy one parsed document into an immutable, digest-verified bundle."""+ source = Path(source)+ canonical_name = source.name+ if not canonical_name or canonical_name in {".", ".."}:+ raise IngressError(f"Document has no canonical basename: {source}")+ pending = pending_root(working_dir)+ bundles = bundles_root(working_dir)+ pending.mkdir(parents=True, exist_ok=True)+ bundles.mkdir(parents=True, exist_ok=True)+ staged_source = pending / canonical_name+ archived_source = pending / "__parsed__" / canonical_name+ final_bundle = bundles / f"{canonical_name}.bundle"+ if staged_source.exists() or archived_source.exists() or final_bundle.exists():+ raise IngressError(f"Canonical basename already exists in this version: {canonical_name}")++ temp_bundle = bundles / f".{canonical_name}.{uuid.uuid4().hex}.tmp"+ temp_bundle.mkdir()+ try:+ asset_files = _asset_files(parsed.asset_dir)+ source_digest = _sha256(source.resolve(strict=True))+ staged_digest = _copy_regular(source, staged_source)+ if source_digest != staged_digest:+ raise IngressError(f"Source changed while staging {canonical_name}")++ markdown = parsed.markdown.encode("utf-8")+ markdown_rel = Path("markdown.utf8")+ markdown_digest = _write_new_bytes(temp_bundle / markdown_rel, markdown)++ decision = None+ blocks_rel: Path | None = None+ blocks_digest: str | None = None+ frozen_blocks: list[dict[str, Any]] | None = None+ if parsed.blocks:+ decision = block_policy.prepare_content_list(+ parsed.blocks,+ engine=parsed.engine,+ source_hash=parsed.source_hash,+ parser_signature=parsed.parser_signature,+ )+ frozen_blocks = _freeze_asset_paths(+ decision.content_list, parsed.asset_dir, asset_files+ )+ blocks_rel = Path("blocks.json")+ blocks_bytes = json.dumps(+ frozen_blocks, ensure_ascii=False, sort_keys=True, separators=(",", ":")+ ).encode("utf-8")+ blocks_digest = _write_new_bytes(temp_bundle / blocks_rel, blocks_bytes)+ elif not parsed.markdown.strip():+ raise IngressError(f"Parsed document is empty: {canonical_name}")++ asset_records: list[dict[str, Any]] = []+ for asset, relative in asset_files:+ target = temp_bundle / "assets" / relative+ digest = _copy_regular(asset, target, allowed_root=Path(parsed.asset_dir))+ asset_records.append(+ {"path": target.relative_to(temp_bundle).as_posix(), "sha256": digest}+ )++ kinds = {+ str(block.get("type") or block.get("label") or "").lower()+ for block in (frozen_blocks or [])+ if isinstance(block, dict)+ }+ modalities = "".join(+ flag+ for flag, names in (+ ("i", {"image", "picture", "drawing", "chart"}),+ ("t", {"table"}),+ ("e", {"equation", "formula"}),+ )+ if kinds & names+ )+ process_options = f"P{modalities}" if frozen_blocks else "F"+ chunk_options = (+ {"paragraph_semantic": {"chunk_token_size": 1200}}+ if frozen_blocks+ else {"fixed_token": {}}+ )+ manifest = {+ "parser_bridge_schema": PARSER_BRIDGE_SCHEMA,+ "canonical_filename": canonical_name,+ "parser": {+ "engine": parsed.engine,+ "source_hash": parsed.source_hash,+ "parser_signature": parsed.parser_signature,+ },+ "source": {+ "path": str(Path("..") / ".." / PENDING_DIRNAME / canonical_name),+ "sha256": staged_digest,+ },+ "markdown": {"path": markdown_rel.as_posix(), "sha256": markdown_digest},+ "blocks": (+ {"path": blocks_rel.as_posix(), "sha256": blocks_digest}+ if blocks_rel is not None+ else None+ ),+ "assets": asset_records,+ "process_options": process_options,+ "chunk_options": chunk_options,+ "block_policy": decision.ledger if decision is not None else None,+ }+ atomic_write_json(temp_bundle / MANIFEST_FILENAME, manifest)+ os.replace(temp_bundle, final_bundle)+ return StagedDocument(+ canonical_name=canonical_name,+ source_path=staged_source,+ bundle_dir=final_bundle,+ manifest_path=final_bundle / MANIFEST_FILENAME,+ process_options=process_options,+ chunk_options=chunk_options,+ audit_ledger=decision.ledger if decision is not None else None,+ )+ except BaseException:+ shutil.rmtree(temp_bundle, ignore_errors=True)+ if staged_source.exists() and not staged_source.is_symlink():+ staged_source.unlink()+ raise+++def load_verified_bundle(working_dir: Path, canonical_name: str) -> tuple[dict[str, Any], Path]:+ """Load and digest-verify one published bundle by canonical basename."""+ if Path(canonical_name).name != canonical_name or Path(canonical_name).is_absolute():+ raise IngressError(f"Invalid canonical basename: {canonical_name!r}")+ bundle = bundles_root(working_dir) / f"{canonical_name}.bundle"+ manifest_path = bundle / MANIFEST_FILENAME+ manifest = json.loads(+ _contained_regular_file(bundle, manifest_path, label="manifest").read_text(encoding="utf-8")+ )+ if (+ not isinstance(manifest, dict)+ or manifest.get("parser_bridge_schema") != PARSER_BRIDGE_SCHEMA+ ):+ raise IngressError(f"Unsupported parser bridge manifest: {manifest_path}")+ if manifest.get("canonical_filename") != canonical_name:+ raise IngressError(f"Bundle basename mismatch: {canonical_name}")++ records: list[tuple[str, dict[str, Any]]] = []+ for key in ("markdown", "blocks"):+ record = manifest.get(key)+ if record is not None:+ if not isinstance(record, dict):+ raise IngressError(f"Malformed {key} record in {manifest_path}")+ records.append((key, record))+ assets = manifest.get("assets")+ if not isinstance(assets, list):+ raise IngressError(f"Malformed assets record in {manifest_path}")+ records.extend(("asset", record) for record in assets if isinstance(record, dict))+ if len(records) != 1 + int(manifest.get("blocks") is not None) + len(assets):+ raise IngressError(f"Malformed asset entry in {manifest_path}")+ for label, record in records:+ rel = Path(str(record.get("path") or ""))+ if rel.is_absolute() or ".." in rel.parts:+ raise IngressError(f"Unsafe {label} path in {manifest_path}")+ path = _contained_regular_file(bundle, bundle / rel, label=label)+ if _sha256(path) != record.get("sha256"):+ raise IngressError(f"Digest mismatch for {label}: {path}")+ return manifest, bundle+++def remove_unaccepted(staged: StagedDocument) -> None:+ """Remove only a pre-enqueue source/bundle whose doc_status does not exist."""+ if staged.source_path.exists() and not staged.source_path.is_symlink():+ staged.source_path.unlink()+ shutil.rmtree(staged.bundle_dir, ignore_errors=True)+++__all__ = [+ "BUNDLES_DIRNAME",+ "INGRESS_DIRNAME",+ "IngressError",+ "PARSER_BRIDGE_SCHEMA",+ "PENDING_DIRNAME",+ "StagedDocument",+ "bundles_root",+ "freeze_document",+ "ingress_root",+ "load_verified_bundle",+ "pending_root",+ "remove_unaccepted",+]diff --git a/deeptutor/services/rag/pipelines/lightrag/parser.py b/deeptutor/services/rag/pipelines/lightrag/parser.pynew file mode 100644index 000000000..c7456ff5e--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/parser.py@@ -0,0 +1,99 @@+"""LightRAG parser that consumes frozen DeepTutor ingress bundles."""++from __future__ import annotations++import hashlib+from pathlib import Path+import time++from lightrag.parser.base import BaseParser++from .ingress import IngressError, load_verified_bundle+from .sidecar import build_ir+++class DeepTutorParser(BaseParser):+ """Third-party parser registered as ``deeptutor`` in LightRAG rc2."""++ engine_name = "deeptutor"++ async def parse(self, ctx):+ from lightrag.constants import (+ FULL_DOCS_FORMAT_LIGHTRAG,+ FULL_DOCS_FORMAT_RAW,+ )+ from lightrag.parser.base import ParseResult+ from lightrag.sidecar.writer import write_sidecar+ from lightrag.utils import strip_control_characters+ from lightrag.utils_pipeline import make_lightrag_doc_content, sidecar_uri_for++ resolved = ctx.resolve(self.engine_name)+ source = resolved.source_path+ if source.is_symlink() or not source.is_file():+ raise IngressError(f"Frozen ingress source is not an ordinary file: {source}")+ manifest, bundle = load_verified_bundle(Path(ctx.rag.working_dir), resolved.document_name)++ digest = hashlib.sha256()+ with source.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ source_record = manifest.get("source")+ if not isinstance(source_record, dict) or digest.hexdigest() != source_record.get("sha256"):+ raise IngressError(f"Frozen source digest mismatch: {resolved.document_name}")++ markdown_record = manifest["markdown"]+ markdown = strip_control_characters(+ (bundle / markdown_record["path"]).read_text(encoding="utf-8")+ )+ if manifest.get("blocks") is None:+ if not markdown.strip():+ raise IngressError(f"Frozen RAW document is empty: {resolved.document_name}")+ await ctx.rag._persist_parsed_full_docs(+ ctx.doc_id,+ {+ "content": markdown,+ "file_path": ctx.file_path,+ "parse_format": FULL_DOCS_FORMAT_RAW,+ "parse_engine": self.engine_name,+ "update_time": int(time.time()),+ },+ )+ await ctx.archive_source(str(source))+ return ParseResult(+ doc_id=ctx.doc_id,+ file_path=ctx.file_path,+ parse_format=FULL_DOCS_FORMAT_RAW,+ content=markdown,+ parse_engine=self.engine_name,+ )++ ir = build_ir(manifest, bundle)+ parsed_data = write_sidecar(+ ir,+ parsed_dir=resolved.parsed_dir,+ doc_id=ctx.doc_id,+ engine=self.engine_name,+ )+ await ctx.rag._persist_parsed_full_docs(+ ctx.doc_id,+ {+ "content": make_lightrag_doc_content(parsed_data["content"]),+ "file_path": ctx.file_path,+ "parse_format": FULL_DOCS_FORMAT_LIGHTRAG,+ "sidecar_location": sidecar_uri_for(resolved.parsed_dir),+ "parse_engine": self.engine_name,+ "update_time": int(time.time()),+ },+ )+ await ctx.archive_source(str(source))+ return ParseResult(+ doc_id=ctx.doc_id,+ file_path=ctx.file_path,+ parse_format=FULL_DOCS_FORMAT_LIGHTRAG,+ content=parsed_data["content"],+ blocks_path=parsed_data["blocks_path"],+ parse_engine=self.engine_name,+ )+++__all__ = ["DeepTutorParser"]diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex ad76b5d0e..7a2f81701 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -1,53 +1,95 @@-"""LightRAG-backed RAG pipeline orchestration.--Implements the same contract as :class:`LlamaIndexPipeline` (see-``..base.RAGPipeline``) but delegates indexing/retrieval to RAG-Anything /-LightRAG. Each KB owns a self-contained LightRAG store under its ``version-N``-directory (see ``storage``).--Documents are turned into a MinerU-style ``content_list`` by DeepTutor's shared-parse layer (``deeptutor/services/parsing``) — the same bridge the question-extractor uses — so multimodal parsing stays a decoupled, cached, engine--pluggable concern and this pipeline only ever feeds LightRAG ready content.--LightRAG is an optional dependency: every method fails with a clear, actionable-message when it is not installed instead of an opaque ``ImportError``.-"""+"""DeepTutor orchestration for the LightRAG 1.5 native document pipeline."""from __future__ import annotationsimport asyncio-from collections.abc import Callable+from dataclasses import dataclass, field, replaceimport loggingfrom pathlib import Pathimport shutilimport traceback-from typing import Any, Dict, List, Optional+from typing import Any, Callable, Dict, List, Optionalfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.index_versioning import (+ list_kb_versions,resolve_storage_dir_for_read,resolve_storage_dir_for_rebuild,)from deeptutor.services.rag.kb_paths import resolve_kb_dir-from . import block_policy, engine, storage+from . import block_policy, engine, ingress, storagefrom . import config as lr_configfrom .worker import OwnerLoopBridge, run_in_worker_looplogger = logging.getLogger(__name__)-DEFAULT_KB_BASE_DIR = str(get_runtime_data_root() / "knowledge_bases")-class LightRagPipeline:- """Index/retrieve KB content via RAG-Anything / LightRAG."""+@dataclass(frozen=True)+class BatchOutcome:+ requested: int+ preflight_failed: dict[str, str] = field(default_factory=dict)+ accepted: int = 0+ processed: tuple[str, ...] = ()+ failed: dict[str, str] = field(default_factory=dict)+ nonterminal: dict[str, str] = field(default_factory=dict)+ missing: tuple[str, ...] = ()+ track_id: str = ""++ @property+ def complete(self) -> bool:+ return (+ self.requested > 0+ and len(self.processed) == self.requested+ and not self.preflight_failed+ and not self.failed+ and not self.nonterminal+ and not self.missing+ )+++class LightRagBatchError(RuntimeError):+ def __init__(self, outcome: BatchOutcome) -> None:+ self.outcome = outcome+ failures = {**outcome.preflight_failed, **outcome.failed}+ detail = "; ".join(f"{name}: {error}" for name, error in sorted(failures.items()))+ message = (+ f"LightRAG batch incomplete: added {len(outcome.processed)}, "+ f"failed {len(failures)}, missing {len(outcome.missing)}, "+ f"nonterminal {len(outcome.nonterminal)}"+ )+ super().__init__(f"{message}: {detail}" if detail else message)++class LightRagNeedsReindexError(RuntimeError):+ """Raised when an append targets a pre-native LightRAG index."""+++def _status_text(row: Any) -> str:+ status = getattr(row, "status", None)+ value = getattr(status, "value", status)+ return str(value or "").strip().lower()+++def _row_name(row: Any) -> str:+ return Path(str(getattr(row, "file_path", "") or "")).name+++def _row_error(row: Any) -> str:+ for key in ("error_msg", "error"):+ value = getattr(row, key, None)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return _status_text(row) or "unknown LightRAG failure"+++class LightRagPipeline:def __init__(self, kb_base_dir: Optional[str] = None, **_: Any) -> None:self.logger = logging.getLogger(__name__)self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR-- # ----- helpers --------------------------------------------------------+ self._status_poll_seconds = 0.2+ self._status_no_progress_seconds = 600.0def _ensure_available(self) -> None:if not lr_config.is_lightrag_available():@@ -68,265 +110,305 @@ class LightRagPipeline:default=lr_config.DEFAULT_MODE,)- def _cleanup_failed_version_dir(self, root_dir: Path) -> None:- try:- if root_dir.is_dir() and not (root_dir / storage.META_FILENAME).exists():- shutil.rmtree(root_dir)- except Exception as exc: # pragma: no cover - best-effort- self.logger.warning("Could not clean up failed version dir %s: %s", root_dir, exc)+ def _stage_documents(+ self, working_dir: Path, file_paths: List[str]+ ) -> tuple[list[ingress.StagedDocument], dict[str, str]]:+ from deeptutor.services.parsing import get_parse_service- async def _ingest(+ parse_service = get_parse_service()+ staged: list[ingress.StagedDocument] = []+ failures: dict[str, str] = {}+ seen: set[str] = set()+ vision_available = lr_config.vision_model_available()+ for raw_path in file_paths:+ path = Path(raw_path)+ name = path.name+ if name in seen:+ failures[name] = "duplicate canonical basename in request"+ continue+ seen.add(name)+ try:+ parsed = parse_service.parse(path)+ item = ingress.freeze_document(working_dir, path, parsed)+ if "i" in item.process_options and not vision_available:+ item = replace(item, process_options=item.process_options.replace("i", ""))+ staged.append(item)+ except Exception as exc:+ failures[name or str(path)] = str(exc)+ return staged, failures++ async def _reconcile(self,rag: Any,- file_paths: List[str],- *,+ staged: list[ingress.StagedDocument],+ preflight_failed: dict[str, str],+ track_id: str,io_bridge: OwnerLoopBridge,- progress_callback: Callable[[int, int], Any] | None = None,- ) -> int:- """Parse each file via the shared parse layer and insert it into LightRAG.-- Returns the number of documents successfully inserted. Per-file failures- are logged and skipped so one bad document doesn't abort the batch.- """- from deeptutor.services.parsing import ParserError, get_parse_service-- parse_service = get_parse_service()- inserted = 0- total = len(file_paths)- for file_path in file_paths:+ progress_callback: Callable[[int, int], Any] | None,+ ) -> BatchOutcome:+ expected = {item.canonical_name: item for item in staged}+ last_snapshot: tuple[tuple[str, str], ...] | None = None+ last_progress = asyncio.get_running_loop().time()+ terminal_count = 0+ while True:io_bridge.raise_if_cancelled()- path = Path(file_path)- try:- doc = parse_service.parse(path)- except ParserError as exc:- self.logger.warning("LightRAG: parse failed for %s: %s", path.name, exc)- continue+ rows = await rag.aget_docs_by_track_id(track_id)+ if not isinstance(rows, dict):+ raise engine.LightRagContractError("aget_docs_by_track_id must return an object")+ by_name: dict[str, tuple[str, Any]] = {}+ duplicates: set[str] = set()+ for doc_id, row in rows.items():+ name = _row_name(row)+ if name in by_name:+ duplicates.add(name)+ by_name[name] = (str(doc_id), row)+ if duplicates:+ raise engine.LightRagContractError(+ f"track_id returned duplicate canonical basenames: {sorted(duplicates)}"+ )- accepted_ledger: dict[str, Any] | None = None- attempt_id: str | None = None- if doc.blocks:- document_id = doc.source_hash or path.stem- decision = block_policy.prepare_content_list(- doc.blocks,- engine=doc.engine,- source_hash=doc.source_hash,- parser_signature=doc.parser_signature,+ snapshot = tuple(+ sorted((name, _status_text(row)) for name, (_, row) in by_name.items())+ )+ if snapshot != last_snapshot:+ last_snapshot = snapshot+ last_progress = asyncio.get_running_loop().time()+ processed = tuple(+ sorted(+ name+ for name, (_, row) in by_name.items()+ if name in expected and _status_text(row) == "processed"+ )+ )+ failed = {+ name: _row_error(row)+ for name, (_, row) in by_name.items()+ if name in expected and _status_text(row) == "failed"+ }+ unknown = {+ name: _status_text(row)+ for name, (_, row) in by_name.items()+ if name in expected+ and _status_text(row)+ not in {+ "pending",+ "parsing",+ "analyzing",+ "processing",+ "preprocessed",+ "processed",+ "failed",+ }+ }+ active = {+ name: _status_text(row)+ for name, (_, row) in by_name.items()+ if name in expected+ and _status_text(row)+ in {"pending", "parsing", "analyzing", "processing", "preprocessed"}+ }+ missing = tuple(sorted(set(expected) - set(by_name)))+ current_terminal = len(processed) + len(failed)+ if progress_callback is not None and current_terminal != terminal_count:+ terminal_count = current_terminal+ await io_bridge.call(+ progress_callback, terminal_count, len(expected) + len(preflight_failed))- if decision.ledger is not None:- outcome = "unknown_types" if decision.unknown_type_counts else "accepted"- _, attempt_id = block_policy.write_attempt_ledger(- Path(rag.working_dir).parent,- document_id,- decision.ledger,- outcome=outcome,- )- counts = decision.ledger["counts"]- self.logger.info(- "MinerU block policy %s raw=%d filtered=%d eligible=%d unknown=%d",- block_policy.POLICY_ID,- counts["raw_total"],- counts["filtered_total"],- counts["eligible_total"],- counts["unknown_total"],- )- if decision.unknown_type_counts:- # Indexed, not dropped and not fatal — say so, because- # this is the signal that the policy needs a new entry.- self.logger.warning(- "LightRAG: %s has MinerU block types with no policy "- "entry (%s); indexing them unclassified",- path.name,- decision.unknown_summary(),+ if not active and not missing:+ outcome = BatchOutcome(+ requested=len(expected) + len(preflight_failed),+ preflight_failed=preflight_failed,+ accepted=len(expected),+ processed=processed,+ failed=failed,+ nonterminal=unknown,+ missing=(),+ track_id=track_id,+ )+ for name in processed:+ item = expected[name]+ if item.audit_ledger is not None:+ doc_id = by_name[name][0]+ block_policy.write_decision_ledger(+ Path(rag.working_dir), doc_id, item.audit_ledger)- accepted_ledger = decision.ledger- content_list = decision.content_list- else:- content_list = (- [{"type": "text", "text": doc.markdown, "page_idx": 0}] if doc.markdown else []+ return outcome+ if unknown:+ return BatchOutcome(+ requested=len(expected) + len(preflight_failed),+ preflight_failed=preflight_failed,+ accepted=len(expected),+ processed=processed,+ failed=failed,+ nonterminal=unknown,+ missing=missing,+ track_id=track_id,)- if not content_list:- self.logger.warning("LightRAG: empty document skipped: %s", path.name)- continue-- await engine.insert(- rag,- content_list,- file_name=path.name,- doc_id=doc.source_hash or path.stem,- )- io_bridge.raise_if_cancelled()- doc_error = storage.document_error(Path(rag.working_dir), doc.source_hash or path.stem)- if doc_error:- raise RuntimeError(f"{path.name}: {doc_error}")- if accepted_ledger is not None:- block_policy.write_decision_ledger(- Path(rag.working_dir),- doc.source_hash or path.stem,- accepted_ledger,- attempt_id=attempt_id,+ if (+ asyncio.get_running_loop().time() - last_progress+ >= self._status_no_progress_seconds+ ):+ return BatchOutcome(+ requested=len(expected) + len(preflight_failed),+ preflight_failed=preflight_failed,+ accepted=len(expected),+ processed=processed,+ failed=failed,+ nonterminal=active,+ missing=missing,+ track_id=track_id,)- inserted += 1- self.logger.info("LightRAG: inserted %s", path.name)- if progress_callback is not None:- await io_bridge.call(progress_callback, inserted, total)- return inserted+ await asyncio.sleep(self._status_poll_seconds)async def _run_indexing(self,working_dir: Path,file_paths: List[str],progress_callback: Callable[[int, int], Any] | None,- ) -> int:- """Run the complete local LightRAG indexing phase off the service loop.-- The RAG instance is constructed and consumed in one worker thread, so- its mutable stores and asyncio primitives never cross event loops.- DeepTutor-owned network calls and progress callbacks cross back through- ``OwnerLoopBridge`` and remain responsive while local JSON storage is- busy in the worker.- """-- async def job(io_bridge: OwnerLoopBridge) -> int:+ ) -> BatchOutcome:+ async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:io_bridge.raise_if_cancelled()- rag = engine.build_rag(working_dir, io_bridge=io_bridge)+ staged, preflight_failed = self._stage_documents(working_dir, file_paths)+ if not staged:+ raise LightRagBatchError(+ BatchOutcome(requested=len(file_paths), preflight_failed=preflight_failed)+ )+ try:+ rag = engine.build_rag(+ working_dir,+ io_bridge=io_bridge,+ enable_vlm=any("i" in item.process_options for item in staged),+ )+ except BaseException:+ for item in staged:+ ingress.remove_unaccepted(item)+ raisefailed = Truetry:- result = await self._ingest(+ await engine.initialize(rag)+ track_id = await engine.enqueue(rag, staged)+ await rag.apipeline_process_enqueue_documents()+ outcome = await self._reconcile(rag,- file_paths,- io_bridge=io_bridge,- progress_callback=progress_callback,+ staged,+ preflight_failed,+ track_id,+ io_bridge,+ progress_callback,)+ if not outcome.complete:+ raise LightRagBatchError(outcome)failed = False- return result+ return outcomefinally:try:await engine.finalize(rag, cancel_pending=failed)except BaseException:if not failed:raise- self.logger.exception(- "LightRAG resource cleanup failed while indexing was aborting"- )+ self.logger.exception("LightRAG cleanup failed while indexing was aborting")return await run_in_worker_loop(job)- # ----- indexing -------------------------------------------------------+ def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:+ if root_dir.is_dir() and not storage.has_any_doc_status(root_dir):+ shutil.rmtree(root_dir)async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()- progress_callback = kwargs.get("progress_callback")kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)- self.logger.info(- "Initializing KB '%s' with %d file(s) using LightRAG", kb_name, len(file_paths)- )try:- count = await self._run_indexing(- storage.working_dir(root_dir), file_paths, progress_callback+ outcome = await self._run_indexing(+ root_dir, file_paths, kwargs.get("progress_callback"))- if count == 0:- self.logger.error("LightRAG: no extractable documents for '%s'", kb_name)- self._cleanup_failed_version_dir(root_dir)- return Falseif not storage.has_output(root_dir):- details = storage.failure_summary(root_dir)- message = f"LightRAG did not produce a ready index for '{kb_name}'"- if details:- message = f"{message}: {details}"- self.logger.error(message)- self._cleanup_failed_version_dir(root_dir)- raise RuntimeError(message)+ raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")storage.write_meta(root_dir)- self.logger.info("KB '%s' initialized with LightRAG (%d docs)", kb_name, count)- return True+ return outcome.completeexcept asyncio.CancelledError:- self._cleanup_failed_version_dir(root_dir)raise- except Exception as exc:- self.logger.error("Failed to initialize LightRAG KB: %s", exc)- self.logger.error(traceback.format_exc())- self._cleanup_failed_version_dir(root_dir)+ except LightRagBatchError as exc:+ if exc.outcome.accepted == 0:+ self._remove_zero_accepted_candidate(root_dir)+ raise+ except Exception:+ self._remove_zero_accepted_candidate(root_dir)raise+ def _legacy_exists(self, kb_dir: Path) -> bool:+ return any(+ entry.get("provider") == storage.PROVIDER+ and entry.get("ready")+ and not storage.meta_is_native_published(Path(str(entry["storage_path"])))+ for entry in list_kb_versions(kb_dir)+ )+async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()- progress_callback = kwargs.get("progress_callback")kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)existing = resolve_storage_dir_for_read(kb_dir, None)- if existing is not None and storage.has_output(existing):- is_update = True+ if existing is not None and storage.meta_is_native_published(existing):root_dir = existing+ is_update = True+ elif existing is not None or self._legacy_exists(kb_dir):+ raise LightRagNeedsReindexError(+ "This LightRAG index predates the native adapter and must be rebuilt before appending."+ )else:- is_update = Falseroot_dir = resolve_storage_dir_for_rebuild(kb_dir, None)-- self.logger.info(- "Adding %d document(s) to LightRAG KB '%s' (update=%s)",- len(file_paths),- kb_name,- is_update,- )+ is_update = Falsetry:- count = await self._run_indexing(- storage.working_dir(root_dir), file_paths, progress_callback+ outcome = await self._run_indexing(+ root_dir, file_paths, kwargs.get("progress_callback"))- if count == 0:- self.logger.warning("LightRAG: no extractable documents to add for '%s'", kb_name)- return Falseif not storage.has_output(root_dir):- details = storage.failure_summary(root_dir)- message = f"LightRAG did not produce a ready index for '{kb_name}'"- if details:- message = f"{message}: {details}"- self.logger.error(message)- if not is_update:- self._cleanup_failed_version_dir(root_dir)- raise RuntimeError(message)+ raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")storage.write_meta(root_dir)- self.logger.info("Added %d doc(s) to LightRAG KB '%s'", count, kb_name)- return True- except asyncio.CancelledError:- if not is_update:- self._cleanup_failed_version_dir(root_dir)+ return outcome.complete+ except LightRagBatchError as exc:+ if not is_update and exc.outcome.accepted == 0:+ self._remove_zero_accepted_candidate(root_dir)raise- except Exception as exc:- self.logger.error("Failed to add documents to LightRAG KB: %s", exc)- self.logger.error(traceback.format_exc())+ except Exception:if not is_update:- self._cleanup_failed_version_dir(root_dir)+ self._remove_zero_accepted_candidate(root_dir)raise- # ----- retrieval -------------------------------------------------------async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)root_dir = resolve_storage_dir_for_read(kb_dir, None)-- if root_dir is None or not storage.has_output(root_dir):+ if root_dir is None or not storage.meta_is_native_published(root_dir):return {"query": query,- "answer": (- "This LightRAG knowledge base has no index yet. Add documents before querying."- ),+ "answer": "This LightRAG knowledge base must be rebuilt for the native pipeline.","content": "","sources": [],"provider": storage.PROVIDER,"needs_reindex": True,}-mode = self._resolve_mode(kb_name, kwargs)try:self._ensure_available()- rag = engine.build_rag(storage.working_dir(root_dir))- answer, sources = await engine.query_with_sources(rag, query, mode)++ async def job(io_bridge: OwnerLoopBridge):+ rag = engine.build_rag(root_dir, io_bridge=io_bridge)+ failed = True+ try:+ await engine.initialize(rag)+ result = await engine.query_with_sources(rag, query, mode)+ failed = False+ return result+ finally:+ await engine.finalize(rag, cancel_pending=failed)++ answer, sources = await run_in_worker_loop(job)except lr_config.LightRagNotAvailableError as exc:return self._error_result(query, exc, error_type="not_configured")except Exception as exc:self.logger.error("LightRAG search failed: %s", exc)self.logger.error(traceback.format_exc())return self._error_result(query, exc, error_type="retrieval_error")-return {"query": query,"answer": answer,@@ -346,15 +428,17 @@ class LightRagPipeline:"error_type": error_type,}- # ----- lifecycle -------------------------------------------------------async def delete(self, kb_name: str, **kwargs) -> bool:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)if kb_dir.exists():shutil.rmtree(kb_dir)- self.logger.info("Deleted LightRAG KB '%s'", kb_name)return Truereturn False-__all__ = ["LightRagPipeline"]+__all__ = [+ "BatchOutcome",+ "LightRagBatchError",+ "LightRagNeedsReindexError",+ "LightRagPipeline",+]diff --git a/deeptutor/services/rag/pipelines/lightrag/sidecar.py b/deeptutor/services/rag/pipelines/lightrag/sidecar.pynew file mode 100644index 000000000..638cf9d59--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/sidecar.py@@ -0,0 +1,320 @@+"""Map frozen DeepTutor MinerU blocks to LightRAG's public Sidecar IR."""++from __future__ import annotations++import json+from pathlib import Path+import re+from typing import Any+++class SidecarMappingError(ValueError):+ """Raised when a structured block cannot be represented without data loss."""+++def _text(item: dict[str, Any]) -> str:+ for key in ("text", "content", "body", "code_body"):+ value = item.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return ""+++def _strings(value: Any) -> list[str]:+ if isinstance(value, list):+ return [str(item).strip() for item in value if str(item).strip()]+ value = str(value or "").strip()+ return [value] if value else []+++def _position(item: dict[str, Any]):+ from lightrag.sidecar.ir import IRPosition++ page = item.get("page_idx", item.get("page"))+ if isinstance(page, bool):+ page = None+ elif isinstance(page, int):+ page = str(page + 1) if page >= 0 else str(page)+ elif page is not None:+ page = str(page).strip() or None+ bbox = item.get("bbox")+ if isinstance(bbox, (list, tuple)) and len(bbox) >= 4:+ try:+ return IRPosition(type="bbox", anchor=page, range=[float(value) for value in bbox[:4]])+ except (TypeError, ValueError):+ pass+ return IRPosition(type="bbox", anchor=page) if page is not None else None+++def _heading(item: dict[str, Any], kind: str) -> tuple[str, int]:+ level = item.get("text_level", item.get("level", 0))+ try:+ level = int(level or 0)+ except (TypeError, ValueError):+ level = 0+ if kind in {"title", "section_header"}:+ return _text(item), max(level, 1)+ if kind == "text" and level > 0:+ return _text(item), level+ return "", 0+++def _rows(value: Any) -> list[list[str]] | None:+ if isinstance(value, str):+ stripped = value.strip()+ if stripped.startswith("["):+ try:+ value = json.loads(stripped)+ except json.JSONDecodeError:+ return None+ else:+ return None+ if not isinstance(value, list):+ return None+ rows: list[list[str]] = []+ for raw_row in value:+ if not isinstance(raw_row, list):+ continue+ rows.append(+ [+ str(cell.get("text", "")).strip() if isinstance(cell, dict) else str(cell).strip()+ for cell in raw_row+ ]+ )+ return rows or None+++def _caption(item: dict[str, Any], *keys: str) -> str:+ direct = str(item.get("caption") or "").strip()+ if direct:+ return direct+ for key in keys:+ values = _strings(item.get(key))+ if values:+ return values[0]+ return ""+++def _resolve_asset(bundle: Path, manifest: dict[str, Any], raw: str) -> Path | None:+ if not raw:+ return None+ relative = Path(raw)+ if relative.is_absolute() or ".." in relative.parts:+ raise SidecarMappingError(f"Asset path escapes the frozen bundle: {raw}")+ candidates: list[Path] = []+ direct = bundle / "assets" / relative+ if direct.is_file():+ candidates.append(direct)+ basename = relative.name+ for record in manifest.get("assets", []):+ path = bundle / str(record.get("path") or "")+ if path.name == basename and path.is_file() and path not in candidates:+ candidates.append(path)+ if len(candidates) > 1:+ raise SidecarMappingError(f"Asset basename is ambiguous in the frozen bundle: {raw}")+ return candidates[0] if candidates else None+++def build_ir(manifest: dict[str, Any], bundle: Path):+ """Return an ``IRDoc`` using only LightRAG's public Sidecar types."""+ from lightrag.sidecar.ir import (+ AssetSpec,+ IRBlock,+ IRDoc,+ IRDrawing,+ IREquation,+ IRTable,+ )++ blocks_record = manifest.get("blocks")+ if not isinstance(blocks_record, dict):+ raise SidecarMappingError("Sidecar mapping requires a blocks payload")+ raw_blocks = json.loads((bundle / blocks_record["path"]).read_text(encoding="utf-8"))+ if not isinstance(raw_blocks, list):+ raise SidecarMappingError("Frozen blocks payload is not an array")++ output: list[Any] = []+ assets: list[Any] = []+ asset_refs: dict[Path, str] = {}+ heading_stack: list[str] = []+ current_lines: list[str] = []+ current_tables: list[Any] = []+ current_drawings: list[Any] = []+ current_equations: list[Any] = []+ current_positions: list[Any] = []+ current_heading = "Preface/Uncategorized"+ current_level = 0+ current_parents: list[str] = []+ sequence = 0+ document_title = ""++ def next_key(prefix: str) -> str:+ nonlocal sequence+ sequence += 1+ return f"{prefix}{sequence}"++ def flush() -> None:+ nonlocal \+ current_lines, \+ current_tables, \+ current_drawings, \+ current_equations, \+ current_positions+ content = "\n".join(line for line in current_lines if line).strip()+ if not content and not (current_tables or current_drawings or current_equations):+ current_lines = []+ current_positions = []+ return+ output.append(+ IRBlock(+ content_template=content,+ heading=current_heading,+ level=current_level,+ parent_headings=list(current_parents),+ positions=list(current_positions),+ tables=list(current_tables),+ drawings=list(current_drawings),+ equations=list(current_equations),+ )+ )+ current_lines = []+ current_tables = []+ current_drawings = []+ current_equations = []+ current_positions = []++ for index, item in enumerate(raw_blocks):+ if not isinstance(item, dict):+ raise SidecarMappingError(f"Structured block {index} is not an object")+ kind = str(item.get("type") or item.get("label") or "").strip().lower()+ heading, level = _heading(item, kind)+ position = _position(item)+ if heading:+ flush()+ heading = re.sub(r"^#{1,6}\s+", "", heading).strip()+ heading_stack = heading_stack[: max(level - 1, 0)]+ current_parents = [value for value in heading_stack if value]+ heading_stack.append(heading)+ current_heading = heading+ current_level = level+ current_lines.append(f"{'#' * min(level, 6)} {heading}")+ if position is not None:+ current_positions.append(position)+ if not document_title and level == 1:+ document_title = heading+ continue++ if kind in {"text", "aside_text", "page_footnote"}:+ value = _text(item)+ if value:+ current_lines.append(value)+ elif kind == "list":+ values = item.get("list_items")+ value = "\n".join(_strings(values)) if isinstance(values, list) else _text(item)+ if value:+ current_lines.append(value)+ elif kind == "code":+ value = str(item.get("code_body") or _text(item)).strip()+ if value:+ current_lines.extend(_strings(item.get("code_caption")))+ current_lines.append(value)+ current_lines.extend(_strings(item.get("code_footnote")))+ elif kind == "table":+ body = item.get("rows", item.get("table_body"))+ table_rows = _rows(body)+ table_html = (+ body.strip() if isinstance(body, str) and "<table" in body.lower() else None+ )+ if not table_rows and not table_html:+ raise SidecarMappingError(f"Structured table {index} has no usable body")+ key = next_key("tb")+ current_tables.append(+ IRTable(+ placeholder_key=key,+ rows=table_rows,+ html=table_html,+ num_rows=int(item.get("num_rows") or (len(table_rows) if table_rows else 0)),+ num_cols=int(+ item.get("num_cols") or (max(map(len, table_rows)) if table_rows else 0)+ ),+ caption=_caption(item, "table_caption"),+ footnotes=_strings(item.get("table_footnote") or item.get("footnotes")),+ table_header=_rows(item.get("header")),+ self_ref=f"blocks.json#/{index}",+ )+ )+ current_lines.append(f"{{{{TBL:{key}}}}}")+ elif kind in {"image", "picture", "drawing", "chart"}:+ raw_path = str(item.get("img_path") or item.get("path") or "")+ asset_path = _resolve_asset(bundle, manifest, raw_path)+ if asset_path is None:+ raise SidecarMappingError(f"Structured {kind} {index} has no verified bundle asset")+ ref = ""+ ref = asset_refs.get(asset_path, "")+ if not ref:+ ref = f"asset-{len(asset_refs) + 1}"+ asset_refs[asset_path] = ref+ assets.append(AssetSpec(ref=ref, suggested_name=asset_path.name, source=asset_path))+ key = next_key("im")+ current_drawings.append(+ IRDrawing(+ placeholder_key=key,+ asset_ref=ref,+ fmt=Path(raw_path).suffix.lower().lstrip(".") or str(item.get("format") or ""),+ caption=_caption(item, "image_caption", "chart_caption", "captions"),+ footnotes=_strings(+ item.get("image_footnote")+ or item.get("chart_footnote")+ or item.get("footnotes")+ ),+ src=str(item.get("src") or ""),+ self_ref=f"blocks.json#/{index}",+ )+ )+ current_lines.append(f"{{{{IMG:{key}}}}}")+ elif kind in {"equation", "formula"}:+ latex = _text(item)+ if not latex:+ raise SidecarMappingError(f"Structured equation {index} has no LaTeX")+ key = next_key("eq")+ inline = str(item.get("text_format") or "").lower() in {"inline", "inline_equation"}+ current_equations.append(+ IREquation(+ placeholder_key=key,+ latex=latex,+ is_block=not inline,+ caption=_caption(item, "equation_caption"),+ footnotes=_strings(item.get("equation_footnote") or item.get("footnotes")),+ self_ref=f"blocks.json#/{index}" if not inline else "",+ )+ )+ current_lines.append(f"{{{{{'EQI' if inline else 'EQ'}:{key}}}}}")+ else:+ value = _text(item)+ if not value:+ raise SidecarMappingError(+ f"Unknown structured block type {kind or '<missing>'!r} at {index} has no preservable text"+ )+ current_lines.append(value)+ if position is not None:+ current_positions.append(position)++ flush()+ if not output:+ raise SidecarMappingError("Structured document produced no Sidecar blocks")+ name = str(manifest.get("canonical_filename") or "document")+ return IRDoc(+ document_name=name,+ document_format=Path(name).suffix.lower().lstrip("."),+ doc_title=document_title or Path(name).stem,+ split_option={+ "parser": str((manifest.get("parser") or {}).get("engine") or ""),+ "parser_signature": str((manifest.get("parser") or {}).get("parser_signature") or ""),+ },+ blocks=output,+ assets=assets,+ bbox_attributes={"origin": "LEFTTOP", "max": 1000},+ )+++__all__ = ["SidecarMappingError", "build_ir"]diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.pyindex eb4941156..0e477ddf9 100644--- a/deeptutor/services/rag/pipelines/lightrag/storage.py+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py@@ -31,6 +31,8 @@ logger = logging.getLogger(__name__)META_FILENAME = "meta.json"PROVIDER = "lightrag"+ADAPTER_SCHEMA = 2+PUBLISHED_STATE = "published"# Glob patterns LightRAG writes once it has actually built chunk/vector data.# A graphml file alone is not enough: LightRAG creates an empty graph at startup@@ -46,11 +48,26 @@ def working_dir(root_dir: Path) -> Path:return Path(root_dir)+def _store_root(root_dir: Path) -> Path:+ """Resolve native workspace storage while retaining legacy flat reads."""+ root = Path(root_dir)+ if (root / _DOC_STATUS_FILENAME).exists() or any(root.glob("vdb_*.json")):+ return root+ meta = _read_meta(root)+ workspace = str((meta or {}).get("workspace") or "").strip()+ if not workspace:+ from .engine import workspace_for++ workspace = workspace_for(root)+ candidate = root / workspace+ return candidate if candidate.is_dir() else root++def has_output(root_dir: Path | None) -> bool:"""True when LightRAG has at least one successfully indexed document."""if root_dir is None:return False- root = Path(root_dir)+ root = _store_root(Path(root_dir))if not root.is_dir():return False@@ -93,7 +110,7 @@ def failure_summary(root_dir: Path | None, *, limit: int = 3) -> str:"""Return a short human-readable summary of failed LightRAG documents."""if root_dir is None:return ""- payload = _read_doc_status(Path(root_dir))+ payload = _read_doc_status(_store_root(Path(root_dir)))if not payload:return ""@@ -116,7 +133,7 @@ def document_error(root_dir: Path | None, doc_id: str) -> str:"""Return the stored LightRAG error for one document, if present."""if root_dir is None or not doc_id:return ""- payload = _read_doc_status(Path(root_dir))+ payload = _read_doc_status(_store_root(Path(root_dir)))if not payload:return ""item = payload.get(doc_id)@@ -142,6 +159,58 @@ def _read_doc_status(root_dir: Path) -> dict[str, Any] | None:return None+def has_any_doc_status(root_dir: Path | None) -> bool:+ if root_dir is None:+ return False+ payload = _read_doc_status(_store_root(Path(root_dir)))+ return bool(payload)+++def _read_meta(root_dir: Path) -> dict[str, Any] | None:+ path = Path(root_dir) / META_FILENAME+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return None+ return payload if isinstance(payload, dict) else None+++def meta_is_native_published(root_dir: Path | None) -> bool:+ if root_dir is None:+ return False+ meta = _read_meta(Path(root_dir))+ return bool(+ meta+ and meta.get("provider") == PROVIDER+ and meta.get("signature") == PROVIDER+ and meta.get("lightrag_adapter_schema") == ADAPTER_SCHEMA+ and meta.get("parser_bridge_schema") == 1+ and meta.get("state") == PUBLISHED_STATE+ and has_output(Path(root_dir))+ )+++def _parser_inputs(root_dir: Path) -> list[dict[str, str]]:+ from .ingress import bundles_root, load_verified_bundle++ records: set[tuple[str, str]] = set()+ for bundle in sorted(bundles_root(root_dir).glob("*.bundle")):+ canonical_name = bundle.name.removesuffix(".bundle")+ manifest, _ = load_verified_bundle(root_dir, canonical_name)+ parser = manifest.get("parser")+ if not isinstance(parser, dict):+ continue+ records.add(+ (+ str(parser.get("engine") or ""),+ str(parser.get("parser_signature") or ""),+ )+ )+ return [+ {"engine": engine, "parser_signature": signature} for engine, signature in sorted(records)+ ]++def write_meta(root_dir: Path) -> None:"""Write a flat-layout ``meta.json`` so the version lists as ready.@@ -153,13 +222,24 @@ def write_meta(root_dir: Path) -> None:"""from deeptutor.services.rag.embedding_signature import embedding_meta_fields+ from .engine import installed_version, workspace_for+target = Path(root_dir)+ previous = _read_meta(target) or {}+ now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"payload = {"version": target.name,"signature": PROVIDER,"provider": PROVIDER,+ "state": PUBLISHED_STATE,+ "lightrag_adapter_schema": ADAPTER_SCHEMA,+ "lightrag_package_version": installed_version(),+ "parser_bridge_schema": 1,+ "parser_inputs": _parser_inputs(target),+ "workspace": workspace_for(target),"layout": "flat",- "created_at": datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z",+ "created_at": str(previous.get("created_at") or now),+ "updated_at": now,**embedding_meta_fields(),}atomic_write_json(target / META_FILENAME, payload)@@ -170,7 +250,9 @@ __all__ = ["PROVIDER","document_error","failure_summary",+ "has_any_doc_status","working_dir","has_output",+ "meta_is_native_published","write_meta",]diff --git a/deeptutor/services/rag/pipelines/lightrag/worker.py b/deeptutor/services/rag/pipelines/lightrag/worker.pyindex 2aca5db31..a1332744c 100644--- a/deeptutor/services/rag/pipelines/lightrag/worker.py+++ b/deeptutor/services/rag/pipelines/lightrag/worker.py@@ -1,6 +1,6 @@"""Event-loop isolation helpers for local LightRAG indexing.-RAG-Anything's local storage backends perform synchronous graph merging and+LightRAG's local storage backends perform synchronous graph merging andJSON serialization from inside async methods. Running those methods on theservice event loop therefore stalls unrelated API and LLM work. This moduleprovides one narrow boundary: run the indexing coroutine on a worker thread'sdiff --git a/deeptutor/services/rag/preflight.py b/deeptutor/services/rag/preflight.pyindex 4d1c87419..ca906a357 100644--- a/deeptutor/services/rag/preflight.py+++ b/deeptutor/services/rag/preflight.py@@ -147,10 +147,19 @@ def _graphrag_preflight() -> dict:def _lightrag_preflight() -> dict:+ package_detail = "pip install 'deeptutor[rag-lightrag]'"try:from .pipelines.lightrag.config import is_lightrag_available-- installed = is_lightrag_available()+ from .pipelines.lightrag.engine import LIGHTRAG_VERSION, installed_version++ current_version = installed_version() if is_lightrag_available() else ""+ installed = current_version == LIGHTRAG_VERSION+ if current_version:+ package_detail = (+ f"Installed {current_version}."+ if installed+ else f"Found {current_version}; required {LIGHTRAG_VERSION}."+ )except Exception:installed = Falseemb_model, emb_dim = _active_embedding()@@ -167,9 +176,9 @@ def _lightrag_preflight() -> dict:[_check("package",- "RAG-Anything package installed",+ "LightRAG package installed",installed,- "Installed." if installed else "pip install 'deeptutor[rag-lightrag]'",+ package_detail,),_check("chat",@@ -189,7 +198,7 @@ def _lightrag_preflight() -> dict:vision_ok,"Active chat model supports vision."if vision_ok- else "Active chat model has no vision — multimodal documents fall back to text.",+ else "Active chat model has no vision — image analysis is disabled.",optional=True,),]diff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.tomlindex 3c2dadb6d..6565e2724 100644--- a/packaging/deeptutor-cli/pyproject.toml+++ b/packaging/deeptutor-cli/pyproject.toml@@ -55,7 +55,7 @@ dependencies = ["openpyxl>=3.1.0","python-pptx>=1.0.0","pypdf>=4.0.0",- "pdfplumber>=0.11.0,<0.11.8",+ "pdfplumber>=0.11.0","reportlab>=4.0.0","defusedxml>=0.7.1",]diff --git a/pyproject.toml b/pyproject.tomlindex fe5a1a097..df25041c5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,8 +12,8 @@ description = "An agent-native intelligent learning companion with multi-agent c# Capped below 3.14 on purpose (issue #664): on 3.14 pip can't find wheels for# some compiled base deps (e.g. faiss-cpu) and silently backtracks into a# doomed source build that dies with "subprocess-exited-with-error". The heavy-# RAG extras (graphrag, rag-lightrag) already carry a `python_version < '3.14'`-# marker for the same reason; capping here makes pip refuse 3.14 with a+# GraphRAG also carries a `python_version < '3.14'` marker; capping the project+# itself makes every install, including LightRAG, refuse 3.14 with a# readable "Requires a different Python" message instead of a build failure.requires-python = ">=3.11,<3.14"readme = "README.md"@@ -61,7 +61,7 @@ dependencies = ["openpyxl>=3.1.0","python-pptx>=1.0.0","pypdf>=4.0.0",- "pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)+ "pdfplumber>=0.11.0","reportlab>=4.0.0","defusedxml>=0.7.1","fastapi>=0.100.0",@@ -109,7 +109,7 @@ cli = ["openpyxl>=3.1.0","python-pptx>=1.0.0","pypdf>=4.0.0",- "pdfplumber>=0.11.0,<0.11.8", # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)+ "pdfplumber>=0.11.0","reportlab>=4.0.0","defusedxml>=0.7.1",]@@ -228,19 +228,11 @@ math-animator = ["manim>=0.19.0"]# (1.4.5) and silently downgrades. Floor is 3.0.1 (3.0.0/3.0.3 were yanked).graphrag = ["graphrag>=3.0.1,<4.0.0; python_version < '3.14'"]-# LightRAG knowledge-base engine (HKUDS/LightRAG) with multimodal parsing via-# RAG-Anything (HKUDS/RAG-Anything). Optional, heavy (pulls MinerU transitively —-# see the pdfplumber pin above). The pipeline imports lazily and the adapter is-# isolated in services/rag/pipelines/lightrag/engine.py. raganything pulls-# `mineru[core]`, which is capped at python <3.14, so this carries the same-# `python_version` marker as graphrag to avoid a silent backtrack/downgrade on-# 3.14+. Floor is 1.0.1 (no 1.0.0 was ever published) with a <2.0.0 ceiling so-# a future API-breaking 2.x isn't pulled in silently.-# 1.2.5 is the first release carrying the ``lightrag_kwargs`` passthrough the-# LightRAG concurrency/extraction settings ride on. Older installs still run —-# engine.py drops knobs the installed version cannot take — but a fresh install-# should get the capable one.-rag-lightrag = ["raganything>=1.2.5,<2.0.0; python_version < '3.14'"]+# Built-in LightRAG provider. The exact release is intentional: the adapter+# isolates a private rc2 source-resolver seam and locks it with smoke tests.+# MinerU remains an independently selected DeepTutor parser and is not a+# transitive dependency of this extra.+rag-lightrag = ["lightrag-hku==1.5.7rc2"]# Dev/test tooling. Mirrors requirements/dev.txt.dev = [diff --git a/requirements/cli.txt b/requirements/cli.txtindex 368baecd6..55811b02f 100644--- a/requirements/cli.txt+++ b/requirements/cli.txt@@ -52,7 +52,7 @@ python-docx>=1.1.0openpyxl>=3.1.0python-pptx>=1.0.0pypdf>=4.0.0-pdfplumber>=0.11.0,<0.11.8 # 0.11.8+ pins pdfminer.six==20251230, conflicts with mineru (via raganything)+pdfplumber>=0.11.0reportlab>=4.0.0defusedxml>=0.7.1diff --git a/tests/fixtures/lightrag_bridge/README.md b/tests/fixtures/lightrag_bridge/README.mdnew file mode 100644index 000000000..8ce329368--- /dev/null+++ b/tests/fixtures/lightrag_bridge/README.md@@ -0,0 +1,45 @@+# LightRAG parser-bridge fixtures++`original.pdf` is generated by `generate_original_pdf.py` and is original+DeepTutor test material licensed under the repository's Apache-2.0 license. It+contains only synthetic text, an equation, a small table, and a drawn rectangle;+it has no third-party document content.++Generated file SHA-256: `e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80`.++Golden parser outputs in this directory must record the exact source commit or+authenticated MinerU API capture date, response schema/version, capture command,+and SHA-256. Secrets and transient service metadata must never be committed.++The current MinerU v4 capture is produced interactively with:++```bash+.venv/bin/python tests/fixtures/lightrag_bridge/capture_current_mineru.py+```++The script prompts privately with `getpass`; it does not accept the token in a+command argument, environment variable, output file, or log.++`mineru-legacy-official-example/content_list.json` is extracted byte-for-byte+from the official MinerU documentation at commit+`61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99` by+`extract_legacy_example.py`. Its provenance explicitly identifies it as an+official schema example, not a live parser run. The authenticated current+capture remains the real-output fixture for `original.pdf`.++## Frozen mapping contract++| MinerU field | LightRAG public Sidecar field | Failure boundary |+| --- | --- | --- |+| `title`, `section_header`, or positive `text_level` | `IRBlock.heading`, `level`, `parent_headings` | Empty headings remain ordinary content and cannot create a hierarchy node. |+| `text`, `content`, `body`, `code_body` | `IRBlock.content_template` | An unknown block with none of these non-empty fields fails the document. |+| `rows` or `table_body` | `IRTable.rows` or `html` | A table with neither a row matrix nor HTML fails before analysis. |+| `table_caption`, `header`, `table_footnote` | `caption`, `table_header`, `footnotes` | Malformed optional values normalize to empty fields; table body remains mandatory. |+| `img_path` or `path` | verified `AssetSpec` plus `IRDrawing.asset_ref` | Absolute/traversal/missing/ambiguous/unfrozen assets fail the document. |+| `image_caption`/`chart_caption`, image/chart footnote, format | `IRDrawing.caption`, `footnotes`, `fmt` | No prompt-only or missing-asset fallback is allowed. |+| equation text/body plus `text_format` | `IREquation.latex`, `is_block` | Empty equation content fails the document. |+| `page_idx` or `page`, and `bbox` | `IRPosition.anchor`, `range` | Integer `page_idx` is converted from zero-based to one-based; invalid bbox is omitted. |++Both raw parser fixtures and expected Sidecar assertions are immutable test+inputs. Production code may import only LightRAG's public Sidecar IR and writer;+the upstream MinerU builder is comparison evidence, not a runtime dependency.diff --git a/tests/fixtures/lightrag_bridge/capture_current_mineru.py b/tests/fixtures/lightrag_bridge/capture_current_mineru.pynew file mode 100644index 000000000..35c36bf5b--- /dev/null+++ b/tests/fixtures/lightrag_bridge/capture_current_mineru.py@@ -0,0 +1,74 @@+"""Capture a current authenticated MinerU v4 result without storing its token."""++from __future__ import annotations++from datetime import datetime, timezone+import getpass+import hashlib+import json+from pathlib import Path+import shutil+import tempfile++from deeptutor.services.parsing.engines.mineru.cloud import parse_cloud+from deeptutor.services.parsing.engines.mineru.config import MinerUConfig++HERE = Path(__file__).resolve().parent+SOURCE = HERE / "original.pdf"+TARGET = HERE / "mineru-v2-current"+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def main() -> None:+ if TARGET.exists():+ raise SystemExit(f"Refusing to overwrite existing capture: {TARGET}")+ token = getpass.getpass("MinerU API token (not stored): ").strip()+ if not token:+ raise SystemExit("No token entered")+ config = MinerUConfig(+ mode="cloud",+ api_token=token,+ model_version="pipeline",+ enable_formula=True,+ enable_table=True,+ )+ try:+ with tempfile.TemporaryDirectory(prefix="deeptutor-mineru-capture-") as raw:+ parsed = parse_cloud(SOURCE, Path(raw), config)+ candidates = sorted(parsed.rglob("*_content_list.json"))+ if len(candidates) != 1:+ raise RuntimeError(f"Expected one content_list artifact, found {len(candidates)}")+ content_root = candidates[0].parent+ shutil.copytree(content_root, TARGET)+ finally:+ token = ""++ files = {+ path.relative_to(TARGET).as_posix(): _sha256(path)+ for path in sorted(TARGET.rglob("*"))+ if path.is_file()+ }+ provenance = {+ "capture_schema": 1,+ "captured_at_utc": datetime.now(timezone.utc).isoformat(),+ "service": "https://mineru.net/api/v4",+ "model_version": "pipeline",+ "authenticated": True,+ "source": {"path": "../original.pdf", "sha256": _sha256(SOURCE)},+ "artifacts": files,+ }+ (TARGET / "deeptutor-fixture-provenance.json").write_text(+ json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"+ )+ print(f"Captured {len(files)} artifact(s) in {TARGET}")+++if __name__ == "__main__":+ main()diff --git a/tests/fixtures/lightrag_bridge/extract_legacy_example.py b/tests/fixtures/lightrag_bridge/extract_legacy_example.pynew file mode 100644index 000000000..8d78fd99a--- /dev/null+++ b/tests/fixtures/lightrag_bridge/extract_legacy_example.py@@ -0,0 +1,47 @@+"""Extract MinerU's official legacy content-list example byte-for-byte."""++from __future__ import annotations++import hashlib+import json+from pathlib import Path+import subprocess++COMMIT = "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99"+SOURCE_PATH = "docs/en/reference/output_files.md"+DEFAULT_REPOSITORY = Path("/home/ubuntu/sources/github.com/opendatalab/MinerU")+HERE = Path(__file__).resolve().parent+TARGET = HERE / "mineru-legacy-official-example"+++def main(repository: Path = DEFAULT_REPOSITORY) -> None:+ if TARGET.exists():+ raise SystemExit(f"Refusing to overwrite existing fixture: {TARGET}")+ markdown = subprocess.check_output(+ ["git", "-C", str(repository), "show", f"{COMMIT}:{SOURCE_PATH}"], text=True+ )+ heading = "#### Content List (content_list.json)"+ section = markdown.split(heading, 1)[1]+ sample = section.split("##### Sample Data", 1)[1]+ payload = sample.split("```json", 1)[1].split("```", 1)[0].strip().encode("utf-8") + b"\n"+ json.loads(payload)+ TARGET.mkdir()+ output = TARGET / "content_list.json"+ output.write_bytes(payload)+ provenance = {+ "fixture_schema": 1,+ "kind": "official-legacy-schema-example",+ "repository": "https://github.com/opendatalab/MinerU.git",+ "commit": COMMIT,+ "source_path": SOURCE_PATH,+ "source_section": heading,+ "content_sha256": hashlib.sha256(payload).hexdigest(),+ "note": "Exact official documentation example; not a live parser capture.",+ }+ (TARGET / "deeptutor-fixture-provenance.json").write_text(+ json.dumps(provenance, indent=2, sort_keys=True) + "\n", encoding="utf-8"+ )+++if __name__ == "__main__":+ main()diff --git a/tests/fixtures/lightrag_bridge/generate_original_pdf.py b/tests/fixtures/lightrag_bridge/generate_original_pdf.pynew file mode 100644index 000000000..2ed132e6e--- /dev/null+++ b/tests/fixtures/lightrag_bridge/generate_original_pdf.py@@ -0,0 +1,56 @@+"""Generate the redistributable MinerU bridge fixture PDF."""++from io import BytesIO+from pathlib import Path++from PIL import Image, ImageDraw+from reportlab.lib.pagesizes import letter+from reportlab.lib.utils import ImageReader+from reportlab.pdfgen import canvas++TARGET = Path(__file__).with_name("original.pdf")+++def main() -> None:+ page = canvas.Canvas(str(TARGET), pagesize=letter, invariant=True)+ page.setTitle("DeepTutor LightRAG Bridge Fixture")+ page.setAuthor("DeepTutor contributors")+ page.setFont("Helvetica-Bold", 18)+ page.drawString(72, 720, "DeepTutor LightRAG Bridge Fixture")+ page.setFont("Helvetica", 11)+ page.drawString(72, 690, "A short paragraph preserves text and heading hierarchy.")+ page.setFont("Times-Italic", 18)+ page.drawCentredString(306, 650, "E = m c^2")++ page.setFont("Helvetica-Bold", 11)+ page.drawString(72, 610, "Table 1. Retrieval engine paths")+ columns = (72, 222, 372)+ rows = (590, 566, 542)+ for x in columns:+ page.line(x, rows[-1], x, rows[0])+ for y in rows:+ page.line(columns[0], y, columns[-1], y)+ page.setFont("Helvetica", 10)+ page.drawString(82, 574, "Engine")+ page.drawString(232, 574, "Path")+ page.drawString(82, 550, "LightRAG")+ page.drawString(232, 550, "Native")++ image = Image.new("RGB", (360, 160), "white")+ draw = ImageDraw.Draw(image)+ draw.line((35, 130, 330, 130), fill="black", width=3)+ draw.line((35, 20, 35, 130), fill="black", width=3)+ draw.line((50, 110, 140, 75, 230, 90, 315, 35), fill="#1f77b4", width=6)+ draw.text((85, 135), "Deterministic fixture chart", fill="black")+ buffer = BytesIO()+ image.save(buffer, format="PNG")+ buffer.seek(0)+ page.drawImage(ImageReader(buffer), 72, 340, width=360, height=160, mask="auto")+ page.setFont("Helvetica", 10)+ page.drawString(72, 322, "Figure 1. Synthetic trend chart.")+ page.showPage()+ page.save()+++if __name__ == "__main__":+ main()diff --git a/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/content_list.json b/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/content_list.jsonnew file mode 100644index 000000000..11f4befb4--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/content_list.json@@ -0,0 +1,60 @@+[+ {+ "type": "text",+ "text": "The response of flow duration curves to afforestation ",+ "text_level": 1,+ "bbox": [+ 62,+ 480,+ 946,+ 904+ ],+ "page_idx": 0+ },+ {+ "type": "image",+ "img_path": "images/a8ecda1c69b27e4f79fce1589175a9d721cbdc1cf78b4cc06a015f3746f6b9d8.jpg",+ "img_caption": [+ "Fig. 1. Annual flow duration curves of daily flows from Pine Creek, Australia, 1989–2000. "+ ],+ "img_footnote": [],+ "bbox": [+ 62,+ 480,+ 946,+ 904+ ],+ "page_idx": 1+ },+ {+ "type": "equation",+ "img_path": "images/181ea56ef185060d04bf4e274685f3e072e922e7b839f093d482c29bf89b71e8.jpg",+ "text": "$$\nQ _ { \\% } = f ( P ) + g ( T )\n$$",+ "text_format": "latex",+ "bbox": [+ 62,+ 480,+ 946,+ 904+ ],+ "page_idx": 2+ },+ {+ "type": "table",+ "img_path": "images/e3cb413394a475e555807ffdad913435940ec637873d673ee1b039e3bc3496d0.jpg",+ "table_caption": [+ "Table 2 Significance of the rainfall and time terms "+ ],+ "table_footnote": [+ "indicates that the rainfall term was significant at the $5 \\%$ level, $T$ indicates that the time term was significant at the $5 \\%$ level, \\* represents significance at the $10 \\%$ level, and na denotes too few data points for meaningful analysis. "+ ],+ "table_body": "<html><body><table><tr><td rowspan=\"2\">Site</td><td colspan=\"10\">Percentile</td></tr><tr><td>10</td><td>20</td><td>30</td><td>40</td><td>50</td><td>60</td><td>70</td><td>80</td><td>90</td><td>100</td></tr><tr><td>Traralgon Ck</td><td>P</td><td>P,*</td><td>P</td><td>P</td><td>P,</td><td>P,</td><td>P,</td><td>P,</td><td>P</td><td>P</td></tr><tr><td>Redhill</td><td>P,T</td><td>P,T</td><td>,*</td><td>**</td><td>P.T</td><td>P,*</td><td>P*</td><td>P*</td><td>*</td><td>,*</td></tr><tr><td>Pine Ck</td><td></td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td><td>T</td><td>na</td><td>na</td></tr><tr><td>Stewarts Ck 5</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P.T</td><td>P.T</td><td>P,T</td><td>na</td><td>na</td><td>na</td></tr><tr><td>Glendhu 2</td><td>P</td><td>P,T</td><td>P,*</td><td>P,T</td><td>P.T</td><td>P,ns</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td></tr><tr><td>Cathedral Peak 2</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Cathedral Peak 3</td><td>P.T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td></tr><tr><td>Lambrechtsbos A</td><td>P,T</td><td>P</td><td>P</td><td>P,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>*,T</td><td>T</td></tr><tr><td>Lambrechtsbos B</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>P,T</td><td>T</td><td>T</td></tr><tr><td>Biesievlei</td><td>P,T</td><td>P.T</td><td>P,T</td><td>P,T</td><td>*,T</td><td>*,T</td><td>T</td><td>T</td><td>P,T</td><td>P,T</td></tr></table></body></html>",+ "bbox": [+ 62,+ 480,+ 946,+ 904+ ],+ "page_idx": 5+ }+]diff --git a/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/deeptutor-fixture-provenance.json b/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/deeptutor-fixture-provenance.jsonnew file mode 100644index 000000000..f4ca91a01--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-legacy-official-example/deeptutor-fixture-provenance.json@@ -0,0 +1,10 @@+{+ "commit": "61cc6886fe3edda8aa1c5b8bd2b6eaedddb8af99",+ "content_sha256": "e3a09b50a8a902a584452ca7085533fa6fe294bffe400c0dcabfdbe0339b92b7",+ "fixture_schema": 1,+ "kind": "official-legacy-schema-example",+ "note": "Exact official documentation example; not a live parser capture.",+ "repository": "https://github.com/opendatalab/MinerU.git",+ "source_path": "docs/en/reference/output_files.md",+ "source_section": "#### Content List (content_list.json)"+}diff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list.json b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list.jsonnew file mode 100644index 000000000..498b3ff6e--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list.json@@ -0,0 +1,70 @@+[+ {+ "type": "text",+ "text": "DeepTutor LightRAG Bridge Fixture",+ "text_level": 2,+ "bbox": [+ 114,+ 70,+ 619,+ 97+ ],+ "page_idx": 0+ },+ {+ "type": "text",+ "text": "A short paragraph preserves text and heading hierarchy.",+ "bbox": [+ 111,+ 114,+ 568,+ 133+ ],+ "page_idx": 0+ },+ {+ "type": "equation",+ "img_path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg",+ "text": "$$\nE = m c ^ { \\wedge } 2\n$$",+ "text_format": "latex",+ "bbox": [+ 434,+ 160,+ 562,+ 181+ ],+ "page_idx": 0+ },+ {+ "type": "table",+ "img_path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg",+ "table_caption": [+ "Table 1. Retrieval engine paths"+ ],+ "table_footnote": [],+ "table_body": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",+ "bbox": [+ 114,+ 251,+ 607,+ 314+ ],+ "page_idx": 0+ },+ {+ "type": "chart",+ "img_path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg",+ "content": "",+ "chart_caption": [+ "Figure 1. Synthetic trend chart."+ ],+ "chart_footnote": [],+ "bbox": [+ 166,+ 386,+ 658,+ 556+ ],+ "page_idx": 0+ }+]\ No newline at end of filediff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.json b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.jsonnew file mode 100644index 000000000..5683e1867--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.json@@ -0,0 +1,101 @@+[+ [+ {+ "type": "title",+ "content": {+ "title_content": [+ {+ "type": "text",+ "content": "DeepTutor LightRAG Bridge Fixture"+ }+ ],+ "level": 2+ },+ "bbox": [+ 114,+ 70,+ 619,+ 97+ ]+ },+ {+ "type": "paragraph",+ "content": {+ "paragraph_content": [+ {+ "type": "text",+ "content": "A short paragraph preserves text and heading hierarchy."+ }+ ]+ },+ "bbox": [+ 111,+ 114,+ 568,+ 133+ ]+ },+ {+ "type": "equation_interline",+ "content": {+ "math_content": "E = m c ^ { \\wedge } 2",+ "math_type": "latex",+ "image_source": {+ "path": "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"+ }+ },+ "bbox": [+ 434,+ 160,+ 562,+ 181+ ]+ },+ {+ "type": "table",+ "content": {+ "image_source": {+ "path": "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"+ },+ "table_caption": [+ {+ "type": "text",+ "content": "Table 1. Retrieval engine paths"+ }+ ],+ "table_footnote": [],+ "html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",+ "table_type": "simple_table",+ "table_nest_level": 1+ },+ "bbox": [+ 114,+ 251,+ 607,+ 314+ ]+ },+ {+ "type": "chart",+ "content": {+ "image_source": {+ "path": "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"+ },+ "content": "",+ "chart_caption": [+ {+ "type": "text",+ "content": "Figure 1. Synthetic trend chart."+ }+ ],+ "chart_footnote": []+ },+ "bbox": [+ 166,+ 386,+ 658,+ 556+ ]+ }+ ]+]\ No newline at end of filediff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_model.json b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_model.jsonnew file mode 100644index 000000000..89a9fe857--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/a5d0461c-c073-4d71-944c-e79759a67637_model.json@@ -0,0 +1,141 @@+[+ {+ "layout_dets": [+ {+ "cls_id": 17,+ "label": "paragraph_title",+ "score": 0.5515,+ "bbox": [+ 195,+ 156,+ 1055,+ 215+ ],+ "index": 1+ },+ {+ "cls_id": 22,+ "label": "text",+ "score": 0.9291,+ "bbox": [+ 191,+ 255,+ 968,+ 295+ ],+ "index": 2+ },+ {+ "cls_id": 5,+ "label": "display_formula",+ "score": 0.9417,+ "bbox": [+ 740,+ 353,+ 958,+ 401+ ],+ "index": 3,+ "latex": "E = m c ^ { \\wedge } 2"+ },+ {+ "cls_id": 7,+ "label": "figure_title",+ "score": 0.9427,+ "bbox": [+ 193,+ 477,+ 653,+ 517+ ],+ "index": 4+ },+ {+ "cls_id": 21,+ "label": "table",+ "score": 0.9627,+ "bbox": [+ 197,+ 554,+ 1034,+ 694+ ],+ "index": 5,+ "html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>"+ },+ {+ "cls_id": 3,+ "label": "chart",+ "score": 0.9352,+ "bbox": [+ 284,+ 851,+ 1122,+ 1226+ ],+ "index": 6+ },+ {+ "cls_id": 7,+ "label": "figure_title",+ "score": 0.9393,+ "bbox": [+ 193,+ 1278,+ 583,+ 1317+ ],+ "index": 7+ },+ {+ "label": "ocr_text",+ "bbox": [+ 200,+ 159,+ 1051,+ 212+ ],+ "score": 1.0,+ "text": ""+ },+ {+ "label": "ocr_text",+ "bbox": [+ 200,+ 260,+ 962,+ 289+ ],+ "score": 1.0,+ "text": ""+ },+ {+ "label": "ocr_text",+ "bbox": [+ 199,+ 478,+ 648,+ 513+ ],+ "score": 1.0,+ "text": ""+ },+ {+ "label": "ocr_text",+ "bbox": [+ 199,+ 1283,+ 578,+ 1313+ ],+ "score": 1.0,+ "text": ""+ }+ ],+ "page_info": {+ "page_no": 0,+ "width": 1700,+ "height": 2200+ }+ }+]\ No newline at end of filediff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/deeptutor-fixture-provenance.json b/tests/fixtures/lightrag_bridge/mineru-v2-current/deeptutor-fixture-provenance.jsonnew file mode 100644index 000000000..cf934bf41--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/deeptutor-fixture-provenance.json@@ -0,0 +1,22 @@+{+ "artifacts": {+ "a5d0461c-c073-4d71-944c-e79759a67637_content_list.json": "e8e5bb9c00a6da26d9a7b93abd6938acf3145503ae734cd05831c56bd7e5e842",+ "a5d0461c-c073-4d71-944c-e79759a67637_content_list_v2.json": "920ef83a39170889d001b75973293fc65b8a7c8ac0b309c807b7d2cdcf199284",+ "a5d0461c-c073-4d71-944c-e79759a67637_model.json": "9574219a0d6f52303d4d46e15c01d19b02bd49b2674f542eebd729ad29af9e59",+ "a5d0461c-c073-4d71-944c-e79759a67637_origin.pdf": "bf173e5d24d268a8a5a25766d190d2b01a124394c5e0e33094c08c6a9d8bbbc4",+ "full.md": "e2861269e39a18874137029375666f79ea75af68d3ccbe490d112d1141368344",+ "images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg": "a4542ec348a798c6a6dba4b89a4ab91d1b23c45b4c50bfaeb8303a4874e1e10d",+ "images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg": "18c517e03a9b15f5e7748ab4187dd8cd349018f7582784425a03bb538c146691",+ "images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg": "53eaf9d9acb37f7f885dd51d17f183590da9068d3fd26d9701b885cf4f8fc970",+ "layout.json": "549cb6fcd708664adb081afa494781a54bea250e1d86acc7776049f2e2c35d63"+ },+ "authenticated": true,+ "capture_schema": 1,+ "captured_at_utc": "2026-08-28T14:56:16.031586+00:00",+ "model_version": "pipeline",+ "service": "https://mineru.net/api/v4",+ "source": {+ "path": "../original.pdf",+ "sha256": "e2abd3404f3a03d90c36feec19786689892434e730841cbdbd2a1a28875f3a80"+ }+}diff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/full.md b/tests/fixtures/lightrag_bridge/mineru-v2-current/full.mdnew file mode 100644index 000000000..031f989df--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/full.md@@ -0,0 +1,13 @@+## DeepTutor LightRAG Bridge Fixture++A short paragraph preserves text and heading hierarchy.++$$+E = m c ^ { \wedge } 2+$$++Table 1. Retrieval engine paths+<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>+++Figure 1. Synthetic trend chart.\ No newline at end of filediff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpgnew file mode 100644index 000000000..adf8356b0Binary files /dev/null and b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg differdiff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpgnew file mode 100644index 000000000..4ca10130aBinary files /dev/null and b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg differdiff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpgnew file mode 100644index 000000000..f3c9f9da7Binary files /dev/null and b/tests/fixtures/lightrag_bridge/mineru-v2-current/images/f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg differdiff --git a/tests/fixtures/lightrag_bridge/mineru-v2-current/layout.json b/tests/fixtures/lightrag_bridge/mineru-v2-current/layout.jsonnew file mode 100644index 000000000..c65e8aabe--- /dev/null+++ b/tests/fixtures/lightrag_bridge/mineru-v2-current/layout.json@@ -0,0 +1,552 @@+{+ "pdf_info": [+ {+ "preproc_blocks": [+ {+ "score": 0.5515,+ "bbox": [+ 70,+ 56,+ 379,+ 77+ ],+ "index": 1,+ "type": "title",+ "lines": [+ {+ "bbox": [+ 72,+ 57,+ 378,+ 76+ ],+ "spans": [+ {+ "bbox": [+ 72,+ 57,+ 378,+ 76+ ],+ "type": "text",+ "content": "DeepTutor LightRAG Bridge Fixture",+ "score": 1.0+ }+ ]+ }+ ],+ "level": 2+ },+ {+ "score": 0.9291,+ "bbox": [+ 68,+ 91,+ 348,+ 106+ ],+ "index": 2,+ "type": "text",+ "lines": [+ {+ "bbox": [+ 72,+ 93,+ 346,+ 104+ ],+ "spans": [+ {+ "bbox": [+ 72,+ 93,+ 346,+ 104+ ],+ "type": "text",+ "content": "A short paragraph preserves text and heading hierarchy.",+ "score": 1.0+ }+ ]+ }+ ]+ },+ {+ "score": 0.9417,+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "index": 3,+ "type": "interline_equation",+ "lines": [+ {+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "spans": [+ {+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "type": "interline_equation",+ "content": "E = m c ^ { \\wedge } 2",+ "image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"+ }+ ]+ }+ ]+ },+ {+ "type": "table",+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "blocks": [+ {+ "score": 0.9427,+ "bbox": [+ 69,+ 171,+ 235,+ 186+ ],+ "index": 4,+ "type": "table_caption",+ "lines": [+ {+ "bbox": [+ 71,+ 172,+ 233,+ 184+ ],+ "spans": [+ {+ "bbox": [+ 71,+ 172,+ 233,+ 184+ ],+ "type": "text",+ "content": "Table 1. Retrieval engine paths",+ "score": 1.0+ }+ ]+ }+ ]+ },+ {+ "score": 0.9627,+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "index": 5,+ "type": "table_body",+ "lines": [+ {+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "spans": [+ {+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "type": "table",+ "html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",+ "image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"+ }+ ]+ }+ ]+ }+ ],+ "index": 5,+ "score": 0.9627+ },+ {+ "type": "chart",+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "blocks": [+ {+ "score": 0.9352,+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "index": 6,+ "type": "chart_body",+ "lines": [+ {+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "spans": [+ {+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "type": "chart",+ "image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"+ }+ ]+ }+ ]+ },+ {+ "score": 0.9393,+ "bbox": [+ 69,+ 460,+ 209,+ 474+ ],+ "index": 7,+ "type": "chart_caption",+ "lines": [+ {+ "bbox": [+ 71,+ 461,+ 208,+ 472+ ],+ "spans": [+ {+ "bbox": [+ 71,+ 461,+ 208,+ 472+ ],+ "type": "text",+ "content": "Figure 1. Synthetic trend chart.",+ "score": 1.0+ }+ ]+ }+ ]+ }+ ],+ "index": 6,+ "score": 0.9352+ }+ ],+ "page_idx": 0,+ "page_size": [+ 612,+ 792+ ],+ "discarded_blocks": [],+ "para_blocks": [+ {+ "score": 0.5515,+ "bbox": [+ 70,+ 56,+ 379,+ 77+ ],+ "index": 1,+ "type": "title",+ "lines": [+ {+ "bbox": [+ 72,+ 57,+ 378,+ 76+ ],+ "spans": [+ {+ "bbox": [+ 72,+ 57,+ 378,+ 76+ ],+ "type": "text",+ "content": "DeepTutor LightRAG Bridge Fixture",+ "score": 1.0+ }+ ]+ }+ ],+ "level": 2+ },+ {+ "score": 0.9291,+ "bbox": [+ 68,+ 91,+ 348,+ 106+ ],+ "index": 2,+ "type": "text",+ "lines": [+ {+ "bbox": [+ 72,+ 93,+ 346,+ 104+ ],+ "spans": [+ {+ "bbox": [+ 72,+ 93,+ 346,+ 104+ ],+ "type": "text",+ "content": "A short paragraph preserves text and heading hierarchy.",+ "score": 1.0+ }+ ]+ }+ ],+ "bbox_fs": [+ 72,+ 93,+ 346,+ 104+ ]+ },+ {+ "score": 0.9417,+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "index": 3,+ "type": "interline_equation",+ "lines": [+ {+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "spans": [+ {+ "bbox": [+ 266,+ 127,+ 344,+ 144+ ],+ "type": "interline_equation",+ "content": "E = m c ^ { \\wedge } 2",+ "image_path": "4934193ff23f79d730c0af8148c70efd879bdc73b2f1d49d76e0ef955da28c70.jpg"+ }+ ]+ }+ ]+ },+ {+ "type": "table",+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "blocks": [+ {+ "score": 0.9427,+ "bbox": [+ 69,+ 171,+ 235,+ 186+ ],+ "index": 4,+ "type": "table_caption",+ "lines": [+ {+ "bbox": [+ 71,+ 172,+ 233,+ 184+ ],+ "spans": [+ {+ "bbox": [+ 71,+ 172,+ 233,+ 184+ ],+ "type": "text",+ "content": "Table 1. Retrieval engine paths",+ "score": 1.0+ }+ ]+ }+ ]+ },+ {+ "score": 0.9627,+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "index": 5,+ "type": "table_body",+ "lines": [+ {+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "spans": [+ {+ "bbox": [+ 70,+ 199,+ 372,+ 249+ ],+ "type": "table",+ "html": "<table><tr><td>Engine</td><td>Path</td></tr><tr><td>LightRAG</td><td>Native</td></tr></table>",+ "image_path": "c0183ed37ed43baf874f25239395a832d77e43cdd877992b7f3eef0163e5d41b.jpg"+ }+ ]+ }+ ]+ }+ ],+ "index": 5,+ "score": 0.9627+ },+ {+ "type": "chart",+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "blocks": [+ {+ "score": 0.9352,+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "index": 6,+ "type": "chart_body",+ "lines": [+ {+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "spans": [+ {+ "bbox": [+ 102,+ 306,+ 403,+ 441+ ],+ "type": "chart",+ "image_path": "f24e98da187ecc134f0b3b1def407fc96edfa0987b84ab2b95a3aa377698255b.jpg"+ }+ ]+ }+ ]+ },+ {+ "score": 0.9393,+ "bbox": [+ 69,+ 460,+ 209,+ 474+ ],+ "index": 7,+ "type": "chart_caption",+ "lines": [+ {+ "bbox": [+ 71,+ 461,+ 208,+ 472+ ],+ "spans": [+ {+ "bbox": [+ 71,+ 461,+ 208,+ 472+ ],+ "type": "text",+ "content": "Figure 1. Synthetic trend chart.",+ "score": 1.0+ }+ ]+ }+ ]+ }+ ],+ "index": 6,+ "score": 0.9352+ }+ ]+ }+ ],+ "_backend": "pipeline",+ "_version_name": "3.4.4"+}\ No newline at end of filediff --git a/tests/services/rag/test_lightrag_ingress.py b/tests/services/rag/test_lightrag_ingress.pynew file mode 100644index 000000000..c65be6fd9--- /dev/null+++ b/tests/services/rag/test_lightrag_ingress.py@@ -0,0 +1,327 @@+from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path++import pytest++from deeptutor.services.parsing import cache as parsing_cache+from deeptutor.services.parsing.types import ParsedDocument+from deeptutor.services.rag.pipelines.lightrag import ingress, sidecar++FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lightrag_bridge"+++def _structured(asset_dir: Path | None = None) -> ParsedDocument:+ return ParsedDocument(+ markdown="# Fixture\n\nBody",+ blocks=[+ {+ "type": "text",+ "text": "Fixture",+ "text_level": 1,+ "page_idx": 0,+ "bbox": [1, 2, 3, 4],+ },+ {"type": "text", "text": "Body", "page_idx": 0},+ {"type": "list", "list_items": ["one", "two"], "page_idx": 0},+ {+ "type": "code",+ "code_body": "print('ok')",+ "code_caption": ["Fixture code"],+ "code_footnote": ["Code note"],+ "page_idx": 0,+ },+ {+ "type": "table",+ "table_body": "<table><tr><td>A</td></tr></table>",+ "table_caption": ["Table caption"],+ "page_idx": 1,+ },+ {+ "type": "image",+ "img_path": "images/chart.png",+ "image_caption": ["Chart caption"],+ "page_idx": 1,+ },+ {"type": "equation", "text": "x^2", "page_idx": 1},+ ],+ asset_dir=asset_dir,+ source_hash="source-sha",+ parser_signature="mineru-signature",+ engine="mineru",+ )+++def test_freeze_is_an_independent_digest_verified_bundle(tmp_path: Path) -> None:+ source = tmp_path / "paper.pdf"+ source.write_bytes(b"original pdf")+ assets = tmp_path / "parser-assets"+ (assets / "images").mkdir(parents=True)+ original_asset = assets / "images" / "chart.png"+ original_asset.write_bytes(b"image")+ working = tmp_path / "version-1"++ staged = ingress.freeze_document(working, source, _structured(assets))+ manifest, bundle = ingress.load_verified_bundle(working, "paper.pdf")++ assert staged.source_path.read_bytes() == b"original pdf"+ assert os.stat(staged.source_path).st_ino != os.stat(source).st_ino+ frozen_asset = bundle / manifest["assets"][0]["path"]+ assert frozen_asset.read_bytes() == b"image"+ assert os.stat(frozen_asset).st_ino != os.stat(original_asset).st_ino+ assert manifest["process_options"] == "Pite"+ assert manifest["chunk_options"] == {"paragraph_semantic": {"chunk_token_size": 1200}}++ source.write_bytes(b"mutated pdf")+ original_asset.write_bytes(b"mutated image")+ assert staged.source_path.read_bytes() == b"original pdf"+ assert frozen_asset.read_bytes() == b"image"+ ingress.load_verified_bundle(working, "paper.pdf")+++def test_absolute_cached_image_path_is_rewritten_to_frozen_asset(tmp_path: Path) -> None:+ source = tmp_path / "paper.pdf"+ source.write_bytes(b"pdf")+ assets = tmp_path / "images"+ assets.mkdir()+ image = assets / "figure.png"+ image.write_bytes(b"image")+ parsed = ParsedDocument(+ markdown="figure",+ blocks=[{"type": "image", "img_path": str(image)}],+ asset_dir=assets,+ engine="mineru",+ )++ staged = ingress.freeze_document(tmp_path / "version-1", source, parsed)+ manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)+ frozen_blocks = json.loads((bundle / manifest["blocks"]["path"]).read_text())++ assert frozen_blocks[0]["img_path"] == "figure.png"+ assert parsed.blocks[0]["img_path"] == str(image)+ assert (bundle / "assets" / "figure.png").read_bytes() == b"image"+++def test_bundle_tamper_and_unsafe_names_fail_closed(tmp_path: Path) -> None:+ source = tmp_path / "notes.md"+ source.write_text("notes", encoding="utf-8")+ working = tmp_path / "version-1"+ staged = ingress.freeze_document(+ working,+ source,+ ParsedDocument(markdown="notes", engine="text_only", source_hash="h", parser_signature="s"),+ )+ assert staged.process_options == "F"+ (staged.bundle_dir / "markdown.utf8").write_text("tampered", encoding="utf-8")+ with pytest.raises(ingress.IngressError, match="Digest mismatch"):+ ingress.load_verified_bundle(working, "notes.md")+ with pytest.raises(ingress.IngressError, match="Invalid canonical basename"):+ ingress.load_verified_bundle(working, "../notes.md")+++def test_bundle_payload_rejects_a_symlinked_parent(tmp_path: Path) -> None:+ source = tmp_path / "notes.md"+ source.write_text("notes", encoding="utf-8")+ working = tmp_path / "version-1"+ staged = ingress.freeze_document(+ working,+ source,+ ParsedDocument(markdown="notes", engine="text_only"),+ )+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "payload").write_text("notes", encoding="utf-8")+ markdown = staged.bundle_dir / "markdown.utf8"+ markdown.unlink()+ nested = staged.bundle_dir / "nested"+ nested.symlink_to(outside, target_is_directory=True)+ manifest = json.loads(staged.manifest_path.read_text(encoding="utf-8"))+ manifest["markdown"]["path"] = "nested/payload"+ staged.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")++ with pytest.raises(ingress.IngressError, match="symbolic link"):+ ingress.load_verified_bundle(working, "notes.md")+++def test_source_and_assets_reject_links(tmp_path: Path) -> None:+ source = tmp_path / "source.pdf"+ source.write_bytes(b"pdf")+ hardlink = tmp_path / "hardlink.pdf"+ os.link(source, hardlink)+ with pytest.raises(ingress.IngressError, match="hard-linked"):+ ingress.freeze_document(tmp_path / "version-hardlink", source, _structured())++ ordinary = tmp_path / "ordinary.pdf"+ ordinary.write_bytes(b"pdf")+ assets = tmp_path / "assets"+ assets.mkdir()+ (assets / "outside.png").write_bytes(b"image")+ (assets / "link.png").symlink_to(assets / "outside.png")+ with pytest.raises(ingress.IngressError, match="symbolic link"):+ ingress.freeze_document(tmp_path / "version-symlink", ordinary, _structured(assets))+++def test_same_canonical_basename_is_rejected_before_enqueue(tmp_path: Path) -> None:+ first = tmp_path / "a" / "same.md"+ second = tmp_path / "b" / "same.md"+ first.parent.mkdir()+ second.parent.mkdir()+ first.write_text("first", encoding="utf-8")+ second.write_text("second", encoding="utf-8")+ parsed = ParsedDocument(markdown="content", engine="text_only")+ working = tmp_path / "version-1"+ ingress.freeze_document(working, first, parsed)+ with pytest.raises(ingress.IngressError, match="basename already exists"):+ ingress.freeze_document(working, second, parsed)+++def test_sidecar_maps_structured_fields_and_positions(tmp_path: Path) -> None:+ source = tmp_path / "paper.pdf"+ source.write_bytes(b"pdf")+ assets = tmp_path / "parser-assets"+ (assets / "images").mkdir(parents=True)+ (assets / "images" / "chart.png").write_bytes(b"image")+ working = tmp_path / "version-1"+ staged = ingress.freeze_document(working, source, _structured(assets))+ manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)++ document = sidecar.build_ir(manifest, bundle)++ assert document.document_name == "paper.pdf"+ assert document.doc_title == "Fixture"+ assert document.split_option == {"parser": "mineru", "parser_signature": "mineru-signature"}+ assert len(document.assets) == 1+ assert document.assets[0].source.read_bytes() == b"image"+ block = document.blocks[0]+ assert block.heading == "Fixture"+ assert block.level == 1+ assert "one\ntwo" in block.content_template+ assert "print('ok')" in block.content_template+ assert "Fixture code" in block.content_template+ assert "Code note" in block.content_template+ assert block.tables[0].html.startswith("<table>")+ assert block.drawings[0].caption == "Chart caption"+ assert block.equations[0].latex == "x^2"+ assert block.positions[0].anchor == "1"+ assert block.positions[0].range == [1.0, 2.0, 3.0, 4.0]+++def test_sidecar_unknown_content_is_preserved_or_rejected(tmp_path: Path) -> None:+ bundle = tmp_path / "bundle"+ bundle.mkdir()+ blocks = bundle / "blocks.json"+ manifest = {+ "canonical_filename": "doc.pdf",+ "parser": {"engine": "mineru", "parser_signature": "s"},+ "blocks": {"path": "blocks.json"},+ "assets": [],+ }+ blocks.write_text(json.dumps([{"type": "new_semantic", "text": "keep me"}]), encoding="utf-8")+ assert "keep me" in sidecar.build_ir(manifest, bundle).blocks[0].content_template+ blocks.write_text(json.dumps([{"type": "new_semantic"}]), encoding="utf-8")+ with pytest.raises(sidecar.SidecarMappingError, match="no preservable text"):+ sidecar.build_ir(manifest, bundle)+++def test_sidecar_asset_traversal_is_rejected(tmp_path: Path) -> None:+ bundle = tmp_path / "bundle"+ bundle.mkdir()+ blocks = bundle / "blocks.json"+ blocks.write_text(+ json.dumps([{"type": "image", "img_path": "../outside.png"}]), encoding="utf-8"+ )+ manifest = {+ "canonical_filename": "doc.pdf",+ "parser": {},+ "blocks": {"path": "blocks.json"},+ "assets": [],+ }+ with pytest.raises(sidecar.SidecarMappingError, match="escapes"):+ sidecar.build_ir(manifest, bundle)+++def test_official_legacy_mineru_golden_maps_without_private_builder(tmp_path: Path) -> None:+ golden = FIXTURES / "mineru-legacy-official-example" / "content_list.json"+ provenance = json.loads(+ (golden.parent / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")+ )+ blocks = json.loads(golden.read_text(encoding="utf-8"))+ # The official example's image bytes are not distributed with its docs;+ # the authenticated current capture covers AssetSpec. The exact legacy+ # table/equation/text records remain untouched here.+ bridge_blocks = [block for block in blocks if block.get("type") != "image"]+ source = tmp_path / "legacy.pdf"+ source.write_bytes(b"legacy fixture source")+ working = tmp_path / "version-1"++ staged = ingress.freeze_document(+ working,+ source,+ ParsedDocument(+ markdown="# Legacy fixture",+ blocks=bridge_blocks,+ engine="mineru",+ source_hash=provenance["content_sha256"],+ parser_signature=provenance["commit"],+ ),+ )+ manifest, bundle = ingress.load_verified_bundle(working, staged.canonical_name)+ document = sidecar.build_ir(manifest, bundle)++ assert provenance["kind"] == "official-legacy-schema-example"+ assert document.doc_title == "The response of flow duration curves to afforestation"+ block = document.blocks[0]+ assert block.tables[0].caption.startswith("Table 2")+ assert "Q _ { \\% }" in block.equations[0].latex+ assert {position.anchor for position in block.positions} == {"1", "3", "6"}+++def test_authenticated_current_mineru_golden_maps_from_public_artifacts(tmp_path: Path) -> None:+ capture = FIXTURES / "mineru-v2-current"+ provenance = json.loads(+ (capture / "deeptutor-fixture-provenance.json").read_text(encoding="utf-8")+ )+ source = (capture / provenance["source"]["path"]).resolve()++ assert provenance["capture_schema"] == 1+ assert provenance["authenticated"] is True+ assert provenance["service"] == "https://mineru.net/api/v4"+ assert hashlib.sha256(source.read_bytes()).hexdigest() == provenance["source"]["sha256"]+ for relative, expected_digest in provenance["artifacts"].items():+ artifact = capture / relative+ assert artifact.is_file()+ assert hashlib.sha256(artifact.read_bytes()).hexdigest() == expected_digest++ markdown, blocks, asset_dir = parsing_cache.load_ir(capture)+ assert blocks is not None+ assert asset_dir is not None+ assert {block["type"] for block in blocks} == {"text", "equation", "table", "chart"}++ staged = ingress.freeze_document(+ tmp_path / "version-1",+ source,+ ParsedDocument(+ markdown=markdown,+ blocks=blocks,+ asset_dir=asset_dir,+ engine="mineru",+ source_hash=provenance["source"]["sha256"],+ parser_signature=provenance["model_version"],+ ),+ )+ manifest, bundle = ingress.load_verified_bundle(tmp_path / "version-1", staged.canonical_name)+ document = sidecar.build_ir(manifest, bundle)++ assert document.doc_title == "original"+ assert document.blocks[0].heading == "DeepTutor LightRAG Bridge Fixture"+ assert document.blocks[0].tables[0].caption == "Table 1. Retrieval engine paths"+ assert "E = m c" in document.blocks[0].equations[0].latex+ assert document.blocks[0].drawings[0].caption == "Figure 1. Synthetic trend chart."+ assert len(document.assets) == 1+ assert (+ document.assets[0].source.read_bytes()+ == (asset_dir / Path(blocks[-1]["img_path"]).name).read_bytes()+ )diff --git a/tests/services/rag/test_lightrag_native_smoke.py b/tests/services/rag/test_lightrag_native_smoke.pynew file mode 100644index 000000000..416584361--- /dev/null+++ b/tests/services/rag/test_lightrag_native_smoke.py@@ -0,0 +1,194 @@+"""Offline integration smoke tests against the real pinned LightRAG SDK."""++from __future__ import annotations++import asyncio+from dataclasses import replace+from pathlib import Path++from lightrag.utils import EmbeddingFunc+import numpy as np++from deeptutor.services.parsing.types import ParsedDocument+from deeptutor.services.rag.index_versioning import list_kb_versions+from deeptutor.services.rag.pipelines.lightrag import engine, ingress, storage+++async def _fake_llm(_prompt, **_kwargs) -> str:+ # This superset satisfies rc2's table/equation analysis schemas. Entity+ # extraction may validly produce zero records; the document still reaches+ # PROCESSED with real parser, chunk, storage and embedding code.+ return '{"name":"fixture","description":"fixture analysis","equation":"x^2","type":"Other"}'+++async def _fake_embedding(texts: list[str]) -> np.ndarray:+ return np.ones((len(texts), 32), dtype=float)+++def _configure_real_sdk(monkeypatch, llm=_fake_llm) -> None:+ monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: llm)+ monkeypatch.setattr(+ engine,+ "build_embedding_func",+ lambda **_kwargs: EmbeddingFunc(+ embedding_dim=32,+ max_token_size=4096,+ func=_fake_embedding,+ ),+ )+ monkeypatch.setattr(+ engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 1}+ )+ monkeypatch.setattr(+ engine, "constructor_kwargs_from_settings", lambda: {"entity_extract_max_gleaning": 0}+ )+++async def _process(working_dir: Path, staged: ingress.StagedDocument) -> dict:+ rag = engine.build_rag(working_dir, enable_vlm=False)+ await engine.initialize(rag)+ failed = True+ try:+ track_id = await engine.enqueue(rag, [staged])+ await rag.apipeline_process_enqueue_documents()+ rows = await rag.aget_docs_by_track_id(track_id)+ failed = False+ return rows+ finally:+ await engine.finalize(rag, cancel_pending=failed)+++def test_real_rc2_raw_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:+ _configure_real_sdk(monkeypatch)+ working = tmp_path / "version-1"+ working.mkdir()+ source = tmp_path / "notes.md"+ source.write_text("DeepTutor native LightRAG fixture.", encoding="utf-8")+ staged = ingress.freeze_document(+ working,+ source,+ ParsedDocument(+ markdown="# Native fixture\n\nDeepTutor uses LightRAG.",+ engine="text_only",+ source_hash="fixture-source",+ parser_signature="fixture-parser",+ ),+ )++ rows = asyncio.run(_process(working, staged))++ assert len(rows) == 1+ row = next(iter(rows.values()))+ assert getattr(row.status, "value", row.status) == "processed"+ assert row.file_path == "notes.md"+ assert storage.has_output(working) is True+ monkeypatch.setattr(+ "deeptutor.services.rag.embedding_signature.embedding_meta_fields",+ lambda: {"embedding": "fixture"},+ )+ storage.write_meta(working)+ assert storage.meta_is_native_published(working) is True+ assert list_kb_versions(tmp_path)[0]["ready"] is True+ meta = storage._read_meta(working)+ assert meta["parser_inputs"] == [{"engine": "text_only", "parser_signature": "fixture-parser"}]+++def test_real_rc2_sidecar_bridge_reaches_processed(monkeypatch, tmp_path: Path) -> None:+ _configure_real_sdk(monkeypatch)+ working = tmp_path / "version-1"+ working.mkdir()+ source = tmp_path / "paper.pdf"+ source.write_bytes(b"%PDF-1.4 fixture")+ assets = tmp_path / "assets"+ assets.mkdir()+ (assets / "figure.png").write_bytes(b"fixture image")+ staged = ingress.freeze_document(+ working,+ source,+ ParsedDocument(+ markdown="# Structured fixture",+ blocks=[+ {"type": "text", "text": "Structured fixture", "text_level": 1, "page_idx": 0},+ {"type": "text", "text": "DeepTutor structured body.", "page_idx": 0},+ {+ "type": "table",+ "table_body": "<table><tr><td>value</td></tr></table>",+ "page_idx": 0,+ },+ {"type": "image", "img_path": "figure.png", "page_idx": 0},+ {"type": "equation", "text": "x^2", "page_idx": 0},+ ],+ asset_dir=assets,+ engine="mineru",+ source_hash="fixture-source",+ parser_signature="fixture-parser",+ ),+ )+ # The image asset still passes through the real Sidecar writer; disabling+ # i only avoids requiring a vision call in this deterministic offline test.+ staged = replace(staged, process_options=staged.process_options.replace("i", ""))++ rows = asyncio.run(_process(working, staged))++ assert len(rows) == 1+ row = next(iter(rows.values()))+ assert getattr(row.status, "value", row.status) == "processed"+ assert row.file_path == "paper.pdf"+ assert storage.has_output(working) is True+ assert list((ingress.pending_root(working) / "__parsed__").glob("paper.pdf"))+++def test_real_rc2_append_uses_only_new_doc_and_links_existing_entity(+ monkeypatch, tmp_path: Path+) -> None:+ async def entity_llm(prompt, **_kwargs) -> str:+ if "Second document" in prompt:+ return (+ "(entity<|#|>SECOND<|#|>CONCEPT<|#|>Second entity)\n"+ "(relation<|#|>SHARED<|#|>SECOND<|#|>links<|#|>Shared links to Second)"+ "<|COMPLETE|>"+ )+ return "(entity<|#|>SHARED<|#|>CONCEPT<|#|>Shared entity)<|COMPLETE|>"++ _configure_real_sdk(monkeypatch, entity_llm)+ working = tmp_path / "version-1"+ working.mkdir()+ first_source = tmp_path / "first.md"+ second_source = tmp_path / "second.md"+ first_source.write_text("First document names Shared.", encoding="utf-8")+ second_source.write_text("Second document links Shared to Second.", encoding="utf-8")+ first = ingress.freeze_document(+ working,+ first_source,+ ParsedDocument(markdown="First document names Shared.", engine="text_only"),+ )++ async def run() -> None:+ rag = engine.build_rag(working)+ await engine.initialize(rag)+ failed = True+ try:+ first_track = await engine.enqueue(rag, [first])+ await rag.apipeline_process_enqueue_documents()+ first_rows = await rag.aget_docs_by_track_id(first_track)+ assert [row.file_path for row in first_rows.values()] == ["first.md"]++ second = ingress.freeze_document(+ working,+ second_source,+ ParsedDocument(+ markdown="Second document links Shared to Second.", engine="text_only"+ ),+ )+ second_track = await engine.enqueue(rag, [second])+ await rag.apipeline_process_enqueue_documents()+ second_rows = await rag.aget_docs_by_track_id(second_track)+ assert [row.file_path for row in second_rows.values()] == ["second.md"]+ assert await rag.chunk_entity_relation_graph.get_node("SHARED") is not None+ assert await rag.chunk_entity_relation_graph.get_node("SECOND") is not None+ assert await rag.chunk_entity_relation_graph.get_edge("SHARED", "SECOND") is not None+ failed = False+ finally:+ await engine.finalize(rag, cancel_pending=failed)++ asyncio.run(run())diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex c16007e9c..adf03083c 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -1,1557 +1,605 @@-"""Unit tests for the LightRAG RAG pipeline + provider routing.--RAG-Anything / LightRAG is an optional dependency that is NOT installed in CI,-so these tests exercise everything that does not require the package (factory-routing, config bridge, storage, lifecycle gating, parse-layer consumption)-directly, and stub the thin ``engine`` adapter + the parse service to cover the-index/search orchestration without the heavy deps.-"""-from __future__ import annotationsimport asyncio-import contextvarsimport inspectimport json-import loggingfrom pathlib import Pathimport sys-import threading-import timeimport typesimport pytest-from deeptutor.services.llm.exceptions import (- LLMAPIError,- LLMAuthenticationError,- LLMConfigError,- LLMParseError,- LLMProviderTransportError,- LLMRateLimitError,- LLMTimeoutError,-)-from deeptutor.services.rag.factory import (- LIGHTRAG_PROVIDER,- get_pipeline,- list_pipelines,- normalize_provider_name,+from deeptutor.services.llm.exceptions import LLMAPIError, LLMAuthenticationError+from deeptutor.services.parsing.types import ParsedDocument+from deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_name+from deeptutor.services.rag.index_versioning import list_kb_versions+from deeptutor.services.rag.pipelines.lightrag import config, engine, storage+from deeptutor.services.rag.pipelines.lightrag.ingress import (+ IngressError,+ load_verified_bundle,+ pending_root,)-from deeptutor.services.rag.index_versioning import resolve_storage_dir_for_read-from deeptutor.services.rag.pipelines.lightrag import (- block_policy,- engine,- storage,+from deeptutor.services.rag.pipelines.lightrag.pipeline import (+ BatchOutcome,+ LightRagBatchError,+ LightRagPipeline,)-from deeptutor.services.rag.pipelines.lightrag import (- config as lr_config,-)-from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagPipeline-from deeptutor.services.rag.pipelines.lightrag.worker import run_in_worker_loop-# --------------------------------------------------------------------------- #-# factory routing + config-# --------------------------------------------------------------------------- #+class _Bridge:+ def __init__(self) -> None:+ self.calls = 0-def test_factory_dispatches_lightrag_lazily(tmp_path) -> None:- pipe = get_pipeline("lightrag", kb_base_dir=str(tmp_path))- assert type(pipe).__name__ == "LightRagPipeline"- # Building the pipeline must NOT import the heavy optional dependency.- assert "raganything" not in sys.modules+ def raise_if_cancelled(self) -> None:+ return None+ async def run(self, factory):+ self.calls += 1+ return await factory()-def test_list_pipelines_includes_lightrag(monkeypatch) -> None:- monkeypatch.setattr(lr_config, "is_lightrag_available", lambda: False)- entry = next(p for p in list_pipelines() if p["id"] == LIGHTRAG_PROVIDER)- assert entry["requires_api_key"] is False- assert entry["configured"] is False+ async def call(self, callback, *args):+ self.calls += 1+ value = callback(*args)+ return await value if inspect.isawaitable(value) else value-def test_normalize_provider_keeps_lightrag() -> None:- assert normalize_provider_name("lightrag") == "lightrag"+def test_factory_routes_without_importing_optional_sdk(tmp_path: Path, monkeypatch) -> None:+ sys.modules.pop("lightrag", None)+ pipeline = get_pipeline("lightrag", kb_base_dir=str(tmp_path))+ assert isinstance(pipeline, LightRagPipeline)+ assert "lightrag" not in sys.modules+ monkeypatch.setattr(config, "is_lightrag_available", lambda: False)+ entry = next(item for item in list_pipelines() if item["id"] == "lightrag")+ assert entry["configured"] is Falseassert normalize_provider_name("LightRAG") == "lightrag"@pytest.mark.parametrize(- "given,expected",- [- ("hybrid", "hybrid"),- ("MIX", "mix"),- ("naive", "naive"),- ("local", "local"),- ("global", "global"),- ("", "hybrid"),- (None, "hybrid"),- ("bogus", "hybrid"),- ],+ ("value", "expected"),+ [("MIX", "mix"), ("local", "local"), (None, "hybrid"), ("invalid", "hybrid")],)-def test_normalize_mode(given, expected) -> None:- assert lr_config.normalize_mode(given) == expected+def test_normalize_mode(value, expected) -> None:+ assert config.normalize_mode(value) == expected-def test_is_lightrag_available_false_when_dependency_missing(monkeypatch) -> None:- def fake_find_spec(name):- return None if name == "raganything" else object()+def test_availability_checks_native_lightrag_module(monkeypatch) -> None:+ seen: list[str] = []- monkeypatch.setattr(lr_config.importlib.util, "find_spec", fake_find_spec)- assert lr_config.is_lightrag_available() is False+ def find_spec(name: str):+ seen.append(name)+ return None+ monkeypatch.setattr(config.importlib.util, "find_spec", find_spec)+ assert config.is_lightrag_available() is False+ assert seen == ["lightrag"]-# --------------------------------------------------------------------------- #-# storage-# --------------------------------------------------------------------------- #+def test_distribution_identity_is_exact_rc2() -> None:+ assert engine.installed_version() == "1.5.7rc2"+ assert engine.LIGHTRAG_DISTRIBUTION == "lightrag-hku"-def test_storage_meta_and_has_output(tmp_path) -> None:- root = tmp_path / "version-1"- root.mkdir()- assert storage.has_output(root) is False- assert storage.has_output(None) is False- (root / "vdb_chunks.json").write_text("{}", encoding="utf-8")- assert storage.has_output(root) is False+def test_preflight_rejects_a_different_installed_lightrag_version(monkeypatch) -> None:+ from deeptutor.services.rag import preflight- (root / "graph_chunk_entity_relation.graphml").write_text("<graph/>", encoding="utf-8")- assert storage.has_output(root) is False+ monkeypatch.setattr(config, "is_lightrag_available", lambda: True)+ monkeypatch.setattr(engine, "installed_version", lambda: "1.5.8")+ monkeypatch.setattr(preflight, "_active_embedding", lambda: ("embedding", 3))+ monkeypatch.setattr(preflight, "_active_chat_model", lambda: ("chat", "openai"))+ report = preflight._lightrag_preflight()+ package = next(check for check in report["checks"] if check["key"] == "package")+ assert package["ok"] is False+ assert package["detail"] == "Found 1.5.8; required 1.5.7rc2."- (root / "kv_store_doc_status.json").write_text(- json.dumps(- {- "doc-1": {- "status": "failed",- "file_path": "bad.docx",- "error_msg": "embedding failed",- "chunks_list": [],- }- }- ),- encoding="utf-8",- )- assert storage.has_output(root) is False- assert storage.failure_summary(root) == "bad.docx: embedding failed"- assert storage.document_error(root, "doc-1") == "embedding failed"- (root / "kv_store_doc_status.json").write_text(- json.dumps(- {- "doc-1": {- "status": "processed",- "file_path": "good.docx",- "chunks_list": ["chunk-1"],- }- }- ),- encoding="utf-8",- )- assert storage.has_output(root) is True-- storage.write_meta(root)- meta = json.loads((root / storage.META_FILENAME).read_text())- assert meta["signature"] == "lightrag"- assert meta["provider"] == "lightrag"---class _FakeEmbeddingFunc:- """Stands in for ``lightrag.utils.EmbeddingFunc``.-- Its signature is deliberately limited to the real dataclass's fields, so a- constructor kwarg the pinned dependency does not accept fails here too.- ``test_fake_embedding_func_matches_the_real_dataclass`` pins the two- together whenever LightRAG is installed.- """-- def __init__(- self,- *,- embedding_dim,- func,- max_token_size=8192,- send_dimensions=None,- model_name=None,- supports_asymmetric=False,- ) -> None:- self.embedding_dim = embedding_dim- self.func = func- self.max_token_size = max_token_size- self.send_dimensions = send_dimensions- self.model_name = model_name- self.supports_asymmetric = supports_asymmetric-- async def __call__(self, *args, **kwargs):- if not self.supports_asymmetric:- kwargs.pop("context", None)- return await self.func(*args, **kwargs)---class _LegacyFakeEmbeddingFunc:- """Models LightRAG before ``supports_asymmetric`` was introduced."""-- def __init__(- self,- *,- embedding_dim,- func,- max_token_size=8192,- send_dimensions=None,- model_name=None,- ) -> None:- self.embedding_dim = embedding_dim- self.func = func- self.max_token_size = max_token_size- self.send_dimensions = send_dimensions- self.model_name = model_name-- async def __call__(self, *args, **kwargs):- return await self.func(*args, **kwargs)---class _RecordingBridge:- def __init__(self) -> None:- self.calls = 0+def test_workspace_is_stable_and_version_specific(tmp_path: Path) -> None:+ first = engine.workspace_for(tmp_path / "version-1")+ assert first == engine.workspace_for(tmp_path / "version-1")+ assert first != engine.workspace_for(tmp_path / "version-2")+ assert first.startswith("deeptutor_")- async def run(self, factory):- self.calls += 1- return await factory()+def _resolver(tmp_path: Path):+ cls = engine._controlled_class()+ rag = object.__new__(cls)+ rag.working_dir = str(tmp_path)+ return rag-def _install_fake_lightrag(monkeypatch, embedding_func_cls=_FakeEmbeddingFunc) -> None:- fake_lightrag = types.ModuleType("lightrag")- fake_utils = types.ModuleType("lightrag.utils")- fake_utils.EmbeddingFunc = embedding_func_cls- monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)- monkeypatch.setitem(sys.modules, "lightrag.utils", fake_utils)+def test_source_resolver_only_reads_version_ingress(tmp_path: Path, monkeypatch) -> None:+ pending = pending_root(tmp_path)+ pending.mkdir(parents=True)+ expected = pending / "doc.pdf"+ expected.write_bytes(b"right")+ decoy = tmp_path / "decoy"+ decoy.mkdir()+ (decoy / "doc.pdf").write_bytes(b"wrong")+ monkeypatch.chdir(decoy)+ rag = _resolver(tmp_path)+ assert rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor") == str(+ expected.resolve()+ )-def test_fake_embedding_func_matches_the_real_dataclass() -> None:- """Guard against the stub drifting from the dependency it stands in for."""- import dataclasses- lightrag_utils = pytest.importorskip("lightrag.utils")[email protected]("bad", ["../doc.pdf", "/tmp/doc.pdf", "nested/doc.pdf"])+def test_source_resolver_rejects_noncanonical_paths(tmp_path: Path, bad: str) -> None:+ rag = _resolver(tmp_path)+ with pytest.raises(IngressError):+ rag._resolve_source_file_for_parser(bad, parser_engine="deeptutor")- real_fields = {field.name for field in dataclasses.fields(lightrag_utils.EmbeddingFunc)}- stub = _FakeEmbeddingFunc if "supports_asymmetric" in real_fields else _LegacyFakeEmbeddingFunc- stub_fields = set(inspect.signature(stub.__init__).parameters.keys() - {"self"})- assert stub_fields == real_fields+def test_source_resolver_rejects_symlink_and_ambiguity(tmp_path: Path) -> None:+ pending = pending_root(tmp_path)+ archived = pending / "__parsed__"+ archived.mkdir(parents=True)+ outside = tmp_path / "outside.pdf"+ outside.write_bytes(b"outside")+ (pending / "doc.pdf").symlink_to(outside)+ rag = _resolver(tmp_path)+ with pytest.raises(IngressError, match="missing"):+ rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor")+ (pending / "doc.pdf").unlink()+ (pending / "doc.pdf").write_bytes(b"one")+ (archived / "doc.pdf").write_bytes(b"two")+ with pytest.raises(IngressError, match="ambiguous"):+ rag._resolve_source_file_for_parser("doc.pdf", parser_engine="deeptutor")-def test_embedding_func_returns_numpy_array(monkeypatch) -> None:- _install_fake_lightrag(monkeypatch)- class _Config:- dim = 3- max_tokens = 99+def test_source_resolver_rejects_other_parser(tmp_path: Path) -> None:+ with pytest.raises(IngressError, match="Unsupported parser"):+ _resolver(tmp_path)._resolve_source_file_for_parser("doc.pdf", parser_engine="mineru")- class _Client:- async def embed(self, texts, *, input_type=None):- del input_type- return [[1, 2, 3] for _ in texts]- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: _Config())- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", lambda: _Client())+def test_vision_adapter_maps_one_base64_unchanged(monkeypatch) -> None:+ captured: dict[str, object] = {}++ class Client:+ def get_vision_model_func(self):+ async def call(prompt, **kwargs):+ captured["prompt"] = prompt+ captured.update(kwargs)+ return "seen"++ return call- bridge = _RecordingBridge()- embedding = lr_config.build_embedding_func(io_bridge=bridge)- vectors = asyncio.run(embedding.func(["a", "b"]))- assert embedding.embedding_dim == 3- assert embedding.max_token_size == 99- assert vectors.shape == (2, 3)- assert hasattr(vectors, "size")- assert bridge.calls == 1+ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: Client())+ func = config.build_vision_model_func()+ assert asyncio.run(func("describe", image_inputs=[{"base64": "sentinel"}])) == "seen"+ assert captured["image_data"] == "sentinel"+ assert captured["allow_image_fallback"] is False@pytest.mark.parametrize(- ("embedding_func_cls", "expected_opt_in"),- [- (_FakeEmbeddingFunc, True),- (_LegacyFakeEmbeddingFunc, None),- ],+ "value",+ [None, [], [{"base64": "a"}, {"base64": "b"}], [{}], ["image"], [{"base64": ""}]],)-def test_embedding_func_maps_lightrag_query_and_document_context(- monkeypatch,- embedding_func_cls,- expected_opt_in,-) -> None:+def test_vision_adapter_rejects_invalid_inputs(monkeypatch, value) -> None:+ class Client:+ def get_vision_model_func(self):+ async def call(*_args, **_kwargs):+ raise AssertionError("prompt-only fallback must not run")++ return call++ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: Client())+ with pytest.raises(ValueError):+ asyncio.run(config.build_vision_model_func()("describe", image_inputs=value))+++def test_embedding_adapter_preserves_query_and_document_roles(monkeypatch) -> None:calls: list[tuple[list[str], str | None]] = []- _install_fake_lightrag(monkeypatch, embedding_func_cls)- class _Config:+ class EmbeddingConfig:dim = 3max_tokens = 99- class _Client:+ class Client:async def embed(self, texts, *, input_type=None):calls.append((list(texts), input_type))return [[1, 2, 3] for _ in texts]- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: _Config())- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", lambda: _Client())-- embedding = lr_config.build_embedding_func()- asyncio.run(embedding(["question"], context="query", _priority=1))- asyncio.run(embedding(["passage"], context="document"))- asyncio.run(embedding(["unlabelled"]))+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", EmbeddingConfig)+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", Client)+ adapter = config.build_embedding_func()+ query = asyncio.run(adapter(["question"], context="query"))+ document = asyncio.run(adapter(["passage"], context="document"))- assert getattr(embedding, "supports_asymmetric", None) is expected_opt_in+ assert query.shape == (1, 3)+ assert document.shape == (1, 3)assert calls == [(["question"], "search_query"),(["passage"], "search_document"),- (["unlabelled"], None),]-def test_lightrag_llm_adapter_preserves_messages_and_drops_extra_kwargs(- monkeypatch,-) -> None:- captured: dict[str, object] = {}+def test_llm_adapter_retries_only_transient_failures(monkeypatch) -> None:+ attempts = 0+ sleeps: list[float] = []- class _Client:+ class Client:def get_model_func(self):- async def model_func(prompt, **kwargs):- captured["prompt"] = prompt- captured.update(kwargs)+ async def call(_prompt, **kwargs):+ nonlocal attempts+ attempts += 1+ assert kwargs["max_retries"] == 0+ if attempts < 3:+ raise LLMAPIError("temporary", status_code=503)return "ok"- return model_func-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())-- bridge = _RecordingBridge()- func = lr_config.build_llm_model_func(io_bridge=bridge)- result = asyncio.run(- func(- "",- system_prompt="sys",- messages=[{"role": "user", "content": "from messages"}],- response_format={"type": "json_object"},- hashing_kv=object(),- keyword_extraction=True,- )- )-- assert result == "ok"- assert captured["prompt"] == ""- assert captured["system_prompt"] == "sys"- assert captured["history_messages"] == []- assert captured["messages"] == [{"role": "user", "content": "from messages"}]- assert captured["max_retries"] == 0- assert captured["allow_image_fallback"] is False- assert "response_format" not in captured- assert "hashing_kv" not in captured- assert "keyword_extraction" not in captured- assert bridge.calls == 1+ return call+ async def sleep(delay: float) -> None:+ sleeps.append(delay)-def test_lightrag_vision_adapter_preserves_messages(monkeypatch) -> None:- captured: dict[str, object] = {}+ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", Client)+ monkeypatch.setattr(config.asyncio, "sleep", sleep)+ assert asyncio.run(config.build_llm_model_func()("prompt")) == "ok"+ assert attempts == 3+ assert sleeps == [1.0, 2.0]- class _Client:- def get_vision_model_func(self):- async def model_func(prompt, **kwargs):- captured["prompt"] = prompt- captured.update(kwargs)- return "ok"-- return model_func- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())-- bridge = _RecordingBridge()- func = lr_config.build_vision_model_func(io_bridge=bridge)- result = asyncio.run(- func(- "",- image_data="abc123",- messages=[{"role": "user", "content": [{"type": "text", "text": "hi"}]}],- )- )+def test_llm_adapter_does_not_retry_authentication_failure(monkeypatch) -> None:+ error = LLMAuthenticationError("unauthorized")+ attempts = 0- assert result == "ok"- assert captured["prompt"] == ""- assert captured["image_data"] == "abc123"- assert captured["messages"] == [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]- assert captured["max_retries"] == 0- assert captured["allow_image_fallback"] is False- assert bridge.calls == 1---def test_lightrag_llm_adapter_uses_three_total_attempts_and_disables_provider_retry(- monkeypatch,-) -> None:- calls: list[dict[str, object]] = []- sleep_delays: list[float] = []- failures = [- LLMAPIError("temporary server error", status_code=503),- LLMRateLimitError("rate limited"),- ]-- class _Client:- def get_model_func(self):- async def model_func(_prompt, **kwargs):- calls.append(kwargs)- if failures:- raise failures.pop(0)- return "ok"-- return model_func-- async def fake_sleep(delay: float) -> None:- sleep_delays.append(delay)-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)-- bridge = _RecordingBridge()- func = lr_config.build_llm_model_func(io_bridge=bridge)-- assert asyncio.run(func("prompt")) == "ok"- assert len(calls) == 3- assert [call["max_retries"] for call in calls] == [0, 0, 0]- assert sleep_delays == [1.0, 2.0]- assert bridge.calls == 3--- "error",- [- LLMTimeoutError("timeout"),- LLMProviderTransportError("provider transport failed"),- TimeoutError("timeout"),- ConnectionError("connection"),- LLMRateLimitError("rate limited"),- LLMAPIError("temporary server error", status_code=500),- LLMAPIError("temporary overload", status_code=529),- LLMAPIError("Error calling Codex: Codex returned HTTP 503."),- LLMAPIError("Error code: 529 - overloaded_error"),- ],-)-def test_lightrag_adapter_retries_classified_transient_errors(monkeypatch, error) -> None:- calls = 0-- class _Client:+ class Client:def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- if calls == 1:- raise error- return "ok"-- return model_func-- async def fake_sleep(_delay: float) -> None:- return None+ async def call(_prompt, **_kwargs):+ nonlocal attempts+ attempts += 1+ raise error- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)+ return call- assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"- assert calls == 2+ monkeypatch.setattr("deeptutor.services.llm.get_llm_client", Client)+ with pytest.raises(LLMAuthenticationError) as caught:+ asyncio.run(config.build_llm_model_func()("prompt"))+ assert caught.value is error+ assert attempts == 1- "error",- [- LLMAuthenticationError("unauthorized"),- LLMAPIError("forbidden", status_code=403),- LLMAPIError("not implemented", status_code=501),- LLMConfigError("bad configuration"),- LLMParseError("bad response"),- ValueError("contract mismatch"),- ],-)-def test_lightrag_adapter_does_not_retry_deterministic_errors(monkeypatch, error) -> None:+def test_preparse_runs_once_and_bundle_ignores_later_parser_drift(+ monkeypatch, tmp_path: Path+) -> None:+ source = tmp_path / "source.md"+ source.write_text("original source", encoding="utf-8")calls = 0- class _Client:- def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- raise error-- return model_func-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())+ class ParseService:+ def parse(self, _path):+ nonlocal calls+ calls += 1+ return ParsedDocument(+ markdown="frozen markdown",+ engine="text_only",+ source_hash="source-hash",+ parser_signature="parser-v1",+ )- with pytest.raises(type(error)) as captured:- asyncio.run(lr_config.build_llm_model_func()("prompt"))+ monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", ParseService)+ monkeypatch.setattr(config, "vision_model_available", lambda: False)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path / "kb"))+ staged, failures = pipeline._stage_documents(tmp_path / "version-1", [str(source)])+ source.write_text("changed after staging", encoding="utf-8")- assert captured.value is error+ manifest, bundle = load_verified_bundle(tmp_path / "version-1", "source.md")assert calls == 1+ assert failures == {}+ assert len(staged) == 1+ assert (bundle / manifest["markdown"]["path"]).read_text() == "frozen markdown"+ assert staged[0].source_path.read_text() == "original source"-def test_lightrag_adapter_exhaustion_reraises_original_final_exception(monkeypatch) -> None:- failures = [- LLMAPIError("first", status_code=502),- LLMAPIError("second", status_code=503),- LLMAPIError("final", status_code=504),- ]- final_error = failures[-1]- calls = 0-- class _Client:- def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- raise failures.pop(0)+class _QueryRag:+ def __init__(self, result) -> None:+ self.result = result+ self.calls = 0+ self.param = None- return model_func+ async def aquery_llm(self, _question, *, param):+ self.calls += 1+ self.param = param+ return self.result- async def fake_sleep(_delay: float) -> None:- return None- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)+def _query_result() -> dict:+ return {+ "status": "success",+ "llm_response": {"is_streaming": False, "content": "answer"},+ "data": {+ "chunks": [+ {+ "chunk_id": "c1",+ "content": "x" * 500,+ "reference_id": "r1",+ "page": 2,+ }+ ],+ "entities": [+ {+ "entity_name": "Euler",+ "entity_type": "person",+ "description": "entity body",+ "source_id": "c1",+ "reference_id": "r1",+ }+ ],+ "relationships": [+ {+ "src_id": "Euler",+ "tgt_id": "Identity",+ "description": "relationship body",+ "keywords": ["math"],+ "weight": 3.5,+ "source_id": "c1",+ "reference_id": "r1",+ }+ ],+ "references": [{"reference_id": "r1", "file_path": "notes.pdf"}],+ },+ "metadata": {"keywords": {"high_level": ["math"]}, "processing_info": {"chunks": 1}},+ }- with pytest.raises(LLMAPIError) as captured:- asyncio.run(lr_config.build_llm_model_func()("prompt"))- assert captured.value is final_error- assert calls == 3+def test_query_uses_one_call_and_preserves_complete_sources(monkeypatch) -> None:+ monkeypatch.setattr(engine, "query_kwargs_from_settings", lambda: {})+ rag = _QueryRag(_query_result())+ answer, sources = asyncio.run(engine.query_with_sources(rag, "q", "hybrid"))+ assert rag.calls == 1+ assert rag.param.stream is False+ assert answer == "answer"+ assert sources[0]["content"] == "x" * 500+ assert sources[0]["kind"] == "chunk"+ assert sources[1]["entity_name"] == "Euler"+ assert sources[2]["weight"] == 3.5+ assert "score" not in sources[2]+ assert sources[3]["kind"] == "reference"+ assert sources[3]["reference"] == {"reference_id": "r1", "file_path": "notes.pdf"}+ assert sources[-1]["metadata"]["processing_info"] == {"chunks": 1}@pytest.mark.parametrize(- ("retry_after", "expected_delay"),- [(7.5, 7.5), (120.0, 60.0), (-1.0, 1.0), ("invalid", 1.0)],+ "result",+ [+ {"status": "failure", "message": "retrieval failed"},+ {"status": "success", "llm_response": {}, "data": {}, "metadata": {}},+ {+ "status": "success",+ "llm_response": {"is_streaming": True, "content": "x"},+ "data": {},+ "metadata": {},+ },+ "not an object",+ ],)-def test_lightrag_adapter_honors_bounded_retry_after(- monkeypatch,- retry_after,- expected_delay,-) -> None:- calls = 0- sleep_delays: list[float] = []-- class _Client:- def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- if calls == 1:- raise LLMRateLimitError("rate limited", retry_after=retry_after)- return "ok"-- return model_func-- async def fake_sleep(delay: float) -> None:- sleep_delays.append(delay)-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)-- assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"- assert sleep_delays == [expected_delay]---def test_lightrag_adapter_honors_retry_after_response_header(monkeypatch) -> None:- calls = 0- sleep_delays: list[float] = []-- class RetryableResponseError(Exception):- status_code = 503- response = types.SimpleNamespace(headers={"Retry-After": "4"})-- class _Client:- def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- if calls == 1:- raise RetryableResponseError("temporary")- return "ok"+def test_query_rejects_failure_and_malformed_envelopes(result) -> None:+ with pytest.raises(engine.LightRagContractError):+ asyncio.run(engine.query_with_sources(_QueryRag(result), "q"))- return model_func- async def fake_sleep(delay: float) -> None:- sleep_delays.append(delay)-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)-- assert asyncio.run(lr_config.build_llm_model_func()("prompt")) == "ok"- assert sleep_delays == [4.0]---def test_lightrag_adapter_preserves_cancellation_without_retry(monkeypatch) -> None:- calls = 0-- class _Client:- def get_model_func(self):- async def model_func(_prompt, **_kwargs):- nonlocal calls- calls += 1- raise asyncio.CancelledError-- return model_func-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())-- with pytest.raises(asyncio.CancelledError):- asyncio.run(lr_config.build_llm_model_func()("prompt"))-- assert calls == 1---async def test_lightrag_vision_adapter_disables_provider_image_fallback(- monkeypatch,-) -> None:- from deeptutor.services.llm.client import LLMClient- from deeptutor.services.llm.config import LLMConfig- from deeptutor.services.llm.multimodal import has_image_parts- from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse-- class ScriptedProvider(LLMProvider):- def __init__(self) -> None:- super().__init__()- self.calls_had_image: list[bool] = []-- async def chat(self, messages, **kwargs):- del kwargs- self.calls_had_image.append(has_image_parts(messages))- if len(self.calls_had_image) == 1:- return LLMResponse(- content="this model does not support images",- finish_reason="error",- )- return LLMResponse(content="text fallback should not run")-- def get_default_model(self) -> str:- return "unknown-model"-- config = LLMConfig(- model="unknown-model",- api_key="test-key",- base_url="https://api.example.com/v1",- binding="custom",- provider_name="custom",+def test_storage_publishes_schema_two_metadata(tmp_path: Path, monkeypatch) -> None:+ (tmp_path / "kv_store_doc_status.json").write_text(+ json.dumps({"id": {"status": "processed", "chunks_list": ["c"]}}), encoding="utf-8")- client = LLMClient(config)- provider = ScriptedProvider()-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: client)- monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", lambda: config)monkeypatch.setattr(- "deeptutor.services.llm.factory.get_runtime_provider",- lambda _config: provider,+ "deeptutor.services.rag.embedding_signature.embedding_meta_fields",+ lambda: {"embedding": "e"},)-- func = lr_config.build_vision_model_func()- with pytest.raises(LLMAPIError, match="does not support images"):- await func("prompt", image_data="QUJD")-- assert provider.calls_had_image == [True]---def test_lightrag_vision_adapter_preserves_payload_and_redacts_retry_log(- monkeypatch,- caplog,-) -> None:- sensitive_message = "prompt-secret base64-secret token-secret account-secret"- image_payload = "base64-secret-image-payload"- image_calls: list[object] = []- retry_settings: list[object] = []- calls = 0-- class _Client:- def get_vision_model_func(self):- async def model_func(_prompt, **kwargs):- nonlocal calls- calls += 1- image_calls.append(kwargs["image_data"])- retry_settings.append(kwargs["max_retries"])- if calls == 1:- raise ConnectionError(sensitive_message)- return "ok"-- return model_func-- async def fake_sleep(_delay: float) -> None:- return None-- monkeypatch.setattr("deeptutor.services.llm.get_llm_client", lambda: _Client())- monkeypatch.setattr(lr_config.asyncio, "sleep", fake_sleep)- caplog.set_level(logging.WARNING, logger=lr_config.__name__)-- func = lr_config.build_vision_model_func()- assert asyncio.run(func("prompt-secret", image_data=image_payload)) == "ok"-- assert calls == 2- assert all(payload is image_payload for payload in image_calls)- assert retry_settings == [0, 0]- assert sensitive_message not in caplog.text- assert "prompt-secret" not in caplog.text- assert image_payload not in caplog.text- assert (- "LightRAG adapter retry attempt=1 exception=ConnectionError status=transport" in caplog.text+ storage.write_meta(tmp_path)+ meta = json.loads((tmp_path / "meta.json").read_text(encoding="utf-8"))+ assert meta["state"] == "published"+ assert meta["lightrag_adapter_schema"] == 2+ assert meta["lightrag_package_version"] == "1.5.7rc2"+ assert meta["parser_inputs"] == []+ assert storage.meta_is_native_published(tmp_path) is True+++def test_flat_schema_two_candidate_fails_closed_until_published(tmp_path: Path) -> None:+ version = tmp_path / "version-1"+ version.mkdir()+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"id": {"status": "processed", "chunks_list": ["c"]}}), encoding="utf-8")+ (version / "meta.json").write_text(+ json.dumps({"provider": "lightrag", "signature": "lightrag", "lightrag_adapter_schema": 2}),+ encoding="utf-8",+ )+ assert list_kb_versions(tmp_path)[0]["ready"] is False+ payload = json.loads((version / "meta.json").read_text())+ payload["state"] = "published"+ (version / "meta.json").write_text(json.dumps(payload), encoding="utf-8")+ assert list_kb_versions(tmp_path)[0]["ready"] is True-def test_build_rag_skips_raganything_parser_install_check(monkeypatch) -> None:- """Regression for issue #594.-- RAG-Anything validates its *default* parser (``mineru``) at LightRAG-init- time, even though DeepTutor only ever inserts a pre-parsed ``content_list``- and never uses RAG-Anything's parser. ``build_rag`` must pre-satisfy that- check so indexing with a different parse engine (e.g. pymupdf4llm) doesn't- hard-fail when MinerU is absent.- """- captured: dict[str, object] = {}-- class _FakeConfig:- def __init__(self, *, working_dir) -> None:- self.working_dir = working_dir- self.parser = "mineru" # RAG-Anything's default-- class _FakeRagAnything:- def __init__(self, *, config, llm_model_func, vision_model_func, embedding_func) -> None:- # Mirror the real constructor: the install check starts unsatisfied.- self._parser_installation_checked = False- captured["config"] = config-- fake_module = types.ModuleType("raganything")- fake_module.RAGAnything = _FakeRagAnything- fake_module.RAGAnythingConfig = _FakeConfig- monkeypatch.setitem(sys.modules, "raganything", fake_module)- monkeypatch.setattr(engine, "build_llm_model_func", lambda: "llm")- monkeypatch.setattr(engine, "build_vision_model_func", lambda: "vision")- monkeypatch.setattr(engine, "build_embedding_func", lambda: "embed")-- rag = engine.build_rag(Path("/tmp/kb-wd")) # noqa: S108-- assert rag._parser_installation_checked is True- assert captured["config"].working_dir == "/tmp/kb-wd"---def test_lightrag_query_initializes_raganything_before_aquery(monkeypatch) -> None:- calls: list[str] = []-- class _Rag:- lightrag = None-- async def _ensure_lightrag_initialized(self):- calls.append("ensure")- self.lightrag = object()- return {"success": True}-- async def aquery(self, question, mode=None, **kwargs):- calls.append("aquery")- assert self.lightrag is not None- assert question == "hello"- assert mode == "hybrid"- assert kwargs == {}- return "answer"-- monkeypatch.setattr(engine, "query_kwargs_from_settings", lambda: {})-- result = asyncio.run(engine.query(_Rag(), "hello", "hybrid"))-- assert result == "answer"- assert calls == ["ensure", "aquery"]---def test_lightrag_query_surfaces_raganything_initialization_failure() -> None:- class _Rag:- lightrag = None-- async def _ensure_lightrag_initialized(self):- return {"success": False, "error": "storage failed"}-- async def aquery(self, question, mode=None, **kwargs): # pragma: no cover- raise AssertionError("aquery should not run")-- with pytest.raises(RuntimeError, match="storage failed"):- asyncio.run(engine.query(_Rag(), "hello", "hybrid"))---def test_lightrag_query_with_sources_keeps_answer_and_exposes_provenance(monkeypatch) -> None:- """The answer path remains RAG-Anything while citations use LightRAG data."""- captured: dict[str, object] = {}-- class _QueryParam:- def __init__(self, **kwargs) -> None:- captured["query_param"] = kwargs-- fake_lightrag = types.ModuleType("lightrag")- fake_lightrag.QueryParam = _QueryParam- monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)- monkeypatch.setattr(engine, "query_kwargs_from_settings", lambda: {"top_k": 3})-- class _LightRag:- async def aquery_data(self, question, *, param):- captured["provenance_query"] = question- captured["provenance_param"] = param- return {- "status": "success",- "data": {- "references": [{"reference_id": "ref-1", "file_path": "/kb/book.pdf"}],- "chunks": [- {- "chunk_id": "chunk-1",- "content": "The retrieved passage.",- "reference_id": "ref-1",- }- ],- "entities": [- {- "entity_name": "Newton's laws",- "entity_type": "concept",- "description": "A mechanics foundation.",- "source_id": "chunk-1",- "reference_id": "ref-1",- }- ],- "relationships": [- {- "src_id": "force",- "tgt_id": "acceleration",- "description": "Force produces acceleration.",- "source_id": "chunk-1",- "reference_id": "ref-1",- }- ],- },+def test_schema_two_metadata_without_processed_workspace_output_is_not_ready(+ tmp_path: Path,+) -> None:+ version = tmp_path / "version-1"+ workspace = version / "workspace"+ workspace.mkdir(parents=True)+ (version / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": 2,+ "state": "published",+ "workspace": "workspace",}-- class _Rag:- lightrag = _LightRag()-- async def aquery(self, question, mode=None, **kwargs):- captured["answer_query"] = (question, mode, kwargs)- return "Grounded answer"-- answer, sources = asyncio.run(engine.query_with_sources(_Rag(), "What is force?", "hybrid"))-- assert answer == "Grounded answer"- assert captured["answer_query"] == ("What is force?", "hybrid", {"top_k": 3})- assert captured["provenance_query"] == "What is force?"- assert captured["query_param"] == {"mode": "hybrid", "top_k": 3}- assert sources == [- {- "title": "book.pdf",- "content": "The retrieved passage.",- "source": "/kb/book.pdf",- "page": "",- "chunk_id": "chunk-1",- "reference_id": "ref-1",- },- {- "title": "Newton's laws",- "content": "A mechanics foundation.",- "source": "/kb/book.pdf",- "page": "",- "entity_id": "Newton's laws",- "entity_type": "concept",- "source_id": "chunk-1",- "reference_id": "ref-1",- },- {- "title": "force->acceleration",- "content": "Force produces acceleration.",- "source": "/kb/book.pdf",- "page": "",- "relation_id": "force->acceleration",- "source_entity_id": "force",- "target_entity_id": "acceleration",- "source_id": "chunk-1",- "reference_id": "ref-1",- },- ]---def test_lightrag_query_sources_falls_back_when_structured_api_is_unavailable() -> None:- class _Rag:- lightrag = object()-- assert asyncio.run(engine.query_sources(_Rag(), "hello", "hybrid")) == []---# --------------------------------------------------------------------------- #-# pipeline lifecycle (engine + parse service stubbed)-# --------------------------------------------------------------------------- #+ ),+ encoding="utf-8",+ )+ (workspace / "kv_store_doc_status.json").write_text(+ json.dumps({"id": {"status": "failed", "chunks_list": []}}), encoding="utf-8"+ )+ assert list_kb_versions(tmp_path)[0]["ready"] is False-class _FakeRag:- def __init__(self, working_dir) -> None:- self.working_dir = Path(working_dir)+def test_legacy_flat_metadata_stays_visible_but_requires_reindex(tmp_path: Path) -> None:+ version = tmp_path / "version-1"+ version.mkdir()+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"id": {"status": "processed", "chunks_list": ["c"]}}), encoding="utf-8"+ )+ (version / "meta.json").write_text(+ json.dumps({"provider": "lightrag", "signature": "lightrag"}), encoding="utf-8"+ )+ assert list_kb_versions(tmp_path)[0]["ready"] is True+ assert storage.meta_is_native_published(version) is False-def _force_available(monkeypatch, available: bool = True) -> None:- monkeypatch.setattr(lr_config, "is_lightrag_available", lambda: available)+def test_batch_outcome_only_completes_all_processed() -> None:+ assert BatchOutcome(requested=1, accepted=1, processed=("a",)).complete is True+ assert BatchOutcome(requested=2, accepted=1, processed=("a",), missing=("b",)).complete is False-def _stub_engine(monkeypatch, answer: str = "ANSWER") -> list[dict]:- """Stub the engine so insert writes a readiness marker and query echoes."""- inserts: list[dict] = []- monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FakeRag(wd))+def test_reconcile_counts_terminal_rows_and_missing(tmp_path: Path) -> None:+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ pipeline._status_no_progress_seconds = 0+ staged = [types.SimpleNamespace(canonical_name="a.pdf", audit_ledger=None)]- async def fake_insert(rag, content_list, *, file_name, doc_id):- inserts.append({"file": file_name, "doc_id": doc_id, "blocks": content_list})- (rag.working_dir / "vdb_chunks.json").write_text(- json.dumps({"vectors": [[1.0]]}), encoding="utf-8"- )- (rag.working_dir / "kv_store_doc_status.json").write_text(- json.dumps(- {- doc_id: {- "status": "processed",- "file_path": file_name,- "chunks_list": ["chunk-1"],- }- }- ),- encoding="utf-8",- )+ class Rag:+ working_dir = str(tmp_path)- async def fake_query_with_sources(rag, question, mode):- return f"{answer}|{mode}", []+ async def aget_docs_by_track_id(self, _track):+ return {"doc-a": types.SimpleNamespace(file_path="a.pdf", status="processed")}- monkeypatch.setattr(engine, "insert", fake_insert)- monkeypatch.setattr(engine, "query_with_sources", fake_query_with_sources)- return inserts+ outcome = asyncio.run(+ pipeline._reconcile(Rag(), staged, {"bad.pdf": "parse failed"}, "track", _Bridge(), None)+ )+ assert outcome.accepted == 1+ assert outcome.processed == ("a.pdf",)+ assert outcome.preflight_failed == {"bad.pdf": "parse failed"}+ assert outcome.complete is False-def _stub_parse(- monkeypatch,- *,- blocks=None,- markdown: str = "# md",- engine_name: str = "fake",- parser_signature: str = "",+def test_indexing_initializes_processes_reconciles_and_finalizes(+ tmp_path: Path, monkeypatch) -> None:- from deeptutor.services.parsing.types import ParsedDocument+ events: list[object] = []+ staged = types.SimpleNamespace(canonical_name="doc.pdf", process_options="F", audit_ledger=None)- class _Service:- def parse(self, path, **_):- return ParsedDocument(- markdown=markdown,- blocks=blocks,- source_hash="h_" + Path(path).stem,- parser_signature=parser_signature,- engine=engine_name,- )-- monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: _Service())+ class Rag:+ working_dir = str(tmp_path)+ async def apipeline_process_enqueue_documents(self):+ events.append("process")-def test_indexing_isolated_from_owner_loop_with_context_and_progress(tmp_path, monkeypatch) -> None:- """Regression for #761: local JSON work must not stall service I/O."""- from deeptutor.services.parsing.types import ParsedDocument+ async def aget_docs_by_track_id(self, track_id):+ assert track_id == "track-1"+ return {"doc-id": types.SimpleNamespace(file_path="doc.pdf", status="processed")}- request_scope = contextvars.ContextVar("lightrag_test_scope", default="missing")- captured: dict[str, object] = {"inserts": [], "progress": [], "parse_threads": []}-- class _ParseService:- def parse(self, path, **_):- captured["parse_threads"].append(threading.get_ident())- source = Path(path)- return ParsedDocument(- markdown="",- blocks=[{"type": "text", "text": source.stem, "page_idx": 0}],- source_hash=f"hash-{source.stem}",- engine="fake",- )-- class _BlockingRag:- def __init__(self, working_dir, io_bridge) -> None:- self.working_dir = Path(working_dir)- self.io_bridge = io_bridge-- async def insert_content_list(self, *, content_list, file_path, doc_id):- captured["worker_thread"] = threading.get_ident()- captured["worker_context"] = request_scope.get()- captured["block_started_at"] = time.monotonic()- time.sleep(0.15)-- async def fake_network_io():- captured["io_thread"] = threading.get_ident()- captured["io_context"] = request_scope.get()- return "io-ok"-- captured["io_result"] = await self.io_bridge.run(fake_network_io)- captured["inserts"].append(- {"content_list": content_list, "file_path": file_path, "doc_id": doc_id}- )- self.working_dir.mkdir(parents=True, exist_ok=True)- (self.working_dir / "kv_store_doc_status.json").write_text(- json.dumps(- {- doc_id: {- "status": "processed",- "file_path": file_path,- "chunks_list": ["chunk-1"],- }- }- ),- encoding="utf-8",- )+ rag = Rag()+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))+ monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: rag)- def fake_build_rag(working_dir, *, io_bridge):- captured["build_thread"] = threading.get_ident()- return _BlockingRag(working_dir, io_bridge)+ async def initialize(_rag):+ events.append("initialize")- monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: _ParseService())- monkeypatch.setattr(engine, "build_rag", fake_build_rag)- _force_available(monkeypatch, True)+ async def enqueue(_rag, documents):+ assert documents == [staged]+ events.append("enqueue")+ return "track-1"- docs = [tmp_path / "one.pdf", tmp_path / "two.pdf"]- for doc in docs:- doc.write_bytes(b"%PDF")+ async def finalize(_rag, *, cancel_pending):+ events.append(("finalize", cancel_pending))- async def scenario() -> bool:- owner_thread = threading.get_ident()- captured["owner_thread"] = owner_thread- request_scope.set("user-761")+ monkeypatch.setattr(engine, "initialize", initialize)+ monkeypatch.setattr(engine, "enqueue", enqueue)+ monkeypatch.setattr(engine, "finalize", finalize)- async def on_progress(current: int, total: int) -> None:- await asyncio.sleep(0)- captured["progress"].append(- (current, total, threading.get_ident(), request_scope.get())- )+ outcome = asyncio.run(pipeline._run_indexing(tmp_path, ["doc.pdf"], None))- async def heartbeat() -> None:- while "block_started_at" not in captured:- await asyncio.sleep(0)- await asyncio.sleep(0.01)- captured["heartbeat_at"] = time.monotonic()-- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- indexing = asyncio.create_task(- pipe.initialize("kb", [str(doc) for doc in docs], progress_callback=on_progress)- )- pulse = asyncio.create_task(heartbeat())- result = await indexing- await pulse- return result-- assert asyncio.run(scenario()) is True- owner_thread = captured["owner_thread"]- assert captured["build_thread"] != owner_thread- assert captured["worker_thread"] != owner_thread- assert set(captured["parse_threads"]) == {captured["worker_thread"]}- assert captured["io_thread"] == owner_thread- assert captured["worker_context"] == "user-761"- assert captured["io_context"] == "user-761"- assert captured["io_result"] == "io-ok"- assert captured["heartbeat_at"] - captured["block_started_at"] < 0.1- assert captured["progress"] == [- (1, 2, owner_thread, "user-761"),- (2, 2, owner_thread, "user-761"),- ]- assert captured["inserts"] == [- {- "content_list": [{"type": "text", "text": "one", "page_idx": 0}],- "file_path": "one.pdf",- "doc_id": "hash-one",- },- {- "content_list": [{"type": "text", "text": "two", "page_idx": 0}],- "file_path": "two.pdf",- "doc_id": "hash-two",- },- ]+ assert outcome.complete is True+ assert events == ["initialize", "enqueue", "process", ("finalize", False)]-def test_indexing_worker_exception_propagates_unchanged(tmp_path, monkeypatch) -> None:- class _IndexingFailure(RuntimeError):- pass-- class _FailingRag:- def __init__(self, working_dir) -> None:- self.working_dir = Path(working_dir)-- async def insert_content_list(self, **_):- raise _IndexingFailure("nano-vdb merge failed")-- monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FailingRag(wd))- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- _force_available(monkeypatch, True)- document = tmp_path / "bad.pdf"- document.write_bytes(b"%PDF")-- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- with pytest.raises(_IndexingFailure, match="nano-vdb merge failed"):- asyncio.run(pipe.initialize("kb", [str(document)]))---def test_indexing_cancellation_waits_for_worker_loop_to_close() -> None:- started = threading.Event()- stopped = threading.Event()- owner_callback_called = False- worker_loop: asyncio.AbstractEventLoop | None = None-- async def scenario() -> None:- async def job(io_bridge) -> None:- nonlocal owner_callback_called, worker_loop- worker_loop = asyncio.get_running_loop()- started.set()- try:- # Stand in for an uninterruptible synchronous NanoVectorDB- # flush. Cancellation is observed at the next bridge call.- time.sleep(0.05)-- def owner_callback() -> None:- nonlocal owner_callback_called- owner_callback_called = True-- await io_bridge.call(owner_callback)- finally:- stopped.set()-- task = asyncio.create_task(run_in_worker_loop(job))- while not started.is_set():- await asyncio.sleep(0)- task.cancel()- with pytest.raises(asyncio.CancelledError):- await task-- asyncio.run(scenario())-- assert stopped.is_set()- assert worker_loop is not None- assert worker_loop.is_closed()- assert owner_callback_called is False---def test_indexing_cancellation_cancels_worker_main_task() -> None:- started = threading.Event()- stopped = threading.Event()- worker_loop: asyncio.AbstractEventLoop | None = None-- async def scenario() -> None:- async def job(_io_bridge) -> None:- nonlocal worker_loop- worker_loop = asyncio.get_running_loop()- started.set()- try:- await asyncio.Event().wait()- finally:- stopped.set()-- task = asyncio.create_task(run_in_worker_loop(job))- while not started.is_set():- await asyncio.sleep(0)- task.cancel()- with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(task, timeout=0.5)-- asyncio.run(scenario())-- assert stopped.is_set()- assert worker_loop is not None- assert worker_loop.is_closed()---def test_indexing_cancellation_escalates_when_worker_suppresses_first_cancel() -> None:- started = threading.Event()- first_cancel = threading.Event()- stopped = threading.Event()- worker_loop: asyncio.AbstractEventLoop | None = None-- async def scenario() -> None:- async def job(_io_bridge) -> None:- nonlocal worker_loop- worker_loop = asyncio.get_running_loop()- started.set()- try:- await asyncio.Event().wait()- except asyncio.CancelledError:- first_cancel.set()- await asyncio.Event().wait()- finally:- stopped.set()-- task = asyncio.create_task(run_in_worker_loop(job, cancel_grace_seconds=0.01))- while not started.is_set():- await asyncio.sleep(0)- task.cancel()- with pytest.raises(asyncio.CancelledError):- await asyncio.wait_for(task, timeout=0.5)-- asyncio.run(scenario())-- assert first_cancel.is_set()- assert stopped.is_set()- assert worker_loop is not None- assert worker_loop.is_closed()---def test_indexing_failure_forces_queue_shutdown_and_finalizes_storage(- tmp_path,- monkeypatch,+def test_partial_failure_is_typed_and_finalizes_with_cancellation(+ tmp_path: Path, monkeypatch) -> None:- calls: list[tuple[object, ...]] = []+ events: list[object] = []+ staged = types.SimpleNamespace(canonical_name="bad.pdf", process_options="F", audit_ledger=None)- class _QueueFunc:- async def __call__(self, *_args, **_kwargs) -> None:- return None+ class Rag:+ working_dir = str(tmp_path)- async def shutdown(self, *, graceful: bool, timeout: float) -> None:- calls.append(("shutdown", graceful, timeout))+ async def apipeline_process_enqueue_documents(self):+ return None- queue_func = _QueueFunc()+ async def aget_docs_by_track_id(self, _track_id):+ return {+ "doc-id": types.SimpleNamespace(+ file_path="bad.pdf", status="failed", error_msg="parse failed"+ )+ }- class _FailingRag:- def __init__(self, working_dir) -> None:- self.working_dir = Path(working_dir)- self.lightrag = types.SimpleNamespace(- role_llm_funcs={"extract": queue_func},- embedding_func=types.SimpleNamespace(func=queue_func),- rerank_model_func=None,- )+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))+ monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: Rag())- async def insert_content_list(self, **_kwargs) -> None:- raise RuntimeError("entity extraction failed")-- async def finalize_storages(self) -> None:- calls.append(("finalize",))-- monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FailingRag(wd))- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- _force_available(monkeypatch, True)- document = tmp_path / "bad.pdf"- document.write_bytes(b"%PDF")-- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- with pytest.raises(RuntimeError, match="entity extraction failed"):- asyncio.run(pipe.initialize("kb", [str(document)]))-- assert calls == [("shutdown", False, 5.0), ("finalize",)]---def test_initialize_requires_lightrag(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, False)- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- with pytest.raises(lr_config.LightRagNotAvailableError):- asyncio.run(pipe.initialize("kb", [str(pdf)]))---def test_initialize_orchestrates_index_and_uses_blocks(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "hi", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "exam.pdf"- pdf.write_bytes(b"%PDF")-- ok = asyncio.run(pipe.initialize("kb", [str(pdf)]))- assert ok is True- assert len(inserts) == 1- assert inserts[0]["file"] == "exam.pdf"- # blocks from the parse layer are passed through verbatim (multimodal path).- assert inserts[0]["blocks"] == [{"type": "text", "text": "hi", "page_idx": 0}]- # version dir is marked ready.- root = resolve_storage_dir_for_read(tmp_path / "kb", None)- assert storage.has_output(root) is True---def test_initialize_filters_only_mineru_layout_blocks(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- raw_blocks = [- {"type": "header", "text": "chapter", "page_idx": 0},- {"type": "text", "text": "body", "page_idx": 0},- {"type": "image", "img_path": "/tmp/image.png", "page_idx": 0}, # noqa: S108- {"type": "footer", "text": "publisher", "page_idx": 0},- {"type": "page_number", "text": "1", "page_idx": 0},- ]- original = json.loads(json.dumps(raw_blocks))- _stub_parse(- monkeypatch,- blocks=raw_blocks,- engine_name="mineru",- parser_signature="mineru-signature",- )- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "exam.pdf"- pdf.write_bytes(b"%PDF")-- assert asyncio.run(pipe.initialize("kb", [str(pdf)])) is True-- assert [item["type"] for item in inserts[0]["blocks"]] == ["text", "image"]- assert raw_blocks == original- root = resolve_storage_dir_for_read(tmp_path / "kb", None)- assert root is not None- ledgers = list((root / block_policy.LEDGER_DIRNAME).glob("*.json"))- assert len(ledgers) == 1- ledger = json.loads(ledgers[0].read_text(encoding="utf-8"))- assert ledger["counts"]["raw_total"] == 5- assert ledger["counts"]["filtered_total"] == 3- assert ledger["counts"]["eligible_multimodal_total"] == 1- assert ledger["counts"]["unknown_total"] == 0- assert ledger["decision"]["ledger_role"] == "current-index"- assert ledger["decision"]["policy_outcome"] == "accepted"- attempts = list((tmp_path / "kb" / block_policy.ATTEMPT_LEDGER_DIRNAME).glob("*.json"))- assert len(attempts) == 1- accepted_attempt = json.loads(attempts[0].read_text(encoding="utf-8"))- assert accepted_attempt["decision"]["policy_outcome"] == "accepted"- assert accepted_attempt["decision"]["attempt_id"] == ledger["decision"]["attempt_id"]---def test_initialize_indexes_unknown_mineru_types_and_records_them(tmp_path, monkeypatch) -> None:- """A new MinerU block type must not take the whole ingest down.-- The type is unrecognized, not unwanted: index it, record the count so the- policy can be extended, and keep the block's own text out of the audit- file.- """- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- _stub_parse(- monkeypatch,- blocks=[{"type": "future_widget", "text": "raw-block-secret", "page_idx": 0}],- engine_name="mineru",- )- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "exam.pdf"- pdf.write_bytes(b"%PDF")-- assert asyncio.run(pipe.initialize("kb", [str(pdf)])) is True-- assert len(inserts) == 1- assert resolve_storage_dir_for_read(tmp_path / "kb", None) is not None- attempts = list((tmp_path / "kb" / block_policy.ATTEMPT_LEDGER_DIRNAME).glob("*.json"))- assert len(attempts) == 1- recorded = json.loads(attempts[0].read_text(encoding="utf-8"))- assert recorded["counts"]["unknown_by_type"] == {"future_widget": 1}- assert recorded["decision"]["ledger_role"] == "attempt"- assert recorded["decision"]["policy_outcome"] == "unknown_types"- assert "raw-block-secret" not in attempts[0].read_text(encoding="utf-8")---def test_add_documents_records_unknown_types_without_blocking_ingest(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- _stub_parse(- monkeypatch,- blocks=[{"type": "text", "text": "accepted", "page_idx": 0}],- engine_name="mineru",- parser_signature="accepted-signature",- )- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "exam.pdf"- pdf.write_bytes(b"%PDF")-- assert asyncio.run(pipe.initialize("kb", [str(pdf)])) is True- root = resolve_storage_dir_for_read(tmp_path / "kb", None)- assert root is not None- current_path = next((root / block_policy.LEDGER_DIRNAME).glob("*.json"))- accepted_payload = current_path.read_text(encoding="utf-8")-- _stub_parse(- monkeypatch,- blocks=[{"type": "future_widget", "text": "later", "page_idx": 0}],- engine_name="mineru",- parser_signature="unknown-type-signature",- )- assert asyncio.run(pipe.add_documents("kb", [str(pdf)])) is True+ async def no_op(*_args, **_kwargs):+ return None- assert len(inserts) == 2- attempts = [- json.loads(path.read_text(encoding="utf-8"))- for path in (tmp_path / "kb" / block_policy.ATTEMPT_LEDGER_DIRNAME).glob("*.json")- ]- assert len(attempts) == 2- recorded = next(- item for item in attempts if item["decision"]["policy_outcome"] == "unknown_types"- )- assert recorded["parser"]["parser_signature"] == "unknown-type-signature"- assert recorded["counts"]["unknown_total"] == 1+ async def enqueue(*_args, **_kwargs):+ return "track-1"+ async def finalize(_rag, *, cancel_pending):+ events.append(("finalize", cancel_pending))-def test_add_documents_insert_failure_keeps_current_accepted_ledger(- tmp_path,- monkeypatch,-) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch)- _stub_parse(- monkeypatch,- blocks=[{"type": "text", "text": "accepted", "page_idx": 0}],- engine_name="mineru",- parser_signature="accepted-signature",- )- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "exam.pdf"- pdf.write_bytes(b"%PDF")-- assert asyncio.run(pipe.initialize("kb", [str(pdf)])) is True- root = resolve_storage_dir_for_read(tmp_path / "kb", None)- assert root is not None- current_path = next((root / block_policy.LEDGER_DIRNAME).glob("*.json"))- accepted_payload = current_path.read_text(encoding="utf-8")-- _stub_parse(- monkeypatch,- blocks=[{"type": "text", "text": "new attempt", "page_idx": 0}],- engine_name="mineru",- parser_signature="new-signature",- )+ monkeypatch.setattr(engine, "initialize", no_op)+ monkeypatch.setattr(engine, "enqueue", enqueue)+ monkeypatch.setattr(engine, "finalize", finalize)- async def fail_insert(*_args, **_kwargs) -> None:- raise RuntimeError("insert failed")+ with pytest.raises(LightRagBatchError) as caught:+ asyncio.run(pipeline._run_indexing(tmp_path, ["bad.pdf"], None))+ assert caught.value.outcome.failed == {"bad.pdf": "parse failed"}+ assert events == [("finalize", True)]- monkeypatch.setattr(engine, "insert", fail_insert)- with pytest.raises(RuntimeError, match="insert failed"):- asyncio.run(pipe.add_documents("kb", [str(pdf)]))- assert current_path.read_text(encoding="utf-8") == accepted_payload- attempts = [- json.loads(path.read_text(encoding="utf-8"))- for path in (tmp_path / "kb" / block_policy.ATTEMPT_LEDGER_DIRNAME).glob("*.json")- ]- assert len(attempts) == 2- latest_attempt = next(- item for item in attempts if item["parser"]["parser_signature"] == "new-signature"+def test_search_failure_is_not_reported_as_empty_success(tmp_path: Path, monkeypatch) -> None:+ root = tmp_path / "version-1"+ root.mkdir()+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.pipeline.resolve_storage_dir_for_read",+ lambda *_args: root,)- assert latest_attempt["decision"]["policy_outcome"] == "accepted"- assert latest_attempt["counts"]["unknown_total"] == 0---def test_ingest_falls_back_to_markdown_when_no_blocks(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- _stub_parse(monkeypatch, blocks=None, markdown="# only markdown")- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "notes.pdf"- pdf.write_bytes(b"%PDF")+ monkeypatch.setattr(storage, "meta_is_native_published", lambda _root: True)+ monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: object())- asyncio.run(pipe.initialize("kb", [str(pdf)]))- assert inserts[0]["blocks"] == [{"type": "text", "text": "# only markdown", "page_idx": 0}]+ async def no_op(*_args, **_kwargs):+ return None+ async def fail(*_args, **_kwargs):+ raise engine.LightRagContractError("retrieval failed")-def test_initialize_no_content_returns_false(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- inserts = _stub_engine(monkeypatch)- _stub_parse(monkeypatch, blocks=None, markdown="") # empty parse- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "blank.pdf"- pdf.write_bytes(b"%PDF")+ monkeypatch.setattr(engine, "initialize", no_op)+ monkeypatch.setattr(engine, "query_with_sources", fail)+ monkeypatch.setattr(engine, "finalize", no_op)- ok = asyncio.run(pipe.initialize("kb", [str(pdf)]))- assert ok is False- assert inserts == []+ result = asyncio.run(pipeline.search("question", "kb"))+ assert result["content"] == ""+ assert result["sources"] == []+ assert result["error_type"] == "retrieval_error"-def test_initialize_fails_when_lightrag_records_doc_failure(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- monkeypatch.setattr(engine, "build_rag", lambda wd, **_: _FakeRag(wd))- async def fake_insert(rag, content_list, *, file_name, doc_id):- (rag.working_dir / "kv_store_doc_status.json").write_text(- json.dumps(- {- doc_id: {- "status": "failed",- "file_path": file_name,- "error_msg": "'list' object has no attribute 'size'",- "chunks_list": [],- }- }- ),- encoding="utf-8",- )-- monkeypatch.setattr(engine, "insert", fake_insert)- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "hi", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- docx = tmp_path / "bad.docx"- docx.write_bytes(b"docx")-- with pytest.raises(RuntimeError, match="list.*size"):- asyncio.run(pipe.initialize("kb", [str(docx)]))-- assert resolve_storage_dir_for_read(tmp_path / "kb", None) is None---def test_search_needs_reindex_without_output(tmp_path) -> None:- res = asyncio.run(LightRagPipeline(kb_base_dir=str(tmp_path)).search("q", "missing"))- assert res["needs_reindex"] is True- assert res["provider"] == "lightrag"---def test_search_not_configured_when_unavailable(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch)- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- asyncio.run(pipe.initialize("kb", [str(pdf)]))-- _force_available(monkeypatch, False)- res = asyncio.run(pipe.search("q", "kb"))- assert res["error_type"] == "not_configured"---def test_search_happy_path_resolves_mode(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch, answer="GROUNDED")- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- asyncio.run(pipe.initialize("kb", [str(pdf)]))-- # Per-KB search_mode is read from kb_config.json next to the store.- (tmp_path / "kb_config.json").write_text(- json.dumps({"knowledge_bases": {"kb": {"search_mode": "local"}}}), encoding="utf-8"+def test_legacy_search_requires_reindex_without_mutating_files(tmp_path: Path) -> None:+ kb = tmp_path / "kb"+ version = kb / "version-1"+ version.mkdir(parents=True)+ meta = version / "meta.json"+ meta.write_text(json.dumps({"provider": "lightrag", "signature": "lightrag"}), encoding="utf-8")+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"id": {"status": "processed", "chunks_list": ["c"]}}),+ encoding="utf-8",)- res = asyncio.run(pipe.search("question?", "kb"))- assert res["answer"] == "GROUNDED|local"- assert res["mode"] == "local"- assert res["provider"] == "lightrag"---def test_search_returns_lightrag_provenance_sources(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch)- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- asyncio.run(pipe.initialize("kb", [str(pdf)]))+ before = {path.name: path.read_bytes() for path in version.iterdir()}- async def fake_query_with_sources(rag, question, mode):- return "Grounded", [{"title": "a.pdf", "chunk_id": "chunk-1"}]+ result = asyncio.run(LightRagPipeline(kb_base_dir=str(tmp_path)).search("q", "kb"))- monkeypatch.setattr(engine, "query_with_sources", fake_query_with_sources)-- res = asyncio.run(pipe.search("question?", "kb"))-- assert res["answer"] == "Grounded"- assert res["sources"] == [{"title": "a.pdf", "chunk_id": "chunk-1"}]---def test_explicit_mode_overrides_kb_config(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch, answer="A")- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- asyncio.run(pipe.initialize("kb", [str(pdf)]))-- res = asyncio.run(pipe.search("q", "kb", mode="global"))- assert res["mode"] == "global"---def test_global_provider_mode_used_when_kb_has_none(tmp_path, monkeypatch) -> None:- _force_available(monkeypatch, True)- _stub_engine(monkeypatch, answer="A")- _stub_parse(monkeypatch, blocks=[{"type": "text", "text": "x", "page_idx": 0}])- pipe = LightRagPipeline(kb_base_dir=str(tmp_path))- pdf = tmp_path / "a.pdf"- pdf.write_bytes(b"%PDF")- asyncio.run(pipe.initialize("kb", [str(pdf)]))-- # No per-KB search_mode, but a global default mode set from the engine card.- (tmp_path / "kb_config.json").write_text(- json.dumps({"defaults": {"provider_modes": {"lightrag": "naive"}}}), encoding="utf-8"- )- res = asyncio.run(pipe.search("q", "kb"))- assert res["mode"] == "naive"+ assert result["needs_reindex"] is True+ assert {path.name: path.read_bytes() for path in version.iterdir()} == beforediff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.pyindex edffb235e..d2178ade3 100644--- a/tests/services/rag/test_lightrag_settings_wiring.py+++ b/tests/services/rag/test_lightrag_settings_wiring.py@@ -1,145 +1,58 @@-"""The LightRAG settings knobs must not break older RAG-Anything installs.--``max_concurrent_files`` rides on ``RAGAnythingConfig`` and-``llm_model_max_async`` / ``entity_extract_max_gleaning`` ride on RAG-Anything's-``lightrag_kwargs`` passthrough — a parameter that only exists from ~1.2.5,-while the supported range starts at 1.0.1. Passing it blind raised TypeError-and took the whole engine down, so the wiring asks the installed class first.--raganything is an optional extra and is absent from CI, so these tests exercise-``build_rag`` against stand-in classes with each constructor shape.-"""+"""Settings are wired directly to the pinned native LightRAG constructor."""from __future__ import annotationsfrom pathlib import Path-import sys-import types-from typing import Any--import pytest--from deeptutor.services.rag.pipelines.lightrag import engine as engine_module---class _ModernConfig:- """RAG-Anything >= 1.2.5: config takes the batch knob."""-- def __init__(self, working_dir: str, max_concurrent_files: int = 1) -> None:- self.working_dir = working_dir- self.max_concurrent_files = max_concurrent_files---class _LegacyConfig:- """RAG-Anything 1.0.x: no batch knob at all."""-- def __init__(self, working_dir: str) -> None:- self.working_dir = working_dir---class _ModernRag:- """RAG-Anything >= 1.2.5: exposes the lightrag_kwargs passthrough."""-- def __init__(- self,- config: Any,- llm_model_func: Any,- vision_model_func: Any,- embedding_func: Any,- lightrag_kwargs: dict[str, Any] | None = None,- ) -> None:- self.config = config- self.lightrag_kwargs = lightrag_kwargs- self.set_content_source_func = None--class _LegacyRag:- """RAG-Anything 1.0.x: no passthrough."""+from deeptutor.services.rag.pipelines.lightrag import engine- def __init__(- self,- config: Any,- llm_model_func: Any,- vision_model_func: Any,- embedding_func: Any,- ) -> None:- self.config = config- self.lightrag_kwargs = None- self.set_content_source_func = None+class _NativeLightRag:+ def __init__(self, **kwargs) -> None:+ self.kwargs = kwargs-def fake_raganything(monkeypatch: pytest.MonkeyPatch):- """Install a stand-in ``raganything`` module with the given class shapes."""- def install(rag_cls: type, config_cls: type) -> None:- module = types.ModuleType("raganything")- module.RAGAnything = rag_cls # type: ignore[attr-defined]- module.RAGAnythingConfig = config_cls # type: ignore[attr-defined]- monkeypatch.setitem(sys.modules, "raganything", module)+def _stub_build(monkeypatch) -> None:+ monkeypatch.setattr(engine, "_require_exact_version", lambda: None)+ monkeypatch.setattr(engine, "_register_parser", lambda: None)+ monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)+ monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")+ monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")- return install-[email protected](autouse=True)-def _stub_adapters(monkeypatch: pytest.MonkeyPatch) -> None:- for name in ("build_llm_model_func", "build_vision_model_func", "build_embedding_func"):- monkeypatch.setattr(engine_module, name, lambda **_kwargs: lambda *a, **k: None)--[email protected](autouse=True)-def _settings(monkeypatch: pytest.MonkeyPatch) -> None:+def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:+ _stub_build(monkeypatch)monkeypatch.setattr(- engine_module, "indexing_kwargs_from_settings", lambda: {"max_concurrent_files": 4}+ engine, "indexing_kwargs_from_settings", lambda: {"max_parallel_parse_native": 4})monkeypatch.setattr(- engine_module,- "lightrag_kwargs_from_settings",+ engine,+ "constructor_kwargs_from_settings",lambda: {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2},)+ rag = engine.build_rag(tmp_path)-def test_modern_raganything_receives_every_knob(fake_raganything, tmp_path: Path) -> None:- fake_raganything(_ModernRag, _ModernConfig)-- rag = engine_module.build_rag(tmp_path)-- assert rag.config.max_concurrent_files == 4- assert rag.lightrag_kwargs == {"llm_model_max_async": 8, "entity_extract_max_gleaning": 2}---def test_legacy_raganything_still_builds(- fake_raganything, tmp_path: Path, caplog: pytest.LogCaptureFixture-) -> None:- """The knobs are dropped with a warning rather than raising TypeError."""- fake_raganything(_LegacyRag, _LegacyConfig)-- with caplog.at_level("WARNING"):- rag = engine_module.build_rag(tmp_path)-- assert rag.lightrag_kwargs is None- assert not hasattr(rag.config, "max_concurrent_files")- assert "max_concurrent_files" in caplog.text- assert "lightrag_kwargs" in caplog.text---def test_mixed_versions_drop_only_the_unsupported_knob(fake_raganything, tmp_path: Path) -> None:- fake_raganything(_LegacyRag, _ModernConfig)-- rag = engine_module.build_rag(tmp_path)-- assert rag.config.max_concurrent_files == 4- assert rag.lightrag_kwargs is None+ assert rag.kwargs["working_dir"] == str(tmp_path)+ assert rag.kwargs["workspace"] == engine.workspace_for(tmp_path)+ assert rag.kwargs["llm_model_func"] == "llm"+ assert rag.kwargs["embedding_func"] == "embedding"+ assert rag.kwargs["auto_manage_storages_states"] is False+ assert rag.kwargs["max_parallel_parse_native"] == 4+ assert rag.kwargs["llm_model_max_async"] == 8+ assert rag.kwargs["entity_extract_max_gleaning"] == 2+ assert rag.kwargs["vlm_process_enable"] is False+ assert "role_llm_configs" not in rag.kwargs-def test_no_configured_knobs_passes_nothing_extra(- fake_raganything, tmp_path: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- monkeypatch.setattr(engine_module, "indexing_kwargs_from_settings", dict)- monkeypatch.setattr(engine_module, "lightrag_kwargs_from_settings", dict)- fake_raganything(_ModernRag, _ModernConfig)+def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -> None:+ _stub_build(monkeypatch)+ monkeypatch.setattr(engine, "build_vision_model_func", lambda **_kwargs: "vision")+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)- rag = engine_module.build_rag(tmp_path)+ rag = engine.build_rag(tmp_path, enable_vlm=True)- assert rag.config.max_concurrent_files == 1 # the library default- assert rag.lightrag_kwargs is None+ role = rag.kwargs["role_llm_configs"]["vlm"]+ assert role.func == "vision"+ assert rag.kwargs["vlm_process_enable"] is Truediff --git a/tests/test_packaging_metadata.py b/tests/test_packaging_metadata.pyindex e0fda7083..daff5a1d2 100644--- a/tests/test_packaging_metadata.py+++ b/tests/test_packaging_metadata.py@@ -82,13 +82,24 @@ def test_pageindex_sdk_range_matches_every_install_surface() -> None:).splitlines().count(expected) == 1+def test_lightrag_extra_is_the_exact_native_sdk_without_parser_transitives() -> None:+ with (REPOSITORY_ROOT / "pyproject.toml").open("rb") as file:+ extras = tomllib.load(file)["project"]["optional-dependencies"]++ requirements = extras["rag-lightrag"]+ assert requirements == ["lightrag-hku==1.5.7rc2"]+ names = [requirement.lower().split("=", 1)[0].split("<", 1)[0] for requirement in requirements]+ assert "raganything" not in names+ assert "mineru" not in names++@pytest.mark.parametrize("expected",["loguru>=0.7.3,<1.0.0","json-repair>=0.57.0,<1.0.0","pyte>=0.8.1",- "pdfplumber>=0.11.0,<0.11.8",+ "pdfplumber>=0.11.0","reportlab>=4.0.0",],)diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex 3b073590b..1d12c3380 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -77,7 +77,7 @@ export interface LightRagConfig {version: number;top_k: number;response_type: string;- /** Files RAG-Anything processes in parallel while indexing. */+ /** Frozen documents LightRAG parses in parallel while indexing. */max_concurrent_files: number;/** Concurrent LLM calls LightRAG's internal queue issues. */llm_model_max_async: number;diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 846e8a812..eec9d7b85 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -2709,7 +2709,7 @@"API key configured": "API key configured","GraphRAG package installed": "GraphRAG package installed","Active chat model": "Active chat model",- "RAG-Anything package installed": "RAG-Anything package installed",+ "LightRAG package installed": "LightRAG package installed","Vision model for multimodal": "Vision model for multimodal","Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.","Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.": "Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 1279f3d24..d6cc78907 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -2709,7 +2709,7 @@"API key configured": "已配置 API 密钥","GraphRAG package installed": "已安装 GraphRAG 依赖包","Active chat model": "已启用对话模型",- "RAG-Anything package installed": "已安装 RAG-Anything 依赖包",+ "LightRAG package installed": "已安装 LightRAG 依赖包","Vision model for multimodal": "用于多模态的视觉模型","Local vector engine — works out of the box. Retrieval uses your active embedding model; install the optional BM25 package to enable hybrid retrieval.": "本地向量引擎,开箱即用。检索使用你当前启用的嵌入模型;可选安装 BM25 包以启用混合检索。","Hosted engine: documents are uploaded to PageIndex's servers and the chat agent reads them through the PageIndex MCP tools. Requires an API key; PDF, Office, text and Markdown formats.": "托管引擎:文档上传到 PageIndex 服务器,聊天 agent 通过 PageIndex MCP 工具阅读文档。需配置 API 密钥;支持 PDF、Office、文本和 Markdown 格式。",