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
Retry safe remote API transport operations
jinzhenj195867269f53
diff --git a/docs/next/sdk/api-parser.md b/docs/next/sdk/api-parser.mdindex ab1f0d5c..f54351c3 100644--- a/docs/next/sdk/api-parser.md+++ b/docs/next/sdk/api-parser.md@@ -77,6 +77,18 @@ class MinerUApiParser(DocumentParser):8. zip 模式从 zip 中读取 middle JSON,并在 `include_images=True` 时读取 middle JSON 引用的图片 sidecar。9. 将 middle JSON 转为 `ParseResult`。+### 传输重试++客户端对可安全重放的传输操作执行有限重试:++- health、upload 状态、job 轮询和产物下载使用 `GET`,可以重试。+- 向 `upload_url` 写入相同文件字节使用 `PUT`,可以重试。+- upload complete 的响应丢失后,客户端先查询 upload 状态;已经完成则读取其中的 File,仍为 pending 才再次 complete。++`POST /v1/parse/jobs` 在 API 提供幂等键契约前不会自动重试。该请求的响应丢失时,服务端可能已经创建任务;直接重放会产生重复任务和费用。++重试耗尽后,doclib 远端解析分别使用 `remote_timeout` 或 `remote_unreachable`,不把客户端传输错误归类为 `parse_failed`。远端 job 自身返回的结构化 `parse_failed` 保持原语义,客户端不根据错误消息文本猜测错误来源。+本地 source:Local Parse Server 必须通过 `--allow-local-source` 开启,并在 `features.sources` 返回 `local`,SDK 才会使用该形式。@@ -137,6 +149,8 @@ API error envelope 应映射为 SDK exception:| `quality_tier_unavailable` | 抛出引擎不可用错误。 || `rate_limit_exceeded` | 抛出可重试错误,并保留 `Retry-After`。 || `service_unavailable` | 抛出可重试错误。 |+| `remote_timeout` | 远端传输超时,有限重试后仍未恢复。 |+| `remote_unreachable` | 远端连接或协议错误,有限重试后仍未恢复。 |当前实现有内部 `_V1APIError`。目标公开契约应复用 `mineru.errors.MineruError` 或统一 SDK exception hierarchy。diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex 5c0de1d1..7001f240 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -24,7 +24,7 @@ from ...filetypes import (file_type_for_extension,is_office_temp_lock_file,)-from ...parser.api_client import _V1APIError+from ...parser.api_client import _APITransportError, _V1APIErrorfrom ...parser.base import ParseResultfrom ...types import QUALITY_TIERS, TIER_ORDER, PageInfo, Tier, select_default_quality_tier, select_parsing_rule_tierfrom ..core.db import DatabaseManager@@ -1076,7 +1076,19 @@ class ParseService:tier=resolved_tier,include_images=Path(file_row["path"]).suffix.lower().lstrip(".") in OFFICE_EXTENSIONS,)- result = await parser.parse_async(file_row["path"], page_range=page_range)+ try:+ result = await parser.parse_async(file_row["path"], page_range=page_range)+ except _APITransportError as exc:+ if via == "remote":+ code = "remote_timeout" if exc.timed_out else "remote_unreachable"+ target = "Remote API"+ else:+ code = "parse_server_unavailable"+ target = "Local parse-server"+ raise ParseFailure(+ code,+ f"{target} transport failed during {exc.stage} after {exc.attempts} attempt(s) ({type(exc.cause).__name__}).",+ ) from exc_remap_api_result_pages_to_page_range(result, page_range)return result, viadiff --git a/mineru/errors.py b/mineru/errors.pyindex 5c8d7a4b..0a8e34aa 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -118,6 +118,8 @@ _ERROR_CODE_STATUS_MAP: dict[str, int] = {"tier_not_cached": 404,"upload_not_found": 404,"watch_not_found": 404,+ "remote_timeout": 503,+ "remote_unreachable": 503,"server_busy": 503,}diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex 3bb2e110..4776e56d 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -13,11 +13,13 @@ import hashlibimport ioimport ipaddressimport json+import loggingimport os+import randomimport timeimport zipfilefrom pathlib import Path-from typing import Any+from typing import Any, Literalfrom urllib.parse import urlparseimport httpx@@ -30,6 +32,23 @@ from .base import DocumentParser, ParseResult_POLL_INTERVAL_SECONDS = 1_POLL_MAX_ATTEMPTS = 3600_TERMINAL_JOB_STATUSES = {"completed", "partial", "failed", "canceled"}+_TRANSPORT_MAX_ATTEMPTS = 3+_TRANSPORT_RETRY_BASE_DELAY_SECONDS = 0.25+_TRANSPORT_RETRY_MAX_DELAY_SECONDS = 2.0++logger = logging.getLogger("mineru.api_client")++_RequestMethod = Literal["GET", "POST", "PUT"]+++class _APITransportError(Exception):+ def __init__(self, *, stage: str, method: _RequestMethod, attempts: int, cause: httpx.TransportError) -> None:+ self.stage = stage+ self.method = method+ self.attempts = attempts+ self.cause = cause+ self.timed_out = isinstance(cause, httpx.TimeoutException)+ super().__init__(f"API transport failed during {stage} after {attempts} attempt(s) ({type(cause).__name__})")class MinerUApiParser(DocumentParser):@@ -142,7 +161,13 @@ class MinerUApiParser(DocumentParser):if self._source_features is not None:return self._source_featureswith httpx.Client(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:- r = cli.get(f"{self._base_url}/v1/health", headers=self._headers())+ r = _request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/health",+ stage="health discovery",+ headers=self._headers(),+ )health = self._check(r)self._source_features = _extract_feature_list(health, "sources")return self._source_features@@ -151,7 +176,13 @@ class MinerUApiParser(DocumentParser):if self._source_features is not None:return self._source_featuresasync with httpx.AsyncClient(timeout=httpx.Timeout(30, connect=10), trust_env=self._trust_env) as cli:- r = await cli.get(f"{self._base_url}/v1/health", headers=self._headers())+ r = await _async_request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/health",+ stage="health discovery",+ headers=self._headers(),+ )health = self._check(r)self._source_features = _extract_feature_list(health, "sources")return self._source_features@@ -204,10 +235,13 @@ class MinerUApiParser(DocumentParser):sha = _sha256_file(file_path)with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:- r = cli.post(+ r = _request_once(+ cli,+ "POST",f"{self._base_url}/v1/uploads",+ stage="upload creation",headers=self._headers(),- json={+ json_body={"filename": file_path.name,"bytes": size,"mime_type": mime_type_for_extension(file_path),@@ -224,14 +258,17 @@ class MinerUApiParser(DocumentParser):if upload_url.startswith("/"):upload_url = f"{self._base_url}{upload_url}"with file_path.open("rb") as fh:- r2 = cli.put(upload_url, content=fh.read(), headers=upload_headers)+ r2 = _request_with_retry(+ cli,+ "PUT",+ upload_url,+ stage="upload content",+ headers=upload_headers,+ content=fh.read(),+ )self._check(r2)- r3 = cli.post(- f"{self._base_url}/v1/uploads/{resp['id']}/complete",- headers=self._headers(),- )- resp3 = self._check(r3)+ resp3 = self._complete_upload(cli, str(resp["id"]))return resp3["file"]["id"]async def _async_upload(self, file_path: Path) -> str:@@ -239,10 +276,13 @@ class MinerUApiParser(DocumentParser):sha = _sha256_file(file_path)async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:- r = await cli.post(+ r = await _async_request_once(+ cli,+ "POST",f"{self._base_url}/v1/uploads",+ stage="upload creation",headers=self._headers(),- json={+ json_body={"filename": file_path.name,"bytes": size,"mime_type": mime_type_for_extension(file_path),@@ -259,21 +299,109 @@ class MinerUApiParser(DocumentParser):if upload_url.startswith("/"):upload_url = f"{self._base_url}{upload_url}"data = file_path.read_bytes()- r2 = await cli.put(upload_url, content=data, headers=upload_headers)+ r2 = await _async_request_with_retry(+ cli,+ "PUT",+ upload_url,+ stage="upload content",+ headers=upload_headers,+ content=data,+ )self._check(r2)- r3 = await cli.post(- f"{self._base_url}/v1/uploads/{resp['id']}/complete",- headers=self._headers(),- )- resp3 = self._check(r3)+ resp3 = await self._async_complete_upload(cli, str(resp["id"]))return resp3["file"]["id"]+ def _complete_upload(self, cli: httpx.Client, upload_id: str) -> dict[str, Any]:+ complete_url = f"{self._base_url}/v1/uploads/{upload_id}/complete"+ last_transport_error: _APITransportError | None = None+ for attempt in range(1, _TRANSPORT_MAX_ATTEMPTS + 1):+ try:+ response = _request_once(+ cli,+ "POST",+ complete_url,+ stage="upload completion",+ headers=self._headers(),+ )+ return self._check(response)+ except _APITransportError as exc:+ last_transport_error = exc+ except _V1APIError as exc:+ if exc.code != "upload_already_terminal":+ raise++ upload = self._get_upload(cli, upload_id)+ if upload.get("status") == "completed":+ return upload+ if attempt < _TRANSPORT_MAX_ATTEMPTS:+ time.sleep(_transport_retry_delay(attempt))++ if last_transport_error is not None:+ raise last_transport_error+ raise _V1APIError("upload_not_ready", f"Upload {upload_id} did not reach completed status")++ async def _async_complete_upload(self, cli: httpx.AsyncClient, upload_id: str) -> dict[str, Any]:+ complete_url = f"{self._base_url}/v1/uploads/{upload_id}/complete"+ last_transport_error: _APITransportError | None = None+ for attempt in range(1, _TRANSPORT_MAX_ATTEMPTS + 1):+ try:+ response = await _async_request_once(+ cli,+ "POST",+ complete_url,+ stage="upload completion",+ headers=self._headers(),+ )+ return self._check(response)+ except _APITransportError as exc:+ last_transport_error = exc+ except _V1APIError as exc:+ if exc.code != "upload_already_terminal":+ raise++ upload = await self._async_get_upload(cli, upload_id)+ if upload.get("status") == "completed":+ return upload+ if attempt < _TRANSPORT_MAX_ATTEMPTS:+ await asyncio.sleep(_transport_retry_delay(attempt))++ if last_transport_error is not None:+ raise last_transport_error+ raise _V1APIError("upload_not_ready", f"Upload {upload_id} did not reach completed status")++ def _get_upload(self, cli: httpx.Client, upload_id: str) -> dict[str, Any]:+ response = _request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/uploads/{upload_id}",+ stage="upload status",+ headers=self._headers(),+ )+ return self._check(response)++ async def _async_get_upload(self, cli: httpx.AsyncClient, upload_id: str) -> dict[str, Any]:+ response = await _async_request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/uploads/{upload_id}",+ stage="upload status",+ headers=self._headers(),+ )+ return self._check(response)+# ── parse execution ──────────────────────────────────────────────def _do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:with httpx.Client(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:- r = cli.post(f"{self._base_url}/v1/parse/jobs", headers=self._headers(), json=payload)+ r = _request_once(+ cli,+ "POST",+ f"{self._base_url}/v1/parse/jobs",+ stage="job submission",+ headers=self._headers(),+ json_body=payload,+ )job = self._check(r)if job.get("status") not in _TERMINAL_JOB_STATUSES:job = self._poll(cli, job["job_id"])@@ -281,7 +409,14 @@ class MinerUApiParser(DocumentParser):async def _async_do_parse(self, payload: dict[str, Any]) -> dict[str, Any]:async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), trust_env=self._trust_env) as cli:- r = await cli.post(f"{self._base_url}/v1/parse/jobs", headers=self._headers(), json=payload)+ r = await _async_request_once(+ cli,+ "POST",+ f"{self._base_url}/v1/parse/jobs",+ stage="job submission",+ headers=self._headers(),+ json_body=payload,+ )job = self._check(r)if job.get("status") not in _TERMINAL_JOB_STATUSES:job = await self._async_poll(cli, job["job_id"])@@ -290,7 +425,13 @@ class MinerUApiParser(DocumentParser):def _poll(self, cli: Any, job_id: str) -> dict[str, Any]:for _ in range(_POLL_MAX_ATTEMPTS): # max 1 hourtime.sleep(_POLL_INTERVAL_SECONDS)- r = cli.get(f"{self._base_url}/v1/parse/jobs/{job_id}", headers=self._headers())+ r = _request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/parse/jobs/{job_id}",+ stage="job polling",+ headers=self._headers(),+ )job = self._check(r)if job.get("status") in _TERMINAL_JOB_STATUSES:return job@@ -299,7 +440,13 @@ class MinerUApiParser(DocumentParser):async def _async_poll(self, cli: Any, job_id: str) -> dict[str, Any]:for _ in range(_POLL_MAX_ATTEMPTS):await asyncio.sleep(_POLL_INTERVAL_SECONDS)- r = await cli.get(f"{self._base_url}/v1/parse/jobs/{job_id}", headers=self._headers())+ r = await _async_request_with_retry(+ cli,+ "GET",+ f"{self._base_url}/v1/parse/jobs/{job_id}",+ stage="job polling",+ headers=self._headers(),+ )job = self._check(r)if job.get("status") in _TERMINAL_JOB_STATUSES:return job@@ -319,6 +466,196 @@ class MinerUApiParser(DocumentParser):# ═══════════════════════════════════════════════════════════════════════+def _request_once(+ client: httpx.Client,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None = None,+ content: bytes | None = None,+) -> httpx.Response:+ return _request(+ client,+ method,+ url,+ stage=stage,+ headers=headers,+ json_body=json_body,+ content=content,+ max_attempts=1,+ )+++def _request_with_retry(+ client: httpx.Client,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None = None,+ content: bytes | None = None,+) -> httpx.Response:+ return _request(+ client,+ method,+ url,+ stage=stage,+ headers=headers,+ json_body=json_body,+ content=content,+ max_attempts=_TRANSPORT_MAX_ATTEMPTS,+ )+++def _request(+ client: httpx.Client,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None,+ content: bytes | None,+ max_attempts: int,+) -> httpx.Response:+ for attempt in range(1, max_attempts + 1):+ try:+ return _send_request(client, method, url, headers=headers, json_body=json_body, content=content)+ except httpx.TransportError as exc:+ if attempt >= max_attempts:+ raise _APITransportError(stage=stage, method=method, attempts=attempt, cause=exc) from exc+ logger.warning(+ "Retrying API transport request: stage=%s method=%s next_attempt=%s/%s error=%s",+ stage,+ method,+ attempt + 1,+ max_attempts,+ type(exc).__name__,+ )+ time.sleep(_transport_retry_delay(attempt))+ raise AssertionError("API transport retry loop exited unexpectedly")+++async def _async_request_once(+ client: httpx.AsyncClient,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None = None,+ content: bytes | None = None,+) -> httpx.Response:+ return await _async_request(+ client,+ method,+ url,+ stage=stage,+ headers=headers,+ json_body=json_body,+ content=content,+ max_attempts=1,+ )+++async def _async_request_with_retry(+ client: httpx.AsyncClient,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None = None,+ content: bytes | None = None,+) -> httpx.Response:+ return await _async_request(+ client,+ method,+ url,+ stage=stage,+ headers=headers,+ json_body=json_body,+ content=content,+ max_attempts=_TRANSPORT_MAX_ATTEMPTS,+ )+++async def _async_request(+ client: httpx.AsyncClient,+ method: _RequestMethod,+ url: str,+ *,+ stage: str,+ headers: dict[str, str],+ json_body: dict[str, Any] | None,+ content: bytes | None,+ max_attempts: int,+) -> httpx.Response:+ for attempt in range(1, max_attempts + 1):+ try:+ return await _async_send_request(client, method, url, headers=headers, json_body=json_body, content=content)+ except httpx.TransportError as exc:+ if attempt >= max_attempts:+ raise _APITransportError(stage=stage, method=method, attempts=attempt, cause=exc) from exc+ logger.warning(+ "Retrying API transport request: stage=%s method=%s next_attempt=%s/%s error=%s",+ stage,+ method,+ attempt + 1,+ max_attempts,+ type(exc).__name__,+ )+ await asyncio.sleep(_transport_retry_delay(attempt))+ raise AssertionError("API transport retry loop exited unexpectedly")+++def _send_request(+ client: httpx.Client,+ method: _RequestMethod,+ url: str,+ *,+ headers: dict[str, str],+ json_body: dict[str, Any] | None,+ content: bytes | None,+) -> httpx.Response:+ if method == "GET":+ return client.get(url, headers=headers)+ if method == "PUT":+ return client.put(url, headers=headers, content=content or b"")+ if json_body is None:+ return client.post(url, headers=headers)+ return client.post(url, headers=headers, json=json_body)+++async def _async_send_request(+ client: httpx.AsyncClient,+ method: _RequestMethod,+ url: str,+ *,+ headers: dict[str, str],+ json_body: dict[str, Any] | None,+ content: bytes | None,+) -> httpx.Response:+ if method == "GET":+ return await client.get(url, headers=headers)+ if method == "PUT":+ return await client.put(url, headers=headers, content=content or b"")+ if json_body is None:+ return await client.post(url, headers=headers)+ return await client.post(url, headers=headers, json=json_body)+++def _transport_retry_delay(attempt: int) -> float:+ exponential = min(+ _TRANSPORT_RETRY_MAX_DELAY_SECONDS,+ _TRANSPORT_RETRY_BASE_DELAY_SECONDS * (2 ** (attempt - 1)),+ )+ return exponential * (0.5 + random.random())++def _sha256_file(path: Path) -> str:h = hashlib.sha256()with path.open("rb") as fh:@@ -550,7 +887,13 @@ def _download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) -> bytes:raise _V1APIError("invalid_response", "No file_id in output reference")with httpx.Client(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:- r = cli.get(f"{parser._base_url}/v1/files/{file_id}/content", headers=parser._headers())+ r = _request_with_retry(+ cli,+ "GET",+ f"{parser._base_url}/v1/files/{file_id}/content",+ stage="output download",+ headers=parser._headers(),+ )_check_download_response(r)return r.content@@ -563,7 +906,13 @@ async def _async_download_bytes(parser: MinerUApiParser, ref: dict[str, Any]) ->async with httpx.AsyncClient(timeout=httpx.Timeout(120, connect=30), follow_redirects=True, trust_env=parser._trust_env) as cli:- r = await cli.get(f"{parser._base_url}/v1/files/{file_id}/content", headers=parser._headers())+ r = await _async_request_with_retry(+ cli,+ "GET",+ f"{parser._base_url}/v1/files/{file_id}/content",+ stage="output download",+ headers=parser._headers(),+ )_check_download_response(r)return r.contentdiff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex dc8266cb..d17e788e 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom types import SimpleNamespacefrom typing import Any+import httpximport pytestfrom PIL import Image@@ -53,7 +54,7 @@ from mineru.doclib.services.search_svc import SearchServicefrom mineru.doclib.types import DocContentExportRequest, FileInfo, InvalidateRequest, ParseResponse, WatchRequestfrom mineru.errors import InvalidRequestError, MineruError, NotFoundErrorfrom mineru.parser import backend_for_tier, resolve_tier_and_backend-from mineru.parser.api_client import _V1APIError+from mineru.parser.api_client import _APITransportError, _V1APIErrorfrom mineru.parser.base import ParseResultfrom mineru.parser import MIDDLE_JSON_SCHEMA_VERSIONfrom mineru.types import Block, BlockType, ContentType, Line, PageInfo, Span, Tier@@ -3636,6 +3637,49 @@ def test_process_doc_preserves_remote_api_error_code(tmp_path: Path) -> None:assert parses[0]["error_msg"] == "Remote authentication failed: user authenticate failed"+ ("cause", "expected_code"),+ [+ (httpx.ReadTimeout("timed out"), "remote_timeout"),+ (httpx.ReadError("connection closed"), "remote_unreachable"),+ ],+)+def test_parse_via_api_maps_transport_errors_by_type(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ cause: httpx.TransportError,+ expected_code: str,+) -> None:+ service = ParseService(+ db=_FakeDB(parses=[], file_row=None),+ fts=_FakeFTS(),+ config_svc=None,+ data_dir=str(tmp_path),+ parse_lock_timeout_sec=1800,+ )++ async def _resolve_api_target(_privacy: str, _tier: Tier) -> tuple[str, str | None, str]:+ return "https://mineru.net/api", "test-key", "remote"++ class _FakeApiParser:+ def __init__(self, **_: object) -> None:+ pass++ async def parse_async(self, _path: str, *, page_range: str = "") -> ParseResult:+ raise _APITransportError(stage="job polling", method="GET", attempts=3, cause=cause)++ service._resolve_api_target = _resolve_api_target # type: ignore[method-assign]+ service._resolve_tier = lambda tier, _via: tier # type: ignore[method-assign]+ monkeypatch.setattr("mineru.parser.api_client.MinerUApiParser", _FakeApiParser)++ with pytest.raises(ParseFailure) as exc_info:+ asyncio.run(service._parse_via_api({"path": "/tmp/doc.pdf"}, "high", "1", "remote"))++ assert exc_info.value.code == expected_code+ assert "job polling" in exc_info.value.message+ assert type(cause).__name__ in exc_info.value.message++@pytest.mark.parametrize(("path", "expected_include_images"),[diff --git a/tests/unittest/test_errors.py b/tests/unittest/test_errors.pyindex f6dacb92..bc090f95 100644--- a/tests/unittest/test_errors.py+++ b/tests/unittest/test_errors.py@@ -100,6 +100,8 @@ def test_http_status_for_error_codes_is_stable() -> None:assert http_status_for("engine_unavailable") == 503assert http_status_for("parse_wait_timeout") == 408assert http_status_for("parse_server_unavailable") == 500+ assert http_status_for("remote_timeout") == 503+ assert http_status_for("remote_unreachable") == 503assert http_status_for("server_busy") == 503assert http_status_for("internal_error") == 500diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex bb507d0c..ef5dcdf0 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -12,6 +12,7 @@ import typesimport zipfilefrom pathlib import Path+import httpximport pytestfrom click.testing import CliRunnerfrom fastapi.testclient import TestClient@@ -1111,6 +1112,169 @@ def test_api_client_poll_timeout_budget_is_one_hour() -> None:assert api_client._POLL_INTERVAL_SECONDS * api_client._POLL_MAX_ATTEMPTS == 60 * 60+def test_api_client_retries_transient_poll_transport_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ parser = MinerUApiParser(api_url="https://mineru.net/api", tier="high")+ calls = 0+ sleep_delays: list[float] = []++ def fake_get(_url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal calls+ assert headers == {}+ calls += 1+ if calls < 3:+ raise httpx.ReadError("connection closed")+ return httpx.Response(200, json={"job_id": "job_1", "status": "completed"})++ monkeypatch.setattr(api_client, "_transport_retry_delay", lambda _attempt: 0.0)+ monkeypatch.setattr(api_client.time, "sleep", sleep_delays.append)++ job = parser._poll(types.SimpleNamespace(get=fake_get), "job_1")++ assert job["status"] == "completed"+ assert calls == 3+ assert sleep_delays == [1, 0.0, 0.0]+++def test_async_api_client_retries_transient_poll_transport_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ parser = MinerUApiParser(api_url="https://mineru.net/api", tier="high")+ calls = 0+ sleep_delays: list[float] = []++ async def fake_get(_url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal calls+ assert headers == {}+ calls += 1+ if calls < 3:+ raise httpx.ReadError("connection closed")+ return httpx.Response(200, json={"job_id": "job_1", "status": "completed"})++ async def fake_sleep(delay: float) -> None:+ sleep_delays.append(delay)++ monkeypatch.setattr(api_client, "_transport_retry_delay", lambda _attempt: 0.0)+ monkeypatch.setattr(api_client.asyncio, "sleep", fake_sleep)++ job = asyncio.run(parser._async_poll(types.SimpleNamespace(get=fake_get), "job_1"))++ assert job["status"] == "completed"+ assert calls == 3+ assert sleep_delays == [1, 0.0, 0.0]+++def test_api_client_retries_upload_content_put(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0++ class _Client:+ def put(self, _url: str, *, headers: dict[str, str], content: bytes) -> httpx.Response:+ nonlocal calls+ assert headers == {"Content-Type": "application/pdf"}+ assert content == b"pdf"+ calls += 1+ if calls == 1:+ raise httpx.WriteError("connection closed")+ return httpx.Response(200)++ monkeypatch.setattr(api_client.time, "sleep", lambda _delay: None)++ response = api_client._request_with_retry(+ _Client(), # type: ignore[arg-type]+ "PUT",+ "https://upload.example/content",+ stage="upload content",+ headers={"Content-Type": "application/pdf"},+ content=b"pdf",+ )++ assert response.status_code == 200+ assert calls == 2+++def test_api_client_recovers_completed_upload_after_lost_complete_response() -> None:+ parser = MinerUApiParser(api_url="https://mineru.net/api", tier="high")+ complete_calls = 0+ status_calls = 0++ class _Client:+ def post(self, _url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal complete_calls+ assert headers == {}+ complete_calls += 1+ raise httpx.ReadError("response lost")++ def get(self, _url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal status_calls+ assert headers == {}+ status_calls += 1+ return httpx.Response(+ 200,+ json={"id": "upload_1", "status": "completed", "file": {"id": "file_1"}},+ )++ upload = parser._complete_upload(_Client(), "upload_1") # type: ignore[arg-type]++ assert upload["file"]["id"] == "file_1"+ assert complete_calls == 1+ assert status_calls == 1+++def test_async_api_client_recovers_completed_upload_after_lost_complete_response() -> None:+ parser = MinerUApiParser(api_url="https://mineru.net/api", tier="high")+ complete_calls = 0+ status_calls = 0++ class _AsyncClient:+ async def post(self, _url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal complete_calls+ assert headers == {}+ complete_calls += 1+ raise httpx.ReadError("response lost")++ async def get(self, _url: str, *, headers: dict[str, str]) -> httpx.Response:+ nonlocal status_calls+ assert headers == {}+ status_calls += 1+ return httpx.Response(+ 200,+ json={"id": "upload_1", "status": "completed", "file": {"id": "file_1"}},+ )++ upload = asyncio.run(parser._async_complete_upload(_AsyncClient(), "upload_1")) # type: ignore[arg-type]++ assert upload["file"]["id"] == "file_1"+ assert complete_calls == 1+ assert status_calls == 1+++def test_api_client_does_not_retry_job_submission_transport_error(monkeypatch: pytest.MonkeyPatch) -> None:+ calls = 0++ class _Client:+ def __init__(self, **_: object) -> None:+ pass++ def __enter__(self) -> "_Client":+ return self++ def __exit__(self, *args: object) -> None:+ return None++ def post(self, _url: str, *, headers: dict[str, str], json: dict[str, object]) -> httpx.Response:+ nonlocal calls+ assert headers == {}+ assert json == {"files": []}+ calls += 1+ raise httpx.ReadError("response lost")++ monkeypatch.setattr(api_client.httpx, "Client", _Client)++ with pytest.raises(api_client._APITransportError) as exc_info:+ MinerUApiParser(api_url="https://mineru.net/api")._do_parse({"files": []})++ assert exc_info.value.stage == "job submission"+ assert exc_info.value.attempts == 1+ assert calls == 1++def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:pdf = tmp_path / "demo.pdf"pdf.write_bytes(b"%PDF-1.7\n")