Skip to content

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

fix: harden v1 router isolation and reconciliation

myhloli2c0a7f613d2b
diff --git a/docker/compose.yaml b/docker/compose.yaml
index e7bc58b4..42b72a3b 100644
--- a/docker/compose.yaml
+++ b/docker/compose.yaml
@@ -92,7 +92,7 @@ services:
stack: 67108864
ipc: host
healthcheck:
- test: ["CMD-SHELL", "curl -f http://localhost:8002/health || exit 1"]
+ test: ["CMD-SHELL", "curl -f http://localhost:8002/v1/health || exit 1"]
deploy:
resources:
reservations:
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.py
index 08437ee8..1c607423 100644
--- a/mineru/kit/router/app.py
+++ b/mineru/kit/router/app.py
@@ -3,7 +3,9 @@
from __future__ import annotations
+import asyncio
import copy
+import hashlib
import time
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Literal
@@ -37,10 +39,29 @@ from .resources import (
from .workers import RouterSettings, WorkerPool, WorkerState
-def _route_or_404(registry: ResourceRegistry, kind: ResourceKind, public_id: str) -> ResourceRoute:
- """读取资源路由,不存在时返回稳定 V1 404 错误。"""
+def _caller_scope(request: Request) -> str:
+ """从 Authorization 派生不可逆的 Router 调用方资源 scope。"""
+ authorization = request.headers.get("authorization", "")
+ if not authorization:
+ return "anonymous"
+ return "auth:" + hashlib.sha256(authorization.encode("utf-8")).hexdigest()
+
+
+def _authorization_headers(request: Request) -> dict[str, str]:
+ """提取后台 Job reconciliation 需要的私有 upstream Authorization。"""
+ authorization = request.headers.get("authorization")
+ return {"authorization": authorization} if authorization else {}
+
+
+def _route_or_404(
+ registry: ResourceRegistry,
+ kind: ResourceKind,
+ public_id: str,
+ owner_scope: str,
+) -> ResourceRoute:
+ """读取当前调用方资源路由,不存在或 scope 不匹配时返回稳定 404。"""
route = registry.find(kind, public_id)
- if route is None:
+ if route is None or route.owner_scope != owner_scope:
raise RouterProxyError(404, f"{kind}_not_found", f"{kind.title()} {public_id} not found")
return route
@@ -70,6 +91,7 @@ def _healthy_worker_or_503(pool: WorkerPool) -> WorkerState:
def _list_registered_files(
registry: ResourceRegistry,
*,
+ owner_scope: str,
after: str | None,
limit: int,
order: Literal["asc", "desc"],
@@ -78,7 +100,7 @@ def _list_registered_files(
"""从 Router 注册表构造 V1 Files 列表与游标。"""
data = [
copy.deepcopy(route.metadata["payload"])
- for route in registry.list("file")
+ for route in registry.list("file", owner_scope=owner_scope)
if isinstance(route.metadata.get("payload"), dict)
and (purpose is None or route.metadata["payload"].get("purpose") == purpose)
]
@@ -97,6 +119,7 @@ def _list_registered_files(
def _list_registered_jobs(
registry: ResourceRegistry,
*,
+ owner_scope: str,
status_filter: str | None,
after: str | None,
limit: int,
@@ -107,7 +130,7 @@ def _list_registered_jobs(
allowed_statuses = set(status_filter.split(",")) if status_filter else None
payloads = [
copy.deepcopy(route.metadata["payload"])
- for route in registry.list("job")
+ for route in registry.list("job", owner_scope=owner_scope)
if isinstance(route.metadata.get("payload"), dict)
]
payloads = [
@@ -136,9 +159,9 @@ def _list_registered_jobs(
}
-def _usage_payload(request: Request, registry: ResourceRegistry, pool: WorkerPool) -> dict[str, Any]:
+def _usage_payload(request: Request, registry: ResourceRegistry, pool: WorkerPool, owner_scope: str) -> dict[str, Any]:
"""聚合当前 Router 进程观察到的 jobs/files 与 worker 并发上限。"""
- jobs = [route.metadata.get("payload") or {} for route in registry.list("job")]
+ jobs = [route.metadata.get("payload") or {} for route in registry.list("job", owner_scope=owner_scope)]
completed_jobs = [payload for payload in jobs if payload.get("status") in {"completed", "partial"}]
files_processed = sum(
1
@@ -168,9 +191,10 @@ def _usage_payload(request: Request, registry: ResourceRegistry, pool: WorkerPoo
async def _cleanup_copied_files(
copied_files: list[CopiedInputFile],
*,
- request: Request,
+ request: Request | None,
pool: WorkerPool,
registry: ResourceRegistry,
+ headers: dict[str, str] | None = None,
) -> list[CopiedInputFile]:
"""幂等删除 cross-worker 输入副本,返回等待后续重试的失败项。"""
pending: list[CopiedInputFile] = []
@@ -183,6 +207,7 @@ async def _cleanup_copied_files(
"DELETE",
f"/v1/files/{copied_file.upstream_file_id}",
request=request,
+ headers=headers,
)
except RouterProxyError:
pending.append(copied_file)
@@ -192,6 +217,7 @@ async def _cleanup_copied_files(
continue
registry.remove_upstream_alias(
"file",
+ owner_scope=copied_file.owner_scope,
worker_id=copied_file.worker_id,
upstream_id=copied_file.upstream_file_id,
)
@@ -201,9 +227,10 @@ async def _cleanup_copied_files(
async def _hydrate_job_output_files(
payload: dict[str, Any],
*,
- request: Request,
+ request: Request | None,
pool: WorkerPool,
registry: ResourceRegistry,
+ headers: dict[str, str] | None = None,
) -> None:
"""读取 Job output files 的完整元数据,使其立即进入 `/v1/files`。"""
seen_public_ids: set[str] = set()
@@ -228,6 +255,7 @@ async def _hydrate_job_output_files(
"GET",
f"/v1/files/{route.upstream_id}",
request=request,
+ headers=headers,
)
if response.status_code >= 400:
route.metadata["hydration_error"] = {
@@ -243,7 +271,7 @@ async def _hydrate_job_output_files(
"message": exc.message,
}
continue
- rewrite_file_payload(metadata, worker, registry)
+ rewrite_file_payload(metadata, worker, registry, route.owner_scope)
route.metadata.pop("hydration_error", None)
@@ -251,15 +279,22 @@ async def _finalize_terminal_job(
route: ResourceRoute,
payload: dict[str, Any],
*,
- request: Request,
+ request: Request | None,
pool: WorkerPool,
registry: ResourceRegistry,
+ headers: dict[str, str] | None = None,
) -> None:
"""在 Job 终态补齐 outputs,并回收或保留待重试的输入副本。"""
if payload.get("status") not in {"completed", "partial", "failed", "canceled"}:
return
try:
- await _hydrate_job_output_files(payload, request=request, pool=pool, registry=registry)
+ await _hydrate_job_output_files(
+ payload,
+ request=request,
+ pool=pool,
+ registry=registry,
+ headers=headers,
+ )
finally:
copied_files = list(route.metadata.get("copied_inputs") or [])
pending = await _cleanup_copied_files(
@@ -267,11 +302,56 @@ async def _finalize_terminal_job(
request=request,
pool=pool,
registry=registry,
+ headers=headers,
)
if pending:
route.metadata["copied_inputs"] = pending
else:
route.metadata.pop("copied_inputs", None)
+ route.metadata.pop("upstream_headers", None)
+
+
+async def _reconcile_jobs_once(registry: ResourceRegistry, pool: WorkerPool) -> None:
+ """后台查询活动或待清理 Job,并统一执行终态资源收敛。"""
+ for route in registry.list("job"):
+ if not route.metadata.get("active_counted") and not route.metadata.get("copied_inputs"):
+ continue
+ worker = pool.get(route.worker_id)
+ headers = dict(route.metadata.get("upstream_headers") or {})
+ try:
+ response = await request_upstream(
+ pool,
+ worker,
+ "GET",
+ f"/v1/parse/jobs/{route.upstream_id}",
+ headers=headers,
+ )
+ if response.status_code >= 400:
+ continue
+ payload = json_or_error(response)
+ rewritten = rewrite_job_payload(payload, worker, registry, pool, route.owner_scope)
+ route.metadata["payload"] = copy.deepcopy(rewritten)
+ await _finalize_terminal_job(
+ route,
+ rewritten,
+ request=None,
+ pool=pool,
+ registry=registry,
+ headers=headers,
+ )
+ except RouterProxyError:
+ continue
+
+
+async def _job_reconcile_loop(
+ registry: ResourceRegistry,
+ pool: WorkerPool,
+ interval_seconds: float,
+) -> None:
+ """按固定间隔运行 Job reconciliation,单次失败不终止循环。"""
+ while True:
+ await asyncio.sleep(interval_seconds)
+ await _reconcile_jobs_once(registry, pool)
def create_app(
@@ -289,10 +369,26 @@ def create_app(
async def _lifespan(application: FastAPI) -> AsyncIterator[None]:
"""启动 worker pool,并在应用关闭时释放全部网络和子进程资源。"""
application.state.started_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ reconcile_task: asyncio.Task[None] | None = None
try:
await pool.start()
+ if resolved_settings.worker_refresh_interval_seconds > 0:
+ reconcile_task = asyncio.create_task(
+ _job_reconcile_loop(
+ registry,
+ pool,
+ resolved_settings.worker_refresh_interval_seconds,
+ ),
+ name="mineru-v1-router-job-reconciler",
+ )
yield
finally:
+ if reconcile_task is not None:
+ reconcile_task.cancel()
+ try:
+ await reconcile_task
+ except asyncio.CancelledError:
+ pass
await pool.close()
source_store.close()
@@ -307,6 +403,12 @@ def create_app(
application.state.worker_pool = pool
application.state.started_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ async def _reconcile_once_for_state() -> None:
+ """向测试和诊断入口暴露一次显式 Job reconciliation。"""
+ await _reconcile_jobs_once(registry, pool)
+
+ application.state.reconcile_jobs_once = _reconcile_once_for_state
+
@application.exception_handler(RouterProxyError)
async def _router_error_handler(_request: Request, exc: RouterProxyError) -> JSONResponse:
"""把 Router 内部错误转换成稳定 V1 error shape。"""
@@ -376,6 +478,7 @@ def create_app(
@application.post("/v1/uploads")
async def create_upload(request: Request) -> Response:
"""按调用方 affinity 选择 worker 并创建 Router upload。"""
+ owner_scope = _caller_scope(request)
worker = pool.select(tier=None, required_sources={"file_id"}, affinity_key=_affinity_key(request))
if worker is None:
raise RouterProxyError(503, "upstream_unavailable", "No upstream accepts file uploads")
@@ -389,28 +492,32 @@ def create_app(
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- rewritten = rewrite_upload_payload(result, worker, registry)
+ rewritten = rewrite_upload_payload(result, worker, registry, owner_scope)
if isinstance(body.get("sha256sum"), str):
rewritten["sha256sum"] = body["sha256sum"]
- route = _route_or_404(registry, "upload", str(rewritten["id"]))
+ route = _route_or_404(registry, "upload", str(rewritten["id"]), owner_scope)
route.metadata["declared"] = copy.deepcopy(body)
return JSONResponse(rewritten, status_code=upstream.status_code)
@application.get("/v1/uploads/{upload_id}")
async def get_upload(upload_id: str, request: Request) -> Response:
"""把 Router upload 查询路由到其所属 worker。"""
- route = _route_or_404(registry, "upload", upload_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "upload", upload_id, owner_scope)
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "GET", f"/v1/uploads/{route.upstream_id}", request=request)
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- return JSONResponse(rewrite_upload_payload(result, worker, registry), status_code=upstream.status_code)
+ return JSONResponse(
+ rewrite_upload_payload(result, worker, registry, owner_scope),
+ status_code=upstream.status_code,
+ )
@application.put("/v1/uploads/{upload_id}/content")
async def upload_content(upload_id: str, request: Request) -> Response:
"""把上传内容流式暂存到 Router,再写入 upload 所属 worker。"""
- route = _route_or_404(registry, "upload", upload_id)
+ route = _route_or_404(registry, "upload", upload_id, _caller_scope(request))
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":
@@ -450,7 +557,8 @@ def create_app(
@application.post("/v1/uploads/{upload_id}/complete")
async def complete_upload(upload_id: str, request: Request) -> Response:
"""完成所属 worker 的 upload,并注册返回的 V1 file。"""
- route = _route_or_404(registry, "upload", upload_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "upload", upload_id, owner_scope)
worker = pool.get(route.worker_id)
stored = source_store.find_upload(upload_id)
if stored is None:
@@ -471,7 +579,7 @@ def create_app(
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- rewritten = rewrite_upload_payload(result, worker, registry)
+ rewritten = rewrite_upload_payload(result, worker, registry, owner_scope)
file_payload = rewritten.get("file")
if not isinstance(file_payload, dict) or not isinstance(file_payload.get("id"), str):
raise RouterProxyError(502, "invalid_upstream_response", "Completed upload did not return a file")
@@ -481,7 +589,8 @@ def create_app(
@application.post("/v1/uploads/{upload_id}/cancel")
async def cancel_upload(upload_id: str, request: Request) -> Response:
"""取消所属 worker 中尚未完成的 upload。"""
- route = _route_or_404(registry, "upload", upload_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "upload", upload_id, owner_scope)
worker = pool.get(route.worker_id)
upstream = await request_upstream(
pool,
@@ -494,33 +603,48 @@ def create_app(
if isinstance(result, Response):
return result
source_store.discard_upload(upload_id)
- return JSONResponse(rewrite_upload_payload(result, worker, registry), status_code=upstream.status_code)
+ return JSONResponse(
+ rewrite_upload_payload(result, worker, registry, owner_scope),
+ status_code=upstream.status_code,
+ )
@application.get("/v1/files")
async def list_files(
+ request: Request,
after: str | None = None,
limit: int = Query(default=100, ge=1, le=1000),
order: Literal["asc", "desc"] = "desc",
purpose: str | None = None,
) -> dict[str, Any]:
"""列出当前 Router 进程注册的 V1 files。"""
- return _list_registered_files(registry, after=after, limit=limit, order=order, purpose=purpose)
+ return _list_registered_files(
+ registry,
+ owner_scope=_caller_scope(request),
+ after=after,
+ limit=limit,
+ order=order,
+ purpose=purpose,
+ )
@application.get("/v1/files/{file_id}")
async def get_file(file_id: str, request: Request) -> Response:
"""查询 Router file 所属 worker 的最新元数据。"""
- route = _route_or_404(registry, "file", file_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "file", file_id, owner_scope)
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "GET", f"/v1/files/{route.upstream_id}", request=request)
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- return JSONResponse(rewrite_file_payload(result, worker, registry), status_code=upstream.status_code)
+ return JSONResponse(
+ rewrite_file_payload(result, worker, registry, owner_scope),
+ status_code=upstream.status_code,
+ )
@application.get("/v1/files/{file_id}/content")
async def get_file_content(file_id: str, request: Request) -> Response:
"""流式代理 Router file 所属 worker 的内容。"""
- route = _route_or_404(registry, "file", file_id)
+ route = _route_or_404(registry, "file", file_id, _caller_scope(request))
return await stream_upstream(
pool,
pool.get(route.worker_id),
@@ -532,13 +656,14 @@ def create_app(
@application.delete("/v1/files/{file_id}")
async def delete_file(file_id: str, request: Request) -> Response:
"""删除所属 worker 的 file,并在成功后清除 Router 映射。"""
- route = _route_or_404(registry, "file", file_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "file", file_id, owner_scope)
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "DELETE", f"/v1/files/{route.upstream_id}", request=request)
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- for job_route in registry.list("job"):
+ for job_route in registry.list("job", owner_scope=owner_scope):
copied_inputs = list(job_route.metadata.get("copied_inputs") or [])
matching = [item for item in copied_inputs if item.source_public_id == file_id]
if not matching:
@@ -570,6 +695,7 @@ def create_app(
@application.post("/v1/parse/jobs")
async def create_job(request: Request) -> Response:
"""选择匹配 tier/source 的 worker,迁移跨 worker files 后创建 V1 job。"""
+ owner_scope = _caller_scope(request)
body = await request.json()
if not isinstance(body, dict):
raise RouterProxyError(400, "invalid_request", "Job request body must be an object")
@@ -596,7 +722,7 @@ def create_app(
public_file_id = source.get("file_id")
if not isinstance(public_file_id, str):
raise RouterProxyError(400, "invalid_request", "file_id source requires a string file_id")
- file_routes.append((source, _route_or_404(registry, "file", public_file_id)))
+ file_routes.append((source, _route_or_404(registry, "file", public_file_id, owner_scope)))
owner_ids = {route.worker_id for _, route in file_routes}
preferred_worker_id = next(iter(owner_ids)) if len(owner_ids) == 1 else None
worker = pool.select(
@@ -623,6 +749,7 @@ def create_app(
copied_files.append(
CopiedInputFile(
source_public_id=route.public_id,
+ owner_scope=owner_scope,
worker_id=worker.worker_id,
upstream_file_id=target_file_id,
)
@@ -656,12 +783,18 @@ def create_app(
registry=registry,
)
raise RouterProxyError(502, "invalid_upstream_response", "Created job did not return a job_id")
- job_route = registry.register("job", worker_id=worker.worker_id, upstream_id=upstream_job_id)
+ job_route = registry.register(
+ "job",
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_job_id,
+ )
job_route.metadata["input_aliases"] = input_aliases
job_route.metadata["copied_inputs"] = copied_files
job_route.metadata["active_counted"] = True
+ job_route.metadata["upstream_headers"] = _authorization_headers(request)
pool.mark_job_started(worker.worker_id)
- rewritten = rewrite_job_payload(result, worker, registry, pool)
+ rewritten = rewrite_job_payload(result, worker, registry, pool, owner_scope)
job_route.metadata["payload"] = copy.deepcopy(rewritten)
await _finalize_terminal_job(
job_route,
@@ -674,6 +807,7 @@ def create_app(
@application.get("/v1/parse/jobs")
async def list_jobs(
+ request: Request,
status_filter: str | None = Query(default=None, alias="status"),
limit: int = Query(default=20, ge=1, le=100),
after: str | None = None,
@@ -683,6 +817,7 @@ def create_app(
"""列出当前 Router 进程创建的 jobs。"""
return _list_registered_jobs(
registry,
+ owner_scope=_caller_scope(request),
status_filter=status_filter,
after=after,
limit=limit,
@@ -693,13 +828,14 @@ def create_app(
@application.get("/v1/parse/jobs/{job_id}")
async def get_job(job_id: str, request: Request) -> Response:
"""查询 Router job 所属 worker 的最新状态并重写所有资源标识。"""
- route = _route_or_404(registry, "job", job_id)
+ owner_scope = _caller_scope(request)
+ route = _route_or_404(registry, "job", job_id, owner_scope)
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "GET", f"/v1/parse/jobs/{route.upstream_id}", request=request)
result = _successful_json(upstream)
if isinstance(result, Response):
return result
- rewritten = rewrite_job_payload(result, worker, registry, pool)
+ rewritten = rewrite_job_payload(result, worker, registry, pool, owner_scope)
await _finalize_terminal_job(
route,
rewritten,
@@ -712,7 +848,7 @@ def create_app(
@application.delete("/v1/parse/jobs/{job_id}")
async def cancel_job(job_id: str, request: Request) -> Response:
"""取消 Router job,并保持公共 job ID。"""
- route = _route_or_404(registry, "job", job_id)
+ route = _route_or_404(registry, "job", job_id, _caller_scope(request))
worker = pool.get(route.worker_id)
upstream = await request_upstream(pool, worker, "DELETE", f"/v1/parse/jobs/{route.upstream_id}", request=request)
result = _successful_json(upstream)
@@ -736,7 +872,7 @@ def create_app(
@application.get("/v1/usage")
async def usage(request: Request) -> dict[str, Any]:
"""返回当前 Router 进程聚合的 V1 usage。"""
- return _usage_payload(request, registry, pool)
+ return _usage_payload(request, registry, pool, _caller_scope(request))
return application
diff --git a/mineru/kit/router/proxy.py b/mineru/kit/router/proxy.py
index b44f07da..c30eefce 100644
--- a/mineru/kit/router/proxy.py
+++ b/mineru/kit/router/proxy.py
@@ -166,13 +166,19 @@ def rewrite_file_payload(
payload: dict[str, Any],
worker: WorkerState,
registry: ResourceRegistry,
+ owner_scope: str,
) -> dict[str, Any]:
"""注册 upstream file 并把响应中的 file ID 改成 Router 公共 ID。"""
rewritten = copy.deepcopy(payload)
upstream_id = str(rewritten.get("id") or rewritten.get("file_id") or "")
if not upstream_id:
return rewritten
- route = registry.register("file", worker_id=worker.worker_id, upstream_id=upstream_id)
+ route = registry.register(
+ "file",
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_id,
+ )
if "id" in rewritten:
rewritten["id"] = route.public_id
if "file_id" in rewritten:
@@ -185,18 +191,24 @@ def rewrite_upload_payload(
payload: dict[str, Any],
worker: WorkerState,
registry: ResourceRegistry,
+ owner_scope: str,
) -> dict[str, Any]:
"""注册 upload 与完成后的 file,并重写 upload URL 和资源标识。"""
rewritten = copy.deepcopy(payload)
upstream_id = str(rewritten.get("id") or "")
if not upstream_id:
return rewritten
- route = registry.register("upload", worker_id=worker.worker_id, upstream_id=upstream_id)
+ route = registry.register(
+ "upload",
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_id,
+ )
rewritten["id"] = route.public_id
if rewritten.get("upload_url") is not None:
rewritten["upload_url"] = f"/v1/uploads/{route.public_id}/content"
if isinstance(rewritten.get("file"), dict):
- rewritten["file"] = rewrite_file_payload(rewritten["file"], worker, registry)
+ rewritten["file"] = rewrite_file_payload(rewritten["file"], worker, registry, owner_scope)
route.metadata["payload"] = copy.deepcopy(rewritten)
return rewritten
@@ -206,13 +218,19 @@ def rewrite_job_payload(
worker: WorkerState,
registry: ResourceRegistry,
pool: WorkerPool,
+ owner_scope: str,
) -> dict[str, Any]:
"""注册 job、输入/输出 files,重写 links,并在终态归还 worker 负载。"""
rewritten = copy.deepcopy(payload)
upstream_id = str(rewritten.get("job_id") or "")
if not upstream_id:
return rewritten
- route = registry.register("job", worker_id=worker.worker_id, upstream_id=upstream_id)
+ route = registry.register(
+ "job",
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_id,
+ )
rewritten["job_id"] = route.public_id
input_aliases = cast(dict[str, str], route.metadata.get("input_aliases") or {})
for file_result in rewritten.get("files") or []:
@@ -224,7 +242,12 @@ def rewrite_job_payload(
if alias is not None:
file_result["file_id"] = alias
else:
- file_route = registry.register("file", worker_id=worker.worker_id, upstream_id=upstream_file_id)
+ file_route = registry.register(
+ "file",
+ owner_scope=owner_scope,
+ worker_id=worker.worker_id,
+ upstream_id=upstream_file_id,
+ )
file_result["file_id"] = file_route.public_id
output_files = file_result.get("output_files")
if isinstance(output_files, dict):
@@ -233,6 +256,7 @@ def rewrite_job_payload(
continue
output_route = registry.register(
"file",
+ owner_scope=owner_scope,
worker_id=worker.worker_id,
upstream_id=output["file_id"],
)
diff --git a/mineru/kit/router/resources.py b/mineru/kit/router/resources.py
index 4149b7fa..207748bb 100644
--- a/mineru/kit/router/resources.py
+++ b/mineru/kit/router/resources.py
@@ -32,6 +32,7 @@ class ResourceRoute:
kind: ResourceKind
public_id: str
+ owner_scope: str
worker_id: str
upstream_id: str
created_at: str = field(default_factory=utc_now_iso)
@@ -53,6 +54,7 @@ class CopiedInputFile:
"""记录一个 Job 为 cross-worker 执行创建的目标 worker 输入副本。"""
source_public_id: str
+ owner_scope: str
worker_id: str
upstream_file_id: str
@@ -159,19 +161,20 @@ class ResourceRegistry:
"file": {},
"job": {},
}
- self._by_upstream: dict[tuple[ResourceKind, str, str], ResourceRoute] = {}
+ self._by_upstream: dict[tuple[ResourceKind, str, str, str], ResourceRoute] = {}
def register(
self,
kind: ResourceKind,
*,
+ owner_scope: str,
worker_id: str,
upstream_id: str,
metadata: dict[str, Any] | None = None,
public_id: str | None = None,
) -> ResourceRoute:
"""注册资源并复用同一 worker/upstream 标识已有的公共映射。"""
- upstream_key = (kind, worker_id, upstream_id)
+ upstream_key = (kind, owner_scope, worker_id, upstream_id)
existing = self._by_upstream.get(upstream_key)
if existing is not None:
if metadata is not None:
@@ -182,6 +185,7 @@ class ResourceRegistry:
route = ResourceRoute(
kind=kind,
public_id=resolved_public_id,
+ owner_scope=owner_scope,
worker_id=worker_id,
upstream_id=upstream_id,
metadata=dict(metadata or {}),
@@ -198,27 +202,43 @@ class ResourceRegistry:
"""按公共标识读取资源路由,不存在时返回 None。"""
return self._by_public[kind].get(public_id)
- def find_upstream(self, kind: ResourceKind, worker_id: str, upstream_id: str) -> ResourceRoute | None:
+ def find_upstream(
+ self,
+ kind: ResourceKind,
+ owner_scope: str,
+ worker_id: str,
+ upstream_id: str,
+ ) -> ResourceRoute | None:
"""按 worker 与 upstream 标识读取已有公共映射。"""
- return self._by_upstream.get((kind, worker_id, upstream_id))
+ return self._by_upstream.get((kind, owner_scope, worker_id, upstream_id))
def alias_upstream(self, route: ResourceRoute, *, worker_id: str, upstream_id: str) -> None:
"""把同一公共资源在另一 worker 中的复制标识绑定到现有记录。"""
- self._by_upstream[(route.kind, worker_id, upstream_id)] = route
+ self._by_upstream[(route.kind, route.owner_scope, worker_id, upstream_id)] = route
- def remove_upstream_alias(self, kind: ResourceKind, *, worker_id: str, upstream_id: str) -> None:
+ def remove_upstream_alias(
+ self,
+ kind: ResourceKind,
+ *,
+ owner_scope: str,
+ worker_id: str,
+ upstream_id: str,
+ ) -> None:
"""删除 cross-worker 副本对应的反向 alias,不影响公共资源主映射。"""
- self._by_upstream.pop((kind, worker_id, upstream_id), None)
+ self._by_upstream.pop((kind, owner_scope, worker_id, upstream_id), None)
- def list(self, kind: ResourceKind) -> list[ResourceRoute]:
- """按注册顺序返回指定类型的全部资源路由。"""
- return list(self._by_public[kind].values())
+ def list(self, kind: ResourceKind, *, owner_scope: str | None = None) -> list[ResourceRoute]:
+ """按注册顺序返回指定类型、可选调用方 scope 的资源路由。"""
+ routes = list(self._by_public[kind].values())
+ if owner_scope is None:
+ return routes
+ return [route for route in routes if route.owner_scope == owner_scope]
def remove(self, kind: ResourceKind, public_id: str) -> ResourceRoute | None:
"""删除公共资源及其反向索引,并返回被删除的记录。"""
route = self._by_public[kind].pop(public_id, None)
if route is not None:
- self._by_upstream.pop((kind, route.worker_id, route.upstream_id), None)
+ self._by_upstream.pop((kind, route.owner_scope, route.worker_id, route.upstream_id), None)
return route
@staticmethod
diff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.py
index e1440610..cce7a32c 100644
--- a/mineru/kit/router/workers.py
+++ b/mineru/kit/router/workers.py
@@ -55,6 +55,23 @@ def worker_base_url(bind_host: str, port: int) -> str:
return f"http://{authority}:{port}"
+def accelerator_device_count(device: str) -> int:
+ """惰性读取指定加速器 runtime 当前可见的设备数量。"""
+ try:
+ if device == "npu":
+ import torch_npu
+
+ return int(torch_npu.npu.device_count())
+ import torch
+
+ accelerator = torch.cuda if device == "cuda" else getattr(torch, device, None)
+ if accelerator is None or not hasattr(accelerator, "device_count"):
+ return 0
+ return int(accelerator.device_count())
+ except (ImportError, AttributeError, RuntimeError, TypeError, ValueError):
+ return 0
+
+
def reserve_local_port(host: str) -> int:
"""在指定 host 上申请一个当前可用的本地 TCP 端口。"""
bind_host = str(host).strip() or "127.0.0.1"
@@ -80,14 +97,23 @@ def parse_local_gpus(value: str) -> list[str | None]:
for env_name in ("CUDA_VISIBLE_DEVICES", "ASCEND_RT_VISIBLE_DEVICES"):
configured = os.getenv(env_name)
if configured:
- devices = [item.strip() for item in configured.split(",") if item.strip() and item.strip() != "-1"]
+ normalized_config = configured.strip().lower()
+ if normalized_config == "all":
+ break
+ devices = [
+ item.strip()
+ for item in configured.split(",")
+ if item.strip() and item.strip().lower() not in {"-1", "none", "void"}
+ ]
if devices:
return devices
+ return [None]
device = get_device().split(":", 1)[0]
if device in {"cpu", "mps"}:
return [None]
- return ["0"]
+ device_count = accelerator_device_count(device)
+ return [str(index) for index in range(device_count)] if device_count > 0 else ["0"]
def visible_device_env_name() -> str:
@@ -456,6 +482,7 @@ class WorkerPool:
__all__ = [
+ "accelerator_device_count",
"ManagedLocalWorker",
"RouterSettings",
"WorkerPool",
diff --git a/tests/unittest/test_v1_router.py b/tests/unittest/test_v1_router.py
index 4a36a102..c8b47ee1 100644
--- a/tests/unittest/test_v1_router.py
+++ b/tests/unittest/test_v1_router.py
@@ -13,7 +13,7 @@ import pytest
from fastapi.testclient import TestClient
from mineru.kit.router import RouterSettings, create_app
-from mineru.kit.router.workers import ManagedLocalWorker, worker_base_url, worker_connect_host
+from mineru.kit.router.workers import ManagedLocalWorker, parse_local_gpus, worker_base_url, worker_connect_host
from mineru.parser.api_server import create_app as create_api_server_app
@@ -301,15 +301,36 @@ def _upload_file(client: TestClient, *, token: str, content: bytes) -> str:
return complete.json()["file"]["id"]
-def _upload_files_on_distinct_workers(client: TestClient, router_app: Any) -> list[str]:
- """上传文件直到获得分别归属两个 worker 的公共 file IDs。"""
+def _upload_files_on_distinct_workers(
+ client: TestClient,
+ router_app: Any,
+ *,
+ token: str,
+) -> list[str]:
+ """在同一 caller scope 下轮换 upload worker,获得跨 worker 文件。"""
+ pool = router_app.state.worker_pool
+ original_select = pool.select
+ healthy_workers = pool.healthy_workers()
+ upload_index = 0
+
+ def _alternating_select(**kwargs: Any) -> Any:
+ """仅对带 affinity 的 Upload 选择轮换 worker,其他选择保持生产逻辑。"""
+ nonlocal upload_index
+ if kwargs.get("tier") is None and kwargs.get("affinity_key"):
+ worker = healthy_workers[upload_index % len(healthy_workers)]
+ upload_index += 1
+ return worker
+ return original_select(**kwargs)
+
+ pool.select = _alternating_select
files_by_worker: dict[str, str] = {}
- for index in range(20):
- public_file_id = _upload_file(client, token=f"distinct-{index}", content=f"pdf-{index}".encode())
- route = router_app.state.registry.get("file", public_file_id)
- files_by_worker.setdefault(route.worker_id, public_file_id)
- if len(files_by_worker) == 2:
- break
+ try:
+ for index in range(2):
+ public_file_id = _upload_file(client, token=token, content=f"pdf-{index}".encode())
+ route = router_app.state.registry.get("file", public_file_id)
+ files_by_worker.setdefault(route.worker_id, public_file_id)
+ finally:
+ pool.select = original_select
assert len(files_by_worker) == 2
return list(files_by_worker.values())
@@ -320,6 +341,7 @@ def test_v1_router_aggregates_capabilities_and_routes_cross_worker_job() -> None
second = _FakeV1Upstream("worker-b", ("standard", "advanced"))
router_app, _ = _make_router(first, second)
staged_path: Path | None = None
+ headers = {"authorization": "Bearer main-cross-worker"}
with TestClient(router_app) as client:
health = client.get("/v1/health")
@@ -332,15 +354,11 @@ def test_v1_router_aggregates_capabilities_and_routes_cross_worker_job() -> None
assert [item["id"] for item in tiers.json()["data"]] == ["basic", "standard", "advanced"]
assert {item["id"] for item in models.json()["data"]} == {"worker-a-model", "worker-b-model"}
- files_by_worker: dict[str, str] = {}
- for index in range(20):
- public_file_id = _upload_file(client, token=f"user-{index}", content=f"pdf-{index}".encode())
- route = router_app.state.registry.get("file", public_file_id)
- files_by_worker.setdefault(route.worker_id, public_file_id)
- if len(files_by_worker) == 2:
- break
- assert len(files_by_worker) == 2
- public_file_ids = list(files_by_worker.values())
+ public_file_ids = _upload_files_on_distinct_workers(
+ client,
+ router_app,
+ token="main-cross-worker",
+ )
stored = router_app.state.source_store.find_file(public_file_ids[0])
assert stored is not None
staged_path = stored.path
@@ -348,6 +366,7 @@ def test_v1_router_aggregates_capabilities_and_routes_cross_worker_job() -> None
created = client.post(
"/v1/parse/jobs",
+ headers=headers,
json={
"tier": "standard",
"files": [{"source": {"type": "file_id", "file_id": file_id}} for file_id in public_file_ids],
@@ -364,19 +383,19 @@ def test_v1_router_aggregates_capabilities_and_routes_cross_worker_job() -> None
target = first if job_route.worker_id == "remote-1" else second
assert copied_upstream_id in target.files
- completed = client.get(f"/v1/parse/jobs/{job_id}")
+ completed = client.get(f"/v1/parse/jobs/{job_id}", headers=headers)
assert completed.status_code == 200
assert completed.json()["status"] == "completed"
assert [item["file_id"] for item in completed.json()["files"]] == public_file_ids
output_id = completed.json()["files"][0]["output_files"]["markdown"]["file_id"]
assert output_id.startswith("file-")
- assert client.get(f"/v1/files/{output_id}/content").content == b"result"
+ assert client.get(f"/v1/files/{output_id}/content", headers=headers).content == b"result"
assert job_route.metadata.get("copied_inputs") is None
assert copied_upstream_id not in target.files
- job_list = client.get("/v1/parse/jobs").json()
- file_list = client.get("/v1/files").json()
- usage = client.get("/v1/usage").json()
+ job_list = client.get("/v1/parse/jobs", headers=headers).json()
+ file_list = client.get("/v1/files", headers=headers).json()
+ usage = client.get("/v1/usage", headers=headers).json()
assert [item["job_id"] for item in job_list["data"]] == [job_id]
assert {item["id"] for item in file_list["data"]}.issuperset(set(public_file_ids))
assert output_id in {item["id"] for item in file_list["data"]}
@@ -489,19 +508,21 @@ def test_terminal_job_read_survives_deleted_output_metadata() -> None:
"""验证 output 删除后 hydration 失败不会阻断 completed Job 读取。"""
upstream = _FakeV1Upstream("worker-a", ("standard",))
router_app, _ = _make_router(upstream)
+ headers = {"authorization": "Bearer output-delete"}
with TestClient(router_app) as client:
file_id = _upload_file(client, token="output-delete", content=b"pdf")
created = client.post(
"/v1/parse/jobs",
+ headers=headers,
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}")
+ completed = client.get(f"/v1/parse/jobs/{job_id}", headers=headers)
output_id = completed.json()["files"][0]["output_files"]["markdown"]["file_id"]
- assert client.delete(f"/v1/files/{output_id}").status_code == 200
+ assert client.delete(f"/v1/files/{output_id}", headers=headers).status_code == 200
- reread = client.get(f"/v1/parse/jobs/{job_id}")
+ reread = client.get(f"/v1/parse/jobs/{job_id}", headers=headers)
assert reread.status_code == 200
assert reread.json()["status"] == "completed"
@@ -510,16 +531,84 @@ def test_terminal_job_read_survives_deleted_output_metadata() -> None:
assert replacement_route.metadata["hydration_error"]["status_code"] == 404
+def test_router_scopes_cached_resources_to_bearer_identity() -> None:
+ """验证 files、jobs、usage 与单资源访问按 bearer caller scope 隔离。"""
+ upstream = _FakeV1Upstream("worker-a", ("standard",))
+ router_app, _ = _make_router(upstream)
+ owner_headers = {"authorization": "Bearer tenant-a"}
+ other_headers = {"authorization": "Bearer tenant-b"}
+
+ with TestClient(router_app) as client:
+ file_id = _upload_file(client, token="tenant-a", content=b"pdf")
+ created = client.post(
+ "/v1/parse/jobs",
+ headers=owner_headers,
+ json={"tier": "standard", "files": [{"source": {"type": "file_id", "file_id": file_id}}]},
+ )
+ job_id = created.json()["job_id"]
+
+ assert [item["id"] for item in client.get("/v1/files", headers=owner_headers).json()["data"]] == [file_id]
+ assert [item["job_id"] for item in client.get("/v1/parse/jobs", headers=owner_headers).json()["data"]] == [job_id]
+ assert client.get("/v1/files", headers=other_headers).json()["data"] == []
+ assert client.get("/v1/parse/jobs", headers=other_headers).json()["data"] == []
+ assert client.get("/v1/files").json()["data"] == []
+ assert client.get("/v1/parse/jobs").json()["data"] == []
+ assert client.get("/v1/usage", headers=other_headers).json()["current"]["jobs_created"] == 0
+ assert client.get(f"/v1/files/{file_id}", headers=other_headers).status_code == 404
+ assert client.get(f"/v1/parse/jobs/{job_id}", headers=other_headers).status_code == 404
+
+
+def test_background_reconciler_finalizes_unpolled_cross_worker_job() -> None:
+ """验证无客户端轮询时后台 reconciliation 仍归还负载并回收副本。"""
+ first = _FakeV1Upstream("worker-a", ("standard",))
+ second = _FakeV1Upstream("worker-b", ("standard",))
+ router_app, _ = _make_router(first, second)
+ headers = {"authorization": "Bearer reconcile"}
+
+ with TestClient(router_app) as client:
+ file_ids = _upload_files_on_distinct_workers(client, router_app, token="reconcile")
+ created = client.post(
+ "/v1/parse/jobs",
+ headers=headers,
+ json={
+ "tier": "standard",
+ "files": [{"source": {"type": "file_id", "file_id": file_id}} for file_id in file_ids],
+ },
+ )
+ job_id = created.json()["job_id"]
+ route = router_app.state.registry.get("job", job_id)
+ worker = first if route.worker_id == "remote-1" else second
+ copied = list(route.metadata["copied_inputs"])
+
+ client.portal.call(router_app.state.reconcile_jobs_once)
+
+ assert route.metadata["payload"]["status"] == "completed"
+ assert route.metadata.get("active_counted") is None
+ assert route.metadata.get("copied_inputs") is None
+ assert route.metadata.get("upstream_headers") is None
+ assert router_app.state.worker_pool.get(route.worker_id).active_jobs == 0
+ assert copied[0].upstream_file_id not in worker.files
+ listed_ids = {item["id"] for item in client.get("/v1/files", headers=headers).json()["data"]}
+ output_id = route.metadata["payload"]["files"][0]["output_files"]["markdown"]["file_id"]
+ assert output_id in listed_ids
+
+
def test_router_reclaims_cross_worker_copy_when_job_is_canceled() -> None:
"""验证取消 Job 时立即删除并解除 cross-worker 输入副本。"""
first = _FakeV1Upstream("worker-a", ("standard",))
second = _FakeV1Upstream("worker-b", ("standard",))
router_app, _ = _make_router(first, second)
+ headers = {"authorization": "Bearer cancel-cross-worker"}
with TestClient(router_app) as client:
- public_file_ids = _upload_files_on_distinct_workers(client, router_app)
+ public_file_ids = _upload_files_on_distinct_workers(
+ client,
+ router_app,
+ token="cancel-cross-worker",
+ )
created = client.post(
"/v1/parse/jobs",
+ headers=headers,
json={
"tier": "standard",
"files": [{"source": {"type": "file_id", "file_id": file_id}} for file_id in public_file_ids],
@@ -532,7 +621,7 @@ def test_router_reclaims_cross_worker_copy_when_job_is_canceled() -> None:
target = first if copied[0].worker_id == "remote-1" else second
assert copied[0].upstream_file_id in target.files
- canceled = client.delete(f"/v1/parse/jobs/{job_id}")
+ canceled = client.delete(f"/v1/parse/jobs/{job_id}", headers=headers)
assert canceled.status_code == 200
assert copied[0].upstream_file_id not in target.files
@@ -540,6 +629,7 @@ def test_router_reclaims_cross_worker_copy_when_job_is_canceled() -> None:
assert (
router_app.state.registry.find_upstream(
"file",
+ copied[0].owner_scope,
copied[0].worker_id,
copied[0].upstream_file_id,
)
@@ -552,11 +642,17 @@ def test_public_source_delete_retries_terminal_copy_cleanup() -> None:
first = _FakeV1Upstream("worker-a", ("standard",))
second = _FakeV1Upstream("worker-b", ("standard",))
router_app, _ = _make_router(first, second)
+ headers = {"authorization": "Bearer delete-retry"}
with TestClient(router_app) as client:
- public_file_ids = _upload_files_on_distinct_workers(client, router_app)
+ public_file_ids = _upload_files_on_distinct_workers(
+ client,
+ router_app,
+ token="delete-retry",
+ )
created = client.post(
"/v1/parse/jobs",
+ headers=headers,
json={
"tier": "standard",
"files": [{"source": {"type": "file_id", "file_id": file_id}} for file_id in public_file_ids],
@@ -568,12 +664,12 @@ def test_public_source_delete_retries_terminal_copy_cleanup() -> None:
target = first if copied[0].worker_id == "remote-1" else second
target.fail_file_delete_once.add(copied[0].upstream_file_id)
- completed = client.get(f"/v1/parse/jobs/{job_id}")
+ completed = client.get(f"/v1/parse/jobs/{job_id}", headers=headers)
assert completed.status_code == 200
assert copied[0].upstream_file_id in target.files
assert job_route.metadata.get("copied_inputs") == copied
- deleted = client.delete(f"/v1/files/{copied[0].source_public_id}")
+ deleted = client.delete(f"/v1/files/{copied[0].source_public_id}", headers=headers)
assert deleted.status_code == 200
assert copied[0].upstream_file_id not in target.files
@@ -647,6 +743,34 @@ def test_managed_worker_formats_connectable_ipv4_and_ipv6_urls(
assert worker_base_url(bind_host, 18000) == expected_url
+def test_auto_local_gpus_expands_visible_accelerator_count(monkeypatch: pytest.MonkeyPatch) -> None:
+ """验证 auto 在无显式设备 CSV 或值为 all 时枚举全部可见 GPU。"""
+ import mineru.kit.router.workers as workers
+
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising=False)
+ monkeypatch.delenv("ASCEND_RT_VISIBLE_DEVICES", raising=False)
+ monkeypatch.setattr(workers, "get_device", lambda: "cuda")
+ monkeypatch.setattr(workers, "accelerator_device_count", lambda _device: 4)
+ assert parse_local_gpus("auto") == ["0", "1", "2", "3"]
+
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "2,4")
+ assert parse_local_gpus("auto") == ["2", "4"]
+
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "all")
+ monkeypatch.setattr(workers, "accelerator_device_count", lambda _device: 3)
+ assert parse_local_gpus("auto") == ["0", "1", "2"]
+
+
+def test_compose_router_healthcheck_uses_v1_path() -> None:
+ """验证 Router Compose profile 只探测正式 `/v1/health`。"""
+ repo_root = Path(__file__).resolve().parents[2]
+ compose_text = (repo_root / "docker/compose.yaml").read_text(encoding="utf-8")
+ router_section = compose_text.split(" mineru-router:", 1)[1].split(" mineru-gradio:", 1)[0]
+
+ assert "http://localhost:8002/v1/health" in router_section
+ assert "http://localhost:8002/health" not in router_section
+
+
def test_managed_router_worker_uses_control_shutdown() -> None:
"""验证托管 worker 优先通过 ManagedProcessControl 正常退出。"""