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
fix(runtime): isolate LMDeploy failure and delegate recovery to hosts
myhloli359f8c79fcb9
diff --git a/docs/next/api/health-models.md b/docs/next/api/health-models.mdindex 65e44e1c..3bd0ac47 100644--- a/docs/next/api/health-models.md+++ b/docs/next/api/health-models.md@@ -55,3 +55,17 @@ Router 合并健康 worker 的模型列表并按 ID 去重。多个版本 ID 表该列表只约束 PDF/图片。正常可用服务的原生文档仍使用 Flash,不要求列表中存在 flash。Tasks 省略 tier 时使用 standard → basic → flash → advanced;只开放 Advanced 时才自动选中它。显式不支持的 PDF/图片档位报错,不改档。完整语义见 [Tasks](https://opendatalab.github.io/MinerU/zh/usage/tasks/)。++## 已加载 LMDeploy 的运行时健康++解析服务每 5 秒探测本应用已创建的 LMDeploy 运行时,单次探测期限 5 秒,后端最多一个在途探测。探测不会初始化惰性模型,也不会为 Flash 服务下载 VLM。++- 确认引擎死亡后锁存 `engine_dead`,健康、能力发现与新任务入口返回 503;运行与排队任务沿既有清理边界失败,不发布未完成结果。原实例不会在同一次请求中自动重建或降级。+- 探测超时、睡眠或暂时不可用返回 503 / `engine_unavailable`,拒绝新推理但不永久标记死亡;后续健康探测恢复后解除。+- Router/Doclib 管理的本地进程沿既有控制通道、关闭超时和恢复策略重建;外部 worker 只停止分配,不由 MinerU 擅自结束其进程。SDK 传播错误,由调用方负责释放和重建。++同一运行时实例的全部关联 owner 都会收到失效状态,缓存命中不能继续交付该死亡实例。健康状态恢复只适用于暂时不可用;永久失效必须释放旧实例,由其宿主管理新的实例。故障请求本身不会静默重试、重建或降低档位。++引擎后台任务退出不一定导致 Python 宿主进程退出。宿主存活时,仍需完成上述错误传播和任务清理;整个托管 worker 退出时,由进程管理者发现退出、清除旧工作状态并重建。CLI 以非零状态退出,SDK 向调用者抛出明确异常;共享库不自行终止调用方进程。++普通单片识别失败仍可回退 MFR。此机制不替代原始引擎崩溃原因调查,也不以解决所有后端崩溃根因为交付前提。日志保留首次错误的异常链;Windows 验收脚本位于 `scripts/acceptance/`,只以受支持的 TurboMind 后端验证故障处理流程。diff --git a/mineru/errors.py b/mineru/errors.pyindex 38b235ff..66221d0e 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -78,6 +78,7 @@ _ERROR_TYPE_MAP: dict[str, ErrorType] = {# engine_error"no_engine": "engine_error","engine_unavailable": "engine_error",+ "engine_dead": "engine_error","parse_empty": "engine_error","parse_failed": "engine_error","parse_page_remap_failed": "engine_error",diff --git a/mineru/model/runtime/ownership.py b/mineru/model/runtime/ownership.pyindex 9d300e2e..735e2f5d 100644--- a/mineru/model/runtime/ownership.py+++ b/mineru/model/runtime/ownership.py@@ -16,10 +16,26 @@ class RuntimeOwner:"""初始化关闭状态、引擎错误及受保护的在途文档计数。"""self.closed = Falseself.engine_error: str | None = None+ self.has_engine_health_probe = False+ self._unavailable_engines: dict[object, str] = {}self._documents = 0self._initializations = 0self._condition = threading.Condition()+ def set_engine_unavailable(self, engine: object, message: str | None) -> None:+ """独立记录各引擎的暂时健康状态,某个恢复不能清除另一引擎的故障。"""+ with self._condition:+ if message is None:+ self._unavailable_engines.pop(engine, None)+ else:+ self._unavailable_engines[engine] = message++ @property+ def engine_unavailable(self) -> str | None:+ """线程安全地向服务接单和健康入口提供暂时不可用原因。"""+ with self._condition:+ return next(iter(self._unavailable_engines.values()), None)+def acquire_document(self) -> None:"""接纳新文档;关闭开始后不允许新的模型使用范围进入。"""with self._condition:diff --git a/mineru/model/vlm/errors.py b/mineru/model/vlm/errors.pyindex 20174c50..5b0f9040 100644--- a/mineru/model/vlm/errors.py+++ b/mineru/model/vlm/errors.py@@ -3,13 +3,28 @@from __future__ import annotations+from ...errors import MineruError++_FATAL_ENGINE_TYPES: dict[str, frozenset[str]] = {+ "vllm": frozenset({"EngineDeadError", "AsyncEngineDeadError"}),+ "mineru_vl_utils": frozenset({"EngineUnavailableError"}),+}+++class EngineNotReadyError(MineruError):+ """健康探测暂时不可用,拒绝新推理但不把实例永久标记为死亡。"""++ def __init__(self, message: str) -> None:+ """保留现有 API 错误码供本地、远程和批处理一致处理。"""+ super().__init__("engine_unavailable", message)+class EngineDeadError(RuntimeError):"""表示本地引擎已死亡,当前进程不能继续接受推理。"""def is_fatal_engine_error(error: BaseException) -> bool:- """遍历异常链和异常组,优先匹配 vLLM 的明确死亡类型。"""+ """遍历异常链和异常组,仅匹配后端明确报告的死亡类型。"""pending = [error]visited: set[int] = set()while pending:@@ -20,7 +35,7 @@ def is_fatal_engine_error(error: BaseException) -> bool:if isinstance(current, EngineDeadError):return Truefor cls in type(current).__mro__:- if cls.__module__.startswith("vllm.") and cls.__name__ in {"EngineDeadError", "AsyncEngineDeadError"}:+ if cls.__name__ in _FATAL_ENGINE_TYPES.get(cls.__module__.split(".", 1)[0], ()):return Trueif any(cls.__name__ == "BaseExceptionGroup" for cls in type(current).__mro__):pending.extend(item for item in getattr(current, "exceptions", ()) if isinstance(item, BaseException))@@ -31,4 +46,4 @@ def is_fatal_engine_error(error: BaseException) -> bool:return False-__all__ = ["EngineDeadError", "is_fatal_engine_error"]+__all__ = ["EngineDeadError", "EngineNotReadyError", "is_fatal_engine_error"]diff --git a/mineru/model/vlm/handles.py b/mineru/model/vlm/handles.pyindex df8a196f..486f9fee 100644--- a/mineru/model/vlm/handles.py+++ b/mineru/model/vlm/handles.py@@ -4,21 +4,27 @@from __future__ import annotationsimport asyncio+import loggingimport threading+import timefrom collections.abc import AsyncIterator, Callable, Iterator, Sequencefrom contextlib import asynccontextmanager, contextmanagerfrom typing import TYPE_CHECKINGfrom ...utils.async_utils import drain_future, run_syncfrom ..runtime.closing import runtime_close_scope-from ..runtime.ownership import RuntimeOwner+from ..runtime.ownership import RuntimeOwner, current_runtime_owner+from .errors import EngineDeadError, EngineNotReadyError, is_fatal_engine_errorfrom .text_recognition import TextRecognitionResult, recognize_text_batchif TYPE_CHECKING:from mineru_vl_utils import MinerUClientfrom mineru_vl_utils.structs import ContentBlock, ExtractResult+ from mineru_vl_utils.vlm_client.base_client import EngineHealthfrom PIL.Image import Image+logger = logging.getLogger(__name__)+class RuntimeHandle:"""将客户端、串行执行锁和创建时确定的资源释放动作放在同一宿主对象中。"""@@ -29,6 +35,8 @@ class RuntimeHandle:*,backend: str,close_engine: Callable[[], None] | None = None,+ probe_engine: Callable[[float], EngineHealth] | None = None,+ close_health_probe: Callable[[], None] | None = None,) -> None:"""保存已创建资源,不修改第三方客户端的属性或推测其内部结构。"""self.backend = backend@@ -37,6 +45,11 @@ class RuntimeHandle:self.execution_lock = threading.Lock() if backend == "mlx-engine" else Noneself._predictor: MinerUClient | None = predictorself._close_engine = close_engine+ self._probe_engine = probe_engine+ self._close_health_probe = close_health_probe+ self._probe_lock = threading.Lock()+ self._fatal_error: BaseException | None = None+ self._health_unavailable: str | None = Noneself._condition = threading.Condition()self._active = 0self._closing = False@@ -54,12 +67,103 @@ class RuntimeHandle:"""让缓存识别正在关闭或已经关闭的宿主句柄。"""return self._closing- @contextmanager- def _use(self, *, acquire_lock: bool = True) -> Iterator[MinerUClient]:- """等待同步推理自然返回后才允许关闭引擎,MLX 使用宿主串行锁。"""+ @property+ def supports_health_probe(self) -> bool:+ """缓存管理者据此开启只读探测,不为未加载模型触发初始化。"""+ return self._probe_engine is not None++ def require_ready(self, *, allow_unavailable: bool = False) -> None:+ """拒绝已经关闭、明确死亡或探测暂时不可用的运行时。"""with self._condition:+ if self._fatal_error is not None:+ raise EngineDeadError(str(self._fatal_error)) from self._fatal_errorif self._closing:raise RuntimeError("VLM runtime is shutting down")+ if self._health_unavailable is not None and not allow_unavailable:+ raise EngineNotReadyError(self._health_unavailable)++ def _mark_fatal(self, error: BaseException) -> None:+ """锁存最早故障并通知全部宿主,记录原始异常链而不重建或降级。"""+ with self._condition:+ first_failure = self._fatal_error is None+ if first_failure:+ self._fatal_error = error+ message = str(self._fatal_error)+ owners = set(self.owners)+ owner = current_runtime_owner()+ if owner is not None:+ owners.add(owner)+ for owner in owners:+ if owner.engine_error is None:+ owner.engine_error = message+ owner.set_engine_unavailable(self, None)+ if first_failure:+ logger.error(+ "VLM engine failed: backend=%s error_type=%s",+ self.backend,+ type(error).__name__,+ exc_info=(type(error), error, error.__traceback__),+ )++ def probe_health(self, timeout: float = 5.0) -> None:+ """执行至多一个宿主探测;超时状态可恢复,明确死亡永不被健康结果覆盖。"""+ if self._probe_engine is None:+ return+ if timeout <= 0:+ raise ValueError("Health probe timeout must be positive")+ started = time.monotonic()+ if not self._probe_lock.acquire(timeout=timeout):+ raise EngineNotReadyError("Another engine health probe is still pending")+ active = False+ try:+ with self._condition:+ if self._closing:+ return+ if self._fatal_error is not None:+ raise EngineDeadError(str(self._fatal_error)) from self._fatal_error+ self._active += 1+ active = True+ try:+ remaining = timeout - (time.monotonic() - started)+ if remaining <= 0:+ raise TimeoutError("Engine health probe deadline elapsed while waiting")+ health = self._probe_engine(remaining)+ if health.state not in {"healthy", "unavailable", "dead"}:+ raise ValueError("Invalid engine health state")+ except Exception as exc:+ if is_fatal_engine_error(exc):+ self._mark_fatal(exc)+ raise+ logger.exception("VLM health probe failed: backend=%s", self.backend)+ message = f"VLM health probe failed: {type(exc).__name__}: {exc}"+ else:+ if health.state == "dead":+ error = EngineDeadError(health.message or "VLM engine is unavailable")+ self._mark_fatal(error)+ raise error+ message = health.message or "VLM engine health is unavailable" if health.state == "unavailable" else None+ with self._condition:+ if self._fatal_error is not None:+ raise EngineDeadError(str(self._fatal_error)) from self._fatal_error+ self._health_unavailable = message+ for owner in tuple(self.owners):+ owner.set_engine_unavailable(self, message)+ if message is not None:+ raise EngineNotReadyError(message)+ finally:+ if active:+ with self._condition:+ self._active -= 1+ self._condition.notify_all()+ self._probe_lock.release()++ @contextmanager+ def _use(self, *, acquire_lock: bool = True, probe: bool = True) -> Iterator[MinerUClient]:+ """等待同步推理自然返回后才允许关闭引擎,MLX 使用宿主串行锁。"""+ if probe:+ self.probe_health()+ with self._condition:+ self.require_ready()self._active += 1predictor = self.predictortry:@@ -68,6 +172,13 @@ class RuntimeHandle:else:with self.execution_lock:yield predictor+ with self._condition:+ if self._fatal_error is not None:+ raise EngineDeadError(str(self._fatal_error)) from self._fatal_error+ except Exception as exc:+ if is_fatal_engine_error(exc):+ self._mark_fatal(exc)+ raisefinally:with self._condition:self._active -= 1@@ -76,6 +187,8 @@ class RuntimeHandle:@asynccontextmanagerasync def _async_use(self) -> AsyncIterator[MinerUClient]:"""可取消地等待串行锁,排队期间取消不得让迟到工作线程开始推理。"""+ if self._probe_engine is not None:+ await run_sync(self.probe_health)lock = self.execution_lockif lock is not None:while True:@@ -86,7 +199,7 @@ class RuntimeHandle:breakawait asyncio.sleep(0.01)try:- with self._use(acquire_lock=False) as predictor:+ with self._use(acquire_lock=False, probe=False) as predictor:yield predictorfinally:if lock is not None:@@ -183,7 +296,11 @@ class RuntimeHandle:if first_error is None:first_error = excfinally:+ for owner in tuple(self.owners):+ owner.set_engine_unavailable(self, None)self._predictor = None+ self._probe_engine = None+ self._close_health_probe = Noneself._closed.set()if first_error is not None:raise first_error@@ -197,7 +314,9 @@ class RuntimeHandle:try:with runtime_close_scope():self._wait_for_calls()- if self.backend == "http-client":+ if self._close_health_probe is not None:+ self._close_health_probe()+ elif self.backend in {"http-client", "lmdeploy-engine"}:asyncio.run(self.predictor.aclose())except BaseException as exc:error = excdiff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.pyindex f377b798..196be98a 100644--- a/mineru/model/vlm/runtime.py+++ b/mineru/model/vlm/runtime.py@@ -25,6 +25,7 @@ from ..runtime.closing import in_runtime_close_scope, runtime_close_scopefrom ..runtime.ownership import RuntimeOwner, current_runtime_owner, runtime_initialization_scopefrom .async_runtime import AsyncVlmPredictorfrom .handles import RuntimeHandle+from .errors import EngineNotReadyErrorfrom .engine_utils import (enable_custom_logits_processors,mod_kwargs_by_device_type,@@ -104,6 +105,8 @@ class ModelSingleton:predictor.pinned = Trueelse:predictor.owners.add(owner)+ if isinstance(predictor, RuntimeHandle) and predictor.supports_health_probe:+ owner.has_engine_health_probe = Truedef _get_or_initialize(self,@@ -138,6 +141,9 @@ class ModelSingleton:detached.append(self._detach(key, cached))elif cached is not None:self._retain(cached)+ if isinstance(cached, RuntimeHandle):+ # 暂时不可用仍沿原实例重探测;明确死亡必须报错,不能在缓存层悄悄重建。+ cached.require_ready(allow_unavailable=True)return cachedelse:pending = None@@ -435,7 +441,30 @@ class ModelSingleton:raiseelapsed = round(time.time() - start_time, 2)logger.info(f"get {backend} predictor cost: {elapsed}s")- return RuntimeHandle(predictor, backend=backend, close_engine=close_engine)+ return RuntimeHandle(+ predictor,+ backend=backend,+ close_engine=close_engine,+ probe_engine=predictor.client.probe_health if backend == "lmdeploy-engine" else None,+ close_health_probe=predictor.client.close_health_probe if backend == "lmdeploy-engine" else None,+ )++ def probe_owner_health(self, owner: RuntimeOwner, timeout: float = 5.0) -> None:+ """只检查该应用已经创建的运行时;快照之后释放缓存锁再等待后端。"""+ with self._lock:+ handles = tuple(+ predictor+ for predictor in self._models.values()+ if isinstance(predictor, RuntimeHandle) and owner in predictor.owners and predictor.supports_health_probe+ )+ unavailable: EngineNotReadyError | None = None+ for predictor in handles:+ try:+ predictor.probe_health(timeout)+ except EngineNotReadyError as exc:+ unavailable = unavailable or exc+ if unavailable is not None:+ raise unavailabledef release_owner(self, owner: RuntimeOwner) -> None:"""排空该应用文档后撤销全部后端租约,保留其它应用和独立解析持有的实例。"""diff --git a/mineru/model/vlm/text_recognition.py b/mineru/model/vlm/text_recognition.pyindex 8fd58bd1..ef37c12a 100644--- a/mineru/model/vlm/text_recognition.py+++ b/mineru/model/vlm/text_recognition.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, TypeAliasfrom mineru_vl_utils.vlm_client.base_client import ClientClosedError, ServerError-from .errors import is_fatal_engine_error+from .errors import EngineNotReadyError, is_fatal_engine_errorif TYPE_CHECKING:from mineru_vl_utils import MinerUClient@@ -19,6 +19,7 @@ def raise_unrecoverable_text_error(error: Exception) -> None:"""关闭、引擎死亡及程序契约错误必须传播,不能降级成单片识别失败。"""if (is_fatal_engine_error(error)+ or isinstance(error, EngineNotReadyError)or isinstance(error,(ClientClosedError, MemoryError, AssertionError, AttributeError, TypeError, LookupError, NotImplementedError),diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.pyindex 115ad7b0..e9e0378a 100644--- a/mineru/parser/api_server.py+++ b/mineru/parser/api_server.py@@ -54,7 +54,7 @@ from ..filetypes import (from ..types import DeploymentTier, PageInfo, Tier, select_default_task_tierfrom ..utils.async_utils import drain_future, run_syncfrom ..model.runtime.ownership import RuntimeOwner, runtime_owner-from ..model.vlm.errors import is_fatal_engine_error+from ..model.vlm.errors import EngineNotReadyError, is_fatal_engine_errorfrom ..utils.logger import configure_global_log_levelfrom ..utils.server import ServerWithDocsfrom ..utils.stdio import configure_standard_streams@@ -834,6 +834,9 @@ class ExecutionStore:if message is not None:self.fail_engine(message)raise_api_error(503, code="engine_dead", message=message)+ unavailable = self.runtime_owner.engine_unavailable+ if unavailable is not None:+ raise_api_error(503, code="engine_unavailable", message=unavailable)def start_task(self,@@ -1771,6 +1774,50 @@ def _preload_server_models(tier: DeploymentTier, *, vlm_config: VlmConfig | None_SHUTDOWN_FORCE_EXIT_SEC = 30.0+_ENGINE_HEALTH_INTERVAL_SECONDS = 5.0+_ENGINE_HEALTH_TIMEOUT_SECONDS = 5.0+_ENGINE_HEALTH_MONITOR = "api-engine-health-monitor"+++def _probe_initialized_engines(owner: RuntimeOwner) -> None:+ """只在应用已有可探测运行时后访问缓存,Flash 和惰性模型不因探测加载。"""+ if not owner.has_engine_health_probe or owner.closed:+ return+ from ..model.vlm.runtime import ModelSingleton++ ModelSingleton().probe_owner_health(owner, _ENGINE_HEALTH_TIMEOUT_SECONDS)+++async def _refresh_engine_health(store: ExecutionStore) -> bool:+ """刷新一次健康并返回是否仍可继续探测;未加载 VLM 时不创建工作线程。"""+ owner = store.runtime_owner+ try:+ if owner.has_engine_health_probe:+ await run_sync(_probe_initialized_engines, owner)+ except EngineNotReadyError:+ owner.set_engine_unavailable(_ENGINE_HEALTH_MONITOR, None)+ except Exception as exc:+ if is_fatal_engine_error(exc):+ store.fail_engine(str(exc))+ return False+ logger.exception("Runtime health monitoring failed")+ owner.set_engine_unavailable(_ENGINE_HEALTH_MONITOR, str(exc) or type(exc).__name__)+ else:+ owner.set_engine_unavailable(_ENGINE_HEALTH_MONITOR, None)+ if owner.engine_error is not None:+ store.fail_engine(owner.engine_error)+ return False+ return True+++async def _monitor_engine_health(store: ExecutionStore) -> None:+ """周期检查已加载引擎,暂时不可用不取消在途任务,死亡沿既有边界排空。"""+ while True:+ await asyncio.sleep(_ENGINE_HEALTH_INTERVAL_SECONDS)+ if not await _refresh_engine_health(store):+ return++def _start_force_exit_timer(seconds: float = _SHUTDOWN_FORCE_EXIT_SEC,*,@@ -1875,6 +1922,7 @@ def create_app(file_store.claim_directory()application.state.task_store.start()collection_task: asyncio.Task[None] | None = None+ engine_health_task: asyncio.Task[None] | None = Noneasync def collect_loop() -> None:"""每五分钟扫描,先清理终态元数据,再释放无引用文件。"""@@ -1911,9 +1959,15 @@ def create_app(_preload_tier,preload_result.engine,)+ # 预加载后先发布真实健康状态,不能在首次后台探测完成前短暂宣称可用。+ if await _refresh_engine_health(execution_store):+ engine_health_task = asyncio.create_task(_monitor_engine_health(execution_store), name="mineru-engine-health")yieldfinally:runtime_owner.reset(token)+ if engine_health_task is not None:+ engine_health_task.cancel()+ await drain_future(asyncio.gather(engine_health_task, return_exceptions=True))if collection_task is not None:collection_task.cancel()await asyncio.gather(collection_task, return_exceptions=True)diff --git a/mineru/utils/async_utils.py b/mineru/utils/async_utils.pyindex 3cfbc54d..9a601b6e 100644--- a/mineru/utils/async_utils.py+++ b/mineru/utils/async_utils.py@@ -15,7 +15,8 @@ async def drain_future(future: asyncio.Future[T]) -> T:"""即使重复取消也等待已有任务结束;仅用于必须完成的资源清理。"""while not future.done():try:- await asyncio.shield(future)+ # wait 不向工作任务传播取消,也不会在取消后附加 shield 的异常日志回调。+ await asyncio.wait((future,))except asyncio.CancelledError:continueexcept BaseException:@@ -27,7 +28,9 @@ async def run_sync(function: Callable[P, T], *args: P.args, **kwargs: P.kwargs)"""在线程中执行同步阶段,取消后等待线程完成再允许调用方释放资源。"""work = asyncio.create_task(asyncio.to_thread(function, *args, **kwargs))try:- return await asyncio.shield(work)+ # 工作线程必须自行结束;异常只由当前等待者收集,避免 Python 3.14 重复报告。+ await asyncio.wait((work,))+ return work.result()except asyncio.CancelledError:try:await drain_future(work)diff --git a/pyproject.toml b/pyproject.tomlindex 0870f964..2b5df297 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -41,7 +41,7 @@ dependencies = ["docvortex>=0.6.21,<0.7","gradio>=6.21,<7","mineru[torch] ; sys_platform == 'darwin' and platform_machine == 'arm64'",- "mineru-vl-utils>=2.0.8,<3",+ "mineru-vl-utils>=2.0.9,<3","mineru-llama-cpp>=0.2.0,<1","click>=8.1.7","loguru>=0.7.2",diff --git a/scripts/acceptance/README-lmdeploy.md b/scripts/acceptance/README-lmdeploy.mdnew file mode 100644index 00000000..230abfef--- /dev/null+++ b/scripts/acceptance/README-lmdeploy.md@@ -0,0 +1,31 @@+# LMDeploy Windows 验收++在已能运行 MinerU Standard 的 Windows CUDA 虚拟环境中执行,使用本次候选 MinerU 与 `mineru-vl-utils 2.0.9` wheel。Windows 的受支持 LMDeploy 后端为 TurboMind;PyTorch 后端不纳入本轮验收,也不作为发布阻塞项。候选包尚未发布;本脚本不会升级 Torch、LMDeploy 或其他推理依赖。++MinerU 候选包沿用当前 `dev` 的 `4.2.0` 版本号,不代表正式版本回退或新版本发布。请按包内 `MANIFEST.json` 和 `SHA256SUMS` 核对本次构建来源,并在用于验收的虚拟环境中安装。++```powershell+.\run-lmdeploy.ps1 -Sample C:\samples\formulas.pdf -InstallCandidates+```++默认后端即 `turbomind`,也可显式传入 `-Backend turbomind`;重复运行时省略 `-InstallCandidates`。如需指定模型根目录,使用 `-ModelsDir C:\MinerU\models`;如有原始故障完整日志,传入 `-IncidentLog C:\logs\original.log`。环境应已准备 Standard 所需模型;服务启动会按正常模型加载流程检查缓存。++分别使用支持的 LMDeploy 0.17/0.18 环境执行。不要为了凑矩阵在同一个正常工作环境中反复自动更换底层依赖。选择包含图像或公式、至少数页的 PDF;若样例太快无法观察到实际活跃推理序列,脚本会报出未完成该项验收,需要换更长样例重跑。API 任务进入 `running` 仍可能只是在做版面分析,不能据此证明 LMDeploy 正在推理。++脚本执行:++1. 启动隔离的回环 API worker,记录真实版本、GPU、实际后端配置和完整日志。+2. 对合成切片执行真实 VLM 推理,并用提供的 PDF 分别完成 Standard/Advanced 转换。+3. 暂缓 Pipeline 循环,验证探测超时返回 `engine_unavailable`、拒绝新任务,随后恢复而不标记永久死亡。+4. 停止空闲后端,验证宿主仍能报告 `engine_dead`;使用正式 `WorkerPool`、`ManagedLocalWorker` 和控制通道替换进程,核对 PID、generation 与恢复后的转换。+5. 确认 LMDeploy 后端有活跃推理序列后,在验收进程内注入明确的健康故障信号,让底层计算自然结束。检查宿主仍能返回正在处理和排队任务的 `engine_dead`、无成功结果链接,并再次重建、完成 Advanced 转换。++第 5 步的 GPU 推理是真实的,健康故障信号是显式注入的;它验证宿主的失效锁存、任务清理和恢复,不宣称复现了自然后端崩溃。不能在活跃的 TurboMind 原生推理期间直接调用 `close()` 来替代该信号:本轮 Windows 0.18 试验中,这种并发资源释放导致了原生访问冲突和整个 worker 退出。进程退出后的管理者恢复应独立记录;旧 worker 已退出、无法读取任务终态时,不能将其计作宿主存活场景通过。++确需复查该原生崩溃时,可在独立验收目录直接调用 Python 脚本并显式传入 `--active-stop close`。该模式保留实际进程退出码、工作目录清理、PID/generation 变化和恢复转换记录;若没有观察到旧任务终态,仍返回 `passed=false` 和非零退出码,即使进程恢复成功也不会算作完整生命周期验收通过。PowerShell 包装入口继续使用默认的 `signal` 模式。++故障注入路由只存在于该脚本启动的临时 worker,不加入正式产品。脚本测试真实 WorkerPool 管理逻辑,不宣称覆盖完整 Router HTTP 代理链;代理链另有本地回归测试。++每次结果写入当前目录下的 `lmdeploy-evidence-*`:`report.json`、各 worker 完整日志和转换 ZIP。`passed=true` 表示本轮自动断言通过,还需检查日志中的未处理异常,并人工核对 ZIP 中的 Markdown/图片等产物。环境存在继承的 `site-packages` 时,同时核对模块实际路径与版本,不能把枚举包元数据时同名覆盖后的值当作实际加载版本。脚本保留在本机的原始事故日志和产物可能包含文档内容,按实际需要提供验收材料。++本轮验收目标是引擎崩溃后的失效锁存、拒绝接单、任务清理和宿主管理恢复,不要求解决导致引擎崩溃的所有后端缺陷。原始事故的第一次异常原因应由原日志和实际复现单独判断;根因尚未确认不阻塞已经独立验证的故障处理修复,也不能因隔离与恢复通过就宣称原始崩溃原因已修复。diff --git a/scripts/acceptance/lmdeploy_lifecycle.py b/scripts/acceptance/lmdeploy_lifecycle.pynew file mode 100644index 00000000..52bdc98a--- /dev/null+++ b/scripts/acceptance/lmdeploy_lifecycle.py@@ -0,0 +1,441 @@+"""Windows LMDeploy 真机验收:真实推理、暂不可用、后台停机与托管进程恢复。"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import importlib.metadata+import io+import json+import os+import platform+import sys+import threading+import time+import traceback+import zipfile+from pathlib import Path+from typing import Any+++def _arguments() -> argparse.Namespace:+ """声明验收输入及子进程参数,普通运行不隐式安装或更换推理依赖。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--sample", type=Path, help="包含图像或公式的真实 PDF,建议至少数页")+ parser.add_argument(+ "--backend", choices=("turbomind",), default="turbomind", help="Windows 验收只覆盖受支持的 TurboMind 后端"+ )+ parser.add_argument("--models-dir", type=Path, help="可选 MinerU 模型根目录,默认沿用已安装环境配置")+ parser.add_argument("--evidence", type=Path, default=Path(f"lmdeploy-evidence-{time.strftime('%Y%m%d-%H%M%S')}"))+ parser.add_argument("--incident-log", type=Path, help="可选:保存原始事故完整日志,用于独立根因调查")+ parser.add_argument(+ "--active-stop",+ choices=("close", "signal"),+ default="signal",+ help="默认 signal 验证宿主存活;close 仅用于独立原生崩溃诊断,可能令 worker 直接退出",+ )+ parser.add_argument("--worker", action="store_true", help=argparse.SUPPRESS)+ parser.add_argument("--port", type=int, help=argparse.SUPPRESS)+ parser.add_argument("--uploads", type=Path, help=argparse.SUPPRESS)+ return parser.parse_args()+++def _versions() -> dict[str, Any]:+ """收集版本和设备信息,不记录 API Key 或整个配置环境。"""+ versions: dict[str, Any] = {"python": sys.version, "platform": platform.platform()}+ for name in ("mineru", "mineru-vl-utils", "docvortex", "lmdeploy", "torch", "transformers"):+ versions[name] = importlib.metadata.version(name)+ import mineru+ import mineru_vl_utils+ from mineru.model.vlm.handles import RuntimeHandle+ from mineru_vl_utils.vlm_client.lmdeploy_engine_client import LmdeployEngineVlmClient+ from packaging.specifiers import SpecifierSet++ versions["mineru_source"] = mineru.__file__+ versions["vl_utils_source"] = mineru_vl_utils.__file__+ if not callable(getattr(RuntimeHandle, "probe_health", None)) or not callable(+ getattr(LmdeployEngineVlmClient, "close_health_probe", None)+ ):+ raise RuntimeError("The candidate MinerU and mineru-vl-utils wheels are not active in this interpreter")+ if versions["lmdeploy"] not in SpecifierSet(">=0.17.0,<0.19"):+ raise RuntimeError("This acceptance covers LMDeploy 0.17 and 0.18 only")+ import torch++ versions["cuda_available"] = torch.cuda.is_available()+ versions["cuda_version"] = torch.version.cuda+ versions["gpu"] = torch.cuda.get_device_name(0) if torch.cuda.is_available() else None+ return versions+++def _worker(args: argparse.Namespace) -> None:+ """启动正式 API app,仅在独立验收进程中增加可控故障注入路由。"""+ log = open(args.evidence / f"worker-{os.getpid()}.log", "a", encoding="utf-8", buffering=1)+ os.dup2(log.fileno(), sys.stdout.fileno())+ os.dup2(log.fileno(), sys.stderr.fileno())+ print(json.dumps({"versions": _versions(), "backend": args.backend}, ensure_ascii=False), flush=True)++ import uvicorn+ from PIL import Image, ImageDraw++ from mineru.config import VlmConfig+ from mineru.model.vlm.runtime import ModelSingleton+ from mineru.parser.api_server import create_app+ from mineru.parser.process_control import ManagedProcessControlWatcher++ application = create_app(+ upload_dir=str(args.uploads),+ tiers=("flash", "basic", "standard", "advanced"),+ concurrency=1,+ preload_models=True,+ vlm_config=VlmConfig(engine="lmdeploy", server_url=""),+ )++ def handle() -> Any:+ """只取得本验收服务已经加载的 LMDeploy 实例,不额外构造模型。"""+ pool = ModelSingleton()+ with pool._lock:+ matches = [item for item in pool._models.values() if item.backend == "lmdeploy-engine"]+ if len(matches) != 1:+ raise RuntimeError(f"Expected one loaded LMDeploy runtime, got {len(matches)}")+ return matches[0]++ @application.get("/_acceptance/runtime")+ async def inspect_runtime() -> dict[str, Any]:+ """核对实际引擎配置和进程,避免误把其他后端当作 LMDeploy 验收。"""+ runtime = handle()+ pipeline = runtime.predictor.client.lmdeploy_engine+ return {+ "pid": os.getpid(),+ "backend": runtime.backend,+ "backend_config": type(pipeline.backend_config).__name__,+ }++ @application.post("/_acceptance/infer")+ async def infer_crop() -> dict[str, Any]:+ """真实调用 VLM 识别合成切片,确保健康状态背后确实存在可工作的模型。"""+ image = Image.new("RGB", (384, 96), "white")+ ImageDraw.Draw(image).text((20, 25), "2 + 2 = 4", fill="black", font_size=32)+ outputs = await handle().aio_batch_recognize_text([image])+ if len(outputs) != 1 or not isinstance(outputs[0], str) or not outputs[0].strip():+ raise RuntimeError(f"Unexpected VLM crop result: {outputs!r}")+ return {"recognized": outputs[0]}++ @application.post("/_acceptance/delay-loop")+ async def delay_loop() -> dict[str, bool]:+ """暂缓 Pipeline 循环以触发有界健康超时,保留宿主服务循环响应能力。"""+ pipeline = handle().predictor.client.lmdeploy_engine++ def delay() -> None:+ """阻塞十二秒,覆盖一次五秒检查间隔及五秒期限,然后自然恢复。"""+ threading.Event().wait(12)++ pipeline.internal_thread.loop.call_soon_threadsafe(delay)+ return {"scheduled": True}++ @application.get("/_acceptance/activity")+ async def inspect_activity() -> dict[str, int]:+ """读取实际后端调度指标,区分 API 任务在途与模型推理在途。"""+ pipeline = handle().predictor.client.lmdeploy_engine+ future = asyncio.run_coroutine_threadsafe(+ pipeline.async_engine.engine.get_health_status(),+ pipeline.internal_thread.loop,+ )+ status = await asyncio.wait_for(asyncio.wrap_future(future), timeout=3)+ metrics = status["schedule_metrics"]+ return {"active_seqs": metrics.active_seqs, "waiting_seqs": metrics.waiting_seqs}++ @application.post("/_acceptance/signal-dead")+ async def signal_dead() -> dict[str, Any]:+ """活跃 GPU 推理期间只注入健康故障信号,允许本机计算自然收尾。"""+ pipeline = handle().predictor.client.lmdeploy_engine+ engine = pipeline.async_engine.engine++ async def inject() -> dict[str, Any]:+ """在所属循环确认真实活跃序列后,只替换验收进程的健康响应。"""+ get_health_status = engine.get_health_status+ status = await get_health_status()+ metrics = status["schedule_metrics"]+ if metrics.active_seqs == 0:+ return {"injected": False, "active_seqs": 0, "waiting_seqs": metrics.waiting_seqs}++ async def report_dead() -> dict[str, Any]:+ """用明确的注入标记模拟整体失效,不并发释放仍在运行的原生资源。"""+ return {"alive": False, "message": "Acceptance injected dead health signal during live inference"}++ engine.get_health_status = report_dead+ return {"injected": True, "active_seqs": metrics.active_seqs, "waiting_seqs": metrics.waiting_seqs}++ future = asyncio.run_coroutine_threadsafe(inject(), pipeline.internal_thread.loop)+ return await asyncio.wait_for(asyncio.wrap_future(future), timeout=3)++ @application.post("/_acceptance/stop-engine")+ async def stop_engine() -> dict[str, bool]:+ """只停止验收进程内的后端,保留 Pipeline 与 API 进程观察故障传播。"""+ pipeline = handle().predictor.client.lmdeploy_engine++ def stop() -> None:+ """使用后端明确的停止接口,不操作私有任务或生产进程。"""+ pipeline.async_engine.engine.close()++ pipeline.internal_thread.loop.call_soon_threadsafe(stop)+ return {"scheduled": True}++ server = uvicorn.Server(uvicorn.Config(application, host="127.0.0.1", port=args.port, log_level="info"))++ def request_shutdown() -> None:+ """复用正式托管控制通道,请求优雅退出后由父管理者负责有界强制停止。"""+ server.should_exit = True++ watcher = ManagedProcessControlWatcher.from_environment(request_shutdown)+ if watcher is not None:+ watcher.start()+ try:+ server.run()+ finally:+ if watcher is not None:+ watcher.close()+ log.close()+++async def _wait_health(client: Any, base: str, code: str | None, timeout: float = 30) -> dict[str, Any]:+ """按公开健康接口等待目标状态,保留明确错误码。"""+ deadline = time.monotonic() + timeout+ last: Any = None+ while time.monotonic() < deadline:+ response = await client.get(base + "/v1/health")+ last = response.json()+ if code is None and response.status_code == 200:+ return last+ if code is not None and response.status_code == 503 and last.get("error", {}).get("code") == code:+ return last+ await asyncio.sleep(0.1)+ raise TimeoutError(f"Health did not reach {code or 'healthy'}: {last}")+++async def _submit(client: Any, base: str, data: bytes, name: str, tier: str) -> dict[str, Any]:+ """走正式 Tasks 清单和上传协议,不调用测试专用解析入口。"""+ response = await client.post(+ base + "/v1/tasks",+ json={+ "tier": tier,+ "files": [{"file_name": name, "bytes": len(data), "sha256sum": hashlib.sha256(data).hexdigest()}],+ },+ )+ response.raise_for_status()+ task = response.json()+ for item in task["files"]:+ upload = item.get("upload")+ if upload:+ response = await client.put(upload["url"], content=data, headers=upload["headers"])+ response.raise_for_status()+ return task+++async def _terminal(client: Any, base: str, task: dict[str, Any], timeout: float = 900) -> dict[str, Any]:+ """等待任务终态,超时保留最后一次完整状态供诊断。"""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ response = await client.get(f"{base}/v1/tasks/{task['task_id']}")+ response.raise_for_status()+ task = response.json()+ if task["status"] in {"completed", "partial", "failed", "canceled"}:+ return task+ await asyncio.sleep(0.1)+ raise TimeoutError(f"Task did not finish: {task}")+++async def _convert(client: Any, base: str, data: bytes, tier: str, evidence: Path, name: str) -> dict[str, Any]:+ """真实转换并检查产物协议,保存 ZIP 供人工核对 Markdown 与版面。"""+ task = await _terminal(client, base, await _submit(client, base, data, name + ".pdf", tier))+ if task["status"] != "completed":+ raise RuntimeError(f"Healthy conversion failed: {task}")+ response = await client.get(task["files"][0]["result_url"])+ response.raise_for_status()+ (evidence / f"{name}.zip").write_bytes(response.content)+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ member = next(item for item in archive.namelist() if item.endswith("middle_json.json"))+ middle = json.loads(archive.read(member))+ if not middle["pages"] or middle["extensions"]["mineru"]["tier"] != tier:+ raise RuntimeError("Result does not match requested tier or contains no pages")+ return task+++async def _accept(args: argparse.Namespace, report: dict[str, Any]) -> None:+ """通过正式 WorkerPool 管理真实进程,故障注入仅存在于验收子进程。"""+ import httpx+ from mineru.kit.router.workers import ManagedLocalWorker, RouterSettings, WorkerPool, WorkerState++ class AcceptanceWorker(ManagedLocalWorker):+ """只替换验收子进程命令,保留正式启停、超时与控制通道实现。"""++ def command(self, port: int, upload_dir: Path) -> list[str]:+ """启动带回环验收路由的正式 API app。"""+ return [+ sys.executable,+ str(Path(__file__).resolve()),+ "--worker",+ "--port",+ str(port),+ "--uploads",+ str(upload_dir),+ "--backend",+ args.backend,+ "--evidence",+ str(args.evidence),+ ]++ settings = RouterSettings(local_gpus="none", worker_tier="standard", preload_models=True)+ local = AcceptanceWorker("acceptance", "127.0.0.1", None, settings)+ state = WorkerState("acceptance", "", "local", local_worker=local)+ pool = WorkerPool(settings)+ pool._workers[state.worker_id] = state+ data = args.sample.read_bytes()++ async def recover() -> None:+ """让现有管理者根据 engine_dead 剔除和替换进程,核对 PID 与 generation。"""+ old_process = local.process+ old_generation = state.generation+ deadline = time.monotonic() + 900+ while time.monotonic() < deadline:+ await pool.refresh(state)+ if state.generation > old_generation and state.healthy:+ assert old_process.poll() is not None+ assert local.process.pid != old_process.pid+ report["recoveries"].append(+ {"old_pid": old_process.pid, "new_pid": local.process.pid, "generation": state.generation}+ )+ return+ await asyncio.sleep(0.2)+ raise TimeoutError("Managed worker did not recover")++ try:+ await pool.refresh(state)+ if not state.healthy:+ raise RuntimeError(f"Worker failed startup: {state.last_error}")+ async with httpx.AsyncClient(timeout=120) as client:+ report["runtime"] = (await client.get(state.base_url + "/_acceptance/runtime")).json()+ assert report["runtime"]["backend_config"] == "TurbomindEngineConfig", report["runtime"]+ response = await client.post(state.base_url + "/_acceptance/infer")+ response.raise_for_status()+ report["real_inference"] = response.json()+ for tier in ("standard", "advanced"):+ await _convert(client, state.base_url, data, tier, args.evidence, f"before-{tier}")+ report["healthy_conversions"] = True+ response = await client.post(state.base_url + "/_acceptance/delay-loop")+ response.raise_for_status()+ report["transient"] = await _wait_health(client, state.base_url, "engine_unavailable")+ response = await client.post(+ state.base_url + "/v1/tasks",+ json={+ "tier": "standard",+ "files": [{"file_name": "unavailable.pdf", "bytes": 3}],+ },+ )+ assert response.status_code == 503 and response.json()["error"]["code"] == "engine_unavailable"+ await _wait_health(client, state.base_url, None)+ report["transient_recovered"] = True+ response = await client.post(state.base_url + "/_acceptance/stop-engine")+ response.raise_for_status()+ report["idle_death"] = await _wait_health(client, state.base_url, "engine_dead")+ await recover()+ await _convert(client, state.base_url, data, "standard", args.evidence, "after-idle-restart")+ jobs = [await _submit(client, state.base_url, data, f"inflight-{i}.pdf", "advanced") for i in range(4)]+ interrupted_runtime = (await client.get(state.base_url + "/_acceptance/runtime")).json()+ interrupted_process = local.process+ interrupted_dir = Path(local.temp_dir.name)+ report["inflight_runtime"] = interrupted_runtime+ report["inflight_stop_mode"] = args.active_stop+ async with asyncio.timeout(60):+ while True:+ snapshots = [(await client.get(f"{state.base_url}/v1/tasks/{job['task_id']}")).json() for job in jobs]+ if args.active_stop == "signal":+ activity = await client.post(state.base_url + "/_acceptance/signal-dead")+ else:+ activity = await client.get(state.base_url + "/_acceptance/activity")+ activity.raise_for_status()+ activity_snapshot = activity.json()+ if activity_snapshot["active_seqs"] > 0:+ if args.active_stop == "signal":+ assert activity_snapshot["injected"]+ report["activity_before_inflight_stop"] = activity_snapshot+ report["tasks_before_inflight_stop"] = [item["status"] for item in snapshots]+ break+ if all(item["status"] in {"completed", "partial", "failed", "canceled"} for item in snapshots):+ raise RuntimeError("No active LMDeploy sequences observed; use a longer PDF sample")+ await asyncio.sleep(0.05)+ if args.active_stop == "close":+ response = await client.post(state.base_url + "/_acceptance/stop-engine")+ response.raise_for_status()+ try:+ report["inflight_health"] = await _wait_health(client, state.base_url, "engine_dead")+ except httpx.TransportError:+ if args.active_stop != "close":+ raise+ # 原生崩溃可能先于 HTTP 响应终止宿主,单独保留进程恢复证据。+ report["inflight_transport_error"] = traceback.format_exc()+ exit_code = await asyncio.to_thread(interrupted_process.wait, 15)+ if exit_code == 0:+ raise RuntimeError("Worker exited without an error after losing the HTTP connection")+ report["inflight_process_exit"] = {"code": exit_code, "hex": f"0x{exit_code & 0xFFFFFFFF:08x}"}+ report["inflight_task_terminal_states_observed"] = False+ else:+ report["inflight_results"] = [await _terminal(client, state.base_url, job, 30) for job in jobs]+ failures = [file for task in report["inflight_results"] for file in task["files"] if file["status"] == "failed"]+ assert len(failures) == len(jobs) and all(file["error"]["code"] == "engine_dead" for file in failures)+ assert all(file.get("result_url") is None for file in failures)+ report["inflight_task_terminal_states_observed"] = True+ assert interrupted_process.poll() is None+ report["host_alive_after_task_cleanup"] = True+ await recover()+ assert not interrupted_dir.exists(), interrupted_dir+ report["interrupted_upload_directory_removed"] = True+ replacement_runtime = (await client.get(state.base_url + "/_acceptance/runtime")).json()+ assert replacement_runtime["pid"] != interrupted_runtime["pid"]+ report["replacement_runtime"] = replacement_runtime+ await _convert(client, state.base_url, data, "advanced", args.evidence, "after-inflight-restart")+ report["recovered_after_active_stop"] = True+ report["passed"] = report["inflight_task_terminal_states_observed"]+ finally:+ await pool.close()+++def main() -> int:+ """保存每次验收的完整报告,失败时也保留 traceback 和所有 worker 日志。"""+ args = _arguments()+ args.evidence = args.evidence.resolve()+ args.evidence.mkdir(parents=True, exist_ok=True)+ os.environ["PYTHONUTF8"] = "1"+ os.environ["MINERU_LMDEPLOY_BACKEND"] = args.backend+ if args.models_dir:+ os.environ["MINERU_MODEL_BASE_DIR"] = str(args.models_dir.resolve())+ if args.worker:+ _worker(args)+ return 0+ report: dict[str, Any] = {+ "passed": False,+ "backend": args.backend,+ "recoveries": [],+ "original_incident_root_cause": "not established; lifecycle fault injection only",+ }+ try:+ if sys.platform != "win32":+ raise RuntimeError("Run this release acceptance on Windows with a configured CUDA MinerU environment")+ if args.sample is None or not args.sample.is_file() or args.sample.suffix.lower() != ".pdf":+ raise ValueError("--sample must point to an existing PDF")+ report["versions"] = _versions()+ report["sample_sha256"] = hashlib.sha256(args.sample.read_bytes()).hexdigest()+ if args.incident_log:+ (args.evidence / "original-incident.log").write_bytes(args.incident_log.read_bytes())+ asyncio.run(_accept(args, report))+ except Exception:+ report["error"] = traceback.format_exc()+ print(report["error"], file=sys.stderr)+ finally:+ (args.evidence / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")+ print(f"Evidence: {args.evidence}")+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/acceptance/run-lmdeploy.ps1 b/scripts/acceptance/run-lmdeploy.ps1new file mode 100644index 00000000..336c6db6--- /dev/null+++ b/scripts/acceptance/run-lmdeploy.ps1@@ -0,0 +1,24 @@+param(+ [Parameter(Mandatory = $true)][string]$Sample,+ [ValidateSet("turbomind")][string]$Backend = "turbomind",+ [string]$Python = "python",+ [string]$ModelsDir = "",+ [string]$IncidentLog = "",+ [switch]$InstallCandidates+)++$ErrorActionPreference = "Stop"+$env:PYTHONUTF8 = "1"+$bundleRoot = $PSScriptRoot+if ($InstallCandidates) {+ $candidateWheels = @(Get-ChildItem -Path (Join-Path $bundleRoot "wheels") -Filter "*.whl" | ForEach-Object { $_.FullName })+ if ($candidateWheels.Count -ne 2) { throw "Expected the two candidate wheels in wheels/." }+ & $Python -m pip install --no-deps --force-reinstall @candidateWheels+ if ($LASTEXITCODE -ne 0) { throw "Candidate installation failed." }+}++$acceptanceArgs = @((Join-Path $bundleRoot "lmdeploy_lifecycle.py"), "--sample", $Sample, "--backend", $Backend)+if ($ModelsDir) { $acceptanceArgs += @("--models-dir", $ModelsDir) }+if ($IncidentLog) { $acceptanceArgs += @("--incident-log", $IncidentLog) }+& $Python @acceptanceArgs+exit $LASTEXITCODEdiff --git a/tests/unittest/test_async_utils_cancellation.py b/tests/unittest/test_async_utils_cancellation.pynew file mode 100644index 00000000..0294734b--- /dev/null+++ b/tests/unittest/test_async_utils_cancellation.py@@ -0,0 +1,81 @@+"""同步阶段取消后正确收尾,不重复报告已经处理的引擎异常。"""++from __future__ import annotations++import asyncio+import threading+from typing import Any++import pytest++from mineru.model.vlm.errors import EngineDeadError+from mineru.utils.async_utils import drain_future, run_sync+++def test_canceled_sync_failure_is_drained_without_unhandled_exception() -> None:+ """重放真机停机竞态:重复取消后等待线程退出,保留取消而不产生孤立异常日志。"""+ started = threading.Event()+ release = threading.Event()+ finished = threading.Event()+ unhandled: list[dict[str, Any]] = []++ def fail_engine() -> None:+ """模拟在取消之后才观察到引擎死亡的同步推理。"""+ started.set()+ try:+ if not release.wait(5):+ raise TimeoutError("Test did not release the inference thread")+ raise EngineDeadError("engine stopped during inference")+ finally:+ finished.set()++ def record_error(loop: asyncio.AbstractEventLoop, context: dict[str, Any]) -> None:+ """收集事件循环未处理错误,以捕获 Python 3.14 的 shield 回调日志。"""+ unhandled.append(context)++ async def scenario() -> None:+ """只取消等待者,不在工作线程实际完成前结束资源租约。"""+ loop = asyncio.get_running_loop()+ loop.set_exception_handler(record_error)+ task = asyncio.create_task(run_sync(fail_engine))+ try:+ async with asyncio.timeout(5):+ while not started.is_set():+ await asyncio.sleep(0)+ task.cancel()+ await asyncio.sleep(0)+ task.cancel()+ await asyncio.sleep(0)+ assert not task.done()+ assert not finished.is_set()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert finished.is_set()+ await asyncio.sleep(0)+ assert not unhandled+ finally:+ release.set()++ asyncio.run(scenario())+++def test_sync_and_drain_preserve_uncanceled_failure() -> None:+ """未取消的同步调用和清理等待仍将原始异常对象交给调用方。"""+ error = EngineDeadError("original failure")++ def fail() -> None:+ """抛出固定异常,检查等待方式没有改写错误语义。"""+ raise error++ async def scenario() -> None:+ """分别检查正常等待和显式清理的错误传播。"""+ with pytest.raises(EngineDeadError) as raised:+ await run_sync(fail)+ assert raised.value is error+ work = asyncio.create_task(asyncio.to_thread(fail))+ with pytest.raises(EngineDeadError) as drained:+ await drain_future(work)+ assert drained.value is error++ asyncio.run(scenario())diff --git a/tests/unittest/test_lmdeploy_acceptance_protocol.py b/tests/unittest/test_lmdeploy_acceptance_protocol.pynew file mode 100644index 00000000..d292a7c7--- /dev/null+++ b/tests/unittest/test_lmdeploy_acceptance_protocol.py@@ -0,0 +1,51 @@+"""验收脚本使用正式 Tasks/健康协议;这里只替换推理,不代替 Windows 真机验收。"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import Any++import httpx+import pytest+from test_doclib_page_selection import _page++from mineru.parser import api_server+from mineru.parser.base import ParseResult+from mineru.types import MiddleJson+from scripts.acceptance.lmdeploy_lifecycle import _convert, _wait_health+++def test_acceptance_upload_poll_download_and_health_protocol(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """脚本能上传、轮询、校验和下载真实服务产物,并读取暂时不可用状态。"""+ monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)++ async def parse(path: str, **kwargs: Any) -> ParseResult:+ """仅隔离 GPU 推理,后续序列化、文件存储和 HTTP 协议均使用正式实现。"""+ return ParseResult(+ MiddleJson(+ is_full_document=True,+ pages=[_page(0, "body")],+ metadata={"file_suffix": "pdf", "producer": {"name": "mineru", "version": "test"}},+ extensions={"mineru": {"tier": kwargs["tier"], "parse_mode": "txt"}},+ )+ )++ monkeypatch.setattr(api_server, "parse_async", parse)++ async def scenario() -> None:+ """在单一循环内启动正式服务生命周期和真实 ASGI 传输。"""+ app = api_server.create_app(upload_dir=str(tmp_path / "uploads"), tiers=("standard",))+ async with app.router.lifespan_context(app):+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://worker") as client:+ task = await _convert(client, "http://worker", b"%PDF-1.7\n", "standard", tmp_path, "accepted")+ assert task["status"] == "completed"+ assert (tmp_path / "accepted.zip").is_file()+ owner = app.state.execution_store.runtime_owner+ owner.set_engine_unavailable("test", "timeout")+ result = await _wait_health(client, "http://worker", "engine_unavailable", 1)+ assert result["error"]["code"] == "engine_unavailable"+ owner.set_engine_unavailable("test", None)+ assert (await _wait_health(client, "http://worker", None, 1))["status"] == "ok"++ asyncio.run(scenario())diff --git a/tests/unittest/test_lmdeploy_engine_lifecycle.py b/tests/unittest/test_lmdeploy_engine_lifecycle.pynew file mode 100644index 00000000..fa6c3aba--- /dev/null+++ b/tests/unittest/test_lmdeploy_engine_lifecycle.py@@ -0,0 +1,275 @@+"""后端真实异常契约、同步运行时失效与服务空闲期健康闭环。"""++from __future__ import annotations++import asyncio+import threading+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from types import SimpleNamespace+from typing import Any+from unittest.mock import MagicMock++import pytest+from fastapi.testclient import TestClient+from mineru_vl_utils.vlm_client.base_client import EngineHealth, EngineUnavailableError, ServerError+from task_test_utils import submit_task, task_url, wait_task++from mineru.model.runtime.ownership import RuntimeOwner+from mineru.model.vlm.errors import EngineDeadError, EngineNotReadyError, is_fatal_engine_error+from mineru.model.vlm.handles import RuntimeHandle+from mineru.model.vlm.runtime import ModelSingleton+from mineru.model.vlm.text_recognition import recognize_text_batch+from mineru.parser import api_server+++class Client:+ """保留真实同步识别调用与关闭接口的后端替身。"""++ def __init__(self) -> None:+ """记录调用、可控故障及关闭状态。"""+ self.error: Exception | None = None+ self.calls = 0+ self.closed = False++ def batch_content_extract(self, images: list[Any], *, types: str) -> list[str]:+ """在真实识别边界抛出指定后端异常或返回成功结果。"""+ self.calls += 1+ if self.error is not None:+ raise self.error+ return [str(item) for item in images]++ def content_extract(self, image: Any, *, type: str) -> str:+ """单片补试仅供可恢复故障对照使用。"""+ return str(image)++ async def aclose(self) -> None:+ """模拟客户端资源排空,底层引擎关闭仍由宿主执行。"""+ self.closed = True++[email protected]("fatal", [False, True])+def test_real_server_error_inheritance_controls_retry(fatal: bool) -> None:+ """真实 ServerError 子类必须依赖致命分类才能禁用补试,普通错误继续恢复。"""+ error = EngineUnavailableError("dead") if fatal else ServerError("bad crop")+ client = SimpleNamespace(batch_content_extract=MagicMock(side_effect=error), content_extract=MagicMock(return_value="ok"))+ if fatal:+ with pytest.raises(EngineUnavailableError) as raised:+ recognize_text_batch(client, [1])+ assert raised.value is error+ client.content_extract.assert_not_called()+ else:+ assert recognize_text_batch(client, [1]) == ["ok"]+ client.content_extract.assert_called_once()+++def test_fatal_runtime_notifies_all_owners_and_rejects_cache_reuse(monkeypatch: pytest.MonkeyPatch) -> None:+ """共享引擎故障通知全部宿主,缓存命中不重建、不调用已经死亡的客户端。"""+ client = Client()+ original = EngineUnavailableError("original failure", error_message="backend details")+ client.error = original+ handle = RuntimeHandle(client, backend="lmdeploy-engine")+ owners = [RuntimeOwner(), RuntimeOwner()]+ handle.owners.update(owners)+ pool = ModelSingleton()+ key = ("test-lmdeploy",)+ monkeypatch.setattr(ModelSingleton, "_models", {key: handle})+ factory = MagicMock()+ try:+ with pytest.raises(EngineUnavailableError):+ handle.batch_recognize_text([1])+ assert all(owner.engine_error == "original failure" for owner in owners)+ client.error = None+ with pytest.raises(EngineDeadError) as raised:+ handle.batch_recognize_text([2])+ assert raised.value.__cause__ is original+ with pytest.raises(EngineDeadError):+ pool._get_or_initialize(key, factory, native_async=False, backend="lmdeploy-engine", max_concurrency=1)+ factory.assert_not_called()+ assert client.calls == 1+ finally:+ handle.shutdown()+++def test_temporary_probe_failure_recovers_but_fatal_state_never_recovers() -> None:+ """探测超时可以恢复,明确死亡即使之后出现健康结果也不能复活。"""+ client = Client()+ status = EngineHealth("unavailable", "probe timed out")++ def probe(timeout: float) -> EngineHealth:+ """按测试状态返回真实探测协议。"""+ return status++ handle = RuntimeHandle(client, backend="lmdeploy-engine", probe_engine=probe)+ owner = RuntimeOwner()+ handle.owners.add(owner)+ try:+ with pytest.raises(EngineNotReadyError):+ handle.batch_recognize_text([1])+ assert client.calls == 0+ assert owner.engine_error is None+ assert owner.engine_unavailable == "probe timed out"+ status = EngineHealth("healthy")+ assert handle.batch_recognize_text([2]) == ["2"]+ assert owner.engine_unavailable is None+ status = EngineHealth("dead", "loop stopped")+ with pytest.raises(EngineDeadError):+ handle.probe_health()+ status = EngineHealth("healthy")+ with pytest.raises(EngineDeadError):+ handle.batch_recognize_text([3])+ assert client.calls == 1+ finally:+ handle.shutdown()+++def test_one_engine_recovery_does_not_clear_another_engine_unavailability() -> None:+ """同一宿主拥有多个模型时,各自暂时状态不可互相覆盖。"""+ owner = RuntimeOwner()+ first, second = object(), object()+ owner.set_engine_unavailable(first, "one")+ owner.set_engine_unavailable(second, "two")+ owner.set_engine_unavailable(first, None)+ assert owner.engine_unavailable == "two"+++def test_close_waits_for_active_health_probe() -> None:+ """关闭与健康探测相交时,必须先结束探测租约再关闭底层资源。"""+ entered = threading.Event()+ release = threading.Event()+ closed = threading.Event()+ client = Client()++ def probe(timeout: float) -> EngineHealth:+ """阻塞探测以核对关闭动作的先后关系。"""+ entered.set()+ assert release.wait(2)+ assert not closed.is_set()+ return EngineHealth("healthy")++ handle = RuntimeHandle(client, backend="lmdeploy-engine", probe_engine=probe, close_engine=closed.set)+ with ThreadPoolExecutor(2) as executor:+ checking = executor.submit(handle.probe_health)+ assert entered.wait(2)+ closing = executor.submit(handle.shutdown)+ assert not closed.wait(0.03)+ release.set()+ checking.result(timeout=2)+ closing.result(timeout=2)+ assert client.closed and closed.is_set()+++def test_idle_server_detects_death_and_transient_recovery(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """无需新解析请求,周期探测就能撤销能力;超时恢复后才重新允许接单。"""+ monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)+ monkeypatch.setattr(api_server, "_ENGINE_HEALTH_INTERVAL_SECONDS", 0.01)+ status = EngineHealth("healthy")++ def probe(timeout: float) -> EngineHealth:+ """模拟已加载的引擎健康变化。"""+ return status++ handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=probe)+ monkeypatch.setattr(ModelSingleton, "_models", {("idle-engine",): handle})+ app = api_server.create_app(upload_dir=str(tmp_path), tiers=("flash",))+ try:+ with TestClient(app) as client:+ owner = app.state.execution_store.runtime_owner+ handle.owners.add(owner)+ handle.pinned = True+ owner.has_engine_health_probe = True++ async def wait_state(code: str | None) -> None:+ """等待监测任务完成状态传播,不使用长时间阻塞睡眠。"""+ async with asyncio.timeout(2):+ while True:+ current = (+ "engine_dead" if owner.engine_error else "engine_unavailable" if owner.engine_unavailable else None+ )+ if current == code:+ return+ await asyncio.sleep(0.005)++ status = EngineHealth("unavailable", "timeout")+ client.portal.call(wait_state, "engine_unavailable")+ response = client.get("/v1/health")+ assert response.status_code == 503+ assert response.json()["error"]["code"] == "engine_unavailable"+ assert owner.engine_error is None+ status = EngineHealth("healthy")+ client.portal.call(wait_state, None)+ assert client.get("/v1/health").status_code == 200+ status = EngineHealth("dead", "engine main loop stopped")+ client.portal.call(wait_state, "engine_dead")+ for endpoint in ("/v1/health", "/v1/tiers", "/v1/models"):+ response = client.get(endpoint)+ assert response.status_code == 503+ assert response.json()["error"]["code"] == "engine_dead"+ response = client.post("/v1/tasks", json={"tier": "flash", "files": [{"file_name": "new.pdf", "bytes": 3}]})+ assert response.status_code == 503+ assert response.json()["error"]["code"] == "engine_dead"+ finally:+ handle.shutdown()+++def test_probe_does_not_initialize_lazy_models(monkeypatch: pytest.MonkeyPatch) -> None:+ """没有创建 VLM 的应用不会为了健康查询访问模型池或下载模型。"""+ probe = MagicMock(side_effect=AssertionError("must not access model pool"))+ monkeypatch.setattr(ModelSingleton, "probe_owner_health", probe)+ api_server._probe_initialized_engines(RuntimeOwner())+ probe.assert_not_called()+++def test_monitor_drains_running_and_queued_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ """后台健康发现死亡时也必须清理已接纳任务,不能等待某次推理主动报错。"""+ monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)+ monkeypatch.setattr(api_server, "_ENGINE_HEALTH_INTERVAL_SECONDS", 0.01)+ stopped = threading.Event()+ entered = threading.Event()+ cleaned = threading.Event()++ def probe(timeout: float) -> EngineHealth:+ """由外部信号模拟后台引擎主循环独立停止。"""+ return EngineHealth("dead", "background loop stopped") if stopped.is_set() else EngineHealth("healthy")++ async def infer(path: str, **kwargs: Any) -> None:+ """保持请求在途,只有健康管理者取消它才会结束。"""+ entered.set()+ try:+ await asyncio.Event().wait()+ finally:+ await asyncio.sleep(0.01)+ cleaned.set()++ monkeypatch.setattr(api_server, "parse_async", infer)+ handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=probe)+ handle.pinned = True+ monkeypatch.setattr(ModelSingleton, "_models", {("engine",): handle})+ app = api_server.create_app(upload_dir=str(tmp_path / "uploads"), tiers=("flash",), concurrency=1)+ try:+ with TestClient(app) as client:+ owner = app.state.execution_store.runtime_owner+ handle.owners.add(owner)+ owner.has_engine_health_probe = True+ jobs = []+ for name in ["running", "queued"]:+ path = tmp_path / f"{name}.pdf"+ path.write_bytes(name.encode())+ jobs.append(submit_task(client, path, tier="flash"))+ assert entered.wait(2)+ stopped.set()+ for job in jobs:+ result = wait_task(client, job)+ assert result["status"] == "failed"+ assert result["files"][0]["error"]["code"] == "engine_dead"+ assert client.get(task_url(client, job)).status_code == 200+ assert cleaned.wait(2)+ finally:+ handle.shutdown()+++def test_fatal_engine_chain_keeps_original_backend_signal() -> None:+ """上层包装异常仍能识别后端致命原因。"""+ error = ValueError("wrapper")+ error.__cause__ = EngineUnavailableError("original")+ assert is_fatal_engine_error(error)diff --git a/tests/unittest/test_runtime_shutdown_regressions.py b/tests/unittest/test_runtime_shutdown_regressions.pyindex 4c54c2e5..d9a55370 100644--- a/tests/unittest/test_runtime_shutdown_regressions.py+++ b/tests/unittest/test_runtime_shutdown_regressions.py@@ -97,6 +97,34 @@ if warm_executor:assert "Exception in thread" not in completed.stderr+def test_lmdeploy_probe_closes_without_new_threads_at_interpreter_exit() -> None:+ """LMDeploy 自有探测在真实解释器退出时走同步关闭,不能依赖已关闭线程池。"""+ completed = _run_isolated('''+ from concurrent.futures import ThreadPoolExecutor+ from mineru_vl_utils.vlm_client.lmdeploy_health import LmdeployHealthProbe++ probe = LmdeployHealthProbe(SimpleNamespace())++ def close_probe() -> None:+ """关闭真实探测适配器并记录顺序。"""+ probe.close()+ print("probe_closed", flush=True)++ def create(self, backend, model_path, server_url, **kwargs):+ """沿真实缓存注册 atexit,底层引擎仅替换为可观察关闭动作。"""+ return RuntimeHandle(Client(), backend=backend, close_health_probe=close_probe,+ close_engine=lambda: print("engine_closed", flush=True))++ runtime.ModelSingleton._create_model = create+ manager.get_model("lmdeploy-engine", "fake", None)+ with ThreadPoolExecutor() as executor:+ executor.submit(lambda: None).result()+ ''')+ assert completed.stdout.splitlines() == ["probe_closed", "engine_closed"]+ assert "Exception ignored in atexit callback" not in completed.stderr+ assert "cannot schedule new futures" not in completed.stderr++def test_sync_close_callback_rejects_another_key_in_its_closing_batch() -> None:"""A 的关闭回调不能等待同批尚未关闭的 B,同时仍允许另一应用借用未关闭键。"""_run_isolated('''