Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix(kit): preserve batch output semantics and classify input failures
myhloli7f97abc9b2fc
diff --git a/.gitattributes b/.gitattributesindex 9ed58410..06510434 100644--- a/.gitattributes+++ b/.gitattributes@@ -2,4 +2,6 @@*.mjs linguist-vendored*.html linguist-documentation*.css linguist-vendored-*.scss linguist-vendored\ No newline at end of file+*.scss linguist-vendored+# PDF 回归样例按二进制保存,保留交叉引用表的定长字节。+tests/fixtures/kit/*.pdf binarydiff --git a/docs/next/cli/mineru-kit-parse.md b/docs/next/cli/mineru-kit-parse.mdindex 4cab2738..e6545676 100644--- a/docs/next/cli/mineru-kit-parse.md+++ b/docs/next/cli/mineru-kit-parse.md@@ -75,9 +75,9 @@ mineru-kit parse saved-page.mhtml -o saved-page.md --tier flash### 多文件输出-多文件或目录输入时,`--output` 只能是目录路径。+多文件或目录输入固定按批处理执行,`--output` 只能是目录路径;即使过滤或处理后只剩一个文档也不改变模式。已有目录按实际类型接受;不存在的路径按目录创建,`results.v1`、`results.md` 等名称均有效。-如果 `--output` 是单文件路径,应在参数校验阶段直接报错。+如果批处理的 `--output` 指向已有普通文件,应在参数校验阶段直接报错。显式单文件输入仍允许覆盖指定输出文件。多文件命名规则与单文件目录模式一致。@@ -154,3 +154,13 @@ remote 模式通过以下参数进入:local 模式的 `ocr-mode`、`disable-image-analysis` 与 `mineru-kit api-server` 一致;`mineru-kit parse --tier` 选择单次解析档位,`api-server --tier` 则选择最高开放档位并包含较低档位,或通过 auto 推荐。`--language` OCR 语言参数已从全部命令移除,传入会报错。完整决策背景见 [ADR-0016](../decisions/0016-mineru-kit-parse-command.md)。++## 批次结果与错误处理++目录候选仍按后缀进行非递归、稳定排序的发现;实际准入复用 DocVortex 内容签名和容器识别。不按 `~$` 名称过滤,合法特殊文件名正常处理。本地与远程请求执行相同的输入校验。++- 确认为不支持的内容:批处理中记录路径、原因并跳过;显式单文件报错。+- 明确的损坏、加密、资源限制、输入缺失或输入权限错误:记录失败,继续其他文件。+- 引擎失效、依赖或连接/认证故障、输出写入故障及无法分类的异常:停止后续工作,不把未知异常当成可跳过输入。++结果摘要报告成功、跳过、失败、未处理数量。至少一个成功且没有失败或全局中止时退出 `0`;有失败、中止或没有成功文档时退出 `1`。已完成产物保留。输出映射和同名冲突在执行前确定,不随最终成功数量变化。diff --git a/mineru/integrations/docvortex.py b/mineru/integrations/docvortex.pyindex 62b3ea9a..247edf05 100644--- a/mineru/integrations/docvortex.py+++ b/mineru/integrations/docvortex.py@@ -5,6 +5,8 @@ from __future__ import annotationsfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom typing import Literal+from zipfile import BadZipFile+from xml.etree.ElementTree import ParseErrorfrom docvortex.errors import DocumentErrorfrom pydantic import BaseModel, ConfigDict, JsonValue@@ -14,6 +16,24 @@ from docvortex.document.contracts import HtmlSourceContextfrom ..errors import InvalidRequestError+@contextmanager+def translate_document_errors(*, native_input: bool = False) -> Iterator[None]:+ """只映射共享引擎已确认的输入错误,不将程序错误或模型失败泛化成坏文件。"""+ from lxml.etree import XMLSyntaxError++ try:+ yield+ except DocumentError as exc:+ code = "file_corrupted" if exc.code == "open_failed" else exc.code+ if code in {"resource_limit", "file_corrupted", "file_encrypted", "file_type_unsupported", "file_too_large"}:+ raise InvalidRequestError(code, exc.message, exc.param) from exc+ raise+ except (BadZipFile, ParseError, XMLSyntaxError) as exc:+ if not native_input:+ raise+ raise InvalidRequestError("file_corrupted", str(exc), "input") from exc++@contextmanagerdef translate_resource_limit() -> Iterator[None]:"""将共享文档资源限制映射为产品输入错误,其他文档异常保留原有处理。"""@@ -76,6 +96,7 @@ def validate_mineru_metadata(document: ModelJson | MiddleJson) -> None:__all__ = ["read_source_properties","translate_resource_limit",+ "translate_document_errors","MinerUMetadata","build_metadata","with_mineru_metadata",diff --git a/mineru/kit/batch_parse.py b/mineru/kit/batch_parse.pynew file mode 100644index 00000000..76cea08f--- /dev/null+++ b/mineru/kit/batch_parse.py@@ -0,0 +1,79 @@+"""Kit 的输入边界和批次错误策略;不依赖文件名推断 Office 锁文件。"""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+import stat+from typing import Literal++from ..errors import InvalidRequestError, MineruError+from ..filetypes import PARSEABLE_EXTENSIONS+from ..integrations.docvortex import translate_document_errors+from ..model.vlm.errors import is_fatal_engine_error+from ..parser.api_client import _V1APIError+from ..parser.file_type import guess_suffix_by_path+from ..types import FILE_SUFFIXES+from ..utils.i18n import t++_INPUT_FAILURE_CODES = frozenset(+ {"file_corrupted", "file_encrypted", "file_too_large", "resource_limit", "file_not_found", "file_permission_denied"}+)+++@dataclass+class BatchParseSummary:+ """记录真实的逐项处理结果,终止时保留尚未处理的数量。"""++ succeeded: int = 0+ skipped: int = 0+ failed: int = 0+ aborted: bool = False++ def message(self, total: int) -> str:+ """以统一摘要替代可能掩盖失败的全部成功提示。"""+ return t(+ "Batch finished: succeeded={succeeded}, skipped={skipped}, failed={failed}, unprocessed={unprocessed}.",+ succeeded=self.succeeded,+ skipped=self.skipped,+ failed=self.failed,+ unprocessed=total - self.succeeded - self.skipped - self.failed,+ )++ @property+ def exit_code(self) -> int:+ """只有至少一个成功且无失败、无系统性中止的批次才成功退出。"""+ return int(self.succeeded == 0 or self.failed > 0 or self.aborted)+++def validate_parse_input(path: Path) -> None:+ """本地与远程分流前验证内容类型,名称只用于候选发现和无签名格式提示。"""+ try:+ if not stat.S_ISREG(path.stat().st_mode):+ raise InvalidRequestError("file_type_unsupported", t("Unsupported file type: {path}", path=path), "input")+ if path.suffix.lower().lstrip(".") not in PARSEABLE_EXTENSIONS:+ raise InvalidRequestError("file_type_unsupported", t("Unsupported file type: {path}", path=path), "input")+ with translate_document_errors(native_input=True):+ suffix = guess_suffix_by_path(path)+ if suffix not in FILE_SUFFIXES and suffix not in PARSEABLE_EXTENSIONS:+ raise InvalidRequestError("file_type_unsupported", t("Unsupported file type: {path}", path=path), "input")+ except FileNotFoundError as exc:+ raise InvalidRequestError("file_not_found", str(exc), "input") from exc+ except PermissionError as exc:+ raise InvalidRequestError("file_permission_denied", str(exc), "input") from exc+++def classify_parse_error(error: Exception) -> tuple[Literal["skipped", "failed", "abort"], str, str]:+ """只隔离明确的输入错误;未知异常、引擎和远程服务故障一律终止批次。"""+ if is_fatal_engine_error(error):+ return "abort", "engine_dead", str(error)+ if isinstance(error, (MineruError, _V1APIError)):+ if error.code == "file_type_unsupported":+ return "skipped", error.code, error.message+ if error.code in _INPUT_FAILURE_CODES:+ return "failed", error.code, error.message+ return "abort", error.code, error.message+ return "abort", "parse_failed", str(error)+++__all__ = ["BatchParseSummary", "classify_parse_error", "validate_parse_input"]diff --git a/mineru/kit/commands/parse.py b/mineru/kit/commands/parse.pyindex 87b0ae78..d0e638e0 100644--- a/mineru/kit/commands/parse.py+++ b/mineru/kit/commands/parse.py@@ -2,6 +2,7 @@ from __future__ import annotationsfrom functools import partialfrom pathlib import Path+from tempfile import TemporaryFilefrom typing import Literal, castimport typer@@ -10,20 +11,21 @@ from ...errors import MineruErrorfrom ...filetypes import ensure_tier_supported_for_parse_extension, is_flash_only_parse_extensionfrom ...parser import MinerUApiParserfrom ...parser import parse as local_parse-from ...parser.api_client import _V1APIError+from ...parser.base import ParseResultfrom ...parser.page_range import normalize_page_range_inputfrom ...types import Tier, validate_tierfrom ...utils.i18n import t+from ..batch_parse import BatchParseSummary, classify_parse_error, validate_parse_inputfrom ..common import (build_remote_api_url,- ensure_supported_inputs,+ OUTPUT_FILE_SUFFIXES,expand_input_paths,parse_result_payload,resolve_batch_output_paths,save_parse_result,)from ..errors import exit_with_message-from ..output import print_info, print_success+from ..output import print_error, print_info, print_successdef parse_cmd(@@ -52,32 +54,32 @@ def parse_cmd("""Parse files or directories into markdown, middle JSON, or zip outputs."""try:pages = normalize_page_range_input(pages)- except MineruError as exc:- exit_with_message(exc.code, str(exc), "pages")+ if tier is not None:+ validate_tier(tier)+ if ocr_mode not in {"auto", "txt", "ocr"}:+ raise ValueError(t("Unsupported OCR mode: {mode}", mode=ocr_mode))+ if format not in OUTPUT_FILE_SUFFIXES:+ raise ValueError(t("Unsupported format: {format}", format=format))+ api_url = build_remote_api_url(remote, remote_url)+ except (MineruError, ValueError) as exc:+ exit_with_message("invalid_request", str(exc))output_format = cast(Literal["markdown", "middle_json", "zip"], format)parse_tier = cast(Tier | None, tier)parse_ocr_mode = cast(Literal["auto", "txt", "ocr"], ocr_mode)if not inputs:exit_with_message("invalid_request", t("At least one input path is required."), "inputs")- api_url = build_remote_api_url(remote, remote_url)raw_paths = [Path(raw).expanduser() for raw in inputs]- if any(path.is_dir() for path in raw_paths) and Path(output).expanduser().suffix:- exit_with_message(- "invalid_request",- t("When input is multiple files or directories, --output must be a directory path."),- "output",- )- has_directory_input = any(path.is_dir() for path in raw_paths)- if len(raw_paths) > 1 and Path(output).expanduser().suffix:- exit_with_message(- "invalid_request",- t("When input is multiple files or directories, --output must be a directory path."),- "output",- )- paths = expand_input_paths(inputs)+ is_batch = any(path.is_dir() for path in raw_paths) or len(raw_paths) > 1try:- ensure_supported_inputs(paths)- destinations = resolve_batch_output_paths(paths, Path(output).expanduser(), output_format)+ paths = expand_input_paths(inputs)+ if not paths:+ raise ValueError(t("No input files found."))+ destinations = resolve_batch_output_paths(paths, Path(output).expanduser(), output_format, batch=is_batch)+ # 在模型加载或远程请求前验证输出根可写;不截断已有结果文件。+ output_parent = next(iter(destinations.values())).parent+ output_parent.mkdir(parents=True, exist_ok=True)+ with TemporaryFile(prefix=".mineru-write-", dir=output_parent):+ passexcept Exception as exc:exit_with_message("invalid_request", str(exc))@@ -87,9 +89,9 @@ def parse_cmd()parse_one = partial(parser.parse, page_range=pages or "")else:- is_batch = has_directory_input or len(paths) > 1- def parse_one(path: Path) -> object:+ def parse_one(path: Path) -> ParseResult:+ """保持单文件显式 tier 校验,批量原生格式始终使用 Flash。"""path_tier: Tier = validate_tier(parse_tier) if parse_tier is not None else "standard"if is_flash_only_parse_extension(path):if not is_batch and parse_tier is not None:@@ -103,15 +105,43 @@ def parse_cmd(page_range=pages or "",)+ summary = BatchParseSummary()for path in paths:try:+ if not is_batch and not api_url and parse_tier is not None and is_flash_only_parse_extension(path):+ ensure_tier_supported_for_parse_extension(parse_tier, path)+ validate_parse_input(path)result = parse_one(path)- dest = destinations[path]+ except Exception as exc:+ disposition, code, message = classify_parse_error(exc)+ if not is_batch:+ exit_with_message(code, t("Failed to parse {path}: {error}", path=path, error=message))+ if disposition == "skipped":+ summary.skipped += 1+ print_info(t("Skipped {path}: [{code}] {error}", path=path, code=code, error=message))+ else:+ summary.failed += 1+ print_error(t("Failed to parse {path}: {error}", path=path, error=f"[{code}] {message}"))+ if disposition == "abort":+ summary.aborted = True+ break+ continue+ dest = destinations[path]+ try:save_parse_result(result, dest, output_format)- if verbose:- print_info(str(parse_result_payload(path, dest, output_format)))- except (MineruError, _V1APIError) as exc:- exit_with_message(exc.code, str(exc), exc.param)except Exception as exc:- exit_with_message("parse_failed", t("Failed to parse {path}: {error}", path=path, error=exc))- print_success(t("Parsed {count} input(s).", count=len(paths)))+ if not is_batch:+ exit_with_message("result_packaging_failed", str(exc), "output")+ summary.failed += 1+ summary.aborted = True+ print_error(t("Failed to write {path}: {error}", path=dest, error=exc))+ break+ summary.succeeded += 1+ if verbose:+ print_info(str(parse_result_payload(path, dest, output_format)))+ if is_batch:+ print_info(summary.message(len(paths)))+ if summary.exit_code:+ raise typer.Exit(summary.exit_code)+ else:+ print_success(t("Parsed {count} input(s).", count=summary.succeeded))diff --git a/mineru/kit/common.py b/mineru/kit/common.pyindex 2d1930da..3eec02f7 100644--- a/mineru/kit/common.py+++ b/mineru/kit/common.py@@ -3,10 +3,12 @@from __future__ import annotationsimport zipfile+import statfrom pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import Literal, TypeAlias+from ..errors import InvalidRequestErrorfrom ..filetypes import PARSEABLE_EXTENSIONSfrom ..parser.base import ParseResultfrom ..parser.writer import FileBasedDataWriter@@ -31,31 +33,21 @@ def expand_input_paths(inputs: list[str]) -> list[Path]:for path in paths:if path.is_dir():for child in sorted(path.iterdir()):- if child.is_file() and child.suffix.lower() in PARSEABLE_SUFFIXES:+ if child.suffix.lower() not in PARSEABLE_SUFFIXES:+ continue+ try:+ is_file = stat.S_ISREG(child.stat().st_mode)+ except (FileNotFoundError, PermissionError):+ # 保留发现后消失或无法读取的候选,交给逐项校验报告,不能静默遗漏。+ expanded.append(child)+ continue+ if is_file:expanded.append(child)else:expanded.append(path)return expanded-def ensure_supported_inputs(paths: list[Path]) -> None:- if not paths:- raise ValueError(t("No input files found."))- for path in paths:- if not path.exists():- raise FileNotFoundError(path)- if path.is_dir():- raise ValueError(t("Directory input must be expanded before validation: {path}", path=path))- if path.suffix.lower() not in PARSEABLE_SUFFIXES:- raise ValueError(t("Unsupported file type: {path}", path=path))---def is_output_path_file_like(path: Path) -> bool:- if path.exists():- return path.is_file()- return path.suffix.lower() in OUTPUT_FILE_SUFFIXES.values()--def resolve_single_output_path(source: Path, output: Path, format: KitFormat) -> Path:if output.exists() and output.is_dir():return output / f"{source.stem}{OUTPUT_FILE_SUFFIXES[format]}"@@ -64,23 +56,28 @@ def resolve_single_output_path(source: Path, output: Path, format: KitFormat) ->return output-def resolve_batch_output_paths(paths: list[Path], output: Path, format: KitFormat) -> dict[Path, Path]:+def resolve_batch_output_paths(paths: list[Path], output: Path, format: KitFormat, *, batch: bool) -> dict[Path, Path]:+ """按原始输入模式统一验证和映射输出;批量目录名称不受后缀限制。"""+ if format not in OUTPUT_FILE_SUFFIXES:+ raise InvalidRequestError("unsupported_output_format", t("Unsupported format: {format}", format=format), "format")if any(path.parent == path for path in paths):raise ValueError(t("Invalid input path."))- if len(paths) > 1 and is_output_path_file_like(output):+ if batch and output.exists() and not output.is_dir():raise ValueError(t("When input is multiple files or directories, --output must be a directory path."))destinations: dict[Path, Path] = {}seen: dict[Path, Path] = {}+ sources = {source.resolve() for source in paths}for source in paths:dest = (resolve_single_output_path(source, output, format)- if len(paths) == 1+ if not batchelse output / f"{source.stem}{OUTPUT_FILE_SUFFIXES[format]}")- if dest.resolve() == source.resolve():+ resolved_dest = dest.resolve()+ if resolved_dest in sources:raise ValueError(t("Output path must not be the same as the input file: {path}", path=source))- existing = seen.get(dest)+ existing = seen.get(resolved_dest)if existing is not None:raise ValueError(t(@@ -90,7 +87,7 @@ def resolve_batch_output_paths(paths: list[Path], output: Path, format: KitFormadest=dest,))- seen[dest] = source+ seen[resolved_dest] = sourcedestinations[source] = destreturn destinationsdiff --git a/mineru/parser/mineru_parser.py b/mineru/parser/mineru_parser.pyindex d5efff24..4e253973 100644--- a/mineru/parser/mineru_parser.py+++ b/mineru/parser/mineru_parser.py@@ -16,7 +16,7 @@ from ..backend.analyze import aio_doc_analyze, doc_analyzefrom ..config import VlmConfig, get_configfrom ..errors import InvalidRequestErrorfrom ..filetypes import IMAGE_EXTENSIONS, PAGE_RANGE_PARSE_EXTENSIONS-from ..integrations.docvortex import read_source_properties, translate_resource_limit+from ..integrations.docvortex import read_source_properties, translate_document_errorsfrom ..utils.async_utils import run_syncfrom ..utils.logger import configure_global_log_levelfrom ..types import FILE_SUFFIXES, FileSuffix, MiddleJson, ModelJson, PageInfo, Tier@@ -77,8 +77,9 @@ class MinerUParser(DocumentParser):if not path.exists():raise FileNotFoundError(path)- with translate_resource_limit():+ with translate_document_errors(native_input=True):prepared = self._prepare_input(path, page_range, source_context)+ with translate_document_errors(native_input=prepared.file_suffix != "pdf"):middle_json, _ = self._run_analysis(prepared)if prepared.file_suffix == "pdf":self._insert_broken_pages(@@ -101,8 +102,9 @@ class MinerUParser(DocumentParser):if not path.exists():raise FileNotFoundError(path)- with translate_resource_limit():+ with translate_document_errors(native_input=True):prepared = await run_sync(self._prepare_input, path, page_range, source_context)+ with translate_document_errors(native_input=prepared.file_suffix != "pdf"):middle_json, _ = await self._arun_analysis(prepared)if prepared.file_suffix == "pdf":self._insert_broken_pages(@@ -153,8 +155,13 @@ class MinerUParser(DocumentParser):page_range = normalize_page_range_input(page_range)file_name = path.stem- file_bytes = path.read_bytes()- suffix = guess_suffix_by_path(path)+ try:+ file_bytes = path.read_bytes()+ suffix = guess_suffix_by_path(path)+ except FileNotFoundError as exc:+ raise InvalidRequestError("file_not_found", str(exc), "input") from exc+ except PermissionError as exc:+ raise InvalidRequestError("file_permission_denied", str(exc), "input") from excsource_suffix = suffixif suffix in IMAGE_EXTENSIONS:@@ -180,7 +187,9 @@ class MinerUParser(DocumentParser):suffix = "pdf"if suffix not in FILE_SUFFIXES:- raise ValueError(f"Unsupported file type: {suffix or path.suffix or 'unknown'}")+ raise InvalidRequestError(+ "file_type_unsupported", f"Unsupported file type: {suffix or path.suffix or 'unknown'}", "input"+ )if source_suffix not in PAGE_RANGE_PARSE_EXTENSIONS and page_range.strip():raise InvalidRequestError("page_range_invalid",@@ -227,11 +236,21 @@ class MinerUParser(DocumentParser):return file_bytes, None, Nonefrom docvortex.document.pdf import PDFDocument+ from pypdfium2 import PdfiumError+ from pypdfium2 import raw as pdfium_rawfrom .page_range import parse_page_range- with PDFDocument(file_bytes) as doc:- page_count = doc.page_count+ try:+ with PDFDocument(file_bytes) as doc:+ page_count = doc.page_count+ except PdfiumError as exc:+ # 只在打开输入文档的边界解释 PDFium 错误码,不掩盖后续算法或引擎错误。+ if exc.err_code == pdfium_raw.FPDF_ERR_PASSWORD:+ raise InvalidRequestError("file_encrypted", str(exc), "input") from exc+ if exc.err_code == pdfium_raw.FPDF_ERR_FORMAT:+ raise InvalidRequestError("file_corrupted", str(exc), "input") from exc+ raisepage_indices = parse_page_range(page_range, page_count)if page_indices == list(range(page_count)):diff --git a/mineru/utils/translations.py b/mineru/utils/translations.pyindex c4f49586..cd3dcd66 100644--- a/mineru/utils/translations.py+++ b/mineru/utils/translations.py@@ -12,6 +12,12 @@ ZH_MESSAGES: dict[str, str] = {# ------------------------------------------------------------------ 共享"JSON output": "JSON 输出","Verbose output": "详细输出",+ "Batch finished: succeeded={succeeded}, skipped={skipped}, failed={failed}, unprocessed={unprocessed}.": (+ "批次完成:成功={succeeded},跳过={skipped},失败={failed},未处理={unprocessed}。"+ ),+ "Skipped {path}: [{code}] {error}": "已跳过 {path}:[{code}] {error}",+ "Failed to write {path}: {error}": "写入 {path} 失败:{error}",+ "Unsupported OCR mode: {mode}": "不支持的 OCR 模式:{mode}","Max rows": "最大行数","Result offset": "结果偏移量","yes": "是",diff --git a/tests/fixtures/kit/encrypted.pdf b/tests/fixtures/kit/encrypted.pdfnew file mode 100644index 00000000..3815023c--- /dev/null+++ b/tests/fixtures/kit/encrypted.pdf@@ -0,0 +1,59 @@+%PDF-1.3+%����+1 0 obj+<<+/Producer <3a8e66c4fc>+>>+endobj+2 0 obj+<<+/Type /Pages+/Count 1+/Kids [ 4 0 R ]+>>+endobj+3 0 obj+<<+/Type /Catalog+/Pages 2 0 R+>>+endobj+4 0 obj+<<+/Type /Page+/Resources <<+>>+/MediaBox [ 0.0 0.0 100 100 ]+/Parent 2 0 R+>>+endobj+5 0 obj+<<+/V 2+/R 3+/Length 128+/P 4294967292+/Filter /Standard+/O <f07a125f587c023f699b1eddfd1f2f0b5ec37995858d27d5d3ae291eb6bb7c9e>+/U <3181cb0612f8b8c675447f496832b2b828bf4e5e4e758a4164004e56fffa0108>+>>+endobj+xref+0 6+0000000000 65535 f+0000000015 00000 n+0000000059 00000 n+0000000118 00000 n+0000000167 00000 n+0000000261 00000 n+trailer+<<+/Size 6+/Root 3 0 R+/Info 1 0 R+/ID [ <3039353331666338613730316337306237633732333030363835363236386463> <3039353331666338613730316337306237633732333030363835363236386463> ]+/Encrypt 5 0 R+>>+startxref+476+%%EOFdiff --git a/tests/unittest/test_document_resource_limits.py b/tests/unittest/test_document_resource_limits.pyindex d098e4fc..dd3d8259 100644--- a/tests/unittest/test_document_resource_limits.py+++ b/tests/unittest/test_document_resource_limits.py@@ -18,7 +18,7 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom mineru.errors import InvalidRequestError, error_type_for, http_status_for-from mineru.integrations.docvortex import read_source_properties+from mineru.integrations.docvortex import read_source_properties, translate_document_errorsfrom mineru.parser import MinerUParser, mineru_parserimport test_task_api@@ -91,12 +91,35 @@ def test_metadata_other_document_errors_stay_optional(monkeypatch: pytest.Monkeyassert read_source_properties(test_task_api.HTML, "html") == DocumentProperties()-def test_parser_preserves_other_document_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """新增转换只接管资源限制,其他共享异常的身份保持原样。"""+def test_parser_preserves_recognized_document_error_code(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """明确输入错误转换为产品异常,保留代码、消息与原始异常链。"""source = tmp_path / "document.html"source.write_bytes(test_task_api.HTML)shared_error = DocumentError("file_corrupted", "Document is malformed")_reject_stage(monkeypatch, "analysis", shared_error)+ with pytest.raises(InvalidRequestError) as raised:+ MinerUParser(tier="flash").parse(source)+ assert raised.value.code == "file_corrupted"+ assert raised.value.__cause__ is shared_error+++def test_xml_failure_outside_native_input_is_not_reclassified() -> None:+ """同类底层异常若发生在模型阶段,不得归入可跳过的输入错误。"""+ from lxml.etree import XMLSyntaxError++ original = XMLSyntaxError("model configuration", 201, 1, 1)+ with pytest.raises(XMLSyntaxError) as raised:+ with translate_document_errors():+ raise original+ assert raised.value is original+++def test_parser_does_not_reclassify_unknown_document_errors(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """未约定的共享错误不能被猜测为可跳过的单文档失败。"""+ source = tmp_path / "document.html"+ source.write_bytes(test_task_api.HTML)+ shared_error = DocumentError("unknown_runtime_contract", "Unexpected state")+ _reject_stage(monkeypatch, "analysis", shared_error)with pytest.raises(DocumentError) as raised:MinerUParser(tier="flash").parse(source)assert raised.value is shared_errordiff --git a/tests/unittest/test_filetypes.py b/tests/unittest/test_filetypes.pyindex 16563bfd..1a164dee 100644--- a/tests/unittest/test_filetypes.py+++ b/tests/unittest/test_filetypes.py@@ -27,7 +27,7 @@ from mineru.filetypes import (normalize_parse_extension,validate_parse_filename,)-from mineru.kit.common import ensure_supported_inputs, expand_input_paths+from mineru.kit.common import expand_input_pathsfrom mineru.parser import parse@@ -244,4 +244,3 @@ def test_mineru_kit_discovers_and_accepts_csv_inputs(tmp_path: Path) -> None:expanded = expand_input_paths([str(tmp_path)])assert expanded == [csv_path]- ensure_supported_inputs(expanded)diff --git a/tests/unittest/test_kit_batch_contract.py b/tests/unittest/test_kit_batch_contract.pynew file mode 100644index 00000000..9bbf808a--- /dev/null+++ b/tests/unittest/test_kit_batch_contract.py@@ -0,0 +1,256 @@+"""以真实原生文档验证批量输出、逐项失败和全局终止的边界。"""++from __future__ import annotations++import errno+from pathlib import Path+from shutil import copyfile+from typing import Any+from zipfile import ZipFile, ZIP_DEFLATED++import pytest+from typer.testing import CliRunner++from mineru.errors import InvalidRequestError+from mineru.kit.batch_parse import validate_parse_input+from mineru.kit.commands import parse+from mineru.kit.common import OUTPUT_FILE_SUFFIXES, resolve_batch_output_paths+from mineru.kit.main import app+from mineru.parser import parse as local_parse+from mineru.parser.api_client import _V1APIError+++def _csv(path: Path) -> Path:+ """生成无需模型或网络即可解析的真实 CSV。"""+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(f"name,value\n{path.stem},1\n", encoding="utf-8")+ return path+++def _invoke(inputs: list[Path], output: Path, *args: str) -> Any:+ """通过公开 Kit CLI 执行同一组输入。"""+ return CliRunner().invoke(app, ["parse", *map(str, inputs), "-o", str(output), "--tier", "flash", *args])++[email protected]("output_format", ["markdown", "middle_json", "zip"])[email protected]("existing", [False, True])[email protected]("name", ["results.v1", "results.md"])+def test_batch_accepts_new_and_existing_dotted_directories(+ tmp_path: Path, output_format: str, existing: bool, name: str+) -> None:+ """只有一个文档的目录也固定使用目录输出,名称和格式相互独立。"""+ source = _csv(tmp_path / "docs" / "one.csv")+ output = tmp_path / name+ if existing:+ output.mkdir()+ (output / "keep.txt").write_text("keep")+ result = _invoke([source.parent], output, "-f", output_format)+ assert result.exit_code == 0, result.output+ assert (output / f"one{OUTPUT_FILE_SUFFIXES[output_format]}").is_file()+ if existing:+ assert (output / "keep.txt").read_text() == "keep"+ assert "succeeded=1" in result.output++[email protected]("name", ["result", "result.md"])+def test_directory_never_overwrites_regular_output_file(tmp_path: Path, name: str) -> None:+ """目录只剩一个输入也不能套用单文件覆盖规则。"""+ source = _csv(tmp_path / "docs" / "one.csv")+ output = tmp_path / name+ output.write_text("keep")+ result = _invoke([source.parent], output)+ assert result.exit_code == 1+ assert output.read_text() == "keep"+ assert "directory path" in " ".join(result.output.split())+ single = _invoke([source], output)+ assert single.exit_code == 0, single.output+ assert "one" in output.read_text()+++def test_directory_uses_content_not_office_owner_filename(tmp_path: Path) -> None:+ """合法特殊名称保留,任何命名的非文档均由内容识别跳过。"""+ source = tmp_path / "docs"+ source.mkdir()+ fixture = Path(__file__).parents[1] / "fixtures/pr5389/table-links.docx"+ copyfile(fixture, source / "~$real.docx")+ (source / "~$owner.docx").write_bytes(b"owner lock metadata")+ (source / "normal-name.docx").write_bytes(b"owner lock metadata")+ _csv(source / "last.csv")+ output = tmp_path / "out"+ result = _invoke([source], output)+ assert result.exit_code == 0, result.output+ assert sorted(p.name for p in output.iterdir()) == ["last.md", "~$real.md"]+ assert "https://example.org/one" in (output / "~$real.md").read_text()+ assert "succeeded=2, skipped=2, failed=0" in " ".join(result.output.split())+ assert (source / "~$owner.docx").exists()+++def test_corrupt_document_does_not_prevent_later_success(tmp_path: Path) -> None:+ """可识别但损坏的 PDF 记录失败,后续 CSV 仍生成真实产物。"""+ source = _csv(tmp_path / "docs" / "b.csv")+ (source.parent / "a.pdf").write_bytes(b"%PDF-1.7\ntruncated")+ output = tmp_path / "out"+ result = _invoke([source.parent], output)+ assert result.exit_code == 1, result.output+ assert (output / "b.md").exists()+ assert "file_corrupted" in result.output+ assert "succeeded=1, skipped=0, failed=1, unprocessed=0" in " ".join(result.output.split())+++def test_encrypted_pdf_is_a_reported_input_failure(tmp_path: Path) -> None:+ """真实密码保护 PDF 记录为加密输入,后续原生文档继续处理。"""+ source = _csv(tmp_path / "docs" / "b.csv")+ copyfile(Path(__file__).parents[1] / "fixtures/kit/encrypted.pdf", source.parent / "a.pdf")+ result = _invoke([source.parent], tmp_path / "out")+ assert result.exit_code == 1, result.output+ assert "file_encrypted" in result.output+ assert (tmp_path / "out" / "b.md").exists()+++def test_malformed_office_xml_is_reported_and_later_document_runs(tmp_path: Path) -> None:+ """真实 DOCX 容器中的损坏正文 XML 属于输入失败,不阻断后续文件。"""+ source = _csv(tmp_path / "docs" / "b.csv")+ fixture = Path(__file__).parents[1] / "fixtures/pr5389/table-links.docx"+ with ZipFile(fixture) as original, ZipFile(source.parent / "a.docx", "w", ZIP_DEFLATED) as broken:+ for item in original.infolist():+ body = b"<w:document" if item.filename == "word/document.xml" else original.read(item.filename)+ broken.writestr(item, body)+ result = _invoke([source.parent], tmp_path / "out")+ assert result.exit_code == 1, result.output+ assert "file_corrupted" in result.output+ assert (tmp_path / "out" / "b.md").exists()+++def test_missing_explicit_batch_input_is_reported_and_remaining_input_runs(tmp_path: Path) -> None:+ """多文件模式隔离单项不存在错误,保留成功文件并非零退出。"""+ source = _csv(tmp_path / "good.csv")+ result = _invoke([tmp_path / "missing.csv", source], tmp_path / "out")+ assert result.exit_code == 1+ assert (tmp_path / "out" / "good.md").exists()+ assert "file_not_found" in result.output+++def test_stat_permission_error_is_not_reported_as_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """路径属性查询也保留权限错误,避免 Path.is_file 吞掉异常后误报不存在。"""+ source = _csv(tmp_path / "secret.csv")+ original = Path.stat++ def denied(path: Path, **kwargs: Any) -> Any:+ """只拒绝该输入的属性读取,其他文件系统调用仍使用真实实现。"""+ if path == source:+ raise PermissionError(errno.EACCES, "denied", str(path))+ return original(path, **kwargs)++ monkeypatch.setattr(Path, "stat", denied)+ with pytest.raises(InvalidRequestError) as raised:+ validate_parse_input(source)+ assert raised.value.code == "file_permission_denied"+++ "code,remaining", [("file_encrypted", True), ("engine_dead", False), ("invalid_api_key", False), ("parse_failed", False)]+)+def test_remote_preserves_error_codes_and_batch_policy(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, code: str, remaining: bool+) -> None:+ """远程只隔离明确输入错误;通用失败不能被猜测为损坏文档。"""+ first = _csv(tmp_path / "a.csv")+ last = _csv(tmp_path / "b.csv")+ calls: list[str] = []++ class Parser:+ def __init__(self, **kwargs: Any) -> None:+ """替换远程传输,保留相同的公开错误契约。"""++ def parse(self, path: Path, *, page_range: str) -> Any:+ """先返回指定错误,后续文件通过真实原生解析生成产物。"""+ calls.append(path.name)+ if path == first:+ raise _V1APIError(code, "detail", "input")+ return local_parse(path, tier="flash")++ monkeypatch.setattr(parse, "MinerUApiParser", Parser)+ result = _invoke([first, last], tmp_path / "out", "--remote-url", "https://example.invalid")+ assert result.exit_code == 1+ assert code in result.output+ assert calls == (["a.csv", "b.csv"] if remaining else ["a.csv"])+ assert (tmp_path / "out" / "b.md").exists() is remaining+++def test_remote_does_not_upload_recognized_non_document(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """远程分流之前进行相同的内容识别,避免为非文档创建服务任务。"""+ source = tmp_path / "owner.docx"+ source.write_bytes(b"not a document")++ class Parser:+ def __init__(self, **kwargs: Any) -> None:+ """允许构造轻量客户端,但禁止请求上传。"""++ def parse(self, path: Path, *, page_range: str) -> Any:+ """已确认的非文档不应到达远程解析器。"""+ pytest.fail("must not upload")++ monkeypatch.setattr(parse, "MinerUApiParser", Parser)+ result = _invoke([source], tmp_path / "out.md", "--remote-url", "https://example.invalid")+ assert result.exit_code == 1+ assert "Unsupported file type" in result.output+ assert not (tmp_path / "out.md").exists()++[email protected]("failure", [ValueError("program contract"), RuntimeError("unknown engine error")])+def test_unknown_failures_abort_instead_of_silently_skipping(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure: Exception+) -> None:+ """程序错误和未知引擎故障不属于可隔离的单文件错误。"""+ sources = [_csv(tmp_path / name) for name in ["a.csv", "b.csv"]]+ calls: list[Path] = []++ def fail(path: Path, **kwargs: Any) -> Any:+ """第一项触发未知故障,后续任务不得开始。"""+ calls.append(path)+ raise failure++ monkeypatch.setattr(parse, "local_parse", fail)+ result = _invoke(sources, tmp_path / "out")+ assert result.exit_code == 1+ assert calls == sources[:1]+ assert "unprocessed=1" in result.output+++def test_write_failure_stops_batch_and_preserves_prior_output(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """磁盘故障终止后续写入,保留已经完成的文档输出。"""+ sources = [_csv(tmp_path / name) for name in ["a.csv", "b.csv", "c.csv"]]+ save = parse.save_parse_result++ def save_or_fail(result: Any, dest: Path, format: str) -> None:+ """第二次写入模拟磁盘空间不足。"""+ if dest.stem == "b":+ raise OSError(errno.ENOSPC, "no space")+ save(result, dest, format)++ monkeypatch.setattr(parse, "save_parse_result", save_or_fail)+ result = _invoke(sources, tmp_path / "out")+ assert result.exit_code == 1+ assert sorted(p.name for p in (tmp_path / "out").iterdir()) == ["a.md"]+ assert "succeeded=1, skipped=0, failed=1, unprocessed=1" in " ".join(result.output.split())+++def test_all_skipped_is_not_reported_as_success(tmp_path: Path) -> None:+ """空结果批次即使只有跳过项也必须非零退出。"""+ source = tmp_path / "docs"+ source.mkdir()+ (source / "owner.docx").write_bytes(b"lock")+ result = _invoke([source], tmp_path / "out")+ assert result.exit_code == 1+ assert "succeeded=0, skipped=1" in result.output+++def test_output_planning_rejects_collision_before_creating_outputs(tmp_path: Path) -> None:+ """目标映射冲突在执行之前拒绝,且不能写回任何源文件。"""+ first = _csv(tmp_path / "one" / "a.csv")+ second = _csv(tmp_path / "two" / "a.csv")+ result = _invoke([first, second], tmp_path / "out")+ assert result.exit_code == 1+ assert not (tmp_path / "out").exists()+ with pytest.raises(ValueError, match="same as the input"):+ resolve_batch_output_paths([first], first, "markdown", batch=False)diff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 1548c8a8..6b5f27f7 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -932,9 +932,11 @@ def test_router_reload_uses_environment_factory(monkeypatch: pytest.MonkeyPatch)def test_parse_rejects_file_output_for_directory_input(tmp_path: Path) -> None:+ """目录输入拒绝实际存在的普通文件,不能由路径名称判断类型。"""source_dir = tmp_path / "docs"source_dir.mkdir()(source_dir / "a.pdf").write_bytes(b"%PDF-1.7\n")+ (tmp_path / "out.md").write_text("keep", encoding="utf-8")result = runner.invoke(app, ["parse", str(source_dir), "-o", str(tmp_path / "out.md")])