Skip to content

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

feat: use dedicated managed parse control channel

jinzhenjdde677561d63
diff --git a/docs/plans/2026-07-22-managed-parse-server-stop-budget-design.md b/docs/plans/2026-07-22-managed-parse-server-stop-budget-design.md
index d5297a90..5579448a 100644
--- a/docs/plans/2026-07-22-managed-parse-server-stop-budget-design.md
+++ b/docs/plans/2026-07-22-managed-parse-server-stop-budget-design.md
@@ -2,9 +2,9 @@
## Problem
-`mineru server stop` waits up to 15 seconds for doclib to stop and release its HOME ownership lock. Managed parse-server shutdown currently applies `parse_server_stop_timeout_sec` independently to stdin EOF, terminate, and kill. With the default value of 10 seconds, shutdown can consume up to 30 seconds before doclib continues its remaining cleanup.
+`mineru server stop` waits up to 15 seconds for doclib to stop and release its HOME ownership lock. Managed parse-server shutdown currently applies `parse_server_stop_timeout_sec` independently to the control shutdown, terminate, and kill stages. With the default value of 10 seconds, shutdown can consume up to 30 seconds before doclib continues its remaining cleanup.
-During model preload, the parse-server process can remain inside model initialization after its stdin watcher sets `server.should_exit`. In the observed E2E failure, it ignored stdin EOF for 10 seconds and terminate for another 10 seconds. The CLI returned after 15 seconds while doclib still held the ownership lock.
+During model preload, the parse-server process can remain inside model initialization after its control watcher sets `server.should_exit`. In the observed E2E failure, it ignored the shutdown request for 10 seconds and terminate for another 10 seconds. The CLI returned after 15 seconds while doclib still held the ownership lock.
## Decision
@@ -12,8 +12,8 @@ Treat `parse_server_stop_timeout_sec` as a total managed parse-server stop budge
For the default 10-second budget:
-- Healthy or established process: wait up to 5 seconds after stdin EOF.
-- Startup or preload process: wait no more than 2 seconds after stdin EOF.
+- Healthy or established process: wait up to 5 seconds after a control shutdown request.
+- Startup or preload process: wait no more than 2 seconds after a control shutdown request.
- Wait up to 3 seconds after terminate.
- Use the remaining budget after kill to reap the process.
@@ -27,11 +27,12 @@ The shutdown policy remains centralized in `stop_managed_parse_server`.
Callers pass whether the managed process is still starting from the existing `ParseServerHealth.local_starting` state. No new configuration keys or timeout logic are added to individual background tasks.
-The parse-server stdin watcher and model preload implementation remain unchanged. Making model initialization cooperatively cancellable would require broader model-runtime changes and is not required to bound doclib shutdown.
+The managed parse-server uses a dedicated `multiprocessing.connection` control channel rather than stdin. Unix uses `AF_UNIX`; Windows uses `AF_PIPE`. Making model initialization cooperatively cancellable would require broader model-runtime changes and is not required to bound doclib shutdown.
## Failure Handling
-- Closing stdin remains the first shutdown action.
+- Sending the control shutdown command is the first shutdown action.
+- If the control channel is unavailable, skip the graceful wait and send terminate.
- If the graceful stage exceeds its allocation, send terminate.
- If terminate exceeds its allocation, send kill.
- If kill or reap fails, log the failure and let doclib continue shutdown instead of extending the configured budget.
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.py
index 3e1bf7c7..6b27ddca 100644
--- a/mineru/doclib/app.py
+++ b/mineru/doclib/app.py
@@ -129,7 +129,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
managed_tier = await get_managed_parse_server_tier(state.config_svc)
health.managed_tier = managed_tier
try:
- proc, managed_url = start_managed_parse_server(
+ proc, managed_url, control = start_managed_parse_server(
tier=managed_tier,
managed_cfg=cfg.doclib.managed_parse_server,
log_cfg=cfg.doclib.log,
@@ -138,6 +138,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
health.managed_url = managed_url
logging.info("Managed parse-server started (PID %d, tier=%s)", proc.pid, managed_tier)
health.managed_proc = proc
+ health.managed_control = control
health.running_managed_tier = managed_tier
health.local_starting = True
health.local_started_at = asyncio.get_event_loop().time()
@@ -209,11 +210,13 @@ def create_app(cfg: Config | None = None) -> FastAPI:
if health.managed_proc:
stop_managed_parse_server(
health.managed_proc,
+ control=health.managed_control,
timeout_sec=cfg.doclib.parse_server_stop_timeout_sec,
reason="doclib shutdown",
startup_in_progress=health.local_starting,
)
health.managed_proc = None
+ health.managed_control = None
for comp in [
"watch",
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
index 9a5642a2..17a6dba7 100644
--- a/mineru/doclib/background/parse_server_health.py
+++ b/mineru/doclib/background/parse_server_health.py
@@ -19,6 +19,7 @@ import httpx
from ...config import LogConfig, ManagedParseServerConfig, config
from ...parser.api_client import should_trust_env_for_url
from ...types import DEPLOYMENT_TIERS, TIERS, DeploymentTier, Tier
+from ...utils.managed_process_control import ManagedProcessControl
from ...utils.stdio import utf8_subprocess_env
from ..config_defaults import CONFIG_DEFAULTS
from ..remote_api import resolve_remote_api_key
@@ -30,7 +31,6 @@ if TYPE_CHECKING:
MAX_RESTART_ATTEMPTS = 3
DEFAULT_MANAGED_URL = "http://127.0.0.1:16580"
-MANAGED_PARSE_SERVER_ENV = "MINERU_MANAGED_PARSE_SERVER"
_NON_RETRYABLE_MODEL_PRELOAD_ERRORS = frozenset(
{
"model_preload_dependency_missing",
@@ -70,6 +70,7 @@ class ParseServerHealth:
running_managed_tier: DeploymentTier | None = None
restart_count: int = 0
managed_proc: subprocess.Popen | None = None
+ managed_control: ManagedProcessControl | None = None
_parse_server_health = ParseServerHealth()
@@ -186,7 +187,7 @@ def start_managed_parse_server(
managed_cfg: ManagedParseServerConfig,
log_cfg: LogConfig | None,
marker: str,
-) -> tuple[subprocess.Popen, str]:
+) -> tuple[subprocess.Popen, str, ManagedProcessControl]:
port = select_available_managed_port(
managed_cfg.host,
managed_cfg.port,
@@ -201,49 +202,67 @@ def start_managed_parse_server(
*api_server_args_for_tier(tier, host=managed_cfg.host, port=port),
]
env = utf8_subprocess_env()
- env[MANAGED_PARSE_SERVER_ENV] = "1"
+ control = ManagedProcessControl.create()
+ env.update(control.child_env())
logger.info("Starting managed parse-server (%s): %s", marker, " ".join(cmd))
- with open_managed_parse_server_logs(marker=marker, log_cfg=log_cfg) as (
- stdout_log_file,
- stderr_log_file,
- ):
- proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=stdout_log_file, stderr=stderr_log_file, env=env)
- return proc, managed_url
+ control.start_accepting()
+ try:
+ with open_managed_parse_server_logs(marker=marker, log_cfg=log_cfg) as (
+ stdout_log_file,
+ stderr_log_file,
+ ):
+ proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=stdout_log_file, stderr=stderr_log_file, env=env)
+ except Exception:
+ control.close()
+ raise
+ return proc, managed_url, control
def stop_managed_parse_server(
proc: subprocess.Popen | None,
*,
+ control: ManagedProcessControl | None = None,
timeout_sec: int,
reason: str,
startup_in_progress: bool = False,
) -> None:
- if proc is None or proc.poll() is not None:
+ if proc is None:
+ if control is not None:
+ control.close()
+ return
+ if proc.poll() is not None:
+ if control is not None:
+ control.close()
return
pid = proc.pid
total_timeout = max(float(timeout_sec), 0.0)
deadline = time.monotonic() + total_timeout
- stdin = getattr(proc, "stdin", None)
- if stdin is not None and not getattr(stdin, "closed", False):
+ graceful_cap = min(2.0, total_timeout * 0.2) if startup_in_progress else total_timeout * 0.5
+ shutdown_sent = control.request_shutdown(graceful_cap) if control is not None else False
+ if shutdown_sent:
try:
- stdin.close()
- except Exception as exc:
- logger.debug("Failed to close managed parse-server stdin (PID %d, reason=%s): %s", pid, reason, exc)
-
- try:
- graceful_cap = min(2.0, total_timeout * 0.2) if startup_in_progress else total_timeout * 0.5
- proc.wait(timeout=min(graceful_cap, max(deadline - time.monotonic(), 0.0)))
- logger.info("Managed parse-server stopped after stdin EOF (PID %d, reason=%s)", pid, reason)
- return
- except subprocess.TimeoutExpired:
- logger.warning("Managed parse-server did not stop after stdin EOF (PID %d, reason=%s), terminating", pid, reason)
+ proc.wait(timeout=min(graceful_cap, max(deadline - time.monotonic(), 0.0)))
+ logger.info("Managed parse-server stopped after control shutdown (PID %d, reason=%s)", pid, reason)
+ if control is not None:
+ control.close()
+ return
+ except subprocess.TimeoutExpired:
+ logger.warning(
+ "Managed parse-server did not stop after control shutdown (PID %d, reason=%s), terminating",
+ pid,
+ reason,
+ )
+ else:
+ logger.warning("Managed parse-server control channel unavailable (PID %d, reason=%s), terminating", pid, reason)
try:
proc.terminate()
terminate_cap = total_timeout * 0.3
proc.wait(timeout=min(terminate_cap, max(deadline - time.monotonic(), 0.0)))
logger.info("Managed parse-server terminated (PID %d, reason=%s)", pid, reason)
+ if control is not None:
+ control.close()
return
except subprocess.TimeoutExpired:
logger.warning("Managed parse-server did not terminate within timeout (PID %d, reason=%s), killing", pid, reason)
@@ -256,6 +275,9 @@ def stop_managed_parse_server(
logger.info("Managed parse-server killed (PID %d, reason=%s)", pid, reason)
except Exception as exc:
logger.error("Failed to kill managed parse-server (PID %d, reason=%s): %s", pid, reason, exc)
+ finally:
+ if control is not None:
+ control.close()
def _managed_parse_server_needs_restart(
@@ -429,14 +451,16 @@ class ParseServerHealthCheck:
managed_tier = await get_managed_parse_server_tier(self.config_svc)
stop_managed_parse_server(
health.managed_proc,
+ control=health.managed_control,
timeout_sec=self.stop_timeout_sec,
reason=reason,
startup_in_progress=health.local_starting,
)
health.managed_proc = None
+ health.managed_control = None
health.running_managed_tier = None
try:
- proc, managed_url = start_managed_parse_server(
+ proc, managed_url, control = start_managed_parse_server(
tier=managed_tier,
managed_cfg=self.managed_parse_server,
log_cfg=self.log_cfg,
@@ -445,6 +469,7 @@ class ParseServerHealthCheck:
health.managed_url = managed_url
logger.info("Managed parse-server restarted (PID %d, tier=%s)", proc.pid, managed_tier)
health.managed_proc = proc
+ health.managed_control = control
health.running_managed_tier = managed_tier
health.local_starting = True
health.local_started_at = asyncio.get_event_loop().time()
@@ -492,11 +517,13 @@ class ParseServerHealthCheck:
health = get_health()
stop_managed_parse_server(
health.managed_proc,
+ control=health.managed_control,
timeout_sec=self.stop_timeout_sec,
reason="health check stop",
startup_in_progress=health.local_starting,
)
health.managed_proc = None
+ health.managed_control = None
def _probe_error(resp: httpx.Response) -> tuple[str, str]:
diff --git a/mineru/parser/api_server.py b/mineru/parser/api_server.py
index 18019446..99e36575 100644
--- a/mineru/parser/api_server.py
+++ b/mineru/parser/api_server.py
@@ -19,7 +19,6 @@ import os
import pathlib
import secrets
import shutil
-import sys
import tempfile
import threading
import time
@@ -50,6 +49,7 @@ from ..render.writer import DataWriter
from ..types import SERVER_TIERS, TIERS_BY_SERVER_TIER, DeploymentTier, PageInfo, ServerTier, Tier, select_default_quality_tier
from ..utils.backend_options import DEFAULT_HYBRID_EFFORT
from ..utils.image_payload import validate_image_sidecar_path
+from ..utils.managed_process_control import ManagedProcessControlWatcher
from ..utils.ocr_language import PUBLIC_OCR_LANGUAGES, validate_public_ocr_lang
from ..utils.stdio import configure_standard_streams
from ..version import __version__
@@ -64,7 +64,6 @@ from .tier import (
_DEFAULT_API_SERVER_TIER: ServerTier = "standard"
_API_SERVER_LANGUAGES = PUBLIC_OCR_LANGUAGES
-_MANAGED_PARSE_SERVER_ENV = "MINERU_MANAGED_PARSE_SERVER"
_MAX_INLINE_BYTES_DEFAULT = 1024 * 1024
_LOCAL_PARSE_OUTPUT_FORMATS: tuple[OutputFormat, ...] = (
"markdown",
@@ -162,27 +161,6 @@ def _env_flag(name: str, default: bool = True) -> bool:
return val.strip().lower() in ("1", "true", "yes", "on")
-def _install_managed_parse_server_stdin_watcher(server: uvicorn.Server) -> threading.Thread | None:
- if not _env_flag(_MANAGED_PARSE_SERVER_ENV, default=False):
- return None
-
- def _watch_stdin_for_eof() -> None:
- stdin_stream = getattr(sys.stdin, "buffer", sys.stdin)
- try:
- stdin_stream.read()
- except Exception:
- return
- server.should_exit = True
-
- watcher = threading.Thread(
- target=_watch_stdin_for_eof,
- name="mineru-managed-parse-server-stdin-sentinel",
- daemon=True,
- )
- watcher.start()
- return watcher
-
-
# ═══════════════════════════════════════════════════════════════════════
# MODELS
# ═══════════════════════════════════════════════════════════════════════
@@ -2430,6 +2408,21 @@ def main(
) -> None:
"""Start the MinerU v1 REST API server."""
configure_standard_streams()
+ shutdown_requested = threading.Event()
+ server_ref: list[uvicorn.Server | None] = [None]
+
+ def _request_shutdown() -> None:
+ shutdown_requested.set()
+ server = server_ref[0]
+ if server is not None:
+ server.should_exit = True
+
+ try:
+ control_watcher = ManagedProcessControlWatcher.from_environment(_request_shutdown)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from None
+ if control_watcher is not None:
+ control_watcher.start()
try:
application = create_app(
upload_dir=upload_dir,
@@ -2447,8 +2440,12 @@ def main(
preload_models=preload_models,
)
except ParseServerStartupError as exc:
+ if control_watcher is not None:
+ control_watcher.close()
raise click.ClickException(str(exc)) from None
except ValueError as exc:
+ if control_watcher is not None:
+ control_watcher.close()
raise click.ClickException(str(exc)) from exc
config = uvicorn.Config(
@@ -2457,8 +2454,14 @@ def main(
port=port,
)
server = uvicorn.Server(config)
- _install_managed_parse_server_stdin_watcher(server)
- server.run()
+ server_ref[0] = server
+ if shutdown_requested.is_set():
+ server.should_exit = True
+ try:
+ server.run()
+ finally:
+ if control_watcher is not None:
+ control_watcher.close()
if __name__ == "__main__":
diff --git a/mineru/utils/managed_process_control.py b/mineru/utils/managed_process_control.py
new file mode 100644
index 00000000..a4e5a121
--- /dev/null
+++ b/mineru/utils/managed_process_control.py
@@ -0,0 +1,256 @@
+"""Private parent-child control channel for managed subprocesses."""
+
+from __future__ import annotations
+
+import logging
+import os
+import secrets
+import tempfile
+import threading
+import time
+from dataclasses import dataclass
+from multiprocessing import AuthenticationError
+from multiprocessing.connection import Client, Connection, Listener
+from pathlib import Path
+from typing import Callable
+
+logger = logging.getLogger("mineru.managed_process_control")
+
+CONTROL_ENV = "MINERU_MANAGED_CONTROL"
+CONTROL_SHUTDOWN = "shutdown"
+CONTROL_CONNECT_TIMEOUT_SEC = 30.0
+CONTROL_CONNECT_RETRY_SEC = 0.1
+
+
+def _control_family() -> str:
+ return "AF_PIPE" if os.name == "nt" else "AF_UNIX"
+
+
+def _create_address(family: str) -> tuple[str, Path | None]:
+ token = secrets.token_hex(12)
+ if family == "AF_PIPE":
+ return rf"\\.\pipe\mineru-managed-{token}", None
+
+ temp_dir = Path("/tmp") if Path("/tmp").is_dir() else Path(tempfile.gettempdir())
+ return str(temp_dir / f"mineru-control-{token}.sock"), None
+
+
+def _encode_control_config(family: str, address: str, authkey: bytes) -> str:
+ return f"{family}:{address}:{authkey.hex()}"
+
+
+def _decode_control_config(value: str) -> tuple[str, str, bytes]:
+ try:
+ family, address, authkey_hex = value.split(":", 2)
+ authkey = bytes.fromhex(authkey_hex)
+ except (TypeError, ValueError) as exc:
+ raise ValueError("invalid managed process control configuration") from exc
+ if family not in {"AF_UNIX", "AF_PIPE"} or not isinstance(address, str) or not address or not authkey:
+ raise ValueError("invalid managed process control configuration")
+ if not isinstance(family, str):
+ raise ValueError("invalid managed process control configuration")
+ return family, address, authkey
+
+
+def cleanup_control_endpoint(family: str, address: str) -> None:
+ if family != "AF_UNIX":
+ return
+ try:
+ Path(address).unlink()
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ logger.debug("Failed to remove managed process control socket %s: %s", address, exc)
+
+
+@dataclass
+class ManagedProcessControl:
+ """Parent-side listener and command channel for one managed process."""
+
+ listener: Listener
+ family: str
+ address: str
+ authkey: bytes
+ cleanup_path: Path | None = None
+
+ def __post_init__(self) -> None:
+ self._connection: Connection | None = None
+ self._connection_ready = threading.Event()
+ self._closed = threading.Event()
+ self._accept_thread: threading.Thread | None = None
+ self._lock = threading.Lock()
+ self._shutdown_requested = False
+ self._shutdown_sent = False
+
+ @classmethod
+ def create(cls) -> "ManagedProcessControl":
+ family = _control_family()
+ address, cleanup_path = _create_address(family)
+ authkey = secrets.token_bytes(32)
+ try:
+ listener = Listener(address=address, family=family, authkey=authkey)
+ except Exception:
+ if cleanup_path is not None:
+ cleanup_control_endpoint(family, str(cleanup_path))
+ raise
+ return cls(listener, family, address, authkey, cleanup_path)
+
+ def child_env(self) -> dict[str, str]:
+ return {CONTROL_ENV: _encode_control_config(self.family, self.address, self.authkey)}
+
+ def start_accepting(self) -> None:
+ if self._accept_thread is not None:
+ return
+ self._accept_thread = threading.Thread(
+ target=self._accept_connection,
+ name="mineru-managed-process-control-accept",
+ daemon=True,
+ )
+ self._accept_thread.start()
+
+ def request_shutdown(self, timeout_sec: float) -> bool:
+ with self._lock:
+ self._shutdown_requested = True
+ if not self._connection_ready.wait(timeout=max(timeout_sec, 0.0)):
+ return False
+ return self._send_shutdown()
+
+ def _send_shutdown(self) -> bool:
+ with self._lock:
+ if self._shutdown_sent:
+ return True
+ connection = self._connection
+ if connection is None:
+ return False
+ try:
+ connection.send(CONTROL_SHUTDOWN)
+ self._shutdown_sent = True
+ return True
+ except (EOFError, OSError):
+ return False
+
+ def close(self) -> None:
+ if self._closed.is_set():
+ return
+ self._closed.set()
+ try:
+ self.listener.close()
+ except OSError:
+ pass
+ with self._lock:
+ connection = self._connection
+ self._connection = None
+ if connection is not None:
+ try:
+ connection.close()
+ except OSError:
+ pass
+ cleanup_control_endpoint(self.family, self.address)
+
+ def _accept_connection(self) -> None:
+ connection: Connection | None = None
+ while not self._closed.is_set():
+ try:
+ connection = self.listener.accept()
+ break
+ except AuthenticationError:
+ logger.warning("Rejected unauthenticated managed process control connection")
+ except (OSError, EOFError) as exc:
+ if not self._closed.is_set():
+ logger.debug("Managed process control listener stopped before connection: %s", exc)
+ return
+
+ if connection is None:
+ return
+ if self._closed.is_set():
+ connection.close()
+ return
+ with self._lock:
+ self._connection = connection
+ self._connection_ready.set()
+ with self._lock:
+ shutdown_requested = self._shutdown_requested
+ if shutdown_requested:
+ self._send_shutdown()
+
+
+@dataclass
+class ManagedProcessControlWatcher:
+ """Child-side watcher for the managed process control channel."""
+
+ on_shutdown: Callable[[], None]
+ family: str
+ address: str
+ authkey: bytes
+ connection_timeout_sec: float = CONTROL_CONNECT_TIMEOUT_SEC
+
+ def __post_init__(self) -> None:
+ self._stop = threading.Event()
+ self._thread: threading.Thread | None = None
+
+ @classmethod
+ def from_environment(cls, on_shutdown: Callable[[], None]) -> "ManagedProcessControlWatcher | None":
+ value = os.environ.get(CONTROL_ENV)
+ if value is None:
+ return None
+ family, address, authkey = _decode_control_config(value)
+ return cls(on_shutdown, family, address, authkey)
+
+ def start(self) -> None:
+ self._thread = threading.Thread(
+ target=self._run,
+ name="mineru-managed-process-control-watcher",
+ daemon=True,
+ )
+ self._thread.start()
+
+ def close(self) -> None:
+ self._stop.set()
+ thread = self._thread
+ if thread is not None and thread is not threading.current_thread():
+ thread.join(timeout=1.0)
+
+ def _run(self) -> None:
+ connection: Connection | None = None
+ try:
+ connection = self._connect()
+ if connection is None:
+ if not self._stop.is_set():
+ logger.error("Managed process control channel could not connect within %.1fs", self.connection_timeout_sec)
+ self.on_shutdown()
+ return
+ while not self._stop.is_set():
+ try:
+ if not connection.poll(CONTROL_CONNECT_RETRY_SEC):
+ continue
+ command = connection.recv()
+ except (EOFError, OSError):
+ if not self._stop.is_set():
+ self.on_shutdown()
+ return
+ if command == CONTROL_SHUTDOWN:
+ self.on_shutdown()
+ return
+ finally:
+ if connection is not None:
+ try:
+ connection.close()
+ except OSError:
+ pass
+ cleanup_control_endpoint(self.family, self.address)
+
+ def _connect(self) -> Connection | None:
+ deadline = time.monotonic() + self.connection_timeout_sec
+ while not self._stop.is_set() and time.monotonic() < deadline:
+ try:
+ return Client(self.address, family=self.family, authkey=self.authkey)
+ except (OSError, EOFError):
+ time.sleep(CONTROL_CONNECT_RETRY_SEC)
+ return None
+
+
+__all__ = [
+ "CONTROL_ENV",
+ "ManagedProcessControl",
+ "ManagedProcessControlWatcher",
+]
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index eeb33fd3..6c9e222b 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -512,8 +512,8 @@ def test_managed_parse_server_startup_writes_stdout_and_stderr_logs(monkeypatch,
assert kwargs["stdout"] is not subprocess.DEVNULL
assert kwargs["stderr"] is not subprocess.DEVNULL
assert kwargs["stdout"] is not kwargs["stderr"]
- assert kwargs["stdin"] is subprocess.PIPE
- assert kwargs["env"]["MINERU_MANAGED_PARSE_SERVER"] == "1"
+ assert kwargs["stdin"] is subprocess.DEVNULL
+ assert kwargs["env"]["MINERU_MANAGED_CONTROL"]
kwargs["stdout"].write("parse stdout\n")
kwargs["stdout"].flush()
kwargs["stderr"].write("parse stderr\n")
@@ -672,7 +672,7 @@ def test_managed_parse_server_shutdown_uses_health_proc(monkeypatch, tmp_path) -
assert not hasattr(state, "parse_server_proc")
assert client.get("/api/v1/server/status").status_code == 200
- assert events == ["stdin.close", "wait:2.0"]
+ assert events == ["terminate", "wait:3.0"]
def test_startup_resets_running_scans_to_failed(monkeypatch, tmp_path) -> None:
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index 69d7cac8..64be3241 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -590,8 +590,8 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: py
assert kwargs["stdout"] is not subprocess.DEVNULL
assert kwargs["stderr"] is not subprocess.DEVNULL
assert kwargs["stdout"] is not kwargs["stderr"]
- assert kwargs["stdin"] is subprocess.PIPE
- assert kwargs["env"]["MINERU_MANAGED_PARSE_SERVER"] == "1"
+ assert kwargs["stdin"] is subprocess.DEVNULL
+ assert kwargs["env"]["MINERU_MANAGED_CONTROL"]
assert kwargs["env"]["PYTHONIOENCODING"] == "utf-8:backslashreplace"
kwargs["stdout"].write("parse helper stdout\n")
kwargs["stdout"].flush()
@@ -604,7 +604,7 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: py
)
monkeypatch.setattr("mineru.doclib.background.parse_server_health.subprocess.Popen", _popen)
- proc, url = start_managed_parse_server(
+ proc, url, control = start_managed_parse_server(
tier="standard",
managed_cfg=ManagedParseServerConfig(host="127.0.0.2", port=16580, port_probe_count=3),
log_cfg=LogConfig(
@@ -619,6 +619,7 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: py
assert popen_calls
assert parse_stdout_log_path.read_text(encoding="utf-8").endswith("parse helper stdout\n")
assert parse_stderr_log_path.read_text(encoding="utf-8").endswith("parse helper stderr\n")
+ control.close()
def test_stop_managed_parse_server_uses_one_total_budget(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -630,16 +631,16 @@ def test_stop_managed_parse_server_uses_one_total_budget(monkeypatch: pytest.Mon
monkeypatch.setattr("mineru.doclib.background.parse_server_health.time.monotonic", _monotonic)
- class _Stdin:
- closed = False
+ class _Control:
+ def request_shutdown(self, timeout_sec: float) -> bool:
+ events.append(("control.shutdown", timeout_sec))
+ return True
def close(self) -> None:
- events.append("stdin.close")
- self.closed = True
+ events.append("control.close")
class _Proc:
pid = 12345
- stdin = _Stdin()
waits = 0
def poll(self) -> None:
@@ -659,10 +660,10 @@ def test_stop_managed_parse_server_uses_one_total_budget(monkeypatch: pytest.Mon
def kill(self) -> None:
events.append("kill")
- stop_managed_parse_server(_Proc(), timeout_sec=4, reason="test")
+ stop_managed_parse_server(_Proc(), control=_Control(), timeout_sec=4, reason="test")
- assert [event for event in events if isinstance(event, str)] == ["stdin.close", "terminate", "kill"]
- waits = [event[1] for event in events if isinstance(event, tuple)]
+ assert [event for event in events if isinstance(event, str)] == ["terminate", "kill", "control.close"]
+ waits = [event[1] for event in events if isinstance(event, tuple) and event[0] == "wait"]
assert waits == pytest.approx([2.0, 1.2, 0.8])
assert sum(waits) == pytest.approx(4.0)
@@ -670,15 +671,15 @@ def test_stop_managed_parse_server_uses_one_total_budget(monkeypatch: pytest.Mon
def test_stop_managed_parse_server_shortens_startup_grace(monkeypatch: pytest.MonkeyPatch) -> None:
waits: list[float] = []
- class _Stdin:
- closed = False
+ class _Control:
+ def request_shutdown(self, timeout_sec: float) -> bool:
+ return True
def close(self) -> None:
- self.closed = True
+ pass
class _Proc:
pid = 12345
- stdin = _Stdin()
def poll(self) -> None:
return None
@@ -688,7 +689,9 @@ def test_stop_managed_parse_server_shortens_startup_grace(monkeypatch: pytest.Mo
monkeypatch.setattr("mineru.doclib.background.parse_server_health.time.monotonic", lambda: 100.0)
- stop_managed_parse_server(_Proc(), timeout_sec=10, reason="startup", startup_in_progress=True)
+ stop_managed_parse_server(
+ _Proc(), control=_Control(), timeout_sec=10, reason="startup", startup_in_progress=True
+ )
assert waits == [2.0]
@@ -811,8 +814,9 @@ def test_managed_parse_server_restart_stops_recorded_proc_before_start(monkeypat
class _Proc:
pid = 67890
- def _stop(proc: object, *, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:
+ def _stop(proc: object, *, control: object, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:
assert proc is old_proc
+ assert control is None
assert timeout_sec == 4
assert reason == "restart"
assert startup_in_progress is True
@@ -847,6 +851,7 @@ def test_managed_parse_server_restart_stops_recorded_proc_before_start(monkeypat
assert events == ["stop", "start"]
assert health.managed_proc.pid == 67890
+ health.managed_control.close()
def test_managed_parse_server_tier_change_detection_triggers_restart(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -898,8 +903,9 @@ def test_managed_parse_server_tier_change_restart_uses_desired_tier(monkeypatch:
class _Proc:
pid = 24680
- def _stop(proc: object, *, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:
+ def _stop(proc: object, *, control: object, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:
assert proc is old_proc
+ assert control is None
assert timeout_sec == 4
assert reason == "tier-change"
assert startup_in_progress is False
@@ -907,13 +913,13 @@ def test_managed_parse_server_tier_change_restart_uses_desired_tier(monkeypatch:
def _start(
*, tier: Tier, managed_cfg: ManagedParseServerConfig, log_cfg: LogConfig | None, marker: str
- ) -> tuple[_Proc, str]:
+ ) -> tuple[_Proc, str, None]:
assert tier == "basic"
assert managed_cfg.host == "127.0.0.2"
assert log_cfg is None
assert marker == "tier change standard->basic"
events.append("start")
- return _Proc(), "http://127.0.0.2:16582"
+ return _Proc(), "http://127.0.0.2:16582", None
monkeypatch.setattr("mineru.doclib.background.parse_server_health.stop_managed_parse_server", _stop)
monkeypatch.setattr("mineru.doclib.background.parse_server_health.start_managed_parse_server", _start)
diff --git a/tests/unittest/test_managed_process_control.py b/tests/unittest/test_managed_process_control.py
new file mode 100644
index 00000000..80518bc1
--- /dev/null
+++ b/tests/unittest/test_managed_process_control.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import threading
+from pathlib import Path
+
+import pytest
+
+from mineru.utils.managed_process_control import (
+ CONTROL_ENV,
+ ManagedProcessControl,
+ ManagedProcessControlWatcher,
+)
+
+
+def test_managed_process_control_sends_shutdown(monkeypatch: pytest.MonkeyPatch) -> None:
+ control = ManagedProcessControl.create()
+ shutdown = threading.Event()
+ monkeypatch.setenv(CONTROL_ENV, control.child_env()[CONTROL_ENV])
+ watcher = ManagedProcessControlWatcher.from_environment(shutdown.set)
+ assert watcher is not None
+
+ control.start_accepting()
+ watcher.start()
+ try:
+ assert control.request_shutdown(timeout_sec=2.0) is True
+ assert shutdown.wait(timeout=2.0) is True
+ finally:
+ watcher.close()
+ control.close()
+ if control.family == "AF_UNIX":
+ assert not Path(control.address).exists()
+
+
+def test_managed_process_control_eof_requests_shutdown(monkeypatch: pytest.MonkeyPatch) -> None:
+ control = ManagedProcessControl.create()
+ shutdown = threading.Event()
+ monkeypatch.setenv(CONTROL_ENV, control.child_env()[CONTROL_ENV])
+ watcher = ManagedProcessControlWatcher.from_environment(shutdown.set)
+ assert watcher is not None
+
+ control.start_accepting()
+ watcher.start()
+ assert control._connection_ready.wait(timeout=2.0)
+ control.close()
+ try:
+ assert shutdown.wait(timeout=2.0) is True
+ finally:
+ watcher.close()
+
+
+def test_managed_process_control_watcher_is_absent_without_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv(CONTROL_ENV, raising=False)
+
+ assert ManagedProcessControlWatcher.from_environment(lambda: None) is None
+
+
+def test_managed_process_control_rejects_invalid_environment(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(CONTROL_ENV, "AF_UNIX:/tmp/only-two-fields")
+
+ with pytest.raises(ValueError, match="invalid managed process control configuration"):
+ ManagedProcessControlWatcher.from_environment(lambda: None)
+
+
+def test_managed_process_control_works_across_subprocess() -> None:
+ control = ManagedProcessControl.create()
+ env = os.environ.copy()
+ env.update(control.child_env())
+ child_code = """
+import sys
+import threading
+from mineru.utils.managed_process_control import ManagedProcessControlWatcher
+
+shutdown = threading.Event()
+watcher = ManagedProcessControlWatcher.from_environment(shutdown.set)
+if watcher is None:
+ sys.exit(2)
+watcher.start()
+if not shutdown.wait(timeout=5):
+ sys.exit(3)
+watcher.close()
+"""
+
+ control.start_accepting()
+ proc = subprocess.Popen(
+ [sys.executable, "-c", child_code],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ text=True,
+ )
+ try:
+ assert control.request_shutdown(timeout_sec=3.0) is True
+ stdout, stderr = proc.communicate(timeout=5)
+ assert proc.returncode == 0, f"stdout={stdout!r} stderr={stderr!r}"
+ finally:
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=2)
+ control.close()
diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.py
index 077b1b1d..116ba0b2 100644
--- a/tests/unittest/test_parser_api_contract.py
+++ b/tests/unittest/test_parser_api_contract.py
@@ -35,7 +35,6 @@ from mineru.parser.api_server import (
JobListItem,
OutputFileRef,
OutputFiles,
- _install_managed_parse_server_stdin_watcher,
create_app,
main,
)
@@ -1736,28 +1735,6 @@ def test_api_server_cli_no_longer_exposes_reload() -> None:
assert "--reload" in result.output
-def test_managed_parse_server_env_enables_stdin_eof_shutdown_watcher(monkeypatch: pytest.MonkeyPatch) -> None:
- server = type("Server", (), {"should_exit": False})()
- monkeypatch.setenv("MINERU_MANAGED_PARSE_SERVER", "1")
- monkeypatch.setattr(api_server.sys, "stdin", type("Stdin", (), {"buffer": io.BytesIO(b"")})())
-
- watcher = _install_managed_parse_server_stdin_watcher(server)
-
- assert watcher is not None
- watcher.join(timeout=1)
- assert server.should_exit is True
-
-
-def test_managed_parse_server_stdin_watcher_is_disabled_without_env(monkeypatch: pytest.MonkeyPatch) -> None:
- server = type("Server", (), {"should_exit": False})()
- monkeypatch.delenv("MINERU_MANAGED_PARSE_SERVER", raising=False)
-
- watcher = _install_managed_parse_server_stdin_watcher(server)
-
- assert watcher is None
- assert server.should_exit is False
-
-
def test_output_files_expose_new_names_without_inline_content() -> None:
ref = OutputFileRef(file_id="file-1", bytes=12)
outputs = OutputFiles(middle_json=ref, structured_content=ref)