Skip to content

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

refactor: improve upload handling and error management in Router

myhloli9f9a74d25c77
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index 706da218..08437ee8 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -221,15 +221,30 @@ async def _hydrate_job_output_files(
if route is None or isinstance(route.metadata.get("payload"), dict):
continue
worker = pool.get(route.worker_id)
- response = await request_upstream(
- pool,
- worker,
- "GET",
- f"/v1/files/{route.upstream_id}",
- request=request,
- )
- metadata = json_or_error(response)
+ try:
+ response = await request_upstream(
+ pool,
+ worker,
+ "GET",
+ f"/v1/files/{route.upstream_id}",
+ request=request,
+ )
+ if response.status_code >= 400:
+ route.metadata["hydration_error"] = {
+ "status_code": response.status_code,
+ "message": response.text,
+ }
+ continue
+ metadata = json_or_error(response)
+ except RouterProxyError as exc:
+ route.metadata["hydration_error"] = {
+ "status_code": exc.status_code,
+ "code": exc.code,
+ "message": exc.message,
+ }
+ continue
rewrite_file_payload(metadata, worker, registry)
+ route.metadata.pop("hydration_error", None)
async def _finalize_terminal_job(
@@ -396,10 +411,19 @@ def create_app(
async def upload_content(upload_id: str, request: Request) -> Response:
"""把上传内容流式暂存到 Router,再写入 upload 所属 worker。"""
route = _route_or_404(registry, "upload", upload_id)
+ upload_payload = route.metadata.get("payload")
+ upload_status = upload_payload.get("status") if isinstance(upload_payload, dict) else None
+ if source_store.is_bound_upload(upload_id) or upload_status == "completed":
+ raise RouterProxyError(409, "upload_already_completed", f"Upload {upload_id} is already completed")
+ if upload_status == "canceled":
+ raise RouterProxyError(409, "upload_already_canceled", f"Upload {upload_id} is already canceled")
worker = pool.get(route.worker_id)
declared = route.metadata.get("declared") if isinstance(route.metadata.get("declared"), dict) else {}
mime_type = str(declared.get("mime_type") or request.headers.get("content-type") or "application/octet-stream")
- stored = await source_store.stage_upload(upload_id, request.stream(), mime_type=mime_type)
+ try:
+ stored = await source_store.stage_upload(upload_id, request.stream(), mime_type=mime_type)
+ except ValueError as exc:
+ raise RouterProxyError(409, "upload_not_writable", str(exc)) from exc
declared_bytes = declared.get("bytes")
if isinstance(declared_bytes, int) and stored.bytes != declared_bytes:
source_store.discard_upload(upload_id)
diff --git a/mineru/kit/router/resources.py b/mineru/kit/router/resources.py
index 457ee0b0..4149b7fa 100644
--- a/mineru/kit/router/resources.py
+++ b/mineru/kit/router/resources.py
@@ -66,6 +66,7 @@ class SourceFileStore:
self._root = Path(self._temp_dir.name)
self._uploads: dict[str, StoredSourceFile] = {}
self._files: dict[str, StoredSourceFile] = {}
+ self._bound_uploads: set[str] = set()
async def stage_upload(
self,
@@ -75,6 +76,8 @@ class SourceFileStore:
mime_type: str,
) -> StoredSourceFile:
"""流式写入一个公共 Upload 的输入字节,并计算实际大小与 SHA256。"""
+ if upload_id in self._bound_uploads:
+ raise ValueError(f"Upload {upload_id} is already bound to a completed file")
path = self._root / "uploads" / upload_id
path.parent.mkdir(parents=True, exist_ok=True)
hasher = hashlib.sha256()
@@ -102,8 +105,13 @@ class SourceFileStore:
"""把已完成 Upload 的暂存输入绑定到 Router 公共 File。"""
stored = self._uploads.pop(upload_id)
self._files[file_id] = stored
+ self._bound_uploads.add(upload_id)
return stored
+ def is_bound_upload(self, upload_id: str) -> bool:
+ """判断 Upload 的暂存路径是否已经绑定到完成后的公共 File。"""
+ return upload_id in self._bound_uploads
+
def find_upload(self, upload_id: str) -> StoredSourceFile | None:
"""读取公共 Upload 对应的私有暂存输入,不存在时返回 None。"""
return self._uploads.get(upload_id)
@@ -114,6 +122,8 @@ class SourceFileStore:
def discard_upload(self, upload_id: str) -> None:
"""删除取消或失败 Upload 的私有暂存输入。"""
+ if upload_id in self._bound_uploads:
+ return
stored = self._uploads.pop(upload_id, None)
if stored is not None:
stored.path.unlink(missing_ok=True)
@@ -128,6 +138,7 @@ class SourceFileStore:
"""清理当前 Router 进程的全部暂存输入。"""
self._uploads.clear()
self._files.clear()
+ self._bound_uploads.clear()
self._temp_dir.cleanup()
diff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.py
index a6770553..e1440610 100644
--- a/mineru/kit/router/workers.py
+++ b/mineru/kit/router/workers.py
@@ -36,9 +36,30 @@ def normalize_base_url(url: str) -> str:
return normalized
+def worker_connect_host(bind_host: str) -> str:
+ """把 worker 监听地址转换成 Router 可主动连接的 loopback 地址。"""
+ normalized = str(bind_host).strip()
+ if normalized.startswith("[") and normalized.endswith("]"):
+ normalized = normalized[1:-1]
+ if normalized in {"", "0.0.0.0"}:
+ return "127.0.0.1"
+ if normalized == "::":
+ return "::1"
+ return normalized
+
+
+def worker_base_url(bind_host: str, port: int) -> str:
+ """构造托管 worker 的可连接 HTTP URL,并为 IPv6 literal 添加方括号。"""
+ connect_host = worker_connect_host(bind_host)
+ authority = f"[{connect_host}]" if ":" in connect_host else connect_host
+ return f"http://{authority}:{port}"
+
+
def reserve_local_port(host: str) -> int:
"""在指定 host 上申请一个当前可用的本地 TCP 端口。"""
- bind_host = "127.0.0.1" if host in {"0.0.0.0", "::", ""} else host
+ bind_host = str(host).strip() or "127.0.0.1"
+ if bind_host.startswith("[") and bind_host.endswith("]"):
+ bind_host = bind_host[1:-1]
family = socket.AF_INET6 if ":" in bind_host else socket.AF_INET
with socket.socket(family, socket.SOCK_STREAM) as sock:
sock.bind((bind_host, 0))
@@ -166,8 +187,7 @@ class ManagedLocalWorker:
upload_dir = Path(self.temp_dir.name) / "uploads"
upload_dir.mkdir(parents=True, exist_ok=True)
port = reserve_local_port(self.host)
- connect_host = "127.0.0.1" if self.host in {"0.0.0.0", "::", ""} else self.host
- self.base_url = f"http://{connect_host}:{port}"
+ self.base_url = worker_base_url(self.host, port)
env = utf8_subprocess_env()
if self.gpu is not None:
env[visible_device_env_name()] = self.gpu
@@ -442,4 +462,6 @@ __all__ = [
"WorkerState",
"normalize_base_url",
"parse_local_gpus",
+ "worker_base_url",
+ "worker_connect_host",
]
diff --git a/tests/unittest/test_v1_router.py b/tests/unittest/test_v1_router.py
index 7d9fd94e..4a36a102 100644
--- a/tests/unittest/test_v1_router.py
+++ b/tests/unittest/test_v1_router.py
@@ -9,10 +9,11 @@ from pathlib import Path
from typing import Any
import httpx
+import pytest
from fastapi.testclient import TestClient
from mineru.kit.router import RouterSettings, create_app
-from mineru.kit.router.workers import ManagedLocalWorker
+from mineru.kit.router.workers import ManagedLocalWorker, worker_base_url, worker_connect_host
from mineru.parser.api_server import create_app as create_api_server_app
@@ -454,6 +455,61 @@ def test_router_discards_staged_upload_with_wrong_sha256() -> None:
assert next(iter(upstream.uploads.values()))["content"] == b""
+def test_completed_upload_rejects_content_rewrite_without_touching_bound_source() -> None:
+ """验证 completed Upload 的后续 PUT 返回 409 且绑定源文件保持不可变。"""
+ upstream = _FakeV1Upstream("worker-a", ("standard",))
+ router_app, _ = _make_router(upstream)
+ original = b"original"
+
+ with TestClient(router_app) as client:
+ created = client.post(
+ "/v1/uploads",
+ json={
+ "filename": "input.pdf",
+ "bytes": len(original),
+ "mime_type": "application/pdf",
+ "purpose": "parse",
+ },
+ )
+ upload_id = created.json()["id"]
+ client.put(f"/v1/uploads/{upload_id}/content", content=original)
+ completed = client.post(f"/v1/uploads/{upload_id}/complete", json={})
+ file_id = completed.json()["file"]["id"]
+ stored = router_app.state.source_store.find_file(file_id)
+ assert stored is not None
+
+ rewritten = client.put(f"/v1/uploads/{upload_id}/content", content=b"modified")
+
+ assert rewritten.status_code == 409
+ assert rewritten.json()["error"]["code"] == "upload_already_completed"
+ assert stored.path.read_bytes() == original
+
+
+def test_terminal_job_read_survives_deleted_output_metadata() -> None:
+ """验证 output 删除后 hydration 失败不会阻断 completed Job 读取。"""
+ upstream = _FakeV1Upstream("worker-a", ("standard",))
+ router_app, _ = _make_router(upstream)
+
+ with TestClient(router_app) as client:
+ file_id = _upload_file(client, token="output-delete", content=b"pdf")
+ created = client.post(
+ "/v1/parse/jobs",
+ json={"tier": "standard", "files": [{"source": {"type": "file_id", "file_id": file_id}}]},
+ )
+ job_id = created.json()["job_id"]
+ completed = client.get(f"/v1/parse/jobs/{job_id}")
+ output_id = completed.json()["files"][0]["output_files"]["markdown"]["file_id"]
+ assert client.delete(f"/v1/files/{output_id}").status_code == 200
+
+ reread = client.get(f"/v1/parse/jobs/{job_id}")
+
+ assert reread.status_code == 200
+ assert reread.json()["status"] == "completed"
+ replacement_output_id = reread.json()["files"][0]["output_files"]["markdown"]["file_id"]
+ replacement_route = router_app.state.registry.get("file", replacement_output_id)
+ assert replacement_route.metadata["hydration_error"]["status_code"] == 404
+
+
def test_router_reclaims_cross_worker_copy_when_job_is_canceled() -> None:
"""验证取消 Job 时立即删除并解除 cross-worker 输入副本。"""
first = _FakeV1Upstream("worker-a", ("standard",))
@@ -571,6 +627,26 @@ def test_managed_router_worker_builds_new_api_server_command(tmp_path: Path) ->
assert "mineru.cli_old" not in " ".join(command)
+ ("bind_host", "expected_connect_host", "expected_url"),
+ [
+ ("", "127.0.0.1", "http://127.0.0.1:18000"),
+ ("0.0.0.0", "127.0.0.1", "http://127.0.0.1:18000"),
+ ("127.0.0.1", "127.0.0.1", "http://127.0.0.1:18000"),
+ ("::", "::1", "http://[::1]:18000"),
+ ("::1", "::1", "http://[::1]:18000"),
+ ],
+)
+def test_managed_worker_formats_connectable_ipv4_and_ipv6_urls(
+ bind_host: str,
+ expected_connect_host: str,
+ expected_url: str,
+) -> None:
+ """验证 wildcard、IPv4 与 IPv6 worker 地址生成合法可连接 URL。"""
+ assert worker_connect_host(bind_host) == expected_connect_host
+ assert worker_base_url(bind_host, 18000) == expected_url
+
+
def test_managed_router_worker_uses_control_shutdown() -> None:
"""验证托管 worker 优先通过 ManagedProcessControl 正常退出。"""