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
feat: implement upload expiration handling and reset restart budget for healthy probes
myhlolic8c3ee4e4a49
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 80d55f2d..c439afc5 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -351,6 +351,8 @@ class ParseServerHealthCheck:if probe.healthy:health.local.last_success_at = now_mshealth.local_starting = False+ # MAX_RESTART_ATTEMPTS bounds consecutive failed recoveries; a healthy probe restores the budget.+ health.restart_count = 0else:health.local.last_failure_at = now_msif probe.error_code != "parse_server_unavailable":diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex b4aef8e8..ef21791c 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -1186,7 +1186,7 @@ class ParseService:if local_mode != "disabled" and health.local.probe.healthy:local_url = _local_parse_server_url(local_mode, health)if local_url:- return local_url, api_key, "local"+ return local_url, await _local_parse_server_api_key(self.config_svc), "local"raise ParseFailure("parse_server_unavailable", "Remote parse-server unavailable and no local fallback")return url, api_key, "remote"@@ -1208,7 +1208,7 @@ class ParseService:)raise ParseFailure("engine_unavailable", "Local parse-server is not ready. Please wait or check server status.")- api_key = (await self.config_svc.get("parse_server.local.self_hosted_api_key")) or None+ api_key = await _local_parse_server_api_key(self.config_svc)return local_url, api_key, "local"async def _fail_task(self, task_id: int, code: str, message: str) -> None:@@ -1681,6 +1681,11 @@ def _local_parse_server_url(mode: str, health: object) -> str | None:return None+async def _local_parse_server_api_key(config_svc: ConfigService) -> str | None:+ """Resolve local parse-server API key (self-hosted only; managed servers take no key)."""+ return (await config_svc.get("parse_server.local.self_hosted_api_key")) or None++def _is_official_remote_url(url: str) -> bool:host = urlparse(url).hostname or ""host = host.lower().rstrip(".")diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 2ccbe779..6960193b 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -739,6 +739,10 @@ class FileStore: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 recdef _read_upload_data(self, upload_id: str) -> bytes:diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex bb6f2d6b..7483069b 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -21,6 +21,7 @@ from mineru.doclib.background.compaction import Compactionfrom mineru.doclib.background.device_monitor import DeviceMonitorfrom mineru.doclib.background.ingest import IngestWorkerPoolfrom mineru.doclib.background.parse_server_health import (+ MAX_RESTART_ATTEMPTS,ParseServerHealth,ParseServerHealthCheck,ProbeResult,@@ -997,6 +998,53 @@ def test_managed_parse_server_tier_change_restart_uses_desired_tier(monkeypatch:assert health.restart_count == 2+def test_healthy_probe_resets_managed_restart_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ """健康探测清零托管重启预算,使 MAX_RESTART_ATTEMPTS 只约束连续恢复失败。"""+ health = ParseServerHealth(+ local=ProbeState(url="http://127.0.0.1:16582"),+ local_mode="managed",+ managed_url="http://127.0.0.1:16582",+ running_managed_tier="standard",+ restart_count=MAX_RESTART_ATTEMPTS - 1,+ )++ class _ConfigSvc:+ async def get(self, key: str) -> str:+ values = {+ "parse_server.local.mode": "managed",+ "parse_server.local.managed_tier": "standard",+ "parse_server.remote.url": "https://mineru.net/api",+ }+ return values.get(key, "")++ class _RemoteApiKey:+ value = "remote-key"++ async def _resolve_remote_key(_svc: object) -> _RemoteApiKey:+ return _RemoteApiKey()++ checker = ParseServerHealthCheck(+ _ConfigSvc(),+ interval_sec=0,+ probe_timeout_sec=2,+ startup_grace_sec=3,+ stop_timeout_sec=4,+ startup_timeout_sec=30,+ )++ async def _probe(_url: str, *, api_key: str | None = None) -> ProbeResult:+ checker.running = False+ return ProbeResult(healthy=True, tiers=["standard"])++ monkeypatch.setattr(checker, "_probe", _probe)+ monkeypatch.setattr("mineru.doclib.background.parse_server_health.get_health", lambda: health)+ monkeypatch.setattr("mineru.doclib.background.parse_server_health.resolve_remote_api_key", _resolve_remote_key)++ asyncio.run(checker.run())++ assert health.restart_count == 0++def test_get_file_stat_returns_typed_file_stat(tmp_path: Path) -> None:source = tmp_path / "note.txt"source.write_text("content", encoding="utf-8")@@ -1117,6 +1165,91 @@ def test_remote_api_target_prefers_config_api_key_over_env(monkeypatch: pytest.Masyncio.run(_run())+def test_remote_api_target_fallback_uses_local_self_hosted_api_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """远程不可用时回退本地 self-hosted,凭证应取本地 key 而非远程 key。"""++ class _ConfigService:+ async def get(self, key: str) -> str:+ values = {+ "parse_server.remote.url": "https://mineru.net/api",+ "parse_server.remote.api_key": "remote-key",+ "parse_server.local.mode": "self_hosted",+ "parse_server.local.self_hosted_api_key": "local-key",+ }+ return values[key]++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_ConfigService(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )++ base_url, api_key, via = await service._resolve_api_target("remote", "standard")++ assert base_url == "http://127.0.0.1:16580"+ assert api_key == "local-key"+ assert via == "local"++ monkeypatch.setattr(+ "mineru.doclib.background.parse_server_health.get_health",+ lambda: ParseServerHealth(+ remote=ProbeState(probe=ProbeResult(error_code="parse_server_unavailable")),+ local=ProbeState(url="http://127.0.0.1:16580", probe=ProbeResult(healthy=True)),+ local_mode="self_hosted",+ self_hosted_url="http://127.0.0.1:16580",+ ),+ )++ asyncio.run(_run())+++def test_remote_api_target_fallback_managed_mode_sends_no_api_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ """managed 本地回退不带凭证(managed server 未配置 key,不校验 Bearer)。"""++ class _ConfigService:+ async def get(self, key: str) -> str:+ values = {+ "parse_server.remote.url": "https://mineru.net/api",+ "parse_server.remote.api_key": "remote-key",+ "parse_server.local.mode": "managed",+ }+ return values.get(key, "")++ async def _run() -> None:+ db = DatabaseManager(str(tmp_path / "doclib.db"))+ await db.initialize()+ service = ParseService(+ db=db,+ fts=FTSManager(db),+ config_svc=_ConfigService(),+ data_dir=str(tmp_path / "data"),+ parse_lock_timeout_sec=1800,+ )++ base_url, api_key, via = await service._resolve_api_target("remote", "standard")++ assert base_url == "http://127.0.0.1:16582"+ assert api_key is None+ assert via == "local"++ monkeypatch.setattr(+ "mineru.doclib.background.parse_server_health.get_health",+ lambda: ParseServerHealth(+ remote=ProbeState(probe=ProbeResult(error_code="parse_server_unavailable")),+ local=ProbeState(url="http://127.0.0.1:16582", probe=ProbeResult(healthy=True)),+ local_mode="managed",+ managed_url="http://127.0.0.1:16582",+ ),+ )++ asyncio.run(_run())++def test_remote_api_target_preserves_probe_invalid_api_key(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:class _ConfigService:async def get(self, key: str) -> str:diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex cf3cde9a..eee51e3a 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -9,6 +9,7 @@ import jsonimport loggingimport subprocessimport sys+import timeimport typesimport zipfilefrom pathlib import Path@@ -2011,6 +2012,47 @@ def test_complete_upload_rejects_size_mismatch(tmp_path: Path) -> None:assert exc_info.value.error.code == "upload_size_mismatch"+def test_get_upload_expires_pending_records_and_discards_staged_data(tmp_path: Path) -> None:+ """expires_at 过后 pending 上传惰性转为 expired 终态并丢弃暂存数据,后续 PUT/complete 收到 409。"""+ file_store = FileStore(tmp_path / "api-files")+ upload = file_store.create_upload(+ CreateUploadRequest.model_validate({"filename": "demo.pdf", "bytes": 4, "mime_type": "application/pdf"})+ )+ file_store.store_upload_data(upload.id, b"demo")+ staged = tmp_path / "api-files" / "blobs" / "_uploads" / upload.id+ assert staged.is_file()++ file_store._uploads[upload.id].expires_at = int(time.time()) - 1++ rec = file_store.get_upload(upload.id)++ assert rec.status == "expired"+ assert 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 机制。"""+ file_store = FileStore(tmp_path / "api-files")+ sha = "00" * 32+ file_store.store_blob(b"demo", sha256hex=sha)+ upload = file_store.create_upload(+ CreateUploadRequest.model_validate(+ {"filename": "demo.pdf", "bytes": 4, "mime_type": "application/pdf", "sha256sum": sha}+ )+ )+ assert upload.status == "completed"++ file_store._uploads[upload.id].expires_at = int(time.time()) - 1++ assert file_store.get_upload(upload.id).status == "completed"++def test_run_job_preserves_input_file_id_and_keeps_source_undownloadable(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,