Skip to content

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

feat: implement process management and shutdown mechanisms for MinerU

myhloliae314ad25651
diff --git a/mineru/backend/vlm/vlm_analyze.py b/mineru/backend/vlm/vlm_analyze.py
index a833b1d7..b774748e 100644
--- a/mineru/backend/vlm/vlm_analyze.py
+++ b/mineru/backend/vlm/vlm_analyze.py
@@ -1,5 +1,7 @@
# Copyright (c) Opendatalab. All rights reserved.
import asyncio
+import atexit
+import gc
import os
import time
import json
@@ -232,12 +234,122 @@ class ModelSingleton:
max_retries=max_retries,
retry_backoff_factor=retry_backoff_factor,
)
+ predictor._mineru_runtime_handles = {
+ "backend": backend,
+ "model": model,
+ "processor": processor,
+ "vllm_llm": vllm_llm,
+ "vllm_async_llm": vllm_async_llm,
+ "lmdeploy_engine": lmdeploy_engine,
+ }
_maybe_enable_serial_execution(predictor, backend)
self._models[key] = predictor
elapsed = round(time.time() - start_time, 2)
logger.info(f"get {backend} predictor cost: {elapsed}s")
return self._models[key]
+ def shutdown(self) -> None:
+ with self._lock:
+ predictors = list(self._models.values())
+ self._models.clear()
+
+ for predictor in predictors:
+ _shutdown_predictor_runtime(predictor)
+
+ gc.collect()
+
+
+def _iter_shutdown_candidates(predictor: MinerUClient):
+ runtime_handles = getattr(predictor, "_mineru_runtime_handles", {})
+ client = getattr(predictor, "client", None)
+
+ seen_ids = set()
+
+ def _yield_candidate(candidate):
+ if candidate is None:
+ return
+ candidate_id = id(candidate)
+ if candidate_id in seen_ids:
+ return
+ seen_ids.add(candidate_id)
+ yield candidate
+
+ for key in ("vllm_llm", "vllm_async_llm", "lmdeploy_engine", "model"):
+ yield from _yield_candidate(runtime_handles.get(key))
+
+ if client is not None:
+ for key in ("vllm_llm", "vllm_async_llm", "lmdeploy_engine", "model"):
+ yield from _yield_candidate(getattr(client, key, None))
+
+
+def _call_nested_shutdown(target, method_path: str, label: str) -> bool:
+ current = target
+ for attr in method_path.split("."):
+ current = getattr(current, attr, None)
+ if current is None:
+ return False
+
+ if not callable(current):
+ return False
+
+ try:
+ current()
+ logger.debug(f"Shutdown {label} via `{method_path}`")
+ return True
+ except TypeError:
+ logger.debug(f"Skip unsupported shutdown call {label}.{method_path}")
+ return False
+ except Exception as exc:
+ logger.debug(f"Failed to shutdown {label} via `{method_path}`: {exc}")
+ return False
+
+
+def _shutdown_runtime_handle(handle) -> None:
+ for method_path in (
+ "shutdown",
+ "close",
+ "stop",
+ "terminate",
+ "destroy",
+ "engine.shutdown",
+ "engine.close",
+ "engine_core.shutdown",
+ "engine_core.close",
+ "llm_engine.shutdown",
+ "llm_engine.close",
+ "llm_engine.model_executor.shutdown",
+ "llm_engine.model_executor.close",
+ "model_executor.shutdown",
+ "model_executor.close",
+ ):
+ if _call_nested_shutdown(handle, method_path, type(handle).__name__):
+ return
+
+
+def _clear_predictor_references(predictor: MinerUClient) -> None:
+ runtime_handles = getattr(predictor, "_mineru_runtime_handles", {})
+ for key in tuple(runtime_handles.keys()):
+ runtime_handles[key] = None
+
+ client = getattr(predictor, "client", None)
+ if client is not None:
+ for attr in ("vllm_llm", "vllm_async_llm", "lmdeploy_engine", "model", "processor"):
+ if hasattr(client, attr):
+ setattr(client, attr, None)
+
+
+def _shutdown_predictor_runtime(predictor: MinerUClient) -> None:
+ for handle in _iter_shutdown_candidates(predictor):
+ _shutdown_runtime_handle(handle)
+ _clear_predictor_references(predictor)
+
+
+def shutdown_cached_models() -> None:
+ ModelSingleton().shutdown()
+
+
+atexit.register(shutdown_cached_models)
+
def _predictor_uses_mlx(predictor: MinerUClient, backend: str | None = None) -> bool:
if backend == "mlx-engine":
diff --git a/mineru/cli/api_client.py b/mineru/cli/api_client.py
index 79e9ba5e..32f71ac6 100644
--- a/mineru/cli/api_client.py
+++ b/mineru/cli/api_client.py
@@ -3,6 +3,7 @@ import atexit
import json
import mimetypes
import os
+import signal
import socket
import subprocess
import sys
@@ -34,6 +35,7 @@ TASK_RESULT_TIMEOUT_SECONDS = 3600
LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS = 10
LOCAL_API_CLEANUP_RETRIES = 8
LOCAL_API_CLEANUP_RETRY_INTERVAL_SECONDS = 0.25
+PROCESS_TREE_CLEANUP_GRACE_SECONDS = 0.1
def get_float_env(name: str, default: float, minimum: float = 0.0) -> float:
@@ -73,6 +75,108 @@ def get_local_api_startup_timeout_seconds(default: float = 300.0) -> float:
LOCAL_API_STARTUP_TIMEOUT_SECONDS = get_local_api_startup_timeout_seconds()
+def build_managed_process_popen_kwargs() -> dict[str, object]:
+ if os.name == "nt":
+ creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
+ if creationflags:
+ return {"creationflags": creationflags}
+ return {}
+ return {"start_new_session": True}
+
+
+def _signal_process_tree(process: subprocess.Popen[bytes], *, force: bool) -> None:
+ if os.name == "nt":
+ command = ["taskkill", "/PID", str(process.pid), "/T"]
+ if force:
+ command.append("/F")
+ try:
+ subprocess.run(
+ command,
+ check=False,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ except Exception as exc:
+ logger.debug(
+ "Failed to signal managed MinerU process tree {} on Windows: {}",
+ process.pid,
+ exc,
+ )
+ return
+
+ sig = signal.SIGKILL if force else signal.SIGTERM
+ try:
+ os.killpg(process.pid, sig)
+ except ProcessLookupError:
+ return
+ except OSError as exc:
+ logger.debug(
+ "Failed to signal managed MinerU process group {}: {}",
+ process.pid,
+ exc,
+ )
+
+
+def cleanup_process_tree_descendants(
+ process: subprocess.Popen[bytes],
+ *,
+ grace_seconds: float = PROCESS_TREE_CLEANUP_GRACE_SECONDS,
+) -> None:
+ if os.name == "nt":
+ return
+
+ _signal_process_tree(process, force=False)
+ if grace_seconds > 0:
+ time.sleep(grace_seconds)
+ _signal_process_tree(process, force=True)
+
+
+def stop_managed_process(
+ process: subprocess.Popen[bytes] | None,
+ *,
+ shutdown_timeout_seconds: float,
+ use_stdin_shutdown_watcher: bool,
+) -> None:
+ if process is None:
+ return
+
+ parent_exited = process.poll() is not None
+
+ if not parent_exited and use_stdin_shutdown_watcher:
+ if process.stdin is not None and not process.stdin.closed:
+ process.stdin.close()
+ try:
+ process.wait(timeout=shutdown_timeout_seconds)
+ parent_exited = True
+ except subprocess.TimeoutExpired:
+ logger.debug(
+ "Managed MinerU process did not stop after stdin EOF within {}s. Falling back to process-tree termination.",
+ shutdown_timeout_seconds,
+ )
+
+ if not parent_exited:
+ _signal_process_tree(process, force=False)
+ try:
+ process.wait(timeout=shutdown_timeout_seconds)
+ parent_exited = True
+ except subprocess.TimeoutExpired:
+ pass
+
+ if not parent_exited:
+ _signal_process_tree(process, force=True)
+ try:
+ process.wait(timeout=shutdown_timeout_seconds)
+ parent_exited = True
+ except subprocess.TimeoutExpired:
+ logger.warning(
+ "Managed MinerU process {} did not exit after forceful stop.",
+ process.pid,
+ )
+
+ if parent_exited:
+ cleanup_process_tree_descendants(process)
+
+
@dataclass(frozen=True)
class UploadAsset:
path: Path
@@ -151,6 +255,7 @@ class LocalAPIServer:
cwd=os.getcwd(),
env=env,
stdin=stdin_target,
+ **build_managed_process_popen_kwargs(),
)
if not self._atexit_registered:
@@ -162,31 +267,12 @@ class LocalAPIServer:
process = self.process
self.process = None
try:
- if process is not None and process.poll() is None:
- if self._use_stdin_shutdown_watcher:
- if process.stdin is not None and not process.stdin.closed:
- process.stdin.close()
- try:
- process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
- return
- except subprocess.TimeoutExpired:
- logger.debug(
- "Local mineru-api did not stop after stdin EOF within {}s. Falling back to SIGTERM.",
- LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
- )
- else:
- logger.debug(
- "Stopping local mineru-api with process termination on Windows."
- )
-
- process.terminate()
- try:
- process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
- return
- except subprocess.TimeoutExpired:
- pass
- process.kill()
- process.wait(timeout=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS)
+ if process is not None:
+ stop_managed_process(
+ process,
+ shutdown_timeout_seconds=LOCAL_API_SHUTDOWN_TIMEOUT_SECONDS,
+ use_stdin_shutdown_watcher=self._use_stdin_shutdown_watcher,
+ )
finally:
if self._atexit_registered:
try:
diff --git a/mineru/cli/fast_api.py b/mineru/cli/fast_api.py
index a360a142..1248b135 100644
--- a/mineru/cli/fast_api.py
+++ b/mineru/cli/fast_api.py
@@ -53,6 +53,7 @@ from mineru.cli.vlm_preload import (
maybe_preload_vlm_model,
split_service_and_model_config,
)
+from mineru.backend.vlm.vlm_analyze import shutdown_cached_models
from mineru.utils.cli_parser import arg_parse
from mineru.utils.check_sys_env import is_mac_environment
from mineru.utils.config_reader import (
@@ -60,6 +61,7 @@ from mineru.utils.config_reader import (
get_processing_window_size,
)
from mineru.utils.guess_suffix_or_lang import guess_suffix_by_path
+from mineru.utils.pdf_image_tools import shutdown_pdf_render_executor
from mineru.version import __version__
os.environ["TORCH_CUDNN_V8_API_DISABLED"] = "1"
@@ -289,6 +291,19 @@ async def shutdown_app_state(app: FastAPI) -> None:
if current_task_manager is not None:
await current_task_manager.shutdown()
app.state.task_manager = None
+ shutdown_runtime_resources()
+
+
+def shutdown_runtime_resources() -> None:
+ try:
+ shutdown_cached_models()
+ except Exception as exc:
+ logger.warning(f"Failed to shutdown cached VLM models: {exc}")
+
+ try:
+ shutdown_pdf_render_executor()
+ except Exception as exc:
+ logger.warning(f"Failed to shutdown PDF render executor: {exc}")
def utc_now_iso() -> str:
diff --git a/mineru/cli/router.py b/mineru/cli/router.py
index ea1c7d00..b57c7e6b 100644
--- a/mineru/cli/router.py
+++ b/mineru/cli/router.py
@@ -29,9 +29,11 @@ from mineru.cli.api_client import (
LOCAL_API_STARTUP_TIMEOUT_SECONDS,
TASK_RESULT_TIMEOUT_SECONDS,
TASK_STATUS_POLL_INTERVAL_SECONDS,
+ build_managed_process_popen_kwargs,
build_http_timeout,
find_free_port,
normalize_base_url,
+ stop_managed_process,
strip_local_api_network_args,
response_detail,
)
@@ -340,7 +342,12 @@ class ManagedLocalServer:
str(resolved_port),
*worker_cli_args,
]
- self.process = subprocess.Popen(command, cwd=os.getcwd(), env=env)
+ self.process = subprocess.Popen(
+ command,
+ cwd=os.getcwd(),
+ env=env,
+ **build_managed_process_popen_kwargs(),
+ )
try:
await self.wait_until_ready(client)
@@ -381,13 +388,12 @@ class ManagedLocalServer:
process = self.process
self.process = None
try:
- if process is not None and process.poll() is None:
- process.terminate()
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait(timeout=5)
+ if process is not None:
+ stop_managed_process(
+ process,
+ shutdown_timeout_seconds=5,
+ use_stdin_shutdown_watcher=False,
+ )
finally:
temp_dir = self.temp_dir
self.temp_dir = None
diff --git a/mineru/utils/pdf_image_tools.py b/mineru/utils/pdf_image_tools.py
index 35f62eec..fb11649f 100644
--- a/mineru/utils/pdf_image_tools.py
+++ b/mineru/utils/pdf_image_tools.py
@@ -187,6 +187,7 @@ def shutdown_pdf_render_executor() -> None:
_pdf_render_executor = None
if executor is not None:
+ _terminate_executor_processes(executor)
executor.shutdown(wait=False, cancel_futures=True)