Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

Add parse failed error envelope

jinzhenj0f61c1ff1283
diff --git a/docs/next/cli/mineru-parse.md b/docs/next/cli/mineru-parse.md
index 5c9c7a85..7695caa4 100644
--- a/docs/next/cli/mineru-parse.md
+++ b/docs/next/cli/mineru-parse.md
@@ -58,7 +58,7 @@ mineru parse <file> [flags]
|------|------|------|------|
| `-o, --output` | path | `-` | 输出路径;`-` 或省略表示 STDOUT |
| `-f, --format` | markdown | markdown | 输出格式。当前仅支持 `markdown`。 |
-| `--json` | bool | false | 输出命令级 JSON;顶层固定为 `{ "parse": ..., "content": ... }` |
+| `--json` | bool | false | 输出命令级 JSON;顶层包含 `{ "parse": ..., "content": ... }`,失败或超时时可包含 `error` |
| `--no-marker` | bool | false | 不输出结构 marker |
### 同步控制
@@ -116,12 +116,13 @@ marker 是 Agent 的控制协议,不应依赖自然语言猜测。
默认输出到 STDOUT,便于 Agent 直接消费。指定 `--output` 时写入文件。
-`--json` 时,`mineru parse` 的顶层返回固定为命令级 envelope:
+`--json` 时,`mineru parse` 的顶层返回命令级 envelope:
```json
{
"parse": { "... parse summary ..." },
- "content": { "... DocContentResponse ..." } | null
+ "content": { "... DocContentResponse ..." } | null,
+ "error": { "... ErrorInfo ..." } | null
}
```
@@ -129,7 +130,9 @@ marker 是 Agent 的控制协议,不应依赖自然语言猜测。
- 当解析结果已可读取时,`content` 为 `DocContentResponse`。
- 当使用 `--no-wait` 或等待超时、解析尚未完成时,`content` 为 `null`。
-- 错误仍返回 [错误码体系](../errors.md) 定义的结构化错误 JSON。
+- 当命令需要保留 parse 状态供调用方继续轮询或诊断时,失败或等待超时可以在同一 envelope 顶层包含 `error`。
+- `parse.status=parsing` 是 CLI 等待超时时的命令级状态;服务端 `ParseResponse.status` 只使用 `pending` 或 `done`。
+- 直接请求错误仍返回 [错误码体系](../errors.md) 定义的结构化错误 JSON。
结构化或可机器消费格式应尽量保持稳定:
diff --git a/docs/next/decisions/0015-cli-output-json-composition.md b/docs/next/decisions/0015-cli-output-json-composition.md
index f93ce23a..d0ce0527 100644
--- a/docs/next/decisions/0015-cli-output-json-composition.md
+++ b/docs/next/decisions/0015-cli-output-json-composition.md
@@ -78,6 +78,7 @@ mineru read <locator> --output out.md --json
- `parse`: 使用 `mineru parse --json` 已定义的稳定解析摘要结构。
- `content`: 当 `--output` 成功写出文件时可以为 `null`;CLI 不要求在写文件成功的同时再把全文内容重复放回 stdout JSON。
- `output`: 顶层对象,至少包含 `status` 和 `path` 两个字段。
+- `error`: 当命令需要同时返回 parse 状态和结构化失败原因时,可以作为顶层对象出现。
- `output.status`: 当前固定为 `written`。
- `output.path`: 实际写入路径,建议为绝对路径或规范化绝对路径。
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index 3dbb0b50..70ddd9e2 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -91,7 +91,7 @@ class ParseResponse:
sha256: str
tier: str
page_range: str
- status: str
+ status: Literal["pending", "done"]
cache_hit: bool
wait_parse_ids: list[int]
created_parse_ids: list[int]
diff --git a/mineru/cli/commands/parse.py b/mineru/cli/commands/parse.py
index c5106c45..254b4e03 100644
--- a/mineru/cli/commands/parse.py
+++ b/mineru/cli/commands/parse.py
@@ -191,13 +191,11 @@ def _parse(
return
# no-wait
- if no_wait or status not in ("pending", "parsing") or not wait_parse_ids:
+ if no_wait or not wait_parse_ids:
if json_mode:
_emit_parse_json_response(result, None)
else:
emit_result(CliContext(json_mode=False), _prepare_parse_summary_output(result))
- if status == "failed":
- emit_result(CliContext(json_mode=json_mode), cli_ok(exit_code=1))
return
# poll until done or timeout
@@ -207,6 +205,7 @@ def _parse(
wait_started_at = time.time()
deadline = time.time() + wait
interval = 0.5
+ latest_wait_status = status
while time.time() < deadline:
time.sleep(interval)
interval = min(interval * 1.2, 3.0)
@@ -218,7 +217,16 @@ def _parse(
wait_id_set = set(wait_parse_ids)
parse_rows = [row for row in s.parses if row.id in wait_id_set]
statuses = {row.status for row in parse_rows}
- st = "done" if parse_rows and statuses == {"done"} else ("failed" if "failed" in statuses else "parsing")
+ if parse_rows and statuses == {"done"}:
+ st = "done"
+ elif "failed" in statuses:
+ st = "failed"
+ elif "parsing" in statuses:
+ st = "parsing"
+ else:
+ st = "pending"
+ if st in ("pending", "parsing"):
+ latest_wait_status = st
if verbose and not json_mode:
_emit_notice(f" Parse status: {st}", json_mode=json_mode)
@@ -248,8 +256,13 @@ def _parse(
_record_parse_wait(client, wait_parse_ids, "timeout", wait_started_at)
timeout_error = MineruError("parse_wait_timeout", f"Parse did not finish within {wait} seconds.", "wait")
if json_mode:
- timeout_result = result.model_copy(update={"status": "parsing", "tip": "Re-run the same command to continue waiting."})
- _emit_parse_json_response(timeout_result, None, error=timeout_error, exit_code=1)
+ _emit_parse_json_response(
+ result,
+ None,
+ error=timeout_error,
+ exit_code=1,
+ parse_overrides={"status": latest_wait_status, "tip": "Re-run the same command to continue waiting."},
+ )
else:
_emit_notice(
f"Parse still in progress (tier={req_tier}). Check status with: mineru show file {file_path}", json_mode=json_mode
@@ -371,10 +384,14 @@ def _emit_parse_json_response(
output: str | None = None,
error: MineruError | None = None,
exit_code: int = 0,
+ parse_overrides: dict[str, str | None] | None = None,
) -> None:
emit_result(
CliContext(json_mode=True),
- cli_ok(_parse_json_payload(parse_result, content, output=output, error=error), exit_code=exit_code),
+ cli_ok(
+ _parse_json_payload(parse_result, content, output=output, error=error, parse_overrides=parse_overrides),
+ exit_code=exit_code,
+ ),
)
@@ -384,9 +401,13 @@ def _parse_json_payload(
*,
output: str | None = None,
error: MineruError | None = None,
+ parse_overrides: dict[str, str | None] | None = None,
) -> dict[str, Any]:
+ parse_payload = parse_result.model_dump(mode="json")
+ if parse_overrides:
+ parse_payload.update(parse_overrides)
payload: dict[str, Any] = {
- "parse": parse_result.model_dump(mode="json"),
+ "parse": parse_payload,
"content": content.model_dump(mode="json") if content is not None else None,
}
if output is not None:
@@ -399,10 +420,8 @@ def _parse_json_payload(
def _prepare_parse_summary_output(parse_result: ParseResponse) -> CliResult[ParseSummaryOutput] | CliResult[None]:
status = parse_result.status
tip = parse_result.tip or ""
- if status in ("pending", "parsing"):
+ if status == "pending":
return cli_ok(ParseSummaryOutput(f"Parse {status}... {tip}"), render=_render_parse_summary)
- if status == "failed":
- return cli_ok(None, notices=["Parse failed: ? — "])
return cli_ok(ParseSummaryOutput(f"Parse complete (tier={parse_result.tier}) {tip}"), render=_render_parse_summary)
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
index accffd65..a82d884b 100644
--- a/mineru/doclib/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -658,13 +658,25 @@ class ParseService:
) -> ParseResponse:
"""Handle a parse request from CLI. Returns info for status polling."""
# ensure the path is current before trusting files.sha256
- file_row = await self.ensure_ingested(path, allow_images=True)
+ refreshed = await self.refresh_file(path, ensure_ingested=True, allow_images=True)
+ if refreshed.status == "unsupported":
+ ext = Path(path).suffix.lower() or Path(path).name
+ raise InvalidRequestError("file_type_unsupported", f"File type is not supported for parsing: {ext}", "path")
+ if refreshed.status in {"missing", "deleted", "unreachable"}:
+ raise InvalidRequestError("file_not_found", f"File {path} not found.", "path")
+ if refreshed.status == "error":
+ code = refreshed.file.error_code if refreshed.file and refreshed.file.error_code else "ingest_failed"
+ message = refreshed.file.error_msg if refreshed.file and refreshed.file.error_msg else "File could not be ingested."
+ raise MineruError(code, message, "path")
+ if refreshed.file is None:
+ raise MineruError("ingest_failed", "File could not be ingested.", "path")
+
+ file_row = cast(FileRow | None, await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,)))
if file_row is None:
- return _failed_response(tier or "flash", page_range or "", "File could not be ingested.")
-
+ raise MineruError("ingest_failed", "File could not be ingested.", "path")
sha256 = file_row["sha256"]
if sha256 is None:
- return _failed_response(tier or "flash", page_range or "", "File could not be ingested.")
+ raise MineruError(file_row.get("error_code") or "ingest_failed", file_row.get("error_msg") or "File could not be ingested.", "path")
doc = cast(DocRow | None, await self.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha256,)))
page_count = doc["page_count"] if doc else 1
short_id = doc["short_id"] if doc else None
@@ -1422,20 +1434,6 @@ def _text_response(sha256: str, short_id: str | None) -> ParseResponse:
)
-def _failed_response(tier: Tier, page_range: str, tip: str) -> ParseResponse:
- return ParseResponse(
- sha256="",
- tier=tier,
- page_range=page_range,
- status=PARSE_STATUS_FAILED,
- cache_hit=False,
- wait_parse_ids=[],
- created_parse_ids=[],
- reused_parse_ids=[],
- tip=tip,
- )
-
-
def _parse_record_response(row: ParseRow) -> dict:
error = None
if row.get("error_code") or row.get("error_msg"):
diff --git a/mineru/doclib/types.py b/mineru/doclib/types.py
index 076ba1eb..d03acdd0 100644
--- a/mineru/doclib/types.py
+++ b/mineru/doclib/types.py
@@ -9,6 +9,7 @@ from pydantic import BaseModel, Field
from ..types import Tier
ParseStatus = Literal["pending", "parsing", "done", "failed", "superseded"]
+ParseSubmitStatus = Literal["pending", "done"]
FileStatus = Literal["active", "deleted", "unreachable"]
ScanStatus = Literal["pending", "running", "done", "failed"]
ScanKind = Literal["manual", "watch"]
@@ -23,9 +24,9 @@ ConfigSource = Literal["default", "override"]
ContentFormat = Literal["markdown", "image"]
ImageFormat = Literal["jpeg", "png", "webp"]
-PARSE_STATUS_PENDING: ParseStatus = "pending"
+PARSE_STATUS_PENDING: ParseStatus | ParseSubmitStatus = "pending"
PARSE_STATUS_PARSING: ParseStatus = "parsing"
-PARSE_STATUS_DONE: ParseStatus = "done"
+PARSE_STATUS_DONE: ParseStatus | ParseSubmitStatus = "done"
PARSE_STATUS_FAILED: ParseStatus = "failed"
PARSE_STATUS_SUPERSEDED: ParseStatus = "superseded"
@@ -103,7 +104,7 @@ class ParseResponse(DoclibModel):
short_id: str | None = None
tier: Tier
page_range: str
- status: ParseStatus
+ status: ParseSubmitStatus
cache_hit: bool = False
wait_parse_ids: list[int] = Field(default_factory=list)
created_parse_ids: list[int] = Field(default_factory=list)
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index c981043c..7f8222c7 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -876,7 +876,7 @@ def test_config_parsing_rules_remove_non_json_prints_message_not_error_tuple(mon
assert "('rule_not_found'" not in result.output
-def test_parse_failed_response_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:
+def test_parse_ingest_error_json_is_machine_readable(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.unsupported"
source.write_bytes(b"unsupported")
@@ -884,14 +884,8 @@ def test_parse_failed_response_exits_nonzero(monkeypatch: Any, tmp_path: Path) -
def __init__(self, *, timeout: int) -> None:
assert timeout == 90
- def ensure_parse(self, request: Any) -> ParseResponse:
- return ParseResponse(
- sha256="",
- tier="flash",
- page_range="",
- status="failed",
- tip="File could not be ingested.",
- )
+ def ensure_parse(self, request: Any) -> None:
+ raise RuntimeError("('ingest_failed', 'File could not be ingested.', 'path')")
monkeypatch.setattr(parse, "DoclibClient", _Client)
@@ -899,8 +893,11 @@ def test_parse_failed_response_exits_nonzero(monkeypatch: Any, tmp_path: Path) -
assert result.exit_code == 1
payload = json.loads(result.output)
- assert payload["parse"]["status"] == "failed"
- assert payload["parse"]["tip"] == "File could not be ingested."
+ assert payload["error"]["type"] == "api_error"
+ assert payload["error"]["code"] == "ingest_failed"
+ assert payload["error"]["message"] == "File could not be ingested."
+ assert payload["error"]["param"] == "path"
+ assert "parse" not in payload
def test_parse_next_marker_quotes_windows_path() -> None:
@@ -1195,6 +1192,18 @@ def test_parse_wait_status_line_is_verbose_only(monkeypatch: Any, tmp_path: Path
def test_parse_wait_timeout_json_returns_timeout_error(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
+ pending = ParseInfo(
+ id=3,
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="flash",
+ page_range="1~1",
+ status="pending",
+ privacy="local",
+ via="local",
+ created_at=3,
+ updated_at=4,
+ )
class _Client:
def __init__(self, *, timeout: int) -> None:
@@ -1210,10 +1219,13 @@ def test_parse_wait_timeout_json_returns_timeout_error(monkeypatch: Any, tmp_pat
created_parse_ids=[3],
)
+ def list_parses(self, **kwargs: Any) -> ListParsesResponse:
+ return ListParsesResponse(parses=[pending], total=1, limit=50, offset=0)
+
def record_observations(self, request: Any) -> Any:
return None
- times = iter([0.0, 0.0, 2.0, 2.0])
+ times = iter([0.0, 0.0, 0.2, 2.0, 2.0])
monkeypatch.setattr(parse, "DoclibClient", _Client)
monkeypatch.setattr(parse.time, "time", lambda: next(times, 2.0))
@@ -1224,7 +1236,7 @@ def test_parse_wait_timeout_json_returns_timeout_error(monkeypatch: Any, tmp_pat
assert payload["error"]["type"] == "timeout_error"
assert payload["error"]["code"] == "parse_wait_timeout"
assert payload["error"]["param"] == "wait"
- assert payload["parse"]["status"] == "parsing"
+ assert payload["parse"]["status"] == "pending"
assert payload["parse"]["wait_parse_ids"] == [3]
assert payload["content"] is None
@@ -1260,6 +1272,54 @@ def test_parse_wait_timeout_text_returns_nonzero_exit(monkeypatch: Any, tmp_path
assert "Parse still in progress" in result.output
+def test_parse_wait_timeout_json_uses_latest_parsing_status(monkeypatch: Any, tmp_path: Path) -> None:
+ source = tmp_path / "demo.pdf"
+ source.write_bytes(b"%PDF-1.7\n")
+ parsing = ParseInfo(
+ id=3,
+ sha256="a" * 64,
+ short_id="aaaaaaa",
+ tier="flash",
+ page_range="1~1",
+ status="parsing",
+ privacy="local",
+ via="local",
+ created_at=3,
+ updated_at=4,
+ )
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 31
+
+ def ensure_parse(self, request: Any) -> ParseResponse:
+ return ParseResponse(
+ sha256="a" * 64,
+ tier="flash",
+ page_range="1~1",
+ status="pending",
+ wait_parse_ids=[3],
+ created_parse_ids=[3],
+ )
+
+ def list_parses(self, **kwargs: Any) -> ListParsesResponse:
+ return ListParsesResponse(parses=[parsing], total=1, limit=50, offset=0)
+
+ def record_observations(self, request: Any) -> Any:
+ return None
+
+ times = iter([0.0, 0.0, 0.2, 2.0, 2.0])
+ monkeypatch.setattr(parse, "DoclibClient", _Client)
+ monkeypatch.setattr(parse.time, "time", lambda: next(times, 2.0))
+
+ result = runner.invoke(app, ["parse", str(source), "--tier", "flash", "--wait", "1", "--json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"]["code"] == "parse_wait_timeout"
+ assert payload["parse"]["status"] == "parsing"
+
+
def test_parse_json_error_output_is_machine_readable(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.pdf"
source.write_bytes(b"%PDF-1.7\n")
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index f1081290..e0eb8a80 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -36,6 +36,7 @@ from mineru.doclib.services import parse_svc as parse_svc_module
from mineru.doclib.services.cleanup_svc import CleanupService
from mineru.doclib.services.config_svc import ConfigService
from mineru.doclib.services.parse_svc import (
+ FileRefreshResult,
ParseFailure,
ParseService,
_local_parse_server_url,
@@ -48,8 +49,8 @@ from mineru.doclib.services.parse_svc import (
)
from mineru.doclib.services.scan_svc import ScanService
from mineru.doclib.services.search_svc import SearchService
-from mineru.doclib.types import DocContentExportRequest, InvalidateRequest, ParseResponse, WatchRequest
-from mineru.errors import InvalidRequestError, NotFoundError
+from mineru.doclib.types import DocContentExportRequest, FileInfo, InvalidateRequest, ParseResponse, WatchRequest
+from mineru.errors import InvalidRequestError, MineruError, NotFoundError
from mineru.parser import backend_for_tier, resolve_tier_and_backend
from mineru.parser.base import ParseResult
from mineru.schema.middle_json import MIDDLE_JSON_SCHEMA_VERSION
@@ -966,6 +967,77 @@ def test_request_parse_rejects_flash_tier_for_remote_quality_inputs(
asyncio.run(_run())
+def test_request_parse_rejects_unsupported_file_type_before_parse_response(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(
+ db=db,
+ fts=FTSManager(db),
+ config_svc=None,
+ data_dir=str(tmp_path / "data"),
+ parse_lock_timeout_sec=1800,
+ )
+ source = tmp_path / "sample.unsupported"
+ source.write_text("content", encoding="utf-8")
+
+ with pytest.raises(InvalidRequestError) as exc_info:
+ await service.request_parse(str(source), tier="flash")
+
+ assert exc_info.value.code == "file_type_unsupported"
+ assert exc_info.value.param == "path"
+
+ asyncio.run(_run())
+
+
+def test_request_parse_raises_ingest_failed_when_file_row_has_no_sha(tmp_path: Path) -> None:
+ async def _run() -> None:
+ db = DatabaseManager(str(tmp_path / "doclib.db"))
+ await db.initialize()
+ service = ParseService(
+ db=db,
+ fts=FTSManager(db),
+ config_svc=None,
+ data_dir=str(tmp_path / "data"),
+ parse_lock_timeout_sec=1800,
+ )
+ source = tmp_path / "sample.pdf"
+ source.write_bytes(b"%PDF-1.4\n")
+ stat = source.stat()
+ now = 1000
+ await db.execute(
+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, sha256, status, first_seen_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?)",
+ (str(source), source.name, "pdf", stat.st_size, int(stat.st_mtime * 1000), "active", now, now),
+ )
+
+ async def _refresh_file(*args: Any, **kwargs: Any) -> FileRefreshResult:
+ return FileRefreshResult(
+ file=FileInfo(
+ path=str(source),
+ filename=source.name,
+ ext="pdf",
+ size_bytes=stat.st_size,
+ mtime_ms=int(stat.st_mtime * 1000),
+ sha256=None,
+ status="active",
+ first_seen_at=now,
+ updated_at=now,
+ ),
+ status="known",
+ )
+
+ service.refresh_file = _refresh_file # type: ignore[method-assign]
+
+ with pytest.raises(MineruError) as exc_info:
+ await service.request_parse(str(source), tier="flash")
+
+ assert exc_info.value.code == "ingest_failed"
+ assert exc_info.value.param == "path"
+
+ asyncio.run(_run())
+
+
def test_force_request_reuses_active_and_creates_only_uncovered_parse(tmp_path: Path) -> None:
sha256 = "e" * 64
source = tmp_path / "doc.pdf"
@@ -3026,9 +3098,7 @@ def test_doclib_office_image_asset_transcodes_to_requested_format(tmp_path: Path
sidecar = image_dir / image_path
sidecar.parent.mkdir(parents=True)
sidecar.write_bytes(
- base64.b64decode(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
- )
+ base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADUlEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")
)
image_span = Span(type=ContentType.IMAGE, bbox=(1, 1, 20, 20), image_path=image_path)
diff --git a/tests/unittest/test_doclib_interface_contract.py b/tests/unittest/test_doclib_interface_contract.py
index f6624c05..e72139f4 100644
--- a/tests/unittest/test_doclib_interface_contract.py
+++ b/tests/unittest/test_doclib_interface_contract.py
@@ -38,6 +38,7 @@ from mineru.doclib.types import (
ParseCoverage,
ParseInfo,
ParseRequest,
+ ParseResponse,
ParseStatus,
ParseServerStatus,
ParsingRuleInfo,
@@ -495,6 +496,15 @@ def test_parse_request_rejects_auto_tier() -> None:
ParseRequest(path="/tmp/a.pdf", tier="auto", page_range="1~5")
+def test_parse_response_status_is_submit_state_only() -> None:
+ with pytest.raises(ValidationError):
+ ParseResponse(sha256="a" * 64, tier="flash", page_range="1", status="parsing")
+
+ response = ParseResponse(sha256="a" * 64, tier="flash", page_range="1", status="pending")
+
+ assert response.status == "pending"
+
+
def test_route_info_exports_from_route_utils() -> None:
route_info = RouteInfo(method="GET", path="/server/status")
assert route_info.method == "GET"