Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

fix(runtime): drain LMDeploy probes before releasing the Pipeline

myhloli8d465c7dd02f
diff --git a/docs/native-async-analysis.md b/docs/native-async-analysis.md
index e090aae7..53c0929d 100644
--- a/docs/native-async-analysis.md
+++ b/docs/native-async-analysis.md
@@ -88,3 +88,5 @@ high 等待外部布局抽取,xhigh 等待两阶段抽取;后置 LLM 增强
确认包索引可解析后,再提高 MinerU 的依赖下限;未完成设备验收前保留发布门槛。
llama.cpp 要求 `mineru-llama-cpp>=0.2.1`。只有明确循环退出或显式关闭映射为公共致命异常,普通 `EngineError` 仍按请求处理。底层保留原始错误类型、错误码和详情;取消后的原生线程排空由底层负责,运行时沿用共享 owner 通知与缓存拒绝规则。健康快照不提供解码进度心跳,也不将无进度推断为死亡;进程级 abort 仍由宿主管理恢复。
+
+LMDeploy 的健康接口可能使用独立执行器,取消协程不等于工作线程已退出。MinerU 的同步、异步及取消关闭都等待同一健康探测实际排空,再释放 Pipeline;不把依赖库的局部关闭超时当作已排空。托管 worker 的总关闭期限、终止和强制退出仍由现有 Router/Doclib 管理器控制。直接 SDK 调用方也必须保持 Pipeline 及其循环存活直至客户端成功关闭。
diff --git a/mineru/model/vlm/handles.py b/mineru/model/vlm/handles.py
index 150a625f..eec96afc 100644
--- a/mineru/model/vlm/handles.py
+++ b/mineru/model/vlm/handles.py
@@ -324,7 +324,11 @@ class RuntimeHandle:
except BaseException as exc:
error = exc
try:
- await self.predictor.aclose()
+ if self._close_health_probe is not None:
+ # 与同步关闭使用相同的排空回调,避免客户端局部超时后仍释放 Pipeline。
+ await run_sync(self._close_health_probe)
+ else:
+ await self.predictor.aclose()
except BaseException as exc:
if error is None:
error = exc
diff --git a/mineru/model/vlm/runtime.py b/mineru/model/vlm/runtime.py
index bf381ff6..22efe7cf 100644
--- a/mineru/model/vlm/runtime.py
+++ b/mineru/model/vlm/runtime.py
@@ -442,7 +442,10 @@ class ModelSingleton:
close_engine=close_engine,
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,
+ # 托管进程的关闭期限由外部管理器控制;释放 Pipeline 前必须真正排空健康工作。
+ close_health_probe=(
+ partial(predictor.client.close_health_probe, timeout=None) if backend == "lmdeploy-engine" else None
+ ),
)
def probe_owner_health(self, owner: RuntimeOwner, timeout: float = 5.0) -> None:
diff --git a/tests/unittest/test_runtime_shutdown_regressions.py b/tests/unittest/test_runtime_shutdown_regressions.py
index c490d107..55fb42d9 100644
--- a/tests/unittest/test_runtime_shutdown_regressions.py
+++ b/tests/unittest/test_runtime_shutdown_regressions.py
@@ -126,6 +126,129 @@ def test_lmdeploy_probe_closes_without_new_threads_at_interpreter_exit() -> None
assert "cannot schedule new futures" not in completed.stderr
[email protected]("mode", ["sync", "async", "cancel"])
+def test_lmdeploy_factory_close_drains_real_health_worker(mode: str) -> None:
+ """真实工厂创建的同步/异步句柄都必须排空健康线程,取消也不能提前销毁引擎。"""
+ _run_isolated(f"mode = {mode!r}\n" + '''
+import sys
+from concurrent.futures import ThreadPoolExecutor, TimeoutError
+from mineru_vl_utils.vlm_client.lmdeploy_engine_client import LmdeployEngineVlmClient
+from mineru_vl_utils.vlm_client.lmdeploy_health import LmdeployHealthProbe
+from mineru.model.vlm.errors import EngineNotReadyError
+
+loop = asyncio.new_event_loop()
+ready, entered, release, finished = (threading.Event() for _ in range(4))
+close_entered, engine_closed = threading.Event(), threading.Event()
+close_deadlines = []
+
+def run_loop() -> None:
+ """为健康探测提供独立循环,退出前验证没有遗留任务。"""
+ asyncio.set_event_loop(loop)
+ loop.call_soon(ready.set)
+ loop.run_forever()
+ assert not asyncio.all_tasks(loop)
+ loop.close()
+
+def native_health():
+ """持续占用通信器,直到测试允许健康工作完成。"""
+ entered.set()
+ assert release.wait(5)
+ finished.set()
+ return {"alive": True}
+
+def close_engine() -> None:
+ """用真实工作线程的完成状态检查引擎释放顺序。"""
+ engine_closed.set()
+ assert finished.is_set(), "Pipeline closed before its health worker finished"
+
+class ShortDeadlineProbe(LmdeployHealthProbe):
+ """缩短客户端默认等待期限,使错误的异步关闭分支能快速暴露。"""
+ def close(self, timeout=0.02):
+ """记录宿主是否把整体关闭期限留给进程管理器。"""
+ close_deadlines.append(timeout)
+ close_entered.set()
+ super().close(timeout)
+
+thread = threading.Thread(target=run_loop, daemon=True)
+thread.start()
+assert ready.wait(2)
+with ThreadPoolExecutor(1) as health_executor, ThreadPoolExecutor(1) as callers:
+ async def get_health_status():
+ """与 TurboMind 一样将工作交给独立执行器。"""
+ return await asyncio.get_running_loop().run_in_executor(health_executor, native_health)
+
+ pipeline = SimpleNamespace(
+ internal_thread=SimpleNamespace(loop=loop, thread=thread, closed=False),
+ async_engine=SimpleNamespace(is_sleeping=False, engine=SimpleNamespace(get_health_status=get_health_status)),
+ close=close_engine,
+ )
+ adapter = object.__new__(LmdeployEngineVlmClient)
+ adapter._health_probe = ShortDeadlineProbe(pipeline)
+ sys.modules["lmdeploy"] = SimpleNamespace(
+ PytorchEngineConfig=lambda **kwargs: SimpleNamespace(),
+ TurbomindEngineConfig=lambda **kwargs: SimpleNamespace(),
+ pipeline=lambda *args, **kwargs: pipeline,
+ )
+ sys.modules["lmdeploy.utils"] = SimpleNamespace(get_logger=lambda name: SimpleNamespace(setLevel=lambda level: None))
+ runtime.MinerUClient = lambda **kwargs: SimpleNamespace(client=adapter, aclose=adapter.aclose)
+ handle = manager._create_model(
+ "lmdeploy-engine", "fake-model", None,
+ lmdeploy_device="cuda", lmdeploy_backend="turbomind", cache_max_entry_count=0.5,
+ )
+
+ async def close_async() -> None:
+ """取消只影响调用方结果,不提前结束后台资源清理。"""
+ work = asyncio.create_task(handle.aclose())
+ if mode == "cancel":
+ assert await asyncio.to_thread(close_entered.wait, 2)
+ work.cancel()
+ try:
+ await work
+ except asyncio.CancelledError:
+ return
+ raise AssertionError("Cancellation was not propagated")
+ await work
+
+ def close_handle() -> None:
+ """走真实句柄的两种关闭入口。"""
+ if mode == "sync":
+ handle.shutdown()
+ else:
+ asyncio.run(close_async())
+
+ try:
+ try:
+ handle.probe_health(0.01)
+ except EngineNotReadyError:
+ pass
+ else:
+ raise AssertionError("Blocked health work was reported healthy")
+ assert entered.wait(2)
+ closing = callers.submit(close_handle)
+ assert close_entered.wait(2)
+ try:
+ with_timeout = False
+ try:
+ closing.result(0.06)
+ except TimeoutError:
+ with_timeout = True
+ assert with_timeout, "Host released a Pipeline with unfinished health work"
+ assert not engine_closed.is_set()
+ assert close_deadlines == [None]
+ finally:
+ release.set()
+ closing.result(2)
+ assert finished.is_set() and engine_closed.is_set()
+ assert handle.is_closed
+ finally:
+ release.set()
+ adapter._health_probe.close(2)
+ loop.call_soon_threadsafe(loop.stop)
+ thread.join(2)
+ assert not thread.is_alive()
+''')
+
+
def test_sync_close_callback_rejects_another_key_in_its_closing_batch() -> None:
"""A 的关闭回调不能等待同批尚未关闭的 B,同时仍允许另一应用借用未关闭键。"""
_run_isolated('''