DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(rag): filter MinerU page-layout blocks before indexing (#949)
NoxsMedia6bc366e5676f
diff --git a/deeptutor/services/rag/pipelines/lightrag/__init__.py b/deeptutor/services/rag/pipelines/lightrag/__init__.pyindex 8c1ba908a..0e4443a2b 100644--- a/deeptutor/services/rag/pipelines/lightrag/__init__.py+++ b/deeptutor/services/rag/pipelines/lightrag/__init__.py@@ -7,6 +7,7 @@ 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``.diff --git a/deeptutor/services/rag/pipelines/lightrag/block_policy.py b/deeptutor/services/rag/pipelines/lightrag/block_policy.pynew file mode 100644index 000000000..048ee8c9a--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/block_policy.py@@ -0,0 +1,266 @@+"""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.+"""++from __future__ import annotations++from collections import Counter+from copy import deepcopy+from dataclasses import dataclass+import hashlib+from pathlib import Path+import re+from typing import Any+import uuid++from deeptutor.services.file_io import atomic_write_json++POLICY_ID = "mineru-legacy-content-list-v1"+LEDGER_DIRNAME = "deeptutor_ingestion_audit"+ATTEMPT_LEDGER_DIRNAME = "deeptutor_ingestion_attempts"++FILTERED_LAYOUT_TYPES = frozenset({"footer", "header", "page_number"})+PRESERVED_AUXILIARY_TYPES = frozenset({"aside_text", "page_footnote"})+PRESERVED_SEMANTIC_TYPES = frozenset(+ {"chart", "code", "equation", "image", "list", "table", "text"}+)+PRESERVED_TYPES = PRESERVED_AUXILIARY_TYPES | PRESERVED_SEMANTIC_TYPES+MULTIMODAL_TYPES = PRESERVED_TYPES - {"text"}++# MinerU renamed its auxiliary block types between output schemas: what the+# legacy ``content_list.json`` calls ``header`` a newer parser emits as+# ``page_header``. Map the newer names back onto the vocabulary the policy is+# written in, so upgrading MinerU keeps classifying blocks instead of+# presenting every layout block as an unrecognized type.+V2_AUXILIARY_EQUIVALENTS = {+ "aside_text": "page_aside_text",+ "footer": "page_footer",+ "header": "page_header",+ "page_footnote": "page_footnote",+ "page_number": "page_number",+}+_V2_TO_LEGACY_TYPE = {+ v2_name: legacy_name+ for legacy_name, v2_name in V2_AUXILIARY_EQUIVALENTS.items()+ if v2_name != legacy_name+}++_SAFE_TYPE = re.compile(r"[a-z][a-z0-9_]{0,63}\Z")+_INVALID_TYPE = "<invalid>"+++@dataclass(frozen=True)+class BlockPolicyDecision:+ """Sanitized policy outcome plus an independent list for indexing."""++ content_list: list[dict[str, Any]]+ ledger: dict[str, Any] | None+ unknown_type_counts: tuple[tuple[str, int], ...] = ()++ def unknown_summary(self) -> str:+ """``type=count`` rundown of block types the policy does not know."""+ return ", ".join(+ f"{content_type}={count}" for content_type, count in self.unknown_type_counts+ )+++def _sanitized_type(block: dict[str, Any]) -> str:+ value = block.get("type")+ if isinstance(value, str) and _SAFE_TYPE.fullmatch(value):+ return value+ return _INVALID_TYPE+++def _sorted_counts(counter: Counter[str]) -> dict[str, int]:+ return dict(sorted(counter.items()))+++def _page_type_key(content_type: str, block: dict[str, Any]) -> str | None:+ page_idx = block.get("page_idx")+ if isinstance(page_idx, int) and page_idx >= 0:+ return f"{content_type}:{page_idx}"+ return None+++def prepare_content_list(+ blocks: list[dict[str, Any]],+ *,+ engine: str,+ source_hash: str,+ parser_signature: str,+) -> BlockPolicyDecision:+ """Derive the indexable content list without mutating parser-owned blocks.++ Only MinerU's legacy structured output is classified. Other parse engines+ retain their existing behavior because their block vocabularies have+ independent contracts.+ """+ if engine != "mineru":+ return BlockPolicyDecision(content_list=blocks, ledger=None)++ raw_counts: Counter[str] = Counter()+ filtered_counts: Counter[str] = Counter()+ eligible_counts: Counter[str] = Counter()+ eligible_multimodal_page_counts: Counter[str] = Counter()+ unknown_counts: Counter[str] = Counter()+ indexable: list[dict[str, Any]] = []++ for raw_block in blocks:+ if not isinstance(raw_block, dict):+ raw_counts[_INVALID_TYPE] += 1+ unknown_counts[_INVALID_TYPE] += 1+ continue+ block = raw_block+ content_type = _sanitized_type(block)+ content_type = _V2_TO_LEGACY_TYPE.get(content_type, content_type)+ raw_counts[content_type] += 1+ if content_type in FILTERED_LAYOUT_TYPES:+ filtered_counts[content_type] += 1+ continue+ if content_type not in PRESERVED_TYPES:+ # Filter only what we positively recognize as page chrome; index+ # anything else. A MinerU release that adds a block type must not+ # silently drop its content, nor abort the whole ingest — before+ # this policy existed every block was indexed, and an unrecognized+ # type is far more likely to be new content than new chrome.+ unknown_counts[content_type] += 1++ eligible_counts[content_type] += 1+ if content_type in MULTIMODAL_TYPES:+ page_type_key = _page_type_key(content_type, block)+ if page_type_key is not None:+ eligible_multimodal_page_counts[page_type_key] += 1+ indexable.append(deepcopy(block))++ ledger: dict[str, Any] = {+ "schema_version": 1,+ "policy": {+ "id": POLICY_ID,+ "input_schema": "legacy-content-list",+ "filtered_layout_types": sorted(FILTERED_LAYOUT_TYPES),+ "preserved_auxiliary_types": sorted(PRESERVED_AUXILIARY_TYPES),+ "preserved_semantic_types": sorted(PRESERVED_SEMANTIC_TYPES),+ "v2_auxiliary_equivalents": dict(sorted(V2_AUXILIARY_EQUIVALENTS.items())),+ "v2_auxiliary_normalized": True,+ },+ "parser": {+ "engine": engine,+ "source_hash": source_hash,+ "parser_signature": parser_signature,+ },+ "counts": {+ "raw_total": len(blocks),+ "raw_by_type": _sorted_counts(raw_counts),+ "filtered_total": sum(filtered_counts.values()),+ "filtered_by_type": _sorted_counts(filtered_counts),+ "eligible_total": len(indexable),+ "eligible_by_type": _sorted_counts(eligible_counts),+ "eligible_multimodal_total": sum(+ count+ for content_type, count in eligible_counts.items()+ if content_type in MULTIMODAL_TYPES+ ),+ "eligible_multimodal_by_type_and_page": _sorted_counts(eligible_multimodal_page_counts),+ "unknown_total": sum(unknown_counts.values()),+ "unknown_by_type": _sorted_counts(unknown_counts),+ },+ "invariants": {+ "input_blocks_mutated": False,+ "eligible_order_preserved": True,+ "unknown_types_indexed": True,+ "raw_parser_artifacts_mutated": False,+ },+ }+ return BlockPolicyDecision(+ content_list=indexable,+ ledger=ledger,+ unknown_type_counts=tuple(sorted(unknown_counts.items())),+ )+++def write_decision_ledger(+ working_dir: Path,+ document_id: str,+ ledger: dict[str, Any],+ *,+ attempt_id: str | None = None,+) -> Path:+ """Persist the accepted decision that corresponds to the current index."""+ document_id_sha256 = hashlib.sha256(document_id.encode()).hexdigest()+ path = Path(working_dir) / LEDGER_DIRNAME / f"{document_id_sha256[:16]}.json"+ decision = {+ "ledger_role": "current-index",+ "policy_outcome": "accepted",+ }+ if attempt_id is not None:+ decision["attempt_id"] = attempt_id+ atomic_write_json(+ path,+ {+ **ledger,+ "document_id_sha256": document_id_sha256,+ "decision": decision,+ },+ )+ return path+++def write_attempt_ledger(+ kb_dir: Path,+ document_id: str,+ ledger: dict[str, Any],+ *,+ outcome: str,+) -> tuple[Path, str]:+ """Persist one immutable policy attempt outside a candidate version.++ ``unknown_types`` means the document indexed, but carried block types the+ policy has no entry for — the signal to extend ``PRESERVED_TYPES`` or+ ``FILTERED_LAYOUT_TYPES``, not an ingest failure.+ """+ if outcome not in {"accepted", "unknown_types"}:+ raise ValueError(f"Unsupported policy outcome: {outcome}")++ document_id_sha256 = hashlib.sha256(document_id.encode()).hexdigest()+ attempt_id = uuid.uuid4().hex+ policy = ledger.get("policy")+ parser = ledger.get("parser")+ policy_id = str(policy.get("id") or "") if isinstance(policy, dict) else ""+ parser_signature = str(parser.get("parser_signature") or "") if isinstance(parser, dict) else ""+ key_material = "\0".join((document_id_sha256, policy_id, parser_signature, outcome, attempt_id))+ attempt_key_sha256 = hashlib.sha256(key_material.encode()).hexdigest()+ path = Path(kb_dir) / ATTEMPT_LEDGER_DIRNAME / f"{attempt_key_sha256}.json"+ atomic_write_json(+ path,+ {+ **ledger,+ "document_id_sha256": document_id_sha256,+ "decision": {+ "attempt_id": attempt_id,+ "attempt_key_sha256": attempt_key_sha256,+ "ledger_role": "attempt",+ "policy_outcome": outcome,+ },+ },+ )+ return path, attempt_id+++__all__ = [+ "ATTEMPT_LEDGER_DIRNAME",+ "BlockPolicyDecision",+ "FILTERED_LAYOUT_TYPES",+ "LEDGER_DIRNAME",+ "MULTIMODAL_TYPES",+ "POLICY_ID",+ "PRESERVED_AUXILIARY_TYPES",+ "PRESERVED_SEMANTIC_TYPES",+ "PRESERVED_TYPES",+ "prepare_content_list",+ "write_attempt_ledger",+ "write_decision_ledger",+]diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex dff0c67d3..29b5660c0 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -31,8 +31,8 @@ from deeptutor.services.rag.index_versioning import ()from deeptutor.services.rag.kb_paths import resolve_kb_dir+from . import block_policy, engine, storagefrom . import config as lr_config-from . import engine, storagefrom .worker import OwnerLoopBridge, run_in_worker_looplogger = logging.getLogger(__name__)@@ -102,9 +102,48 @@ class LightRagPipeline:self.logger.warning("LightRAG: parse failed for %s: %s", path.name, exc)continue- content_list = doc.blocks or (- [{"type": "text", "text": doc.markdown, "page_idx": 0}] if doc.markdown else []- )+ 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,+ )+ 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(),+ )+ accepted_ledger = decision.ledger+ content_list = decision.content_list+ else:+ content_list = (+ [{"type": "text", "text": doc.markdown, "page_idx": 0}] if doc.markdown else []+ )if not content_list:self.logger.warning("LightRAG: empty document skipped: %s", path.name)continue@@ -119,6 +158,13 @@ class LightRagPipeline: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,+ )inserted += 1self.logger.info("LightRAG: inserted %s", path.name)if progress_callback is not None:diff --git a/tests/services/rag/test_lightrag_block_policy.py b/tests/services/rag/test_lightrag_block_policy.pynew file mode 100644index 000000000..ded9980bf--- /dev/null+++ b/tests/services/rag/test_lightrag_block_policy.py@@ -0,0 +1,216 @@+"""Tests for the MinerU content-list policy at the LightRAG boundary."""++from __future__ import annotations++from copy import deepcopy+import json+from pathlib import Path++import pytest++from deeptutor.services.rag.pipelines.lightrag import block_policy+++def test_mineru_policy_filters_layout_and_preserves_semantic_order() -> None:+ blocks = [+ {"type": "header", "text": "chapter", "page_idx": 0},+ {"type": "text", "text": "body", "page_idx": 0, "meta": {"rank": 1}},+ {"type": "aside_text", "text": "aside", "page_idx": 0},+ {"type": "image", "img_path": "images/a.png", "page_idx": 1},+ {"type": "page_footnote", "text": "note", "page_idx": 1},+ {"type": "footer", "text": "publisher", "page_idx": 1},+ {"type": "page_number", "text": "2", "page_idx": 1},+ ]+ original = deepcopy(blocks)++ decision = block_policy.prepare_content_list(+ blocks,+ engine="mineru",+ source_hash="source-hash",+ parser_signature="parser-signature",+ )++ assert [item["type"] for item in decision.content_list] == [+ "text",+ "aside_text",+ "image",+ "page_footnote",+ ]+ assert decision.ledger is not None+ assert decision.ledger["counts"] == {+ "raw_total": 7,+ "raw_by_type": {+ "aside_text": 1,+ "footer": 1,+ "header": 1,+ "image": 1,+ "page_footnote": 1,+ "page_number": 1,+ "text": 1,+ },+ "filtered_total": 3,+ "filtered_by_type": {"footer": 1, "header": 1, "page_number": 1},+ "eligible_total": 4,+ "eligible_by_type": {+ "aside_text": 1,+ "image": 1,+ "page_footnote": 1,+ "text": 1,+ },+ "eligible_multimodal_total": 3,+ "eligible_multimodal_by_type_and_page": {+ "aside_text:0": 1,+ "image:1": 1,+ "page_footnote:1": 1,+ },+ "unknown_total": 0,+ "unknown_by_type": {},+ }+ decision.content_list[0]["meta"]["rank"] = 99+ assert blocks == original+++def test_mineru_policy_indexes_unknown_types_and_never_logs_their_content() -> None:+ """An unrecognized block type is content, not chrome, and not a failure.++ A MinerU release that adds a block type must not silently drop the block+ (the user loses text they can see in the document) nor abort the ingest+ (the whole KB stops working over a layout label). It is counted so the+ policy can be extended, and the count is all the ledger may ever hold —+ document text must never reach an audit file.+ """+ blocks = [+ {"type": "future_widget", "text": "prompt-secret", "page_idx": 0},+ {"type": "Prompt secret invalid type", "text": "token-secret", "page_idx": 0},+ ]++ decision = block_policy.prepare_content_list(+ blocks,+ engine="mineru",+ source_hash="source-hash",+ parser_signature="parser-signature",+ )++ assert [item["text"] for item in decision.content_list] == [+ "prompt-secret",+ "token-secret",+ ]+ assert decision.ledger is not None+ serialized = json.dumps(decision.ledger)+ assert "prompt-secret" not in serialized+ assert "token-secret" not in serialized+ assert decision.ledger["counts"]["unknown_by_type"] == {+ "<invalid>": 1,+ "future_widget": 1,+ }+ assert decision.unknown_summary() == "<invalid>=1, future_widget=1"+++def test_mineru_v2_auxiliary_names_are_normalized_to_the_policy_vocabulary() -> None:+ """Upgrading MinerU must not turn every layout block into an unknown type.++ The newer parser emits ``page_header`` where the legacy ``content_list``+ emitted ``header``. Without normalizing, page chrome would stop being+ filtered and would instead be reported as unrecognized on every document.+ """+ blocks = [+ {"type": "page_header", "text": "chapter", "page_idx": 0},+ {"type": "text", "text": "body", "page_idx": 0},+ {"type": "page_aside_text", "text": "aside", "page_idx": 0},+ {"type": "page_footer", "text": "publisher", "page_idx": 0},+ {"type": "page_number", "text": "2", "page_idx": 0},+ {"type": "page_footnote", "text": "note", "page_idx": 0},+ ]++ decision = block_policy.prepare_content_list(+ blocks,+ engine="mineru",+ source_hash="source-hash",+ parser_signature="parser-signature",+ )++ assert [item["type"] for item in decision.content_list] == [+ "text",+ "page_aside_text",+ "page_footnote",+ ]+ assert decision.ledger is not None+ assert decision.ledger["counts"]["filtered_by_type"] == {+ "footer": 1,+ "header": 1,+ "page_number": 1,+ }+ assert decision.ledger["counts"]["unknown_by_type"] == {}+++def test_non_mineru_blocks_keep_the_existing_pipeline_contract() -> None:+ blocks = [{"type": "header", "text": "Docling heading", "page_idx": 0}]++ decision = block_policy.prepare_content_list(+ blocks,+ engine="docling",+ source_hash="source-hash",+ parser_signature="parser-signature",+ )++ assert decision.content_list is blocks+ assert decision.ledger is None+++def test_decision_ledger_uses_a_hashed_document_identifier(tmp_path: Path) -> None:+ decision = block_policy.prepare_content_list(+ [{"type": "text", "text": "body", "page_idx": 0}],+ engine="mineru",+ source_hash="source-hash",+ parser_signature="parser-signature",+ )+ assert decision.ledger is not None++ path = block_policy.write_decision_ledger(+ tmp_path,+ "private-document-name",+ decision.ledger,+ )++ assert path.parent.name == block_policy.LEDGER_DIRNAME+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert path.stem == payload["document_id_sha256"][:16]+ assert payload["decision"] == {+ "ledger_role": "current-index",+ "policy_outcome": "accepted",+ }+ assert "private-document-name" not in path.read_text(encoding="utf-8")+++def test_attempt_ledger_is_unique_and_does_not_expose_identifiers(tmp_path: Path) -> None:+ decision = block_policy.prepare_content_list(+ [{"type": "future_widget", "text": "secret", "page_idx": 0}],+ engine="mineru",+ source_hash="source-hash",+ parser_signature="private-parser-signature",+ )+ assert decision.ledger is not None++ first_path, first_id = block_policy.write_attempt_ledger(+ tmp_path,+ "private-document-name",+ decision.ledger,+ outcome="unknown_types",+ )+ second_path, second_id = block_policy.write_attempt_ledger(+ tmp_path,+ "private-document-name",+ decision.ledger,+ outcome="unknown_types",+ )++ assert first_path != second_path+ assert first_id != second_id+ assert first_path.parent.name == block_policy.ATTEMPT_LEDGER_DIRNAME+ payload = json.loads(first_path.read_text(encoding="utf-8"))+ assert first_path.stem == payload["decision"]["attempt_key_sha256"]+ assert payload["decision"]["attempt_id"] == first_id+ assert payload["decision"]["ledger_role"] == "attempt"+ assert payload["decision"]["policy_outcome"] == "unknown_types"+ assert "private-document-name" not in first_path.name+ assert "private-parser-signature" not in first_path.namediff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex efa05e3d5..33706761e 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -38,8 +38,14 @@ from deeptutor.services.rag.factory import (normalize_provider_name,)from deeptutor.services.rag.index_versioning import resolve_storage_dir_for_read-from deeptutor.services.rag.pipelines.lightrag import config as lr_config-from deeptutor.services.rag.pipelines.lightrag import engine, storage+from deeptutor.services.rag.pipelines.lightrag import (+ block_policy,+ engine,+ storage,+)+from deeptutor.services.rag.pipelines.lightrag import (+ config as lr_config,+)from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagPipelinefrom deeptutor.services.rag.pipelines.lightrag.worker import run_in_worker_loop@@ -765,7 +771,14 @@ def _stub_engine(monkeypatch, answer: str = "ANSWER") -> list[dict]:return inserts-def _stub_parse(monkeypatch, *, blocks=None, markdown: str = "# md") -> None:+def _stub_parse(+ monkeypatch,+ *,+ blocks=None,+ markdown: str = "# md",+ engine_name: str = "fake",+ parser_signature: str = "",+) -> None:from deeptutor.services.parsing.types import ParsedDocumentclass _Service:@@ -774,7 +787,8 @@ def _stub_parse(monkeypatch, *, blocks=None, markdown: str = "# md") -> None:markdown=markdown,blocks=blocks,source_hash="h_" + Path(path).stem,- engine="fake",+ parser_signature=parser_signature,+ engine=engine_name,)monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", lambda: _Service())@@ -1093,6 +1107,169 @@ def test_initialize_orchestrates_index_and_uses_blocks(tmp_path, monkeypatch) ->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++ 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+++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",+ )++ async def fail_insert(*_args, **_kwargs) -> None:+ raise RuntimeError("insert failed")++ 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"+ )+ 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)