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): share lifecycle state across local VLM backends
myhloli64300daec20d
diff --git a/docs/native-async-analysis.md b/docs/native-async-analysis.mdindex 6b881796..a67c269f 100644--- a/docs/native-async-analysis.md+++ b/docs/native-async-analysis.md@@ -29,7 +29,30 @@ PDF 的 high/xhigh 分析在使用本地 vLLM 或远程 HTTP 时,通过常驻## 分层实现MinerU 拥有模型构造、缓存、运行时、文档编排和 API 任务生命周期。mineru-vl-utils 提供原生异步抽取及-HTTP 连接关闭接口,不关闭调用方提供的引擎或 executor。DocVortex 的基础访问、语义协议和确定性处理职责不变。+HTTP 连接与健康探测清理接口,不关闭调用方提供的引擎或 executor。DocVortex 的基础访问、语义协议和确定性处理职责不变。++## 引擎健康与故障传播++依赖适配层将 vLLM 与 LMDeploy 的明确死亡统一为 `EngineUnavailableError`,保留原始异常链。+普通请求失败和探测超时不使用该异常;批量容错和 MFR 回退不能吞掉明确死亡。++| 后端 | `health_probe_mode` | 健康入口 |+| --- | --- | --- |+| LMDeploy | `sync` | `probe_health(timeout)`,在 Pipeline 循环查询 |+| vLLM AsyncLLM | `async` | `aio_probe_health(timeout)`,在运行时所属循环查询 |+| vLLM 离线 LLM、MLX | `none` | 不提供探测;不通过私有对象伪造健康 |++MinerU 托管的 vLLM 同步调用仍使用 AsyncLLM,所以同样具备空闲健康探测。+API 只探测已加载的实例,默认周期和期限均为五秒,每实例最多一个在途探测。+异步探测的外部等待期限不依赖引擎循环,因此引擎循环阻塞时 API 仍能返回暂不可用。++同步句柄与异步代理共享 `RuntimeLifecycle`。明确死亡永久锁存,并通知全部 owner;缓存命中及后续调用拒绝+复用旧实例。健康和接单统一返回 `503 engine_dead`,未完成任务失败并清理结果。托管进程由既有 Router/Doclib+机制替换,外部 worker 仅摘除。CLI 非零退出,SDK 调用方自行释放并重建。++探测超时返回 `503 engine_unavailable`,拒绝新推理但允许继续探测;恢复健康后可解除,不能覆盖已锁存的死亡。+MLX 未知运行时异常只使当前请求失败,不进行 MFR 回退或永久隔离,后续请求仍可使用该实例。+取消依旧等待各后端完成必要清理,不将 Future 取消等同于 GPU 或线程工作结束。同步与异步 PDF 窗口共同使用准备输入和结果回填函数,保持原生表格优先、文本/公式处理、图像开关与页序。high 等待外部布局抽取,xhigh 等待两阶段抽取;后置 LLM 增强使用现有协程。diff --git a/mineru/model/vlm/async_runtime.py b/mineru/model/vlm/async_runtime.pyindex eabcdd62..94b66fb5 100644--- a/mineru/model/vlm/async_runtime.py+++ b/mineru/model/vlm/async_runtime.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport asyncioimport concurrent.futuresimport threading+import timefrom collections.abc import Awaitable, Callable, Sequencefrom typing import TYPE_CHECKING, Any, TypeVar@@ -13,6 +14,7 @@ from ...utils.async_utils import drain_future, run_syncfrom ..runtime import ownershipfrom .errors import EngineDeadError, is_fatal_engine_errorfrom .handles import RuntimeHandle+from .lifecycle import RuntimeLifecyclefrom .text_recognition import TextRecognitionResult, raise_unrecoverable_text_error, validate_text_resultif TYPE_CHECKING:@@ -55,13 +57,12 @@ class AsyncVlmPredictor:raise ValueError("VLM max_concurrency must be positive")self.backend = backendself.max_concurrency = max_concurrency- self.owners: set[ownership.RuntimeOwner] = set()- self.pinned = False+ self.lifecycle = RuntimeLifecycle(backend)self._factory = factoryself._ready: concurrent.futures.Future[None] = concurrent.futures.Future()self._state_lock = threading.Lock()- self._closing = False- self._fatal_error: BaseException | None = None+ self._probe_lock = threading.Lock()+ self._health_submission: _Submission | None = Noneself._shutdown_lock = threading.Lock()self._submissions: set[_Submission] = set()self._thread = threading.Thread(target=self._serve, name=f"mineru-{backend}", daemon=True)@@ -70,6 +71,7 @@ class AsyncVlmPredictor:async def _initialize(self) -> None:"""在固定循环创建引擎和共享请求信号量。"""self._runtime_handle = self._factory()+ self.lifecycle = self._runtime_handle.lifecycletry:self._predictor = self._runtime_handle.predictorself._semaphore = asyncio.Semaphore(self.max_concurrency)@@ -89,6 +91,8 @@ class AsyncVlmPredictor:if not self._ready.done():self._ready.set_exception(exc)finally:+ if self._ready.done() and self._ready.exception() is None and not self.lifecycle.closing:+ self.lifecycle.mark_fatal(EngineDeadError("VLM runtime event loop stopped unexpectedly"))pending = asyncio.all_tasks(self._loop)for task in pending:task.cancel()@@ -101,7 +105,72 @@ class AsyncVlmPredictor:@propertydef is_closed(self) -> bool:"""供缓存边界识别已经关闭或启动失败的旧代理。"""- return self._closing or not self._thread.is_alive()+ return self.lifecycle.closing or (self._ready.done() and self._ready.exception() is not None)++ @property+ def owners(self) -> set[ownership.RuntimeOwner]:+ """代理与内部句柄共用宿主集合,避免失效通知遗漏一层。"""+ return self.lifecycle.owners++ @property+ def pinned(self) -> bool:+ """从共享状态读取独立调用方的固定租约。"""+ return self.lifecycle.pinned++ @property+ def supports_health_probe(self) -> bool:+ """仅已成功创建并声明健康协议的运行时参与探测。"""+ return (+ self._ready.done()+ and self._ready.exception() is None+ and self._runtime_handle is not None+ and self._runtime_handle.supports_health_probe+ )++ def require_ready(self, *, allow_unavailable: bool = False) -> None:+ """统一缓存和提交边界的判断,异常退出的循环视为明确死亡。"""+ self.lifecycle.require_ready(allow_unavailable=allow_unavailable)+ if not self._thread.is_alive():+ self.lifecycle.mark_fatal(EngineDeadError("VLM runtime event loop is closed"))+ self.lifecycle.raise_if_dead()++ def probe_health(self, timeout: float = 5.0) -> None:+ """由调用方线程限定等待期限,循环阻塞时保留唯一的在途探测。"""+ from mineru_vl_utils.vlm_client.base_client import EngineHealth++ if not self.supports_health_probe:+ return+ if threading.current_thread() is self._thread:+ raise RuntimeError("Cannot synchronously probe from the VLM runtime thread")+ if timeout <= 0:+ raise ValueError("Health probe timeout must be positive")+ self.lifecycle.raise_if_dead()+ started = time.monotonic()+ if not self._probe_lock.acquire(timeout=timeout):+ self.lifecycle.apply_health(EngineHealth("unavailable", "Another engine health probe is still pending"))+ return+ try:+ if self.lifecycle.closing:+ return+ self.require_ready(allow_unavailable=True)+ remaining = timeout - (time.monotonic() - started)+ if remaining <= 0:+ self.lifecycle.apply_health(EngineHealth("unavailable", "Engine health probe deadline elapsed"))+ return+ if self._health_submission is None:+ self._health_submission = self._submit(+ lambda: self._runtime_handle.aio_probe_health(remaining), health_probe=True+ )+ submission = self._health_submission+ try:+ submission.result.result(timeout=remaining)+ except concurrent.futures.TimeoutError:+ self.lifecycle.apply_health(EngineHealth("unavailable", f"VLM health probe timed out after {timeout:g}s"))+ finally:+ if submission.finished.done():+ self._health_submission = None+ finally:+ self._probe_lock.release()def wait_ready(self) -> None:"""等待惰性构造完成,并原样传播初始化错误。"""@@ -109,7 +178,7 @@ class AsyncVlmPredictor:raise RuntimeError("Cannot synchronously wait for the VLM runtime from its own thread")self._ready.result()- def _submit(self, operation: Callable[[], Awaitable[T]]) -> _Submission:+ def _submit(self, operation: Callable[[], Awaitable[T]], *, health_probe: bool = False) -> _Submission:"""在线程安全边界接收请求,关闭开始后拒绝新增请求。"""if threading.current_thread() is self._thread:raise RuntimeError("Cannot submit a blocking bridge from the VLM runtime thread")@@ -118,19 +187,13 @@ class AsyncVlmPredictor:async def execute() -> T:"""在所属循环执行调用级操作,不占用等待线程。"""try:- if self._fatal_error is not None:- raise EngineDeadError(str(self._fatal_error)) from self._fatal_error- return await operation()+ self.lifecycle.require_ready(allow_unavailable=health_probe)+ result = await operation()+ self.lifecycle.raise_if_dead()+ return resultexcept Exception as exc:if self.backend != "http-client" and is_fatal_engine_error(exc):- with self._state_lock:- if self._fatal_error is None:- self._fatal_error = exc- for owner in tuple(self.owners):- owner.engine_error = str(exc)- owner = ownership.runtime_owner.get()- if owner is not None:- owner.engine_error = str(exc)+ self.lifecycle.mark_fatal(exc)raisedef finish(task: asyncio.Task[T]) -> None:@@ -152,10 +215,7 @@ class AsyncVlmPredictor:submission.task.cancel()with self._state_lock:- if self._fatal_error is not None:- raise EngineDeadError(str(self._fatal_error)) from self._fatal_error- if self._closing:- raise RuntimeError("VLM runtime is shutting down")+ self.require_ready(allow_unavailable=health_probe)self._loop.call_soon_threadsafe(start)return submission@@ -171,6 +231,7 @@ class AsyncVlmPredictor:def _call(self, operation: Callable[[], Awaitable[T]]) -> T:"""同步等待同一异步引擎;中断后等待实际请求清理。"""+ self.probe_health()submission = self._submit(operation)try:return submission.result.result()@@ -181,10 +242,13 @@ class AsyncVlmPredictor:async def _acall(self, operation: Callable[[], Awaitable[T]]) -> T:"""桥接调用方循环,取消后等待引擎清理完成而非仅取消 Future。"""+ if self.supports_health_probe:+ await run_sync(self.probe_health)submission = self._submit(operation)result = asyncio.wrap_future(submission.result)try:- return await asyncio.shield(result)+ await asyncio.wait([result])+ return result.result()except asyncio.CancelledError:self._cancel_submission(submission)await drain_future(asyncio.wrap_future(submission.finished))@@ -196,6 +260,7 @@ class AsyncVlmPredictor:async def _recognize_text(self, images: list[Image]) -> list[TextRecognitionResult]:"""逐请求隔离识别异常,跨文档共享并发额度,取消后排空所有切片。"""+async def recognize(image: Image) -> TextRecognitionResult:"""单片失败不会取消同批成功请求,程序错误和引擎故障仍向上传播。"""try:@@ -214,10 +279,14 @@ class AsyncVlmPredictor:for task in done:task.result()return [task.result() for task in tasks]- except BaseException:+ except BaseException as primary:for task in pending:task.cancel()- await drain_future(asyncio.gather(*tasks, return_exceptions=True))+ results = await drain_future(asyncio.gather(*tasks, return_exceptions=True))+ if isinstance(primary, Exception) and not is_fatal_engine_error(primary):+ for result in results:+ if isinstance(result, Exception) and is_fatal_engine_error(result):+ raise resultraisedef batch_recognize_text(self, images: list[Image]) -> list[TextRecognitionResult]:@@ -325,7 +394,7 @@ class AsyncVlmPredictor:self._thread.join()returnwith self._state_lock:- self._closing = True+ self.lifecycle.begin_close()work = asyncio.run_coroutine_threadsafe(self._close(), self._loop)try:work.result()diff --git a/mineru/model/vlm/errors.py b/mineru/model/vlm/errors.pyindex 5b0f9040..483a96ee 100644--- a/mineru/model/vlm/errors.py+++ b/mineru/model/vlm/errors.py@@ -3,12 +3,9 @@from __future__ import annotations-from ...errors import MineruError+from mineru_vl_utils.vlm_client.base_client import EngineUnavailableError-_FATAL_ENGINE_TYPES: dict[str, frozenset[str]] = {- "vllm": frozenset({"EngineDeadError", "AsyncEngineDeadError"}),- "mineru_vl_utils": frozenset({"EngineUnavailableError"}),-}+from ...errors import MineruErrorclass EngineNotReadyError(MineruError):@@ -19,31 +16,13 @@ class EngineNotReadyError(MineruError):super().__init__("engine_unavailable", message)-class EngineDeadError(RuntimeError):+class EngineDeadError(EngineUnavailableError):"""表示本地引擎已死亡,当前进程不能继续接受推理。"""def is_fatal_engine_error(error: BaseException) -> bool:- """遍历异常链和异常组,仅匹配后端明确报告的死亡类型。"""- pending = [error]- visited: set[int] = set()- while pending:- current = pending.pop()- if id(current) in visited:- continue- visited.add(id(current))- if isinstance(current, EngineDeadError):- return True- for cls in type(current).__mro__:- if cls.__name__ in _FATAL_ENGINE_TYPES.get(cls.__module__.split(".", 1)[0], ()):- return True- if any(cls.__name__ == "BaseExceptionGroup" for cls in type(current).__mro__):- pending.extend(item for item in getattr(current, "exceptions", ()) if isinstance(item, BaseException))- if current.__cause__ is not None:- pending.append(current.__cause__)- elif current.__context__ is not None and not current.__suppress_context__:- pending.append(current.__context__)- return False+ """只消费依赖库公共故障契约,不维护第二份后端类型识别规则。"""+ return EngineUnavailableError.find_in(error) is not None__all__ = ["EngineDeadError", "EngineNotReadyError", "is_fatal_engine_error"]diff --git a/mineru/model/vlm/handles.py b/mineru/model/vlm/handles.pyindex 486f9fee..150a625f 100644--- a/mineru/model/vlm/handles.py+++ b/mineru/model/vlm/handles.py@@ -7,14 +7,15 @@ import asyncioimport loggingimport threadingimport time-from collections.abc import AsyncIterator, Callable, Iterator, Sequence+from collections.abc import AsyncIterator, Awaitable, 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, current_runtime_owner-from .errors import EngineDeadError, EngineNotReadyError, is_fatal_engine_error+from ..runtime.ownership import RuntimeOwner+from .errors import is_fatal_engine_error+from .lifecycle import RuntimeLifecyclefrom .text_recognition import TextRecognitionResult, recognize_text_batchif TYPE_CHECKING:@@ -36,23 +37,22 @@ class RuntimeHandle:backend: str,close_engine: Callable[[], None] | None = None,probe_engine: Callable[[float], EngineHealth] | None = None,+ aio_probe_engine: Callable[[float], Awaitable[EngineHealth]] | None = None,close_health_probe: Callable[[], None] | None = None,) -> None:"""保存已创建资源,不修改第三方客户端的属性或推测其内部结构。"""self.backend = backend- self.owners: set[RuntimeOwner] = set()- self.pinned = False+ self.lifecycle = RuntimeLifecycle(backend)self.execution_lock = threading.Lock() if backend == "mlx-engine" else Noneself._predictor: MinerUClient | None = predictorself._close_engine = close_engineself._probe_engine = probe_engine+ self._aio_probe_engine = aio_probe_engineself._close_health_probe = close_health_probeself._probe_lock = threading.Lock()- self._fatal_error: BaseException | None = None- self._health_unavailable: str | None = None- self._condition = threading.Condition()+ self._condition = self.lifecycle.conditionself._active = 0- self._closing = False+ self._close_started = Falseself._closed = threading.Event()@property@@ -65,62 +65,61 @@ class RuntimeHandle:@propertydef is_closed(self) -> bool:"""让缓存识别正在关闭或已经关闭的宿主句柄。"""- return self._closing+ return self.lifecycle.closing@propertydef supports_health_probe(self) -> bool:"""缓存管理者据此开启只读探测,不为未加载模型触发初始化。"""- return self._probe_engine is not None+ return self._probe_engine is not None or self._aio_probe_engine is not None++ @property+ def owners(self) -> set[RuntimeOwner]:+ """向缓存暴露唯一状态中的宿主集合。"""+ return self.lifecycle.owners++ @property+ def pinned(self) -> bool:+ """独立 SDK 或 CLI 固定租约同样属于共享状态。"""+ return self.lifecycle.pinneddef 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_error- if 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__),- )+ """同步和异步运行时共用同一就绪规则。"""+ self.lifecycle.require_ready(allow_unavailable=allow_unavailable)++ async def aio_probe_health(self, timeout: float = 5.0) -> None:+ """由异步代理在所属循环调用,期限由外层跨线程等待同时保障。"""+ if self._aio_probe_engine is None:+ return+ try:+ health = await self._aio_probe_engine(timeout)+ except Exception as error:+ if is_fatal_engine_error(error):+ self.lifecycle.mark_fatal(error)+ raise+ from mineru_vl_utils.vlm_client.base_client import EngineHealth++ health = EngineHealth("unavailable", f"VLM health probe failed: {type(error).__name__}: {error}")+ self.lifecycle.apply_health(health)def probe_health(self, timeout: float = 5.0) -> None:"""执行至多一个宿主探测;超时状态可恢复,明确死亡永不被健康结果覆盖。"""+ from mineru_vl_utils.vlm_client.base_client import EngineHealth+if self._probe_engine is None:returnif timeout <= 0:raise ValueError("Health probe timeout must be positive")+ self.lifecycle.raise_if_dead()started = time.monotonic()if not self._probe_lock.acquire(timeout=timeout):- raise EngineNotReadyError("Another engine health probe is still pending")+ self.lifecycle.apply_health(EngineHealth("unavailable", "Another engine health probe is still pending"))+ returnactive = Falsetry:with self._condition:- if self._closing:+ if self.lifecycle.closing:return- if self._fatal_error is not None:- raise EngineDeadError(str(self._fatal_error)) from self._fatal_error+ self.lifecycle.raise_if_dead()self._active += 1active = Truetry:@@ -132,24 +131,14 @@ class RuntimeHandle:raise ValueError("Invalid engine health state")except Exception as exc:if is_fatal_engine_error(exc):- self._mark_fatal(exc)+ self.lifecycle.mark_fatal(exc)raiselogger.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)+ self.lifecycle.apply_health(health)+ return+ self.lifecycle.apply_health(EngineHealth("unavailable", message))finally:if active:with self._condition:@@ -173,11 +162,10 @@ class RuntimeHandle:with self.execution_lock:yield predictorwith self._condition:- if self._fatal_error is not None:- raise EngineDeadError(str(self._fatal_error)) from self._fatal_error+ self.lifecycle.raise_if_dead()except Exception as exc:if is_fatal_engine_error(exc):- self._mark_fatal(exc)+ self.lifecycle.mark_fatal(exc)raisefinally:with self._condition:@@ -193,7 +181,7 @@ class RuntimeHandle:if lock is not None:while True:with self._condition:- if self._closing:+ if self.lifecycle.closing:raise RuntimeError("VLM runtime is shutting down")if lock.acquire(blocking=False):break@@ -274,9 +262,10 @@ class RuntimeHandle:def _begin_close(self) -> bool:"""只让一个调用方执行关闭,其余调用方等待同一个完成信号。"""with self._condition:- if self._closing:+ if self._close_started:return False- self._closing = True+ self._close_started = True+ self.lifecycle.begin_close()return Truedef _wait_for_calls(self) -> None:@@ -296,10 +285,10 @@ class RuntimeHandle:if first_error is None:first_error = excfinally:- for owner in tuple(self.owners):- owner.set_engine_unavailable(self, None)+ self.lifecycle.finish_close()self._predictor = Noneself._probe_engine = None+ self._aio_probe_engine = Noneself._close_health_probe = Noneself._closed.set()if first_error is not None:@@ -351,7 +340,8 @@ class RuntimeHandle:work = asyncio.create_task(self._close_client())error: BaseException | None = Nonetry:- await asyncio.shield(work)+ await asyncio.wait([work])+ work.result()except BaseException as exc:error = exctry:diff --git a/mineru/model/vlm/lifecycle.py b/mineru/model/vlm/lifecycle.pynew file mode 100644index 00000000..cb14ab8d--- /dev/null+++ b/mineru/model/vlm/lifecycle.py@@ -0,0 +1,117 @@+"""同步句柄与异步代理共享的实例生命周期,不负责执行或重建引擎。"""++from __future__ import annotations++import logging+import threading++from mineru_vl_utils.vlm_client.base_client import EngineHealth++from ..runtime.ownership import RuntimeOwner, runtime_owner+from .errors import EngineDeadError, EngineNotReadyError++logger = logging.getLogger(__name__)+++class RuntimeLifecycle:+ """锁存首个致命错误,并在同一状态锁下管理宿主关联及暂不可用状态。"""++ def __init__(self, backend: str) -> None:+ """仅创建轻量状态,不触发线程、循环或模型加载。"""+ self.backend = backend+ self.condition = threading.Condition()+ self.owners: set[RuntimeOwner] = set()+ self.pinned = False+ self.closing = False+ self._fatal_error: BaseException | None = None+ self._unavailable: str | None = None++ def raise_if_dead(self) -> None:+ """所有入口共用永久失效判定,异常链指回最初故障。"""+ with self.condition:+ if self._fatal_error is not None:+ raise EngineDeadError(str(self._fatal_error)) from self._fatal_error++ def require_ready(self, *, allow_unavailable: bool = False) -> None:+ """允许暂不可用实例接受健康复查,但不允许新的推理。"""+ with self.condition:+ self.raise_if_dead()+ if self.closing:+ raise RuntimeError("VLM runtime is shutting down")+ if self._unavailable is not None and not allow_unavailable:+ raise EngineNotReadyError(self._unavailable)++ def retain(self, owner: RuntimeOwner | None) -> None:+ """拒绝新宿主借用死亡实例,并同步既有的暂不可用状态。"""+ with self.condition:+ if owner is not None and self._fatal_error is not None and owner.engine_error is None:+ owner.engine_error = str(self._fatal_error)+ self.require_ready(allow_unavailable=True)+ if owner is None:+ self.pinned = True+ else:+ self.owners.add(owner)+ owner.set_engine_unavailable(self, self._unavailable)++ def release(self, owner: RuntimeOwner) -> None:+ """撤销一个宿主的关联,不清除其他宿主的故障或租约。"""+ with self.condition:+ self.owners.discard(owner)+ owner.set_engine_unavailable(self, None)++ def mark_fatal(self, error: BaseException) -> None:+ """只记录首次完整异常,后续故障仍通知全部关联宿主。"""+ with self.condition:+ first = self._fatal_error is None+ if first:+ self._fatal_error = error+ message = str(self._fatal_error)+ owners = set(self.owners)+ current = runtime_owner.get()+ if current is not None:+ owners.add(current)+ self._unavailable = None+ for owner in owners:+ if owner.engine_error is None:+ owner.engine_error = message+ owner.set_engine_unavailable(self, None)+ if first:+ logger.error(+ "VLM engine failed: backend=%s error_type=%s",+ self.backend,+ type(error).__name__,+ exc_info=(type(error), error, error.__traceback__),+ )++ def apply_health(self, health: EngineHealth) -> None:+ """迟到的健康结果不能覆盖死亡,关闭开始后不再发布探测状态。"""+ with self.condition:+ self.raise_if_dead()+ if self.closing:+ return+ if health.state == "dead":+ error = EngineDeadError(health.message or "VLM engine is unavailable")+ self.mark_fatal(error)+ raise error+ if health.state not in {"healthy", "unavailable"}:+ raise ValueError("Invalid engine health state")+ self._unavailable = (+ (health.message or "VLM engine health is unavailable") if health.state == "unavailable" else None+ )+ for owner in tuple(self.owners):+ owner.set_engine_unavailable(self, self._unavailable)+ self.require_ready()++ def begin_close(self) -> None:+ """停止接纳新工作;实际关闭动作仍由各运行时按执行机制排空。"""+ with self.condition:+ self.closing = True++ def finish_close(self) -> None:+ """资源释放后移除暂不可用记录,不撤销永久死亡的宿主通知。"""+ with self.condition:+ for owner in tuple(self.owners):+ owner.set_engine_unavailable(self, None)+++__all__ = ["RuntimeLifecycle"]diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.pyindex 196be98a..bf381ff6 100644--- a/mineru/model/vlm/runtime.py+++ b/mineru/model/vlm/runtime.py@@ -11,21 +11,19 @@ import timefrom collections.abc import Callablefrom contextvars import ContextVar, copy_contextfrom dataclasses import dataclass, field-from pathlib import Pathfrom functools import partial+from pathlib import Pathfrom typing import Any, Literalfrom loguru import loggerfrom mineru_vl_utils import MinerUClientfrom ..registry import MINERU_2_5_PRO_2605_1_2B, vlm_model_repo-from ..runtime.device import get_device-from ..runtime.platform import is_mac_os_version_supportedfrom ..runtime.closing import in_runtime_close_scope, runtime_close_scope+from ..runtime.device import get_devicefrom ..runtime.ownership import RuntimeOwner, current_runtime_owner, runtime_initialization_scope+from ..runtime.platform import is_mac_os_version_supportedfrom .async_runtime import AsyncVlmPredictor-from .handles import RuntimeHandle-from .errors import EngineNotReadyErrorfrom .engine_utils import (enable_custom_logits_processors,mod_kwargs_by_device_type,@@ -33,6 +31,8 @@ from .engine_utils import (set_default_gpu_memory_utilization,set_lmdeploy_backend,)+from .errors import EngineNotReadyError+from .handles import RuntimeHandle@dataclass(eq=False)@@ -101,12 +101,9 @@ class ModelSingleton:def _retain(self, predictor: RuntimeHandle | AsyncVlmPredictor) -> None:"""发布或复用前重新校验应用,防止关闭后的预热结果进入缓存。"""owner = current_runtime_owner()- if owner is None:- predictor.pinned = True- else:- predictor.owners.add(owner)- if isinstance(predictor, RuntimeHandle) and predictor.supports_health_probe:- owner.has_engine_health_probe = True+ predictor.lifecycle.retain(owner)+ if owner is not None and predictor.supports_health_probe:+ owner.has_engine_health_probe = Truedef _get_or_initialize(self,@@ -141,9 +138,7 @@ 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)+ cached.require_ready(allow_unavailable=True)return cachedelse:pending = None@@ -445,7 +440,8 @@ class ModelSingleton:predictor,backend=backend,close_engine=close_engine,- probe_engine=predictor.client.probe_health if backend == "lmdeploy-engine" else None,+ probe_engine=predictor.client.probe_health if predictor.client.health_probe_mode == "sync" else None,+ aio_probe_engine=predictor.client.aio_probe_health if predictor.client.health_probe_mode == "async" else None,close_health_probe=predictor.client.close_health_probe if backend == "lmdeploy-engine" else None,)@@ -455,7 +451,7 @@ class ModelSingleton:handles = tuple(predictorfor predictor in self._models.values()- if isinstance(predictor, RuntimeHandle) and owner in predictor.owners and predictor.supports_health_probe+ if owner in predictor.owners and predictor.supports_health_probe)unavailable: EngineNotReadyError | None = Nonefor predictor in handles:@@ -472,7 +468,7 @@ class ModelSingleton:with self._lock:closing = []for key, predictor in tuple(self._models.items()):- predictor.owners.discard(owner)+ predictor.lifecycle.release(owner)if not predictor.owners and not predictor.pinned:closing.append(self._detach(key, predictor))self._close_detached(closing)diff --git a/scripts/acceptance/README-vlm-lifecycle.md b/scripts/acceptance/README-vlm-lifecycle.mdnew file mode 100644index 00000000..3570d25b--- /dev/null+++ b/scripts/acceptance/README-vlm-lifecycle.md@@ -0,0 +1,43 @@+# VLM 生命周期联合验收++先安装同一候选批次的 MinerU 与 mineru-vl-utils wheel,保存版本、源码位置与 SHA256。+真实设备结果与异常源码契约检查分开记录,不以模拟通过代替 GPU 验收。++## Linux / WSL2 vLLM++为 `0.19.1` 与 `0.30.0` 分别使用独立的 uv Python 3.12 环境。环境可复用只读模型缓存,不复用另一版本的包目录。++```bash+uv venv --python 3.12 .venv-vllm019+uv pip install --python .venv-vllm019/bin/python 'vllm==0.19.1'+# 在该环境安装本批候选 wheels 及 MinerU 的解析依赖,再运行:+.venv-vllm019/bin/python scripts/acceptance/vllm_lifecycle.py \+ --sample demo/pdfs/demo2.pdf --models-dir /path/to/models --evidence output/vllm019+```++第二个环境改为 `vllm==0.30.0`,使用独立 evidence 目录。脚本需要同目录的 `lmdeploy_lifecycle.py`。+它复用正式 WorkerPool、Tasks 和结果下载流程,验证真实切片、Standard/Advanced 产物、循环阻塞时超时恢复、+空闲真实 shutdown、运行中信号注入、任务清理及托管进程替换。++运行中注入只在真实引擎已经交出 token、请求尚未退出时触发;其结论是宿主存活时的故障处理,不是原始崩溃根因。+`--active-stop close` 是额外关闭诊断;整进程退出与引擎独立死亡分别报告,不能放宽断言将前者算作后者通过。+验收路由只存在于回环地址上的独立测试 worker,不加入生产服务。++## Windows LMDeploy++沿用 [LMDeploy 验收说明](README-lmdeploy.md),分别验证 TurboMind 0.17/0.18;不把 Windows PyTorch 列为通过条件。++## macOS MLX++```bash+python scripts/acceptance/mlx_lifecycle.py \+ --sample demo/pdfs/demo2.pdf --evidence output/mlx-lifecycle+```++保存真实解析产物,验证同步生成开始后的取消等待、未知错误向上传播、同实例后续真实推理成功及缓存释放。+未知错误是显式测试注入,不是对 MLX 原生崩溃的宣称。++## 检查报告++同时检查 `report.json`、worker 完整日志与结果 ZIP/Markdown。出现未处理异常、重复异常日志、错误档位或空产物均需调查。+代码测试、上游版本契约、三平台真机、依赖发布及发布包安装验证分别记录状态。diff --git a/scripts/acceptance/lmdeploy_lifecycle.py b/scripts/acceptance/lmdeploy_lifecycle.pyindex 52bdc98a..bfa39463 100644--- a/scripts/acceptance/lmdeploy_lifecycle.py+++ b/scripts/acceptance/lmdeploy_lifecycle.py@@ -19,9 +19,10 @@ from pathlib import Pathfrom typing import Any-def _arguments() -> argparse.Namespace:+def _arguments(default_engine: str = "lmdeploy") -> argparse.Namespace:"""声明验收输入及子进程参数,普通运行不隐式安装或更换推理依赖。"""parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--engine", choices=("lmdeploy", "vllm"), default=default_engine)parser.add_argument("--sample", type=Path, help="包含图像或公式的真实 PDF,建议至少数页")parser.add_argument("--backend", choices=("turbomind",), default="turbomind", help="Windows 验收只覆盖受支持的 TurboMind 后端"@@ -41,10 +42,10 @@ def _arguments() -> argparse.Namespace:return parser.parse_args()-def _versions() -> dict[str, Any]:+def _versions(engine: str = "lmdeploy") -> 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"):+ for name in ("mineru", "mineru-vl-utils", "docvortex", engine, "torch", "transformers"):versions[name] = importlib.metadata.version(name)import mineruimport mineru_vl_utils@@ -58,8 +59,10 @@ def _versions() -> dict[str, Any]: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"):+ if engine == "lmdeploy" and versions["lmdeploy"] not in SpecifierSet(">=0.17.0,<0.19"):raise RuntimeError("This acceptance covers LMDeploy 0.17 and 0.18 only")+ if engine == "vllm" and versions["vllm"] not in {"0.19.1", "0.30.0"}:+ raise RuntimeError("This GPU acceptance covers vLLM 0.19.1 and 0.30.0")import torchversions["cuda_available"] = torch.cuda.is_available()@@ -275,6 +278,8 @@ async def _accept(args: argparse.Namespace, report: dict[str, Any]) -> None:sys.executable,str(Path(__file__).resolve()),"--worker",+ "--engine",+ args.engine,"--port",str(port),"--uploads",@@ -315,7 +320,8 @@ async def _accept(args: argparse.Namespace, report: dict[str, Any]) -> None: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"]+ expected = "AsyncLLM" if args.engine == "vllm" else "TurbomindEngineConfig"+ assert report["runtime"]["backend_config"] == expected, report["runtime"]response = await client.post(state.base_url + "/_acceptance/infer")response.raise_for_status()report["real_inference"] = response.json()@@ -362,7 +368,7 @@ async def _accept(args: argparse.Namespace, report: dict[str, Any]) -> None:report["tasks_before_inflight_stop"] = [item["status"] for item in snapshots]breakif all(item["status"] in {"completed", "partial", "failed", "canceled"} for item in snapshots):- raise RuntimeError("No active LMDeploy sequences observed; use a longer PDF sample")+ raise RuntimeError("No active engine 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")@@ -400,9 +406,9 @@ async def _accept(args: argparse.Namespace, report: dict[str, Any]) -> None:await pool.close()-def main() -> int:+def main(default_engine: str = "lmdeploy") -> int:"""保存每次验收的完整报告,失败时也保留 traceback 和所有 worker 日志。"""- args = _arguments()+ args = _arguments(default_engine)args.evidence = args.evidence.resolve()args.evidence.mkdir(parents=True, exist_ok=True)os.environ["PYTHONUTF8"] = "1"@@ -410,20 +416,28 @@ def main() -> int:if args.models_dir:os.environ["MINERU_MODEL_BASE_DIR"] = str(args.models_dir.resolve())if args.worker:- _worker(args)+ if args.engine == "vllm":+ from vllm_lifecycle import run_worker++ run_worker(args)+ else:+ _worker(args)return 0report: dict[str, Any] = {"passed": False,"backend": args.backend,+ "engine": args.engine,"recoveries": [],"original_incident_root_cause": "not established; lifecycle fault injection only",}try:- if sys.platform != "win32":+ if args.engine == "lmdeploy" and sys.platform != "win32":raise RuntimeError("Run this release acceptance on Windows with a configured CUDA MinerU environment")+ if args.engine == "vllm" and sys.platform != "linux":+ raise RuntimeError("Run vLLM release acceptance on Linux/WSL2 with a configured CUDA 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["versions"] = _versions(args.engine)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())diff --git a/scripts/acceptance/mlx_lifecycle.py b/scripts/acceptance/mlx_lifecycle.pynew file mode 100644index 00000000..e0284eea--- /dev/null+++ b/scripts/acceptance/mlx_lifecycle.py@@ -0,0 +1,130 @@+"""macOS MLX 真机验收:真实解析、在途取消排空和未知错误后的实例复用。"""++from __future__ import annotations++import argparse+import asyncio+import hashlib+import importlib.metadata+import json+import platform+import sys+import threading+import time+import traceback+from pathlib import Path+from typing import Any+++async def accept(sample: Path, evidence: Path, report: dict[str, Any]) -> None:+ """所有注入只发生在独立验收进程,真实模型与产物始终可复核。"""+ from PIL import Image, ImageDraw++ from mineru.config import VlmConfig+ from mineru.model.vlm.client import get_vlm_predictor+ from mineru.parser import parse_async+ from mineru.parser.writer import FileBasedDataWriter++ settings = VlmConfig(engine="mlx", server_url="")+ for tier in ("standard", "advanced"):+ result = await parse_async(sample, tier=tier, vlm_config=settings)+ assert result.middle_json.pages+ result.save(FileBasedDataWriter(str(evidence / tier)))+ report[tier] = {+ "pages": len(result.middle_json.pages),+ "markdown_characters": len((evidence / tier / "markdown.md").read_text(encoding="utf-8")),+ }+ runtime, backend = get_vlm_predictor(settings)+ assert backend == "mlx-engine"+ client = runtime.predictor.client+ assert client.health_probe_mode == "none"+ original = client.generate+ entered, drained = threading.Event(), threading.Event()+ image = Image.new("RGB", (512, 128), "white")+ ImageDraw.Draw(image).text((20, 30), "2 + 2 = 4; MinerU lifecycle", fill="black", font_size=28)++ def observe_generate(*args: Any, **kwargs: Any) -> Any:+ """进入真实同步生成后记录开始,直到真实生成自然退出才记录完成。"""+ entered.set()+ try:+ return original(*args, **kwargs)+ finally:+ drained.set()++ def unknown_failure(*args: Any, **kwargs: Any) -> Any:+ """显式模拟未分类执行故障,不声称这是 MLX 自身的崩溃。"""+ raise RuntimeError("acceptance injected unknown MLX execution failure")++ try:+ client.generate = observe_generate+ task = asyncio.create_task(runtime.aio_batch_recognize_text([image]))+ assert await asyncio.to_thread(entered.wait, 30), "Real MLX generation did not start"+ assert not drained.is_set(), "Generation already finished before cancellation"+ start = time.monotonic()+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ else:+ raise AssertionError("Cancellation was not propagated")+ assert drained.is_set()+ report["cancellation"] = {"drained": True, "return_seconds": time.monotonic() - start}+ client.generate = unknown_failure+ try:+ await runtime.aio_batch_recognize_text([image])+ except RuntimeError as error:+ assert "acceptance injected unknown" in str(error)+ else:+ raise AssertionError("Unknown execution failure was swallowed")+ runtime.require_ready()+ client.generate = original+ result = await runtime.aio_batch_recognize_text([image])+ assert len(result) == 1 and isinstance(result[0], str) and result[0].strip(), result+ report["unknown_failure"] = {"injected": True, "instance_reused": True, "next_real_inference": result}+ report["passed"] = True+ finally:+ client.generate = original+ image.close()+++def main() -> int:+ """始终保存版本、输入哈希、错误与关闭状态,缺少实机环境时明确失败。"""+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--sample", type=Path, required=True)+ parser.add_argument("--evidence", type=Path, required=True)+ args = parser.parse_args()+ args.evidence.mkdir(parents=True, exist_ok=True)+ report: dict[str, Any] = {"passed": False, "python": sys.version, "platform": platform.platform()}+ try:+ if sys.platform != "darwin":+ raise RuntimeError("MLX acceptance requires macOS with Apple Silicon")+ report["versions"] = {+ name: importlib.metadata.version(name) for name in ("mineru", "mineru-vl-utils", "mlx-vlm", "mlx")+ }+ import mineru_vl_utils++ import mineru++ report["source_paths"] = {"mineru": mineru.__file__, "mineru_vl_utils": mineru_vl_utils.__file__}+ report["sample_sha256"] = hashlib.sha256(args.sample.read_bytes()).hexdigest()+ asyncio.run(accept(args.sample, args.evidence, report))+ except Exception:+ report["error"] = traceback.format_exc()+ print(report["error"], file=sys.stderr)+ finally:+ from mineru.model.vlm.runtime import ModelSingleton, shutdown_cached_models++ try:+ shutdown_cached_models()+ assert not ModelSingleton._models+ report["runtime_cache_released"] = True+ except Exception:+ report["passed"] = False+ report["cleanup_error"] = traceback.format_exc()+ (args.evidence / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/acceptance/vllm_lifecycle.py b/scripts/acceptance/vllm_lifecycle.pynew file mode 100644index 00000000..bf7ef159--- /dev/null+++ b/scripts/acceptance/vllm_lifecycle.py@@ -0,0 +1,176 @@+"""Linux/WSL2 vLLM 真机验收,复用现有任务与托管进程验收流程。"""++from __future__ import annotations++import argparse+import asyncio+import json+import os+import sys+import threading+from collections.abc import AsyncIterator, Callable+from copy import copy+from typing import Any+++async def observe_generation(+ generate: Callable[..., AsyncIterator[Any]],+ active: set[str],+ metrics: dict[str, int],+ cumulative_output_kind: Any,+ *args: Any,+ **kwargs: Any,+) -> AsyncIterator[Any]:+ """验收时观察非终态 token;只改变输出投递方式,不改生成参数或共享配置。"""+ sampling = copy(kwargs["sampling_params"])+ sampling.output_kind = cumulative_output_kind+ kwargs["sampling_params"] = sampling+ request_id = kwargs["request_id"]+ try:+ async for output in generate(*args, **kwargs):+ count = sum(len(choice.token_ids) for choice in output.outputs)+ if count and not output.finished:+ active.add(request_id)+ metrics["token_events"] += 1+ if output.finished:+ active.discard(request_id)+ yield output+ finally:+ active.discard(request_id)+++def run_worker(args: argparse.Namespace) -> None:+ """仅在独立验收 worker 注入路由及观测,生产模块不包含故障注入。"""+ import uvicorn+ from lmdeploy_lifecycle import _versions+ from PIL import Image, ImageDraw+ from vllm.sampling_params import RequestOutputKind+ from vllm.v1.engine.exceptions import EngineDeadError++ 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++ 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("vllm")}), flush=True)+ application = create_app(+ upload_dir=str(args.uploads),+ tiers=("flash", "basic", "standard", "advanced"),+ concurrency=1,+ preload_models=True,+ vlm_config=VlmConfig(engine="vllm", server_url=""),+ )+ active: set[str] = set()+ metrics = {"token_events": 0}+ instrumented = False++ def handle() -> Any:+ """取得本应用已加载的唯一异步引擎,不为了观察而创建模型。"""+ pool = ModelSingleton()+ with pool._lock:+ found = [item for item in pool._models.values() if item.backend == "vllm-async-engine"]+ if len(found) != 1:+ raise RuntimeError(f"Expected one vLLM runtime, got {len(found)}")+ return found[0]++ async def instrument() -> None:+ """在引擎循环观察真实输出 token,避免把任务 running 当作 GPU 在途证据。"""+ nonlocal instrumented+ if instrumented:+ return+ engine = handle()._predictor.client.vllm_async_llm+ original = engine.generate++ async def generate(*args: Any, **kwargs: Any) -> AsyncIterator[Any]:+ """真实客户端默认只接收终态,验收改为累计投递以观察尚未完成的 token。"""+ async for output in observe_generation(original, active, metrics, RequestOutputKind.CUMULATIVE, *args, **kwargs):+ yield output++ engine.generate = generate+ instrumented = True++ @application.get("/_acceptance/runtime")+ async def inspect_runtime() -> dict[str, Any]:+ """同时安装仅供验收使用的输出观测,并报告真实引擎身份。"""+ runtime = handle()+ await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(instrument(), runtime._loop))+ return {"pid": os.getpid(), "backend": runtime.backend, "backend_config": "AsyncLLM"}++ @application.post("/_acceptance/infer")+ async def infer_crop() -> dict[str, Any]:+ """执行真实切片识别,健康检查通过不能代替推理验证。"""+ image = Image.new("RGB", (384, 96), "white")+ try:+ ImageDraw.Draw(image).text((20, 25), "2 + 2 = 4", fill="black", font_size=32)+ outputs = await handle().aio_batch_recognize_text([image])+ assert len(outputs) == 1 and isinstance(outputs[0], str) and outputs[0].strip(), outputs+ return {"recognized": outputs[0]}+ finally:+ image.close()++ @application.post("/_acceptance/delay-loop")+ async def delay_loop() -> dict[str, bool]:+ """只阻塞引擎循环,API 循环必须仍能给出暂不可用响应。"""++ def delay() -> None:+ """覆盖五秒周期与五秒期限,随后自然恢复。"""+ threading.Event().wait(12)++ handle()._loop.call_soon_threadsafe(delay)+ return {"scheduled": True}++ async def activity(inject: bool = False) -> dict[str, Any]:+ """在模型循环中原子观测输出与注入健康错误,避免查询后请求已经结束。"""+ snapshot = {"active_seqs": len(active), "token_events": metrics["token_events"], "injected": False}+ if inject and active:++ async def report_dead() -> None:+ """注入真实 vLLM 致命异常类型,仍允许本机 GPU 工作自然结束。"""+ raise EngineDeadError()++ # 适配器保存公开回调,替换回调是本验收唯一的合成死亡信号。+ handle()._predictor.client._health_probe._check_health = report_dead+ snapshot["injected"] = True+ return snapshot++ @application.get("/_acceptance/activity")+ async def inspect_activity() -> dict[str, Any]:+ """读取已产生真实 token 且尚未退出的推理数。"""+ return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(activity(), handle()._loop))++ @application.post("/_acceptance/signal-dead")+ async def signal_dead() -> dict[str, Any]:+ """在活跃推理期间注入健康故障;报告明确标注为信号注入。"""+ return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(activity(True), handle()._loop))++ @application.post("/_acceptance/stop-engine")+ async def stop_engine() -> dict[str, bool]:+ """在所属循环调用真实公开 shutdown,保留 API 进程观察空闲死亡。"""+ runtime = handle()+ runtime._loop.call_soon_threadsafe(runtime._predictor.client.vllm_async_llm.shutdown)+ 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()+++if __name__ == "__main__":+ from lmdeploy_lifecycle import main++ raise SystemExit(main("vllm"))diff --git a/tests/unittest/test_engine_dead_lifecycle.py b/tests/unittest/test_engine_dead_lifecycle.pyindex 5ef1eb95..2e69d9ab 100644--- a/tests/unittest/test_engine_dead_lifecycle.py+++ b/tests/unittest/test_engine_dead_lifecycle.py@@ -15,6 +15,8 @@ import httpximport pytestfrom fastapi.testclient import TestClient+from mineru_vl_utils.vlm_client.base_client import EngineUnavailableError+from mineru.model.vlm.errors import EngineDeadError, is_fatal_engine_errorfrom mineru.parser import api_serverfrom mineru.kit.router import workers@@ -24,7 +26,7 @@ def test_fatal_classifier_uses_types_and_exception_chain() -> None:"""普通 EngineCore 文本和网络超时不是死亡;明确类型及 cause 是死亡。"""assert not is_fatal_engine_error(RuntimeError("EngineCore request invalid"))assert not is_fatal_engine_error(httpx.ReadTimeout("enginecore timeout"))- fatal_type = type("EngineDeadError", (RuntimeError,), {"__module__": "vllm.v1.engine.exceptions"})+ fatal_type = EngineUnavailableErrorwrapper = ValueError("wrapped")wrapper.__cause__ = fatal_type("dead")assert is_fatal_engine_error(wrapper)diff --git a/tests/unittest/test_lmdeploy_engine_lifecycle.py b/tests/unittest/test_lmdeploy_engine_lifecycle.pyindex fa6c3aba..f1b21cba 100644--- a/tests/unittest/test_lmdeploy_engine_lifecycle.py+++ b/tests/unittest/test_lmdeploy_engine_lifecycle.py@@ -18,6 +18,7 @@ from task_test_utils import submit_task, task_url, wait_taskfrom mineru.model.runtime.ownership import RuntimeOwnerfrom mineru.model.vlm.errors import EngineDeadError, EngineNotReadyError, is_fatal_engine_errorfrom mineru.model.vlm.handles import RuntimeHandle+from mineru.model.vlm.async_runtime import AsyncVlmPredictorfrom mineru.model.vlm.runtime import ModelSingletonfrom mineru.model.vlm.text_recognition import recognize_text_batchfrom mineru.parser import api_server@@ -159,7 +160,10 @@ def test_close_waits_for_active_health_probe() -> None:assert client.closed and closed.is_set()-def test_idle_server_detects_death_and_transient_recovery(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:[email protected]("asynchronous", [False, True])+def test_idle_server_detects_death_and_transient_recovery(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool+) -> None:"""无需新解析请求,周期探测就能撤销能力;超时恢复后才重新允许接单。"""monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)monkeypatch.setattr(api_server, "_ENGINE_HEALTH_INTERVAL_SECONDS", 0.01)@@ -169,14 +173,26 @@ def test_idle_server_detects_death_and_transient_recovery(tmp_path: Path, monkey"""模拟已加载的引擎健康变化。"""return status- handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=probe)+ async def async_probe(timeout: float) -> EngineHealth:+ """使用同一健康变化验证异步运行时真实跨循环桥接。"""+ return probe(timeout)++ if asynchronous:+ handle = AsyncVlmPredictor(+ lambda: RuntimeHandle(Client(), backend="vllm-async-engine", aio_probe_engine=async_probe),+ backend="vllm-async-engine",+ max_concurrency=1,+ )+ handle.wait_ready()+ else:+ 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_ownerhandle.owners.add(owner)- handle.pinned = True+ handle.lifecycle.pinned = Trueowner.has_engine_health_probe = Trueasync def wait_state(code: str | None) -> None:@@ -220,7 +236,8 @@ def test_probe_does_not_initialize_lazy_models(monkeypatch: pytest.MonkeyPatch)probe.assert_not_called()-def test_monitor_drains_running_and_queued_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:[email protected]("asynchronous", [False, True])+def test_monitor_drains_running_and_queued_tasks(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, asynchronous: bool) -> None:"""后台健康发现死亡时也必须清理已接纳任务,不能等待某次推理主动报错。"""monkeypatch.setattr(api_server, "_preflight_tier_dependencies", lambda *args: None)monkeypatch.setattr(api_server, "_ENGINE_HEALTH_INTERVAL_SECONDS", 0.01)@@ -242,8 +259,21 @@ def test_monitor_drains_running_and_queued_tasks(tmp_path: Path, monkeypatch: pycleaned.set()monkeypatch.setattr(api_server, "parse_async", infer)- handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=probe)- handle.pinned = True++ async def async_probe(timeout: float) -> EngineHealth:+ """使用同一健康变化验证异步运行时真实跨循环桥接。"""+ return probe(timeout)++ if asynchronous:+ handle = AsyncVlmPredictor(+ lambda: RuntimeHandle(Client(), backend="vllm-async-engine", aio_probe_engine=async_probe),+ backend="vllm-async-engine",+ max_concurrency=1,+ )+ handle.wait_ready()+ else:+ handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=probe)+ handle.lifecycle.pinned = Truemonkeypatch.setattr(ModelSingleton, "_models", {("engine",): handle})app = api_server.create_app(upload_dir=str(tmp_path / "uploads"), tiers=("flash",), concurrency=1)try:@@ -273,3 +303,27 @@ def test_fatal_engine_chain_keeps_original_backend_signal() -> None:error = ValueError("wrapper")error.__cause__ = EngineUnavailableError("original")assert is_fatal_engine_error(error)+++def test_probe_lock_timeout_marks_owner_unavailable_and_dead_rejects_immediately() -> None:+ """等待在途探测也受健康期限约束,明确死亡无需再次等待被占用的探测锁。"""+ import time++ handle = RuntimeHandle(Client(), backend="lmdeploy-engine", probe_engine=lambda timeout: EngineHealth("healthy"))+ owner = RuntimeOwner()+ handle.lifecycle.retain(owner)+ try:+ with handle._probe_lock:+ with pytest.raises(EngineNotReadyError):+ handle.probe_health(0.01)+ assert owner.engine_unavailable is not None+ handle.probe_health()+ assert owner.engine_unavailable is None+ handle.lifecycle.mark_fatal(EngineUnavailableError("already dead"))+ with handle._probe_lock:+ start = time.monotonic()+ with pytest.raises(EngineDeadError):+ handle.probe_health(1)+ assert time.monotonic() - start < 0.2+ finally:+ handle.shutdown()diff --git a/tests/unittest/test_native_async_runtime.py b/tests/unittest/test_native_async_runtime.pyindex e410c076..b84cba0d 100644--- a/tests/unittest/test_native_async_runtime.py+++ b/tests/unittest/test_native_async_runtime.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport threading+from types import SimpleNamespacefrom concurrent.futures import ThreadPoolExecutorfrom typing import Any@@ -21,6 +22,7 @@ class _AsyncClient:def __init__(self) -> None:"""在运行时线程内创建同步观测信号和异步阻塞门。"""self.loop = asyncio.get_running_loop()+ self.client = SimpleNamespace(health_probe_mode="none")self.active = 0self.peak = 0self.closed = False@@ -391,6 +393,12 @@ def test_vllm_runtime_uses_standard_progress_label(backend = object.__new__(VllmAsyncEngineVlmClient)backend.max_concurrency = 2+ from mineru_vl_utils.vlm_client.vllm_health import VllmHealthProbe++ async def check_health() -> None:+ """本测试只验证进度与清理,声明替身引擎健康可用。"""++ backend._health_probe = VllmHealthProbe(check_health)async def predict(image: Any, prompt: str = "", **kwargs: Any) -> str:"""仅替换 GPU 单请求,保持真实异步批处理和布局回填。"""diff --git a/tests/unittest/test_runtime_shutdown_regressions.py b/tests/unittest/test_runtime_shutdown_regressions.pyindex d9a55370..c490d107 100644--- a/tests/unittest/test_runtime_shutdown_regressions.py+++ b/tests/unittest/test_runtime_shutdown_regressions.py@@ -29,6 +29,7 @@ class Client:def __init__(self) -> None:"""初始化关闭计数。"""self.close_calls = 0+ self.client = SimpleNamespace(health_probe_mode="none")async def aclose(self) -> None:"""完成一次可观察的连接清理。"""diff --git a/tests/unittest/test_vllm_acceptance_protocol.py b/tests/unittest/test_vllm_acceptance_protocol.pynew file mode 100644index 00000000..623ccbca--- /dev/null+++ b/tests/unittest/test_vllm_acceptance_protocol.py@@ -0,0 +1,37 @@+"""核对真机验收的观测条件,避免 FINAL_ONLY 终态被误认为活跃推理。"""++import asyncio+from collections.abc import AsyncIterator+from types import SimpleNamespace+from typing import Any++from scripts.acceptance.vllm_lifecycle import observe_generation+++def test_active_observation_requires_unfinished_real_token_and_keeps_sampling() -> None:+ """改变副本的输出投递方式,真实非终态才计为活跃,退出及时清理。"""++ async def run() -> None:+ """逐帧检查 token 与 finished 状态,而不是只检查生成器已进入。"""+ active: set[str] = set()+ metrics = {"token_events": 0}+ sampling = SimpleNamespace(output_kind="FINAL_ONLY", temperature=0.2)++ async def generate(**kwargs: Any) -> AsyncIterator[Any]:+ """提供空帧、非终态 token 和终态帧三种真实协议形态。"""+ assert kwargs["sampling_params"] is not sampling+ assert kwargs["sampling_params"].output_kind == "CUMULATIVE"+ assert kwargs["sampling_params"].temperature == sampling.temperature+ yield SimpleNamespace(outputs=[], finished=False)+ yield SimpleNamespace(outputs=[SimpleNamespace(token_ids=[1])], finished=False)+ yield SimpleNamespace(outputs=[SimpleNamespace(token_ids=[1, 2])], finished=True)++ states = []+ async for _ in observe_generation(generate, active, metrics, "CUMULATIVE", sampling_params=sampling, request_id="one"):+ states.append(bool(active))+ assert states == [False, True, False]+ assert metrics["token_events"] == 1+ assert not active+ assert sampling.output_kind == "FINAL_ONLY"++ asyncio.run(run())diff --git a/tests/unittest/test_vlm_shared_lifecycle.py b/tests/unittest/test_vlm_shared_lifecycle.pynew file mode 100644index 00000000..e68379cc--- /dev/null+++ b/tests/unittest/test_vlm_shared_lifecycle.py@@ -0,0 +1,202 @@+"""跨同步句柄、常驻循环和缓存验证同一生命周期契约。"""++from __future__ import annotations++import asyncio+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace+from typing import Any, Iterator+from unittest.mock import MagicMock++import pytest+from mineru_vl_utils.vlm_client.base_client import EngineHealth, EngineUnavailableError++from mineru.model.runtime.ownership import RuntimeOwner, runtime_owner+from mineru.model.vlm.async_runtime import AsyncVlmPredictor+from mineru.model.vlm.errors import EngineDeadError, EngineNotReadyError+from mineru.model.vlm.handles import RuntimeHandle+from mineru.model.vlm.runtime import ModelSingleton+++def runtime() -> Iterator[AsyncVlmPredictor]:+ """使用真实常驻循环和可控公开探测回调,不依赖 GPU 或远程服务。"""+ state = SimpleNamespace(error=None, health=EngineHealth("healthy"), calls=0, probes=0, closed=False)++ async def infer(images: list[Any], **kwargs: Any) -> list[Any]:+ """记录实际进入推理的次数,并传播指定错误。"""+ state.calls += 1+ if state.error is not None:+ raise state.error+ return images++ async def probe(timeout: float) -> EngineHealth:+ """确认健康回调运行在同一个专属事件循环。"""+ assert threading.current_thread().name == "mineru-vllm-async-engine"+ state.probes += 1+ return state.health++ async def close() -> None:+ """记录客户端已在所属循环清理。"""+ state.closed = True++ client = SimpleNamespace(aio_batch_two_step_extract=infer, aclose=close, test_state=state)+ instance = AsyncVlmPredictor(+ lambda: RuntimeHandle(client, backend="vllm-async-engine", aio_probe_engine=probe),+ backend="vllm-async-engine",+ max_concurrency=2,+ )+ instance.wait_ready()+ try:+ yield instance+ finally:+ instance.shutdown()+ assert state.closed+++def test_async_death_uses_shared_state_and_rejects_cache_borrow(+ runtime: AsyncVlmPredictor, monkeypatch: pytest.MonkeyPatch+) -> None:+ """死亡通知全部宿主,迟到宿主不能从缓存借用旧实例或触发重建。"""+ state = runtime._predictor.test_state+ assert runtime.lifecycle is runtime._runtime_handle.lifecycle+ owners = [RuntimeOwner(), RuntimeOwner()]+ for owner in owners:+ runtime.lifecycle.retain(owner)+ original = EngineUnavailableError("original backend failure")+ state.error = original+ with pytest.raises(EngineUnavailableError) as raised:+ runtime.batch_two_step_extract([1])+ assert raised.value is original+ assert all(owner.engine_error == str(original) for owner in owners)+ state.error = None+ with pytest.raises(EngineDeadError) as raised:+ asyncio.run(runtime.aio_batch_two_step_extract([2]))+ assert raised.value.__cause__ is original+ assert state.calls == 1+ key = ("dead-async",)+ monkeypatch.setattr(ModelSingleton, "_models", {key: runtime})+ newcomer = RuntimeOwner()+ token = runtime_owner.set(newcomer)+ factory = MagicMock()+ try:+ with pytest.raises(EngineDeadError):+ ModelSingleton()._get_or_initialize(key, factory, native_async=True, backend=runtime.backend, max_concurrency=2)+ finally:+ runtime_owner.reset(token)+ factory.assert_not_called()+ assert newcomer not in runtime.owners+ assert newcomer.engine_error == str(original)+++def test_blocked_engine_loop_times_out_without_duplicate_probes(runtime: AsyncVlmPredictor) -> None:+ """循环阻塞时超时由外部计时,多次检查不排队创建额外探测。"""+ owner = RuntimeOwner()+ runtime.lifecycle.retain(owner)+ entered, release = threading.Event(), threading.Event()++ def block() -> None:+ """有界阻塞引擎循环,不阻塞测试线程或 API 所属循环。"""+ entered.set()+ assert release.wait(3)++ runtime._loop.call_soon_threadsafe(block)+ assert entered.wait(1)+ started = time.monotonic()+ try:+ for _ in range(3):+ with pytest.raises(EngineNotReadyError):+ runtime.probe_health(0.02)+ assert time.monotonic() - started < 0.5+ assert owner.engine_error is None+ assert owner.engine_unavailable+ assert runtime._predictor.test_state.probes == 0+ with pytest.raises(EngineNotReadyError):+ runtime._submit(lambda: runtime._two_step([1], None, None))+ finally:+ release.set()+ runtime.probe_health(1)+ assert runtime._predictor.test_state.probes == 1+ assert owner.engine_unavailable is None+ assert runtime.batch_two_step_extract([2]) == [2]+++def test_late_health_cannot_resurrect_fatal_runtime(runtime: AsyncVlmPredictor) -> None:+ """已在途的健康检查完成时,推理线程记录的死亡状态仍有优先级。"""+ entered, release = threading.Event(), threading.Event()++ async def probe(timeout: float) -> EngineHealth:+ """模拟探测在真正读取结果之前暂停。"""+ entered.set()+ await asyncio.to_thread(release.wait, 2)+ return EngineHealth("healthy")++ runtime._runtime_handle._aio_probe_engine = probe+ with ThreadPoolExecutor(1) as pool:+ future = pool.submit(runtime.probe_health, 1)+ assert entered.wait(1)+ runtime.lifecycle.mark_fatal(EngineUnavailableError("dead while probing"))+ release.set()+ with pytest.raises(EngineDeadError):+ future.result(2)+ with pytest.raises(EngineDeadError):+ runtime.require_ready()+++def test_close_drains_scheduled_probe_before_engine_release(runtime: AsyncVlmPredictor) -> None:+ """关闭与尚未执行的健康检查交错,也必须退出而不留下循环任务。"""+ entered, release = threading.Event(), threading.Event()++ def block() -> None:+ """在探测提交前暂停引擎循环,制造开始与关闭的竞态。"""+ entered.set()+ release.wait(2)++ runtime._loop.call_soon_threadsafe(block)+ assert entered.wait(1)+ with pytest.raises(EngineNotReadyError):+ runtime.probe_health(0.01)+ with ThreadPoolExecutor(1) as pool:+ closing = pool.submit(runtime.shutdown)+ release.set()+ closing.result(2)+ assert not runtime._thread.is_alive()+++def test_mlx_unknown_runtime_failure_does_not_retry_or_poison_instance() -> None:+ """未知 MLX 故障只使当前请求失败,不做单片补试或永久隔离。"""+ error = RuntimeError("unknown Metal execution failure")+ client = SimpleNamespace(batch_content_extract=MagicMock(side_effect=error), content_extract=MagicMock())+ handle = RuntimeHandle(client, backend="mlx-engine")+ owner = RuntimeOwner()+ handle.lifecycle.retain(owner)+ try:+ with pytest.raises(RuntimeError) as raised:+ handle.batch_recognize_text([1])+ assert raised.value is error+ client.content_extract.assert_not_called()+ assert owner.engine_error is None+ client.batch_content_extract.side_effect = None+ client.batch_content_extract.return_value = ["recognized"]+ assert handle.batch_recognize_text([2]) == ["recognized"]+ finally:+ handle.shutdown()+++def test_failed_async_initialization_is_closed_without_a_live_instance() -> None:+ """构造失败仍被标记为关闭,不与已成功创建后死亡且需锁存的实例混淆。"""++ def fail() -> RuntimeHandle:+ """模拟模型尚未创建成功时的输入错误。"""+ raise ValueError("initialization failed")++ runtime = AsyncVlmPredictor(fail, backend="vllm-async-engine", max_concurrency=1)+ try:+ with pytest.raises(ValueError, match="initialization failed"):+ runtime.wait_ready()+ assert runtime.is_closed+ finally:+ runtime.shutdown()+ assert not runtime._thread.is_alive()