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
Expire terminal resources with shared blob leases and Router cache collection; Refs #5495
myhloli56f90f988311
diff --git a/mineru/kit/router/app.py b/mineru/kit/router/app.pyindex c4c54b88..95f255d4 100644--- a/mineru/kit/router/app.py+++ b/mineru/kit/router/app.py@@ -46,6 +46,7 @@ from .resources import (SourceFileStore,stored_file_chunks,)+from ...utils.retention import RETENTION_SCAN_INTERVAL_SECONDSfrom .workers import RouterSettings, WorkerPool, WorkerState@@ -306,6 +307,7 @@ async def _finalize_terminal_job("""在 Job 终态补齐 outputs,并回收或保留待重试的输入副本。"""if payload.get("status") not in {"completed", "partial", "failed", "canceled"}:return+ route.metadata.setdefault("terminal_at", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))try:await _hydrate_job_output_files(payload,@@ -332,7 +334,7 @@ async def _finalize_terminal_job(async def _reconcile_jobs_once(registry: ResourceRegistry, pool: WorkerPool) -> None:"""后台查询活动或待清理 Job,并统一执行终态资源收敛。"""- for route in registry.list("job"):+ for route in registry.list("job", include_expired=True):if not route.metadata.get("active_counted") and not route.metadata.get("copied_inputs"):continueworker = pool.get(route.worker_id)@@ -346,6 +348,9 @@ async def _reconcile_jobs_once(registry: ResourceRegistry, pool: WorkerPool) ->headers=headers,)if response.status_code >= 400:+ cached = route.metadata.get("payload") or {}+ if response.status_code == 404 and cached.get("status") in {"completed", "partial", "failed", "canceled"}:+ await _finalize_terminal_job(route, cached, request=None, pool=pool, registry=registry, headers=headers)continuepayload = json_or_error(response)rewritten = rewrite_job_payload(payload, worker, registry, pool, route.owner_scope)@@ -380,8 +385,8 @@ def create_app() -> FastAPI:"""创建完整代理 MinerU V1 资源面的 Router FastAPI 应用。"""resolved_settings = settings or RouterSettings.from_env()- registry = ResourceRegistry()- source_store = SourceFileStore()+ registry = ResourceRegistry(resolved_settings.retention_seconds)+ source_store = SourceFileStore(resolved_settings.retention_seconds)async def _invalidate_replaced_worker(worker: WorkerState) -> None:"""在本地 worker replacement 发布前移除旧 generation 的资源状态。"""@@ -420,7 +425,17 @@ def create_app("""启动 worker pool,并在应用关闭时释放全部网络和子进程资源。"""application.state.started_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())reconcile_task: asyncio.Task[None] | None = None+ collection_task: asyncio.Task[None] | None = None++ async def collection_loop() -> None:+ """每五分钟同步回收过期公共路由与无引用源文件缓存。"""+ while True:+ await asyncio.sleep(RETENTION_SCAN_INTERVAL_SECONDS)+ registry.collect_expired(source_store)+try:+ if resolved_settings.retention_seconds:+ collection_task = asyncio.create_task(collection_loop(), name="mineru-router-retention")await pool.start()if resolved_settings.worker_refresh_interval_seconds > 0:reconcile_task = asyncio.create_task(@@ -433,6 +448,9 @@ def create_app()yieldfinally:+ if collection_task is not None:+ collection_task.cancel()+ await asyncio.gather(collection_task, return_exceptions=True)if reconcile_task is not None:reconcile_task.cancel()try:@@ -545,7 +563,12 @@ def create_app(cached, str(body.get("filename") or "input.bin"), worker, request=request, pool=pool, declaration=body)rewritten = rewrite_upload_payload(result, worker, registry, owner_scope)- source_store.bind_source(str(rewritten["file"]["id"]), cached, owner_scope=owner_scope)+ source_store.bind_source(+ str(rewritten["file"]["id"]),+ cached,+ owner_scope=owner_scope,+ expires_at=rewritten["file"].get("expires_at"),+ )return JSONResponse(rewritten)upstream_body = dict(body)# 本地未命中时必须收到源字节;仅凭 worker 的 blob 命中无法支持跨 worker 复制。@@ -580,41 +603,42 @@ def create_app(async def upload_content(upload_id: str, request: Request) -> Response:"""把上传内容流式暂存到 Router,再写入 upload 所属 worker。"""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":- 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")- 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)- raise RouterProxyError(- 400,- "upload_size_mismatch",- f"Expected {declared_bytes} upload bytes, received {stored.bytes}",+ with registry.pin_route(route):+ 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")+ 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)+ raise RouterProxyError(+ 400,+ "upload_size_mismatch",+ f"Expected {declared_bytes} upload bytes, received {stored.bytes}",+ )+ declared_sha256 = declared.get("sha256sum")+ if isinstance(declared_sha256, str) and stored.sha256sum != declared_sha256:+ source_store.discard_upload(upload_id)+ raise RouterProxyError(400, "upload_sha256_mismatch", "Uploaded content SHA256 does not match request")+ upstream = await request_upstream(+ pool,+ worker,+ "PUT",+ f"/v1/uploads/{route.upstream_id}/content",+ request=request,+ content=stored_file_chunks(stored.path),+ headers={"content-type": "application/octet-stream"},)- declared_sha256 = declared.get("sha256sum")- if isinstance(declared_sha256, str) and stored.sha256sum != declared_sha256:- source_store.discard_upload(upload_id)- raise RouterProxyError(400, "upload_sha256_mismatch", "Uploaded content SHA256 does not match request")- upstream = await request_upstream(- pool,- worker,- "PUT",- f"/v1/uploads/{route.upstream_id}/content",- request=request,- content=stored_file_chunks(stored.path),- headers={"content-type": "application/octet-stream"},- )- return passthrough_response(upstream)+ return passthrough_response(upstream)@application.post("/v1/uploads/{upload_id}/complete")async def complete_upload(upload_id: str, request: Request) -> Response:@@ -642,7 +666,9 @@ def create_app(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")- source_store.bind_file(upload_id, file_payload["id"], owner_scope=owner_scope)+ source_store.bind_file(+ upload_id, file_payload["id"], owner_scope=owner_scope, expires_at=file_payload.get("expires_at")+ )return JSONResponse(rewritten, status_code=upstream.status_code)@application.post("/v1/uploads/{upload_id}/cancel")@@ -856,7 +882,7 @@ def create_app(public_id = str(rewritten["id"])route = _route_or_404(registry, "file", public_id, owner_scope)registered_inputs.append(route)- source_store.bind_source(public_id, stored, owner_scope=owner_scope)+ source_store.bind_source(public_id, stored, owner_scope=owner_scope, expires_at=rewritten.get("expires_at"))input_aliases[route.upstream_id] = public_idfiles[index]["source"] = {"type": "file_id", "file_id": route.upstream_id}for source, route in file_routes:diff --git a/mineru/kit/router/cli.py b/mineru/kit/router/cli.pyindex 335ce6f4..a71f5aef 100644--- a/mineru/kit/router/cli.py+++ b/mineru/kit/router/cli.py@@ -30,6 +30,13 @@ def router_cmd(worker_host: str = typer.Option("127.0.0.1", "--worker-host", help=t("Host for managed api-server workers")),worker_tier: str = typer.Option("standard", "--worker-tier", help=t("Managed worker tier: flash, basic, standard")),worker_concurrency: int = typer.Option(1, "--worker-concurrency", help=t("Concurrency per managed worker")),+ retention_seconds: int | None = typer.Option(+ None,+ "--retention-seconds",+ min=0,+ envvar="MINERU_API_RETENTION_SECONDS",+ help="Terminal retention seconds (default 86400; 0 disables collection)",+ ),preload_models: bool = typer.Option(False, "--preload-models", help=t("Preload models in managed workers")),) -> None:"""启动只暴露 MinerU V1 API 的独立 Router 服务。"""@@ -51,6 +58,7 @@ def router_cmd(worker_tier=cast(ServerTier, worker_tier),worker_concurrency=worker_concurrency,preload_models=preload_models,+ retention_seconds=retention_seconds,)except ValueError as exc:exit_with_message("invalid_request", str(exc))diff --git a/mineru/kit/router/resources.py b/mineru/kit/router/resources.pyindex 471acefb..cd6f6460 100644--- a/mineru/kit/router/resources.py+++ b/mineru/kit/router/resources.py@@ -6,12 +6,14 @@ from __future__ import annotationsimport hashlibimport secretsimport tempfile+import timefrom collections.abc import AsyncIteratorfrom contextlib import contextmanagerfrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterator, Literal+from ...utils.retention import resolve_retention_secondsResourceKind = Literal["upload", "file", "job"]@@ -63,10 +65,12 @@ class CopiedInputFile:class SourceFileStore:"""在 Router 临时目录中保存可供 cross-worker 重传的输入字节。"""- def __init__(self) -> None:+ def __init__(self, retention_seconds: int = 86400) -> None:"""创建由当前 Router 进程独占并在关闭时清理的临时目录。"""self._temp_dir = tempfile.TemporaryDirectory(prefix="mineru-v1-router-sources-")self._root = Path(self._temp_dir.name)+ self.retention_seconds = retention_seconds+ self._file_expiry: dict[str, int | None] = {}self._uploads: dict[str, StoredSourceFile] = {}self._files: dict[str, StoredSourceFile] = {}self._bound_uploads: set[str] = set()@@ -115,14 +119,16 @@ class SourceFileStore:previous.path.unlink(missing_ok=True)return stored- def bind_file(self, upload_id: str, file_id: str, *, owner_scope: str = "anonymous") -> StoredSourceFile:+ def bind_file(+ self, upload_id: str, file_id: str, *, owner_scope: str = "anonymous", expires_at: int | None = None+ ) -> StoredSourceFile:"""把已完成 Upload 的暂存输入绑定到 Router 公共 File。"""stored = self._uploads.pop(upload_id)- self.bind_source(file_id, stored, owner_scope=owner_scope)+ self.bind_source(file_id, stored, owner_scope=owner_scope, expires_at=expires_at)self._bound_uploads.add(upload_id)return stored- def bind_source(self, file_id: str, stored: StoredSourceFile, *, owner_scope: str) -> None:+ def bind_source(self, file_id: str, stored: StoredSourceFile, *, owner_scope: str, expires_at: int | None = None) -> None:"""为公共文件增加缓存引用,并建立调用方隔离的哈希索引。"""previous = self._files.get(file_id)if previous is not None:@@ -132,6 +138,11 @@ class SourceFileStore:ids.discard(file_id)if not ids:self._hash_files.pop(previous_key, None)+ self._file_expiry[file_id] = (+ expires_at+ if expires_at is not None+ else (int(time.time()) + self.retention_seconds if self.retention_seconds else None)+ )self._files[file_id] = storedself._file_scopes[file_id] = owner_scopeself._hash_files.setdefault((owner_scope, stored.sha256sum), set()).add(file_id)@@ -142,7 +153,8 @@ class SourceFileStore:"""只查当前调用方仍持有的源字节,不使用 worker 的哈希声明。"""for file_id in sorted(self._hash_files.get((owner_scope, sha256sum), set())):stored = self._files.get(file_id)- if stored is not None and stored.path.is_file():+ deadline = self._file_expiry.get(file_id)+ if stored is not None and (deadline is None or deadline > time.time()) and stored.path.is_file():return storedreturn None@@ -181,6 +193,7 @@ class SourceFileStore:def discard_upload(self, upload_id: str) -> None:"""删除取消或失败 Upload 的私有暂存输入。"""if upload_id in self._bound_uploads:+ self._bound_uploads.discard(upload_id)returnstored = self._uploads.pop(upload_id, None)if stored is not None:@@ -188,6 +201,7 @@ class SourceFileStore:def delete_file(self, file_id: str) -> None:"""删除公共 File 绑定的私有暂存输入。"""+ self._file_expiry.pop(file_id, None)stored = self._files.pop(file_id, None)if stored is not None:scope = self._file_scopes.pop(file_id, "anonymous")@@ -204,6 +218,7 @@ class SourceFileStore:self._files.clear()self._bound_uploads.clear()self._file_scopes.clear()+ self._file_expiry.clear()self._hash_files.clear()self._pins.clear()self._temp_dir.cleanup()@@ -219,8 +234,9 @@ async def stored_file_chunks(path: Path, chunk_size: int = 1024 * 1024) -> Asyncclass ResourceRegistry:"""维护当前 Router 进程创建或发现的 uploads、files 与 jobs。"""- def __init__(self) -> None:+ def __init__(self, retention_seconds: int | None = None) -> None:"""初始化按公共标识和 upstream 标识建立的双向索引。"""+ self.retention_seconds = resolve_retention_seconds(retention_seconds)self._by_public: dict[ResourceKind, dict[str, ResourceRoute]] = {"upload": {},"file": {},@@ -259,13 +275,75 @@ class ResourceRegistry:self._by_upstream[upstream_key] = routereturn route+ @contextmanager+ def pin_route(self, route: ResourceRoute) -> Iterator[None]:+ """资源流式写入或复制期间保留路由;到期后新的请求仍不可访问。"""+ route.metadata["pins"] = route.metadata.get("pins", 0) + 1+ try:+ yield+ finally:+ route.metadata["pins"] -= 1+ if not route.metadata["pins"]:+ route.metadata.pop("pins")++ def is_expired(self, route: ResourceRoute) -> bool:+ """优先沿用上游显式期限;任务从清理完成时间开始计算保留期限。"""+ payload = route.metadata.get("payload") or {}+ if route.kind == "job":+ if payload.get("status") not in {"completed", "partial", "failed", "canceled"}:+ return False+ if not self.retention_seconds:+ return False+ origin = payload.get("finished_at") or route.metadata.get("terminal_at")+ if origin is None:+ route.metadata["terminal_at"] = utc_now_iso()+ origin = route.metadata["terminal_at"]+ else:+ explicit = payload.get("expires_at")+ if isinstance(explicit, (int, float)):+ return explicit <= time.time()+ if not self.retention_seconds:+ return False+ origin = route.created_at+ try:+ stamp = datetime.fromisoformat(str(origin).replace("Z", "+00:00")).timestamp()+ except ValueError:+ return False+ return stamp + self.retention_seconds <= time.time()++ def collect_expired(self, sources: SourceFileStore) -> None:+ """同步清理路由和源缓存,运行或待回收副本仍持有的文件暂不物理删除。"""+ protected: set[str] = set()+ for route in self._by_public["job"].values():+ payload = route.metadata.get("payload") or {}+ if payload.get("status") not in {"completed", "partial", "failed", "canceled"} or route.metadata.get(+ "copied_inputs"+ ):+ protected.update(file.get("file_id") for file in payload.get("files", []) if file.get("file_id"))+ protected.update(copy.source_public_id for copy in route.metadata.get("copied_inputs", []))+ for kind, routes in self._by_public.items():+ for public_id, route in tuple(routes.items()):+ if (+ not self.is_expired(route)+ or public_id in protected+ or route.metadata.get("copied_inputs")+ or route.metadata.get("pins")+ ):+ continue+ self.remove(kind, public_id)+ if kind == "file":+ sources.delete_file(public_id)+ elif kind == "upload":+ sources.discard_upload(public_id)+def get(self, kind: ResourceKind, public_id: str) -> ResourceRoute:"""按公共标识读取资源路由,不存在时抛出 KeyError。"""return self._by_public[kind][public_id]def find(self, kind: ResourceKind, public_id: str) -> ResourceRoute | None:"""按公共标识读取资源路由,不存在时返回 None。"""- return self._by_public[kind].get(public_id)+ route = self._by_public[kind].get(public_id)+ return route if route is not None and not self.is_expired(route) else Nonedef find_upstream(self,@@ -292,9 +370,9 @@ class ResourceRegistry:"""删除 cross-worker 副本对应的反向 alias,不影响公共资源主映射。"""self._by_upstream.pop((kind, owner_scope, worker_id, upstream_id), None)- def list(self, kind: ResourceKind, *, owner_scope: str | None = None) -> list[ResourceRoute]:+ def list(self, kind: ResourceKind, *, owner_scope: str | None = None, include_expired: bool = False) -> list[ResourceRoute]:"""按注册顺序返回指定类型、可选调用方 scope 的资源路由。"""- routes = list(self._by_public[kind].values())+ routes = [route for route in self._by_public[kind].values() if include_expired or not self.is_expired(route)]if owner_scope is None:return routesreturn [route for route in routes if route.owner_scope == owner_scope]@@ -303,7 +381,9 @@ class ResourceRegistry:"""删除公共资源及其反向索引,并返回被删除的记录。"""route = self._by_public[kind].pop(public_id, None)if route is not None:- self._by_upstream.pop((kind, route.owner_scope, route.worker_id, route.upstream_id), None)+ for key, value in tuple(self._by_upstream.items()):+ if value is route:+ self._by_upstream.pop(key)return routedef remove_worker(self, worker_id: str) -> list[ResourceRoute]:diff --git a/mineru/kit/router/tasks.py b/mineru/kit/router/tasks.pyindex f40e0fa3..a56b9732 100644--- a/mineru/kit/router/tasks.py+++ b/mineru/kit/router/tasks.py@@ -6,6 +6,7 @@ import asyncioimport jsonimport timefrom collections.abc import Awaitable, Callable+from contextlib import ExitStackfrom typing import Anyfrom fastapi import FastAPI, Request, Response@@ -58,11 +59,19 @@ class RouterTaskBackend:self.sources: SourceFileStore = request.app.state.source_storeself.registry: ResourceRegistry = request.app.state.registryself.pool: WorkerPool = request.app.state.worker_pool+ self._input_pins = ExitStack()++ def release_uploads(self) -> None:+ """关闭预检阶段持有的输入引用,传输或校验失败也会释放。"""+ self._input_pins.close()async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:"""只复用本调用方在 Router 中仍持有的源字节。"""stored = self.sources.find_hash(self.owner_scope, sha256sum)- return TaskUpload(stored.path, filename, stored.bytes, stored.sha256sum, stored.mime_type) if stored else None+ if stored is None:+ return None+ self._input_pins.enter_context(self.sources.pin(stored))+ return TaskUpload(stored.path, filename, stored.bytes, stored.sha256sum, stored.mime_type)async def submit(self, body: CreateJobRequest, uploads: dict[int, TaskUpload]) -> dict[str, Any]:"""委托共享提交服务,源字节传输也纳入相同的负载预占。"""diff --git a/mineru/kit/router/workers.py b/mineru/kit/router/workers.pyindex d8df7e23..98ad26b5 100644--- a/mineru/kit/router/workers.py+++ b/mineru/kit/router/workers.py@@ -23,6 +23,7 @@ from ...model.runtime.device import get_devicefrom ...parser.process_control import ManagedProcessControlfrom ...types import SERVER_TIERS, ServerTier, Tierfrom ...utils.stdio import utf8_subprocess_env+from ...utils.retention import resolve_retention_secondsDEFAULT_WORKER_REFRESH_INTERVAL_SECONDS = 2.0DEFAULT_WORKER_STARTUP_TIMEOUT_SECONDS = 300.0@@ -134,10 +135,12 @@ class RouterSettings:worker_tier: ServerTier = "standard"worker_concurrency: int = 1preload_models: bool = False+ retention_seconds: int | None = Noneworker_refresh_interval_seconds: float = DEFAULT_WORKER_REFRESH_INTERVAL_SECONDSdef __post_init__(self) -> None:"""校验 worker tier、并发数和刷新间隔。"""+ object.__setattr__(self, "retention_seconds", resolve_retention_seconds(self.retention_seconds))if self.worker_tier not in SERVER_TIERS:raise ValueError(f"Unsupported worker tier: {self.worker_tier}")if self.worker_concurrency <= 0:@@ -167,6 +170,7 @@ class RouterSettings:def apply_to_env(self) -> None:"""把 Router 配置写入 reload 子进程可读取的环境变量。"""+ os.environ["MINERU_API_RETENTION_SECONDS"] = str(self.retention_seconds)os.environ["MINERU_ROUTER_UPSTREAM_URLS_JSON"] = json.dumps(list(self.upstream_urls))os.environ["MINERU_ROUTER_LOCAL_GPUS"] = self.local_gpusos.environ["MINERU_ROUTER_WORKER_HOST"] = self.worker_host@@ -205,6 +209,8 @@ class ManagedLocalWorker:self.settings.worker_tier,"--concurrency",str(self.settings.worker_concurrency),+ "--retention-seconds",+ str(self.settings.retention_seconds),"--log-level","warning",*(["--preload-models"] if self.settings.preload_models else []),diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex a635725d..7a11cd39 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -11,6 +11,7 @@ import jsonimport loggingimport osimport pathlib+import reimport secretsimport shutilimport tempfile@@ -19,7 +20,7 @@ import timeimport zipfilefrom contextlib import asynccontextmanagerfrom copy import deepcopy-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Annotated, Any, AsyncIterator, Awaitable, Callable, Literal, NoReturn, TypedDictfrom urllib.parse import urlparse@@ -35,6 +36,8 @@ from fastapi_offline import FastAPIOfflinefrom fastapi.middleware.gzip import GZipMiddlewarefrom fastapi.responses import JSONResponsefrom fastapi.security import HTTPBearer+from filelock import FileLock, Timeout as FileLockTimeout+from ..utils.retention import resolve_retention_seconds, RETENTION_SCAN_INTERVAL_SECONDSfrom pydantic import BaseModel, ConfigDict, Fieldfrom starlette.datastructures import State@@ -642,18 +645,126 @@ class _FileRecord:sha256sum: str | None = Noneexpires_at: int | None = Noneupload_id: str | None = None+ job_id: str | None = Noneclass FileStore:"""Content-addressed blob storage with in-memory metadata."""- def __init__(self, root: pathlib.Path) -> None:+ def __init__(self, root: pathlib.Path, retention_seconds: int = 86400) -> None:+ self._lock = threading.RLock()+ self.retention_seconds = retention_seconds+ self._pins: dict[str, int] = {}+ self._job_output_pins: dict[str, set[str]] = {}+ self._owner_lock = FileLock(str(root / ".mineru-service.lock"))self._root = rootself._blobs = root / "blobs"self._blobs.mkdir(parents=True, exist_ok=True)self._uploads: dict[str, _UploadRecord] = {}self._files: dict[str, _FileRecord] = {}+ def claim_directory(self) -> None:+ """服务启动时独占上传目录,避免多个进程的内存元数据互相误删。"""+ try:+ self._owner_lock.acquire(timeout=0)+ except FileLockTimeout as exc:+ raise RuntimeError("Upload directory is already owned by another API service") from exc++ def release_directory(self) -> None:+ """关闭服务时释放目录占用,元数据仍只在本进程内维护。"""+ self._owner_lock.release()++ def acquire_inputs(self, file_ids: list[str]) -> dict[str, str]:+ """提交时一次性校验输入并取得 blob 租约,文件视图到期不影响排队任务。"""+ with self._lock:+ records = {file_id: self.get_file(file_id) for file_id in file_ids}+ values = {file_id: rec.sha256sum for file_id, rec in records.items() if rec.sha256sum is not None}+ for sha in values.values():+ self._pins[sha] = self._pins.get(sha, 0) + 1+ return values++ def release_inputs(self, values: dict[str, str]) -> None:+ """最后一个排队或运行任务退出后才释放共享输入引用。"""+ with self._lock:+ for sha in values.values():+ self._pins[sha] -= 1+ if not self._pins[sha]:+ self._pins.pop(sha)+ values.clear()++ def pin_cached_blob(self, sha: str) -> pathlib.Path | None:+ """哈希复用检查和取得传输引用保持原子性,过期视图不能被新请求复用。"""+ with self._lock:+ now = int(time.time())+ if not any(+ rec.sha256sum == sha and (rec.expires_at is None or rec.expires_at > now) for rec in self._files.values()+ ):+ return None+ path = self._blob_abs(sha)+ if not path.is_file():+ return None+ self._pins[sha] = self._pins.get(sha, 0) + 1+ return path++ def unpin_cached_blob(self, sha: str) -> None:+ """请求提交或校验失败后释放哈希预检的引用。"""+ with self._lock:+ self._pins[sha] -= 1+ if not self._pins[sha]:+ self._pins.pop(sha)++ def finalize_outputs(self, job_id: str, finished: int) -> None:+ """产物从任务清理完成时计时,部分失败和取消产生的产物采用相同期限。"""+ with self._lock:+ for rec in self._files.values():+ if rec.job_id == job_id:+ rec.expires_at = finished + self.retention_seconds if self.retention_seconds else None+ for sha in self._job_output_pins.pop(job_id, set()):+ self._pins[sha] -= 1+ if not self._pins[sha]:+ self._pins.pop(sha)++ def collect_expired(self) -> None:+ """回收过期视图和无引用受管 blob,启动时也可清理上次遗留的旧文件。"""+ if not self.retention_seconds:+ return+ with self._lock:+ now = int(time.time())+ for file_id, rec in tuple(self._files.items()):+ if rec.expires_at is not None and rec.expires_at <= now:+ self._files.pop(file_id)+ for upload_id, rec in tuple(self._uploads.items()):+ if rec.expires_at <= now:+ self._uploads.pop(upload_id)+ (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)+ referenced = {rec.sha256sum for rec in self._files.values()} | set(self._pins)+ for prefix in self._blobs.iterdir():+ if prefix.is_symlink() or not prefix.is_dir() or not re.fullmatch(r"[0-9a-f]{2}", prefix.name):+ continue+ for blob in prefix.iterdir():+ sha = prefix.name + blob.name+ if (+ blob.is_symlink()+ or not blob.is_file()+ or not re.fullmatch(r"[0-9a-f]{62}(?:\.[0-9a-f]{16})?", blob.name)+ ):+ continue+ if sha in referenced:+ continue+ # 刚写入但尚未注册的文件及当前扫描期间的写入受锁和年龄门槛保护。+ if blob.stat().st_mtime + self.retention_seconds <= now:+ blob.unlink(missing_ok=True)+ pending = self._blobs / "_uploads"+ if pending.is_dir():+ for blob in pending.iterdir():+ if (+ blob.is_file()+ and re.fullmatch(r"upload_[0-9a-f]{24}", blob.name)+ and blob.name not in self._uploads+ and blob.stat().st_mtime + self.retention_seconds <= now+ ):+ blob.unlink(missing_ok=True)+# ── ID generation ────────────────────────────────────────────────@staticmethod@@ -674,76 +785,96 @@ class FileStore:return self._blobs / self._blob_path(sha256hex)def blob_exists(self, sha256hex: str) -> bool:- return self._blob_abs(sha256hex).is_file()+ with self._lock:+ return self._blob_abs(sha256hex).is_file()def store_blob(self, data: bytes, *, sha256hex: str) -> None:"""原子写入已校验的内容,避免并发读取尚未写完的 blob。"""- p = self._blob_abs(sha256hex)- if not p.is_file():- p.parent.mkdir(parents=True, exist_ok=True)- temporary = p.with_name(p.name + "." + secrets.token_hex(8))- try:- temporary.write_bytes(data)- os.replace(temporary, p)- finally:- temporary.unlink(missing_ok=True)+ with self._lock:+ p = self._blob_abs(sha256hex)+ if not p.is_file():+ p.parent.mkdir(parents=True, exist_ok=True)+ temporary = p.with_name(p.name + "." + secrets.token_hex(8))+ try:+ temporary.write_bytes(data)+ os.replace(temporary, p)+ finally:+ temporary.unlink(missing_ok=True)def register_source_file(self, filename: str, path: pathlib.Path, sha256sum: str, file_id: str | None = None) -> str:"""从已校验的暂存文件原子注册源字节及独立的文件名视图。"""- target = self._blob_abs(sha256sum)- if not target.is_file():- target.parent.mkdir(parents=True, exist_ok=True)- temporary = target.with_name(target.name + "." + secrets.token_hex(8))- try:- shutil.copyfile(path, temporary)- os.replace(temporary, target)- finally:- temporary.unlink(missing_ok=True)- now = int(time.time())- file_id = file_id or self._new_file_id()- self._files[file_id] = _FileRecord(- id=file_id,- filename=filename,- bytes=target.stat().st_size,- created_at=now,- purpose="parse",- sha256sum=sha256sum,- expires_at=now + 3600,- )- return file_id+ with self._lock:+ target = self._blob_abs(sha256sum)+ if not target.is_file():+ target.parent.mkdir(parents=True, exist_ok=True)+ temporary = target.with_name(target.name + "." + secrets.token_hex(8))+ try:+ shutil.copyfile(path, temporary)+ os.replace(temporary, target)+ finally:+ temporary.unlink(missing_ok=True)+ now = int(time.time())+ file_id = file_id or self._new_file_id()+ self._files[file_id] = _FileRecord(+ id=file_id,+ filename=filename,+ bytes=target.stat().st_size,+ created_at=now,+ purpose="parse",+ sha256sum=sha256sum,+ expires_at=now + self.retention_seconds if self.retention_seconds else None,+ )+ return file_iddef read_blob(self, sha256hex: str) -> bytes:- p = self._blob_abs(sha256hex)- if not p.is_file():- raise FileNotFoundError(sha256hex)- return p.read_bytes()+ with self._lock:+ p = self._blob_abs(sha256hex)+ if not p.is_file():+ raise FileNotFoundError(sha256hex)+ return p.read_bytes()# ── uploads ──────────────────────────────────────────────────────def create_upload(self, req: CreateUploadRequest, *, base_url: str = "") -> UploadResponse:- now = int(time.time())- expires_seconds = req.expires_after.seconds if req.expires_after else 3600-- # sha256sum dedup- if req.sha256sum and self.blob_exists(req.sha256sum):- if self._blob_abs(req.sha256sum).stat().st_size != req.bytes:- _raise_api_error(- 400,- error_type="invalid_request_error",- code="upload_size_mismatch",- message="Declared size does not match the cached file",- param="bytes",+ with self._lock:+ now = int(time.time())+ expires_seconds = req.expires_after.seconds if req.expires_after else 3600++ # sha256sum dedup+ if req.sha256sum and self.blob_exists(req.sha256sum):+ if self._blob_abs(req.sha256sum).stat().st_size != req.bytes:+ _raise_api_error(+ 400,+ error_type="invalid_request_error",+ code="upload_size_mismatch",+ message="Declared size does not match the cached file",+ param="bytes",+ )+ file_id = self._new_file_id()+ self._files[file_id] = _FileRecord(+ id=file_id,+ filename=req.filename,+ bytes=req.bytes,+ created_at=now,+ purpose=req.purpose,+ sha256sum=req.sha256sum,+ expires_at=now + expires_seconds,)- file_id = self._new_file_id()- self._files[file_id] = _FileRecord(- id=file_id,- filename=req.filename,- bytes=req.bytes,- created_at=now,- purpose=req.purpose,- sha256sum=req.sha256sum,- expires_at=now + expires_seconds,- )+ upload_id = self._new_upload_id()+ self._uploads[upload_id] = _UploadRecord(+ id=upload_id,+ filename=req.filename,+ bytes=req.bytes,+ mime_type=req.mime_type,+ created_at=now,+ expires_at=now + expires_seconds,+ purpose=req.purpose,+ sha256sum=req.sha256sum,+ status="completed",+ file_id=file_id,+ )+ return self._make_upload_response(self._uploads[upload_id], base_url=base_url, expose_upload_url=True)+upload_id = self._new_upload_id()self._uploads[upload_id] = _UploadRecord(id=upload_id,@@ -754,201 +885,205 @@ class FileStore:expires_at=now + expires_seconds,purpose=req.purpose,sha256sum=req.sha256sum,- status="completed",- file_id=file_id,)return self._make_upload_response(self._uploads[upload_id], base_url=base_url, expose_upload_url=True)- upload_id = self._new_upload_id()- self._uploads[upload_id] = _UploadRecord(- id=upload_id,- filename=req.filename,- bytes=req.bytes,- mime_type=req.mime_type,- created_at=now,- expires_at=now + expires_seconds,- purpose=req.purpose,- sha256sum=req.sha256sum,- )- return self._make_upload_response(self._uploads[upload_id], base_url=base_url, expose_upload_url=True)-def get_upload(self, upload_id: str) -> _UploadRecord:- rec = self._uploads.get(upload_id)- if rec is None:- _raise_api_error(- 404,- error_type="invalid_request_error",- code="upload_not_found",- message=f"Upload {upload_id} not found",- )- if rec.status == "pending" and int(time.time()) >= rec.expires_at:- # 惰性过期:过期后 pending 记录转为终态并丢弃暂存数据,PUT/complete/cancel 均收到 409。- rec.status = "expired"- (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)- return rec+ with self._lock:+ rec = self._uploads.get(upload_id)+ if rec is None:+ _raise_api_error(+ 404,+ error_type="invalid_request_error",+ code="upload_not_found",+ message=f"Upload {upload_id} not found",+ )+ if int(time.time()) >= rec.expires_at:+ rec.status = "expired"+ (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)+ _raise_api_error(+ 404, error_type="invalid_request_error", code="upload_not_found", message=f"Upload {upload_id} expired"+ )+ return recdef _read_upload_data(self, upload_id: str) -> bytes:- p = self._blobs / "_uploads" / upload_id- if not p.is_file():- _raise_api_error(- 409,- error_type="invalid_request_error",- code="upload_not_ready",- message="Upload bytes not yet received",- )- return p.read_bytes()+ with self._lock:+ p = self._blobs / "_uploads" / upload_id+ if not p.is_file():+ _raise_api_error(+ 409,+ error_type="invalid_request_error",+ code="upload_not_ready",+ message="Upload bytes not yet received",+ )+ return p.read_bytes()def complete_upload(self, upload_id: str, sha256hex: str | None) -> UploadResponse:- rec = self.get_upload(upload_id)- if rec.status == "completed":- _raise_api_error(- 409,- error_type="invalid_request_error",- code="upload_already_terminal",- message="Upload is already completed",- )- if rec.status in ("cancelled", "expired"):- _raise_api_error(- 409,- error_type="invalid_request_error",- code="upload_already_terminal",- message=f"Upload is {rec.status}",- )+ with self._lock:+ rec = self.get_upload(upload_id)+ if rec.status == "completed":+ _raise_api_error(+ 409,+ error_type="invalid_request_error",+ code="upload_already_terminal",+ message="Upload is already completed",+ )+ if rec.status in ("cancelled", "expired"):+ _raise_api_error(+ 409,+ error_type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",+ )- # compute sha256 from uploaded data if not provided- data = self._read_upload_data(upload_id)- if len(data) != rec.bytes:- _raise_api_error(- 413,- error_type="invalid_request_error",- code="upload_size_mismatch",- message=f"Upload expects {rec.bytes} bytes, received {len(data)}",- )- actual_sha = hashlib.sha256(data).hexdigest()+ # compute sha256 from uploaded data if not provided+ data = self._read_upload_data(upload_id)+ if len(data) != rec.bytes:+ _raise_api_error(+ 413,+ error_type="invalid_request_error",+ code="upload_size_mismatch",+ message=f"Upload expects {rec.bytes} bytes, received {len(data)}",+ )+ actual_sha = hashlib.sha256(data).hexdigest()- if sha256hex and sha256hex != actual_sha:- _raise_api_error(- 400,- error_type="invalid_request_error",- code="file_hash_mismatch",- message="SHA-256 mismatch",- )- if rec.sha256sum and rec.sha256sum != actual_sha:- _raise_api_error(- 400,- error_type="invalid_request_error",- code="file_hash_mismatch",- message="SHA-256 mismatch",- )+ if sha256hex and sha256hex != actual_sha:+ _raise_api_error(+ 400,+ error_type="invalid_request_error",+ code="file_hash_mismatch",+ message="SHA-256 mismatch",+ )+ if rec.sha256sum and rec.sha256sum != actual_sha:+ _raise_api_error(+ 400,+ error_type="invalid_request_error",+ code="file_hash_mismatch",+ message="SHA-256 mismatch",+ )- # move from upload blob to content-addressed blob- sha = sha256hex or actual_sha- if not self.blob_exists(sha):- self.store_blob(data, sha256hex=sha)- # remove temp upload blob- (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)+ # move from upload blob to content-addressed blob+ sha = sha256hex or actual_sha+ if not self.blob_exists(sha):+ self.store_blob(data, sha256hex=sha)+ # remove temp upload blob+ (self._blobs / "_uploads" / upload_id).unlink(missing_ok=True)- now = int(time.time())- file_id = self._new_file_id()- self._files[file_id] = _FileRecord(- id=file_id,- filename=rec.filename,- bytes=rec.bytes,- created_at=now,- purpose=rec.purpose,- sha256sum=sha,- expires_at=rec.expires_at,- upload_id=upload_id,- )- rec.status = "completed"- rec.file_id = file_id- rec.sha256sum = sha- return self._make_upload_response(rec)+ now = int(time.time())+ file_id = self._new_file_id()+ self._files[file_id] = _FileRecord(+ id=file_id,+ filename=rec.filename,+ bytes=rec.bytes,+ created_at=now,+ purpose=rec.purpose,+ sha256sum=sha,+ expires_at=rec.expires_at,+ upload_id=upload_id,+ )+ rec.status = "completed"+ rec.file_id = file_id+ rec.sha256sum = sha+ return self._make_upload_response(rec)def cancel_upload(self, upload_id: str) -> UploadResponse:- rec = self.get_upload(upload_id)- if rec.status in ("completed", "cancelled", "expired"):- _raise_api_error(- 409,- error_type="invalid_request_error",- code="upload_already_terminal",- message=f"Upload is {rec.status}",- )- rec.status = "cancelled"- return self._make_upload_response(rec)+ with self._lock:+ rec = self.get_upload(upload_id)+ if rec.status in ("completed", "cancelled", "expired"):+ _raise_api_error(+ 409,+ error_type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",+ )+ rec.status = "cancelled"+ return self._make_upload_response(rec)def store_upload_data(self, upload_id: str, data: bytes) -> None:"""Store raw bytes for an upload (before complete)."""- rec = self.get_upload(upload_id)- if rec.status != "pending":- _raise_api_error(- 409,- error_type="invalid_request_error",- code="upload_already_terminal",- message=f"Upload is {rec.status}",- )- if len(data) != rec.bytes:- _raise_api_error(- 413,- error_type="invalid_request_error",- code="upload_size_mismatch",- message=f"Upload expects {rec.bytes} bytes, received {len(data)}",- )- # store temporarily under upload_id in blobs dir- p = self._blobs / "_uploads" / upload_id- p.parent.mkdir(parents=True, exist_ok=True)- p.write_bytes(data)+ with self._lock:+ rec = self.get_upload(upload_id)+ if rec.status != "pending":+ _raise_api_error(+ 409,+ error_type="invalid_request_error",+ code="upload_already_terminal",+ message=f"Upload is {rec.status}",+ )+ if len(data) != rec.bytes:+ _raise_api_error(+ 413,+ error_type="invalid_request_error",+ code="upload_size_mismatch",+ message=f"Upload expects {rec.bytes} bytes, received {len(data)}",+ )+ # store temporarily under upload_id in blobs dir+ p = self._blobs / "_uploads" / upload_id+ p.parent.mkdir(parents=True, exist_ok=True)+ p.write_bytes(data)def _make_upload_response(self, rec: _UploadRecord, *, base_url: str = "", expose_upload_url: bool = False) -> UploadResponse:- resp = UploadResponse(- id=rec.id,- bytes=rec.bytes,- created_at=rec.created_at,- expires_at=rec.expires_at,- filename=rec.filename,- mime_type=rec.mime_type,- purpose=rec.purpose,- sha256sum=rec.sha256sum,- status=rec.status,- )- if expose_upload_url and rec.status == "pending":- resp.upload_url = f"{base_url}/v1/uploads/{rec.id}/content"- resp.upload_method = "PUT"- resp.upload_headers = {"Content-Type": rec.mime_type}- elif rec.status == "completed" and rec.file_id and rec.file_id in self._files:- resp.file = self._make_file_object(self._files[rec.file_id])- return resp+ with self._lock:+ resp = UploadResponse(+ id=rec.id,+ bytes=rec.bytes,+ created_at=rec.created_at,+ expires_at=rec.expires_at,+ filename=rec.filename,+ mime_type=rec.mime_type,+ purpose=rec.purpose,+ sha256sum=rec.sha256sum,+ status=rec.status,+ )+ if expose_upload_url and rec.status == "pending":+ resp.upload_url = f"{base_url}/v1/uploads/{rec.id}/content"+ resp.upload_method = "PUT"+ resp.upload_headers = {"Content-Type": rec.mime_type}+ elif rec.status == "completed" and rec.file_id and rec.file_id in self._files:+ resp.file = self._make_file_object(self._files[rec.file_id])+ return resp# ── files ────────────────────────────────────────────────────────- def create_file_for_output(self, filename: str, data: bytes, *, sha256hex: str | None = None) -> str:+ def create_file_for_output(+ self, filename: str, data: bytes, *, sha256hex: str | None = None, job_id: str | None = None+ ) -> str:"""Store parse-output data and return a file_id."""- sha = sha256hex or hashlib.sha256(data).hexdigest()- self.store_blob(data, sha256hex=sha)- now = int(time.time())- file_id = self._new_file_id()- self._files[file_id] = _FileRecord(- id=file_id,- filename=filename,- bytes=len(data),- created_at=now,- purpose="parse_output",- sha256sum=sha,- )- return file_id+ with self._lock:+ sha = sha256hex or hashlib.sha256(data).hexdigest()+ self.store_blob(data, sha256hex=sha)+ now = int(time.time())+ file_id = self._new_file_id()+ self._files[file_id] = _FileRecord(+ id=file_id,+ filename=filename,+ bytes=len(data),+ created_at=now,+ purpose="parse_output",+ sha256sum=sha,+ job_id=job_id,+ expires_at=(now + self.retention_seconds) if self.retention_seconds and job_id is None else None,+ )+ if job_id is not None:+ pins = self._job_output_pins.setdefault(job_id, set())+ if sha not in pins:+ pins.add(sha)+ self._pins[sha] = self._pins.get(sha, 0) + 1+ return file_iddef get_file(self, file_id: str) -> _FileRecord:- rec = self._files.get(file_id)- if rec is None:- _raise_api_error(- 404,- error_type="invalid_request_error",- code="file_not_found",- message=f"File {file_id} not found",- )- return rec+ with self._lock:+ rec = self._files.get(file_id)+ if rec is None or (rec.expires_at is not None and rec.expires_at <= int(time.time())):+ _raise_api_error(+ 404,+ error_type="invalid_request_error",+ code="file_not_found",+ message=f"File {file_id} not found",+ )+ return rec@staticmethoddef _make_file_object(rec: _FileRecord) -> FileObjectModel:@@ -963,32 +1098,34 @@ class FileStore:)def read_file_data(self, file_id: str) -> bytes:- rec = self.get_file(file_id)- if rec.purpose != "parse_output":- _raise_api_error(- 403,- error_type="permission_error",- code="feature_requires_api_key",- message="Source files cannot be downloaded",- )- if rec.sha256sum is None:- _raise_api_error(- 500,- error_type="api_error",- code="internal_error",- message="File has no sha256sum",- )- return self.read_blob(rec.sha256sum)+ with self._lock:+ rec = self.get_file(file_id)+ if rec.purpose != "parse_output":+ _raise_api_error(+ 403,+ error_type="permission_error",+ code="feature_requires_api_key",+ message="Source files cannot be downloaded",+ )+ if rec.sha256sum is None:+ _raise_api_error(+ 500,+ error_type="api_error",+ code="internal_error",+ message="File has no sha256sum",+ )+ return self.read_blob(rec.sha256sum)def delete_file(self, file_id: str) -> None:- if file_id not in self._files:- _raise_api_error(- 404,- error_type="invalid_request_error",- code="file_not_found",- message=f"File {file_id} not found",- )- del self._files[file_id]+ with self._lock:+ if file_id not in self._files:+ _raise_api_error(+ 404,+ error_type="invalid_request_error",+ code="file_not_found",+ message=f"File {file_id} not found",+ )+ del self._files[file_id]def list_files(self,@@ -998,27 +1135,29 @@ class FileStore:order: str,purpose: FilePurpose | None,) -> FileListResponse:- recs = list(self._files.values())- # filter- if purpose is not None:- recs = [r for r in recs if r.purpose == purpose]- # sort by created_at- reverse = order == "desc"- recs.sort(key=lambda r: r.created_at, reverse=reverse)- # cursor- start = 0- if after is not None:- for i, r in enumerate(recs):- if r.id == after:- start = i + 1- break- page = recs[start : start + limit]- return FileListResponse(- data=[self._make_file_object(r) for r in page],- first_id=page[0].id if page else None,- last_id=page[-1].id if page else None,- has_more=(start + limit) < len(recs),- )+ with self._lock:+ now = int(time.time())+ recs = [rec for rec in self._files.values() if rec.expires_at is None or rec.expires_at > now]+ # filter+ if purpose is not None:+ recs = [r for r in recs if r.purpose == purpose]+ # sort by created_at+ reverse = order == "desc"+ recs.sort(key=lambda r: r.created_at, reverse=reverse)+ # cursor+ start = 0+ if after is not None:+ for i, r in enumerate(recs):+ if r.id == after:+ start = i + 1+ break+ page = recs[start : start + limit]+ return FileListResponse(+ data=[self._make_file_object(r) for r in page],+ first_id=page[0].id if page else None,+ last_id=page[-1].id if page else None,+ has_more=(start + limit) < len(recs),+ )# ── defaults → app state ─────────────────────────────────────────@@ -1141,6 +1280,8 @@ class _JobRecord:progress: JobProgress | None = Nonefiles: list[JobFileResult] = None # type: ignore[assignment]links: JobLinks | None = None+ input_blobs: dict[str, str] = field(default_factory=dict)+ file_store: FileStore | None = Nonedef __post_init__(self) -> None:if self.files is None:@@ -1152,7 +1293,8 @@ class _JobRecord:class JobStore:- def __init__(self, concurrency: int = 1) -> None:+ def __init__(self, concurrency: int = 1, retention_seconds: int = 86400) -> None:+ self.retention_seconds = retention_secondsself._jobs: dict[str, _JobRecord] = {}self._concurrency = max(1, concurrency)self._semaphore = asyncio.Semaphore(self._concurrency)@@ -1212,6 +1354,9 @@ class JobStore:"""回收句柄并读取异常,覆盖任务首次执行前就被取消的路径。"""self._tasks.pop(rec.id, None)rec.finished_at = self._now()+ if rec.file_store is not None:+ rec.file_store.finalize_outputs(rec.id, int(time.time()))+ rec.file_store.release_inputs(rec.input_blobs)if not task.cancelled():error = task.exception()if error is not None:@@ -1242,8 +1387,9 @@ class JobStore:for job_id, task in tasks:if not task.done():rec = self._jobs[job_id]- if rec.status != "canceled":+ if rec.status not in {"canceled", "failed"}:rec.status = "canceled"+ if not task.cancelling():task.cancel()try:await drain_future(asyncio.gather(*(task for _, task in tasks), return_exceptions=True))@@ -1287,10 +1433,28 @@ class JobStore:))rec.progress.total = len(rec.files)+ rec.input_blobs = file_store.acquire_inputs(+ [entry.source.file_id for entry in req.files if isinstance(entry.source, FileIdSource)]+ )+ rec.file_store = file_storeself._jobs[job_id] = recreturn rec+ def collect_expired(self) -> None:+ """按清理完成时间删除终态任务、事件及其文件视图,运行任务不受 TTL 影响。"""+ if not self.retention_seconds:+ return+ now = time.time()+ for job_id, rec in tuple(self._jobs.items()):+ if job_id in self._tasks or rec.finished_at is None:+ continue+ finished = datetime.fromisoformat(rec.finished_at.replace("Z", "+00:00")).timestamp()+ if finished + self.retention_seconds <= now:+ self._jobs.pop(job_id)+ self._completion_events.pop(job_id, None)+def get(self, job_id: str) -> _JobRecord:+ self.collect_expired()rec = self._jobs.get(job_id)if rec is None:_raise_api_error(@@ -1325,6 +1489,7 @@ class JobStore:created_after: str | None,order: str = "desc",) -> JobListResponse:+ self.collect_expired()recs = list(self._jobs.values())if status_filter:allowed = set(status_filter.split(","))@@ -1385,6 +1550,7 @@ class JobStore:),limits=UsageLimits(max_concurrent_jobs=self._concurrency,+ max_file_retention_days=(self.retention_seconds + 86399) // 86400 if self.retention_seconds else None,),)@@ -1453,6 +1619,7 @@ async def _extract_bytes(max_inline_bytes: int = _MAX_INLINE_BYTES_DEFAULT,allow_http_source: bool = False,max_url_bytes: int = _MAX_FILE_SIZE_BYTES_DEFAULT,+ input_blobs: dict[str, str] | None = None,) -> _ExtractedSource:"""按既有来源策略读取字节,并保留不会由临时文件替代的来源上下文。"""_validate_source_policy(@@ -1462,10 +1629,12 @@ async def _extract_bytes(allow_http_source=allow_http_source,)if isinstance(source, FileIdSource):- rec = file_store.get_file(source.file_id)- if rec.sha256sum is None:+ sha = (input_blobs or {}).get(source.file_id)+ if sha is None:+ sha = file_store.get_file(source.file_id).sha256sum+ if sha is None:raise ValueError("File has no content")- return _ExtractedSource(file_store.read_blob(rec.sha256sum))+ return _ExtractedSource(file_store.read_blob(sha))if isinstance(source, UrlSource):async with httpx.AsyncClient(timeout=url_timeout) as cli:# 流式读取并在超过 max_url_bytes 时中止,避免无上限响应被整包缓冲进内存。@@ -1536,6 +1705,7 @@ async def _run_job(max_inline_bytes=max_inline_bytes,allow_http_source=allow_http_source,max_url_bytes=max_url_bytes,+ input_blobs=rec.input_blobs,)data = extracted.datasuffix = pathlib.Path(fr.name).suffix@@ -1593,19 +1763,21 @@ async def _run_job(content_bytes = _text_utf8_bytes(md or "")sha = hashlib.sha256(content_bytes).hexdigest()file_store.store_blob(content_bytes, sha256hex=sha)- fid = file_store.create_file_for_output(f"{fr.name}.md", content_bytes, sha256hex=sha)+ fid = file_store.create_file_for_output(f"{fr.name}.md", content_bytes, sha256hex=sha, job_id=rec.id)output_files.markdown = OutputFileRef(file_id=fid, bytes=len(content_bytes))elif fmt == "middle_json":mj = _json_utf8_bytes(result.to_dict(skip_defaults=True))sha = hashlib.sha256(mj).hexdigest()file_store.store_blob(mj, sha256hex=sha)- fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha)+ fid = file_store.create_file_for_output(f"{fr.name}.middle.json", mj, sha256hex=sha, job_id=rec.id)output_files.middle_json = OutputFileRef(file_id=fid, bytes=len(mj))elif fmt == "structured_content":cl2 = _json_utf8_bytes(await run_sync(result.structured_content))sha = hashlib.sha256(cl2).hexdigest()file_store.store_blob(cl2, sha256hex=sha)- fid = file_store.create_file_for_output(f"{fr.name}.structured_content.json", cl2, sha256hex=sha)+ fid = file_store.create_file_for_output(+ f"{fr.name}.structured_content.json", cl2, sha256hex=sha, job_id=rec.id+ )output_files.structured_content = OutputFileRef(file_id=fid, bytes=len(cl2))# zip@@ -1613,7 +1785,7 @@ async def _run_job(zip_bytes = await run_sync(_build_self_contained_zip_output, result)zip_sha = hashlib.sha256(zip_bytes).hexdigest()file_store.store_blob(zip_bytes, sha256hex=zip_sha)- zip_fid = file_store.create_file_for_output(f"{fr.name}.zip", zip_bytes, sha256hex=zip_sha)+ zip_fid = file_store.create_file_for_output(f"{fr.name}.zip", zip_bytes, sha256hex=zip_sha, job_id=rec.id)output_files.zip = OutputFileRef(file_id=zip_fid, bytes=len(zip_bytes))fr.status = "completed"@@ -2070,7 +2242,12 @@ async def submit_parse_job(job_store=job_store,)- job_store.start_task(rec, _bg_run)+ try:+ job_store.start_task(rec, _bg_run)+ except BaseException:+ file_store.release_inputs(rec.input_blobs)+ job_store._jobs.pop(rec.id, None)+ raisereturn rec@@ -2366,6 +2543,7 @@ def create_app(image_analysis: bool = True,preload_models: bool = False,vlm_config: VlmConfig | None = None,+ retention_seconds: int | None = None,) -> FastAPI:"""Create a FastAPI application implementing the MinerU v1 REST API.@@ -2403,6 +2581,7 @@ def create_app(vlm_config:Complete VLM connection configuration override; defaults to global model.vlm settings."""+ retention_seconds = resolve_retention_seconds(retention_seconds)upload_dir = upload_dir or ""tier = _normalize_server_tier(tier)server_tiers = _request_tiers_for_server_tier(tier, no_flash=no_flash, no_advanced=no_advanced)@@ -2448,8 +2627,22 @@ def create_app(application.state.vlm_config = vlm_configapplication.state.model_preload_error = Nonejob_store: JobStore = application.state.job_store+ file_store: FileStore = application.state.file_store+ file_store.claim_directory()+ collection_task: asyncio.Task[None] | None = None++ async def collect_loop() -> None:+ """每五分钟扫描,先清理终态元数据,再释放无引用文件。"""+ while True:+ await asyncio.sleep(RETENTION_SCAN_INTERVAL_SECONDS)+ job_store.collect_expired()+ await run_sync(file_store.collect_expired)++ if retention_seconds:+ collection_task = asyncio.create_task(collect_loop(), name="mineru-api-retention")token = runtime_owner.set(job_store.runtime_owner)try:+ file_store.collect_expired()if _preload_tier is not None:logger.info("Initializing VLM client and local models for startup tier %s", _preload_tier)try:@@ -2474,9 +2667,13 @@ def create_app(yieldfinally:runtime_owner.reset(token)+ if collection_task is not None:+ collection_task.cancel()+ await asyncio.gather(collection_task, return_exceptions=True)try:await job_store.shutdown()finally:+ file_store.release_directory()if not upload_dir and _upload_dir.exists():shutil.rmtree(_upload_dir, ignore_errors=True)@@ -2535,8 +2732,8 @@ def create_app(application.state.preload_models = preload_modelsapplication.state.vlm_config = vlm_configapplication.state.model_preload_error = None- FileStore(_upload_dir).install(application.state)- JobStore(concurrency=concurrency).install(application.state)+ FileStore(_upload_dir, retention_seconds=retention_seconds).install(application.state)+ JobStore(concurrency=concurrency, retention_seconds=retention_seconds).install(application.state)application.add_middleware(GZipMiddleware, minimum_size=1000)@application.exception_handler(ApiServerError)@@ -2621,6 +2818,13 @@ def _build_server_log_config(log_level: str) -> dict[str, Any]:@click.command()+ "--retention-seconds",+ default=None,+ type=click.IntRange(min=0),+ envvar="MINERU_API_RETENTION_SECONDS",+ help="Terminal resource retention in seconds (default: 86400; 0 disables collection)",+)@click.option("--host", default="127.0.0.1", help="Server host")@click.option("--port", default=8000, type=int, help="Server port")@click.option(@@ -2739,6 +2943,7 @@ def main(vlm_http_timeout: int | None,vlm_max_concurrency: int | None,log_level: str | None,+ retention_seconds: int | None = None,) -> None:"""合并显式 VLM 参数后启动 MinerU v1 REST API 服务,不修改全局配置。"""configure_standard_streams()@@ -2791,6 +2996,7 @@ def main(image_analysis=not disable_image_analysis,preload_models=preload_models,vlm_config=vlm_settings,+ retention_seconds=retention_seconds,)except ParseServerStartupError as exc:if control_watcher is not None:diff --git a/mineru/parser/task_api.py b/mineru/parser/task_api.pyindex 11a3d2ba..1a8630f1 100644--- a/mineru/parser/task_api.py+++ b/mineru/parser/task_api.py@@ -55,6 +55,10 @@ class TaskUpload:class TaskBackend(Protocol):"""便捷接口只依赖显式任务和文件操作,不维护独立队列。"""+ def release_uploads(self) -> None:+ """释放请求预检取得的输入租约,包括校验失败和取消路径。"""+ ...+async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:"""查找当前调用方可复用的源字节。"""...@@ -378,9 +382,14 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:async def create_task(request: Request) -> Response:"""提交任务后立即返回公共 ID,缓存命中时不读取请求主体。"""backend = factory(request)- with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:- body, uploads, skipped = await _prepare_submission(request, backend, Path(directory), sync=False, force_zip=False)- job = await backend.submit(body, uploads)+ try:+ with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:+ body, uploads, skipped = await _prepare_submission(+ request, backend, Path(directory), sync=False, force_zip=False+ )+ job = await backend.submit(body, uploads)+ finally:+ backend.release_uploads()return JSONResponse(task_payload(job),status_code=202,@@ -430,11 +439,14 @@ def build_task_router(factory: Callable[[Request], TaskBackend]) -> APIRouter:) -> Response:"""同步包装共享异步任务,等待超时不取消后台工作。"""backend = factory(request)- with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:- body, uploads, skipped = await _prepare_submission(- request, backend, Path(directory), sync=True, force_zip=response_format == "zip"- )- job = await backend.submit(body, uploads)+ try:+ with tempfile.TemporaryDirectory(prefix="mineru-task-") as directory:+ body, uploads, skipped = await _prepare_submission(+ request, backend, Path(directory), sync=True, force_zip=response_format == "zip"+ )+ job = await backend.submit(body, uploads)+ finally:+ backend.release_uploads()job = await backend.wait(job["job_id"], wait_timeout)response = await build_task_result(job, backend, response_format)if skipped and request.scope.get("http_version") == "1.1":@@ -452,12 +464,22 @@ class ApiTaskBackend:self.request = requestself.files: FileStore = request.app.state.file_storeself.jobs: JobStore = request.app.state.job_store+ self._cached_pins: list[str] = []self.access: AccessLevel = "registered" if request.app.state.api_key else "anonymous"+ def release_uploads(self) -> None:+ """释放当前请求的哈希预检引用,失败和取消同样经过此处。"""+ for sha in self._cached_pins:+ self.files.unpin_cached_blob(sha)+ self._cached_pins.clear()+async def find_upload(self, sha256sum: str, filename: str) -> TaskUpload | None:- """从内容寻址存储查询已有字节,并使用本次文件名。"""- path = self.files._blob_abs(sha256sum)- return TaskUpload(path, filename, path.stat().st_size, sha256sum) if path.is_file() else None+ """原子查找并持有可复用字节,直到提交或输入校验完成。"""+ path = self.files.pin_cached_blob(sha256sum)+ if path is None:+ return None+ self._cached_pins.append(sha256sum)+ return TaskUpload(path, filename, path.stat().st_size, sha256sum)async def submit(self, body: CreateJobRequest, uploads: dict[int, TaskUpload]) -> dict[str, Any]:"""注册源字节后调用共享任务提交函数,失败时回滚文件视图。"""diff --git a/mineru/utils/retention.py b/mineru/utils/retention.pynew file mode 100644index 00000000..25a0eaf1--- /dev/null+++ b/mineru/utils/retention.py@@ -0,0 +1,25 @@+# Copyright (c) Opendatalab. All rights reserved.+"""API 与 Router 共用的终态资源保留配置。"""++from __future__ import annotations++import os++DEFAULT_RETENTION_SECONDS = 86400+RETENTION_SCAN_INTERVAL_SECONDS = 300+RETENTION_ENV = "MINERU_API_RETENTION_SECONDS"+++def resolve_retention_seconds(value: int | None = None) -> int:+ """显式参数优先于环境变量;零禁用回收,负数和非法值立即报错。"""+ if value is None:+ try:+ value = int(os.environ.get(RETENTION_ENV, str(DEFAULT_RETENTION_SECONDS)))+ except ValueError as exc:+ raise ValueError(f"{RETENTION_ENV} must be a non-negative integer") from exc+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:+ raise ValueError("retention_seconds must be a non-negative integer")+ return value+++__all__ = ["DEFAULT_RETENTION_SECONDS", "RETENTION_SCAN_INTERVAL_SECONDS", "RETENTION_ENV", "resolve_retention_seconds"]diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 36f26534..fb290c4e 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -1990,7 +1990,7 @@ def test_complete_upload_rejects_size_mismatch(tmp_path: Path) -> None:def test_get_upload_expires_pending_records_and_discards_staged_data(tmp_path: Path) -> None:- """expires_at 过后 pending 上传惰性转为 expired 终态并丢弃暂存数据,后续 PUT/complete 收到 409。"""+ """上传到期后的新读取、写入和完成请求统一返回 404,并丢弃暂存数据。"""file_store = FileStore(tmp_path / "api-files")upload = file_store.create_upload(CreateUploadRequest.model_validate({"filename": "demo.pdf", "bytes": 4, "mime_type": "application/pdf"})@@ -2001,20 +2001,19 @@ def test_get_upload_expires_pending_records_and_discards_staged_data(tmp_path: Pfile_store._uploads[upload.id].expires_at = int(time.time()) - 1- rec = file_store.get_upload(upload.id)-- assert rec.status == "expired"+ for operation in (+ lambda: file_store.get_upload(upload.id),+ lambda: file_store.store_upload_data(upload.id, b"demo"),+ lambda: file_store.complete_upload(upload.id, None),+ ):+ with pytest.raises(api_server.ApiServerError) as exc_info:+ operation()+ assert exc_info.value.status_code == 404assert not staged.is_file()- with pytest.raises(api_server.ApiServerError) as exc_info:- file_store.store_upload_data(upload.id, b"demo")- assert exc_info.value.status_code == 409- with pytest.raises(api_server.ApiServerError) as exc_info:- file_store.complete_upload(upload.id, None)- assert exc_info.value.status_code == 409-def test_get_upload_keeps_completed_records_after_expiry(tmp_path: Path) -> None:- """completed 是终态,expires_at 过后不再翻转,文件保留交给独立的 retention 机制。"""+def test_get_upload_hides_completed_records_after_expiry(tmp_path: Path) -> None:+ """已完成上传到期后同样不允许新的读取请求复用该上传视图。"""file_store = FileStore(tmp_path / "api-files")sha = "00" * 32file_store.store_blob(b"demo", sha256hex=sha)@@ -2027,7 +2026,9 @@ def test_get_upload_keeps_completed_records_after_expiry(tmp_path: Path) -> Nonefile_store._uploads[upload.id].expires_at = int(time.time()) - 1- assert file_store.get_upload(upload.id).status == "completed"+ with pytest.raises(api_server.ApiServerError) as exc_info:+ file_store.get_upload(upload.id)+ assert exc_info.value.status_code == 404def test_run_job_preserves_input_file_id_and_keeps_source_undownloadable(@@ -2610,9 +2611,7 @@ def test_api_server_model_preload_failure_keeps_health_diagnostics_and_rejects_c) -> None:_stub_api_server_dependency_preflight(monkeypatch)- def _fail_preload(- startup_tier: DeploymentTier, *, vlm_config: VlmConfig | None = None- ) -> api_server._ModelPreloadResult:+ def _fail_preload(startup_tier: DeploymentTier, *, vlm_config: VlmConfig | None = None) -> api_server._ModelPreloadResult:"""模拟包含 VLM 初始化在内的服务预加载失败。"""raise ValueError("CUDA is not available.")@@ -2637,9 +2636,7 @@ def test_api_server_model_preload_is_opt_in_and_ignored_for_flash(tmp_path: Path_stub_api_server_dependency_preflight(monkeypatch)calls: list[str] = []- def _preload(- startup_tier: DeploymentTier, *, vlm_config: VlmConfig | None = None- ) -> api_server._ModelPreloadResult:+ def _preload(startup_tier: DeploymentTier, *, vlm_config: VlmConfig | None = None) -> api_server._ModelPreloadResult:"""记录预加载调用,兼容显式 VLM 配置传入。"""calls.append(startup_tier)return api_server._ModelPreloadResult(tier=startup_tier, engine="test")diff --git a/tests/unittest/test_resource_retention.py b/tests/unittest/test_resource_retention.pynew file mode 100644index 00000000..879bafe7--- /dev/null+++ b/tests/unittest/test_resource_retention.py@@ -0,0 +1,281 @@+"""API 资源 TTL、共享字节租约、存储重启与 Router 缓存回收回归。"""++from __future__ import annotations++import asyncio+import hashlib+import os+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++import pytest+from fastapi.testclient import TestClient++from mineru.parser import api_server+from mineru.parser.api_server import ApiServerError, CreateJobRequest, FileStore, JobStore+from mineru.kit.router.resources import ResourceRegistry, SourceFileStore, StoredSourceFile+from mineru.utils.retention import resolve_retention_seconds+++def clock(monkeypatch: pytest.MonkeyPatch) -> list[int]:+ """只替换墙上时间,不影响事件循环超时和任务调度。"""+ value = [2_000_000_000]+ monkeypatch.setattr(api_server.time, "time", lambda: value[0])+ monkeypatch.setattr(+ JobStore, "_now", staticmethod(lambda: datetime.fromtimestamp(value[0], timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))+ )+ return value+++def _source(store: FileStore, tmp_path: Path, data: bytes = b"document") -> tuple[str, str]:+ """注册真实共享 blob,并使磁盘年龄能由测试墙上时间控制。"""+ path = tmp_path / "input.pdf"+ path.write_bytes(data)+ sha = hashlib.sha256(data).hexdigest()+ file_id = store.register_source_file("input.pdf", path, sha)+ os.utime(store._blob_abs(sha), (0, 0))+ return file_id, sha+++def test_retention_config_defaults_and_overrides(monkeypatch: pytest.MonkeyPatch) -> None:+ """API 参数优先于统一环境变量;默认一天、零禁用、非法配置拒绝启动。"""+ monkeypatch.delenv("MINERU_API_RETENTION_SECONDS", raising=False)+ assert resolve_retention_seconds() == 86400+ monkeypatch.setenv("MINERU_API_RETENTION_SECONDS", "172800")+ assert resolve_retention_seconds() == 172800 and resolve_retention_seconds(0) == 0+ for raw in ("-1", "bad"):+ monkeypatch.setenv("MINERU_API_RETENTION_SECONDS", raw)+ with pytest.raises(ValueError):+ resolve_retention_seconds()+++def test_shared_hash_and_queue_leases_survive_expired_views(tmp_path: Path, clock: list[int]) -> None:+ """两文件、两任务共享同一哈希,视图到期后最后一个任务释放前字节不能删除。"""+ store = FileStore(tmp_path / "files", retention_seconds=10)+ first, sha = _source(store, tmp_path)+ second, _ = _source(store, tmp_path)+ leases = [store.acquire_inputs([file]) for file in (first, second)]+ clock[0] += 11+ store.collect_expired()+ assert not store._files and store._blob_abs(sha).is_file()+ with pytest.raises(ApiServerError) as exc:+ store.get_file(first)+ assert exc.value.status_code == 404+ assert store.pin_cached_blob(sha) is None+ store.release_inputs(leases[0])+ store.collect_expired()+ assert store._blob_abs(sha).is_file()+ data = asyncio.run(api_server._extract_bytes(api_server.FileIdSource(file_id=second), store, input_blobs=leases[1]))+ assert data.data == b"document"+ store.release_inputs(leases[1])+ store.collect_expired()+ assert not store._blob_abs(sha).exists() and not store._pins+++def test_output_retention_starts_after_cleanup(tmp_path: Path, clock: list[int]) -> None:+ """长任务的产物和输入受到保护;完成后清理事件与产物按同一期限删除。"""++ async def scenario() -> None:+ """手动控制运行、排队、完成和回收的交错顺序。"""+ files = FileStore(tmp_path / "files", retention_seconds=10)+ source, sha = _source(files, tmp_path)+ jobs = JobStore(concurrency=1, retention_seconds=10)+ req = CreateJobRequest.model_validate({"tier": "flash", "files": [{"source": {"type": "file_id", "file_id": source}}]})+ gate = asyncio.Event()+ records = [jobs.create(req, files) for _ in range(2)]+ outputs: list[str] = []++ async def work(rec: Any) -> None:+ """创建早期产物,然后等待;第二个排队任务读取已过期视图的租约。"""+ rec.status = "running"+ output = files.create_file_for_output("out.md", b"result", job_id=rec.id)+ outputs.append(output)+ await gate.wait()+ extracted = await api_server._extract_bytes(req.files[0].source, files, input_blobs=rec.input_blobs)+ assert extracted.data == b"document"+ rec.status = "completed"++ for rec in records:+ jobs.start_task(rec, lambda rec=rec: work(rec))+ await asyncio.sleep(0)+ clock[0] += 100+ jobs.collect_expired()+ files.collect_expired()+ assert len(jobs._jobs) == 2 and len(outputs) == 1 and files._blob_abs(sha).exists()+ assert files.get_file(outputs[0]).expires_at is None+ gate.set()+ for rec in records:+ await jobs.wait_for_terminal(rec.id, 2)+ assert not files._pins+ assert all(files.get_file(file).expires_at == clock[0] + 10 for file in outputs)+ clock[0] += 11+ for file in outputs:+ with pytest.raises(ApiServerError) as exc:+ files.read_file_data(file)+ assert exc.value.status_code == 404+ jobs.collect_expired()+ files.collect_expired()+ assert not jobs._jobs and not jobs._completion_events and not files._files+ assert not any(files._blobs.glob("??/*"))+ await jobs.shutdown()++ asyncio.run(scenario())+++def test_cached_preflight_pins_and_last_reference_delete(tmp_path: Path, clock: list[int]) -> None:+ """删除最后文件与哈希复用交错时,预检租约保护路径直到提交或拒绝完成。"""+ store = FileStore(tmp_path / "files", retention_seconds=10)+ file_id, sha = _source(store, tmp_path)+ path = store.pin_cached_blob(sha)+ store.delete_file(file_id)+ store.collect_expired()+ assert path.is_file()+ replacement = store.register_source_file("new.pdf", path, sha)+ store.unpin_cached_blob(sha)+ store.collect_expired()+ assert store.get_file(replacement).sha256sum == sha+ store.delete_file(replacement)+ store.collect_expired()+ assert not path.exists()+++def test_startup_orphan_cleanup_and_directory_ownership(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, clock: list[int]+) -> None:+ """重启清理旧无引用受管文件;未知路径保留,第二实例不能占用相同目录。"""+ root = tmp_path / "files"+ orphan_store = FileStore(root, retention_seconds=10)+ _, sha = _source(orphan_store, tmp_path)+ unknown = root / "blobs/unknown.txt"+ unknown.write_text("keep")+ monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)+ app = api_server.create_app(upload_dir=str(root), tier="flash", retention_seconds=10)+ with TestClient(app):+ assert not orphan_store._blob_abs(sha).exists() and unknown.exists()+ other = api_server.create_app(upload_dir=str(root), tier="flash", retention_seconds=10)+ with pytest.raises(RuntimeError, match="already owned"):+ with TestClient(other):+ pass+ with TestClient(api_server.create_app(upload_dir=str(root), tier="flash", retention_seconds=10)):+ pass+++def test_disabled_collection_preserves_blobs_and_jobs(tmp_path: Path, clock: list[int]) -> None:+ """零策略保留源字节和产物,显式上传期限仍由其本身控制。"""+ files = FileStore(tmp_path / "files", retention_seconds=0)+ file, sha = _source(files, tmp_path)+ out = files.create_file_for_output("out.md", b"output")+ clock[0] += 1_000_000+ files.collect_expired()+ assert files.get_file(file).expires_at is None and files.get_file(out).expires_at is None+ assert files._blob_abs(sha).exists()+++def test_router_expiry_cache_pins_and_alias_cleanup(tmp_path: Path, clock: list[int]) -> None:+ """Router 到期立即隐藏资源,复制租约保留路径,扫描同步清除公共与反向索引。"""+ sources = SourceFileStore(retention_seconds=10)+ registry = ResourceRegistry(retention_seconds=10)+ path = sources._root / "input"+ path.write_bytes(b"input")+ stored = StoredSourceFile(path, 5, hashlib.sha256(b"input").hexdigest(), "application/pdf")+ file = registry.register("file", owner_scope="one", worker_id="worker", upstream_id="file-up")+ sources.bind_source(file.public_id, stored, owner_scope="one", expires_at=clock[0] + 10)+ registry.alias_upstream(file, worker_id="copy", upstream_id="copy-file")+ job = registry.register("job", owner_scope="one", worker_id="worker", upstream_id="job-up")+ job.metadata["payload"] = {"status": "running", "files": [{"file_id": file.public_id}]}+ with sources.pin(stored):+ clock[0] += 11+ registry.collect_expired(sources)+ assert registry.find("file", file.public_id) is None+ assert sources.find_hash("one", stored.sha256sum) is None+ assert path.exists() and registry.find("job", job.public_id) is job+ job.metadata["payload"]["status"] = "failed"+ job.metadata["payload"]["finished_at"] = JobStore._now()+ registry.collect_expired(sources)+ assert registry.find_upstream("file", "one", "copy", "copy-file") is None+ assert path.exists()+ assert not path.exists()+ clock[0] += 11+ registry.collect_expired(sources)+ assert not registry._by_public["job"] and not registry._by_upstream+ sources.close()+++def test_queued_cancel_releases_input_before_execution(tmp_path: Path, clock: list[int]) -> None:+ """首次调度前取消的任务同样释放输入租约及完成事件,不进入解析。"""++ async def scenario() -> None:+ """取消早于 run_owned 的首次执行,覆盖没有 finally 执行机会的分支。"""+ files = FileStore(tmp_path / "files", retention_seconds=10)+ source, sha = _source(files, tmp_path)+ jobs = JobStore(retention_seconds=10)+ req = CreateJobRequest.model_validate({"tier": "flash", "files": [{"source": {"type": "file_id", "file_id": source}}]})+ rec = jobs.create(req, files)++ async def forbidden() -> None:+ """排队取消后不允许调用此操作。"""+ raise AssertionError("must not execute")++ jobs.start_task(rec, forbidden)+ jobs.cancel(rec.id)+ await jobs.wait_for_terminal(rec.id, 2)+ assert rec.status == "canceled" and not files._pins+ clock[0] += 11+ files.collect_expired()+ jobs.collect_expired()+ assert not files._blob_abs(sha).exists() and not jobs._completion_events+ await jobs.shutdown()++ asyncio.run(scenario())+++def test_hash_preflight_rejection_releases_request_lease(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """哈希命中后的 Content-Length 校验失败不会泄漏请求持有的 blob 引用。"""+ monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)+ app = api_server.create_app(upload_dir=str(tmp_path / "files"), tier="flash")+ with TestClient(app) as client:+ _, sha = _source(app.state.file_store, tmp_path)+ response = client.post(+ f"/v1/tasks?filename=input.pdf&sha256sum={sha}&tier=flash",+ content=b"bad",+ headers={"Content-Type": "application/octet-stream"},+ )+ assert response.status_code == 400+ assert not app.state.file_store._pins and not app.state.job_store._jobs+++def test_gc_interleaves_with_blob_writes_and_downloads(tmp_path: Path, clock: list[int]) -> None:+ """多个线程写相同哈希、下载和删除时,回收只允许产生规范 404,不出现残缺字节。"""+ from concurrent.futures import ThreadPoolExecutor++ files = FileStore(tmp_path / "files", retention_seconds=10)+ data = b"download" * 10000++ def work(index: int) -> None:+ """每个下载视图都有独立引用,扫描不能删除另一个线程刚写完的文件。"""+ file = files.create_file_for_output(f"out-{index}.md", data)+ files.collect_expired()+ assert files.read_file_data(file) == data+ files.delete_file(file)+ files.collect_expired()++ with ThreadPoolExecutor(max_workers=4) as pool:+ list(pool.map(work, range(20)))+ clock[0] += 11+ files.collect_expired()+ assert not files._files and not files._pins+++def test_router_expired_routes_remain_available_for_copy_cleanup(clock: list[int]) -> None:+ """到期任务对用户隐藏,但后台必须继续看见等待重试的副本清理记录。"""+ from mineru.kit.router.resources import CopiedInputFile++ registry = ResourceRegistry(retention_seconds=10)+ route = registry.register("job", owner_scope="one", worker_id="worker", upstream_id="job-up")+ route.metadata["payload"] = {"status": "failed", "finished_at": JobStore._now()}+ route.metadata["copied_inputs"] = [CopiedInputFile("file-one", "one", "worker", "file-copy")]+ clock[0] += 11+ assert registry.list("job") == []+ assert registry.list("job", include_expired=True) == [route]diff --git a/tests/unittest/test_v1_router.py b/tests/unittest/test_v1_router.pyindex 6ff79474..b22f4ea4 100644--- a/tests/unittest/test_v1_router.py+++ b/tests/unittest/test_v1_router.py@@ -241,7 +241,7 @@ class _FakeV1Upstream:"object": "upload","bytes": upload["bytes"],"created_at": 1,- "expires_at": 3601,+ "expires_at": int(time.time()) + 3600,"filename": upload["filename"],"purpose": upload.get("purpose", "parse"),"mime_type": upload["mime_type"],