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: harden server lifecycle and CLI rendering
jinzhenj93260e9a4e30
diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.pyindex ba823398..2c9c3530 100644--- a/mineru/cli/commands/server.py+++ b/mineru/cli/commands/server.py@@ -13,9 +13,9 @@ from typing import Anyimport typerfrom rich.panel import Panelfrom rich.table import Table+from rich.text import Textfrom ...config import config-from ...doclib.endpoint import remove_endpoint_filefrom ...doclib.instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lockfrom ...doclib.types import ServerStatusResponse, TCPServerStatusfrom ...errors import MineruError@@ -185,7 +185,6 @@ def _wait_for_server_stop(timeout: float = 15.0) -> bool:with doclib_home_lock():if _server_running():continue- _cleanup_local_endpoint_files()return Trueexcept DoclibLockUnavailable:pass@@ -524,7 +523,7 @@ def _render_server_status(data: ServerStatusResponse) -> Iterator[RenderableObjelogs = _get(data, key, [])if logs:log_text = "".join(logs)- panel = Panel(log_text.strip() or "(empty)", title=title, border_style="dim")+ panel = Panel(Text(log_text.strip() or "(empty)"), title=title, border_style="dim")yield panel@@ -594,14 +593,6 @@ def _error_summary_rows(error_summary: Any) -> list[tuple[str, str, int]]:return rows-def _cleanup_local_endpoint_files() -> None:- try:- os.unlink(_socket_path())- except OSError:- pass- remove_endpoint_file(_endpoint_path())--def _ensure_log_dir(path: str) -> None:log_dir = os.path.dirname(path)if log_dir:diff --git a/mineru/cli/output.py b/mineru/cli/output.pyindex 2ca7352a..0eae8a14 100644--- a/mineru/cli/output.py+++ b/mineru/cli/output.py@@ -13,8 +13,8 @@ from rich.text import Textfrom .contracts import RenderableObject-console = Console()-stderr_console = Console(stderr=True)+console = Console(markup=False)+stderr_console = Console(stderr=True, markup=False)def print_rich(*objects: RenderableObject) -> None:diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 10196070..9cd2e002 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -19,9 +19,9 @@ from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponsefrom loguru import logger as loguru_logger-from ..config import Config, LogConfig, _mineru_home, config+from ..config import Config, LogConfig, _mineru_home, config, get_config_sourcefrom ..errors import MineruError, error_response, http_status_for-from .endpoint import EndpointTransport, remove_endpoint_file, uds_available, write_endpoint_file+from .endpoint import EndpointTransport, read_endpoint_file, remove_endpoint_file, uds_available, write_endpoint_filefrom .instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lockfrom .server import DoclibServerfrom .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING, SCAN_STATUS_FAILED, SCAN_STATUS_RUNNING@@ -31,6 +31,8 @@ if TYPE_CHECKING:else:LoguruMessage = Any+logger = logging.getLogger("mineru.doclib.app")+def create_app(cfg: Config | None = None) -> FastAPI:"""Create the new interface-backed FastAPI app."""@@ -208,6 +210,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:health.managed_proc,timeout_sec=cfg.doclib.parse_server_stop_timeout_sec,reason="doclib shutdown",+ startup_in_progress=health.local_starting,)health.managed_proc = None@@ -236,7 +239,10 @@ def create_app(cfg: Config | None = None) -> FastAPI:try:yieldfinally:- await shutdown()+ try:+ await shutdown()+ finally:+ _run_discovery_cleanup(state)app.router.lifespan_context = lifespan@@ -317,6 +323,7 @@ class AppState:self.tcp_host: str = ""self.tcp_port: int | None = Noneself.config: Config | None = None+ self.discovery_cleanup: Callable[[], None] | None = NoneREQUIRED_SCHEMA_TABLES = {@@ -452,21 +459,32 @@ def _run_server(cfg: Config) -> None:"Enable doclib.tcp or disable doclib.uds.")- remove_endpoint_file(endpoint_path)- if uds_enabled:- try:- os.unlink(uds_path)- except OSError:- pass+ app = create_app(cfg)+ server_id = app.state.doclib_state.server_id+ log_source = get_config_source("doclib.log.level") if cfg is config else "provided"+ logger.info(+ "Doclib logging configured level=%s source=%s path=%s",+ logging.getLevelName(_resolve_log_level(cfg.doclib.log)),+ log_source,+ os.path.expanduser(cfg.doclib.log.resolved_app_path),+ )+ _remove_stale_discovery_files(endpoint_path, uds_path if uds_enabled else None)sockets: list[socket.socket] = []transports: list[EndpointTransport] = []+ uds_identity: tuple[int, int] | None = Noneloop: asyncio.AbstractEventLoop | None = None++ def cleanup_discovery() -> None:+ _remove_owned_endpoint_file(endpoint_path, server_id)+ if uds_enabled and uds_identity is not None:+ _remove_owned_uds_path(uds_path, uds_identity)++ app.state.doclib_state.discovery_cleanup = cleanup_discoverytry:- app = create_app(cfg)write_endpoint_file(endpoint_path,pid=os.getpid(),- server_id=app.state.doclib_state.server_id,+ server_id=server_id,transports=[],)uv_config = uvicorn.Config(@@ -481,6 +499,7 @@ def _run_server(cfg: Config) -> None:uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)uds_sock.bind(uds_path)os.chmod(uds_path, cfg.doclib.uds.permission)+ uds_identity = _path_identity(uds_path)uds_sock.listen(cfg.doclib.tcp.backlog)sockets.append(uds_sock)transports.append(EndpointTransport(type="uds", path=uds_path))@@ -504,9 +523,17 @@ def _run_server(cfg: Config) -> None:write_endpoint_file(endpoint_path,pid=os.getpid(),- server_id=app.state.doclib_state.server_id,+ server_id=server_id,transports=transports,)+ logger.debug(+ "Doclib endpoint published path=%s pid=%d server_id=%s transports=%d",+ endpoint_path,+ os.getpid(),+ server_id,+ len(transports),+ )+print("MinerU server listening on " + " and ".join(_format_transport(transport) for transport in transports))loop = asyncio.new_event_loop()@@ -524,16 +551,85 @@ def _run_server(cfg: Config) -> None:loop.close()for bound_socket in sockets:bound_socket.close()- if uds_enabled:- try:- os.unlink(uds_path)- except OSError:- pass- remove_endpoint_file(endpoint_path)+ _run_discovery_cleanup(app.state.doclib_state)+++def _path_identity(path: str) -> tuple[int, int] | None:+ try:+ stat_result = os.stat(path, follow_symlinks=False)+ except OSError:+ return None+ return stat_result.st_dev, stat_result.st_ino+++def _run_discovery_cleanup(state: AppState) -> None:+ cleanup = state.discovery_cleanup+ if cleanup is None:+ return+ state.discovery_cleanup = None+ cleanup()+++def _remove_stale_discovery_files(endpoint_path: str, uds_path: str | None) -> None:+ previous = read_endpoint_file(endpoint_path)+ logger.debug(+ "Removing stale doclib discovery files endpoint=%s previous_pid=%s previous_server_id=%s uds=%s",+ endpoint_path,+ previous.pid if previous is not None else None,+ previous.server_id if previous is not None else None,+ uds_path,+ )+ remove_endpoint_file(endpoint_path, reason="startup_stale_cleanup")+ if uds_path is not None:+ try:+ os.unlink(uds_path)+ except FileNotFoundError:+ pass+++def _remove_owned_endpoint_file(endpoint_path: str, server_id: str) -> None:+ current = read_endpoint_file(endpoint_path)+ if current is None:+ logger.debug("Doclib endpoint already absent during shutdown path=%s server_id=%s", endpoint_path, server_id)+ return+ if current.server_id != server_id:+ logger.warning(+ "Skipping doclib endpoint cleanup because ownership changed path=%s expected_server_id=%s current_server_id=%s",+ endpoint_path,+ server_id,+ current.server_id,+ )+ return+ remove_endpoint_file(endpoint_path, reason="shutdown_owned_cleanup")+ logger.debug("Removed owned doclib endpoint path=%s server_id=%s", endpoint_path, server_id)+++def _remove_owned_uds_path(uds_path: str, expected_identity: tuple[int, int]) -> None:+ current_identity = _path_identity(uds_path)+ if current_identity is None:+ logger.debug("Doclib UDS path already absent during shutdown path=%s", uds_path)+ return+ if current_identity != expected_identity:+ logger.warning(+ "Skipping doclib UDS cleanup because path identity changed path=%s expected=%s current=%s",+ uds_path,+ expected_identity,+ current_identity,+ )+ return+ try:+ os.unlink(uds_path)+ except FileNotFoundError:+ return+ logger.debug("Removed owned doclib UDS path=%s identity=%s", uds_path, expected_identity)+++def _resolve_log_level(log_cfg: LogConfig) -> int:+ return getattr(logging, log_cfg.level.upper(), logging.INFO)def _setup_logging(log_cfg: LogConfig) -> None:- level = getattr(logging, log_cfg.level.upper(), logging.INFO)+ level = _resolve_log_level(log_cfg)log_path = os.path.expanduser(log_cfg.resolved_app_path)access_log_path = os.path.expanduser(log_cfg.resolved_access_path)_ensure_log_dir(log_path)@@ -567,7 +663,7 @@ def _setup_logging(log_cfg: LogConfig) -> None:logger.addHandler(access_handler)logging.captureWarnings(True)- _setup_loguru_bridge(log_cfg.level.upper())+ _setup_loguru_bridge(logging.getLevelName(level))def _ensure_log_dir(path: str) -> None:diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.pyindex 8302c86a..2958b5b0 100644--- a/mineru/doclib/background/parse_server_health.py+++ b/mineru/doclib/background/parse_server_health.py@@ -210,11 +210,19 @@ def start_managed_parse_server(return proc, managed_url-def stop_managed_parse_server(proc: subprocess.Popen | None, *, timeout_sec: int, reason: str) -> None:+def stop_managed_parse_server(+ proc: subprocess.Popen | None,+ *,+ timeout_sec: int,+ reason: str,+ startup_in_progress: bool = False,+) -> None:if proc is None or proc.poll() is not None:returnpid = proc.pid+ total_timeout = max(float(timeout_sec), 0.0)+ deadline = time.monotonic() + total_timeoutstdin = getattr(proc, "stdin", None)if stdin is not None and not getattr(stdin, "closed", False):try:@@ -223,7 +231,8 @@ def stop_managed_parse_server(proc: subprocess.Popen | None, *, timeout_sec: intlogger.debug("Failed to close managed parse-server stdin (PID %d, reason=%s): %s", pid, reason, exc)try:- proc.wait(timeout=timeout_sec)+ 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)returnexcept subprocess.TimeoutExpired:@@ -231,7 +240,8 @@ def stop_managed_parse_server(proc: subprocess.Popen | None, *, timeout_sec: inttry:proc.terminate()- proc.wait(timeout=timeout_sec)+ 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)returnexcept subprocess.TimeoutExpired:@@ -241,7 +251,7 @@ def stop_managed_parse_server(proc: subprocess.Popen | None, *, timeout_sec: inttry:proc.kill()- proc.wait(timeout=timeout_sec)+ proc.wait(timeout=max(deadline - time.monotonic(), 0.0))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)@@ -416,7 +426,12 @@ class ParseServerHealthCheck:if count_restart:health.restart_count += 1managed_tier = await get_managed_parse_server_tier(self.config_svc)- stop_managed_parse_server(health.managed_proc, timeout_sec=self.stop_timeout_sec, reason=reason)+ stop_managed_parse_server(+ health.managed_proc,+ timeout_sec=self.stop_timeout_sec,+ reason=reason,+ startup_in_progress=health.local_starting,+ )health.managed_proc = Nonehealth.running_managed_tier = Nonetry:@@ -474,7 +489,12 @@ class ParseServerHealthCheck:async def stop(self) -> None:self.running = Falsehealth = get_health()- stop_managed_parse_server(health.managed_proc, timeout_sec=self.stop_timeout_sec, reason="health check stop")+ stop_managed_parse_server(+ health.managed_proc,+ timeout_sec=self.stop_timeout_sec,+ reason="health check stop",+ startup_in_progress=health.local_starting,+ )health.managed_proc = Nonediff --git a/mineru/doclib/endpoint.py b/mineru/doclib/endpoint.pyindex e2cd63c4..3428affe 100644--- a/mineru/doclib/endpoint.py+++ b/mineru/doclib/endpoint.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import loggingimport osimport socketfrom dataclasses import dataclass@@ -11,6 +12,8 @@ from typing import Any, Literalfrom ..config import Config, config+logger = logging.getLogger("mineru.doclib.endpoint")+TransportType = Literal["uds", "tcp"]@@ -65,9 +68,11 @@ def write_endpoint_file(path: str | os.PathLike[str], *, pid: int, server_id: stos.replace(tmp_path, endpoint_path)-def remove_endpoint_file(path: str | os.PathLike[str]) -> None:+def remove_endpoint_file(path: str | os.PathLike[str], *, reason: str) -> None:+ endpoint_path = Path(path).expanduser()+ logger.debug("Removing doclib endpoint path=%s pid=%d reason=%s", endpoint_path, os.getpid(), reason)try:- Path(path).expanduser().unlink()+ endpoint_path.unlink()except OSError:passdiff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex b46d600b..846dceed 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -6,10 +6,13 @@ import shleximport sysfrom collections.abc import Iteratorfrom contextlib import contextmanager+from io import StringIOfrom pathlib import Pathfrom typing import Anyimport pytest+from rich.console import Console+from rich.text import Textfrom typer.main import get_commandfrom typer.testing import CliRunner@@ -517,7 +520,7 @@ def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> Ndata_dir="/tmp/mineru",sqlite_path="/tmp/doclib.db",log_path="/tmp/doclib.log",- app_logs=["app\n"],+ app_logs=["app [/Users/jinzhenj/.mineru]\n"],access_logs=["access\n"],stderr_logs=["stderr\n"],stdout_logs=["stdout\n"],@@ -536,8 +539,9 @@ def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> N"Recent Parse Server Stderr Logs","Recent Parse Server Stdout Logs",]- assert [panel["renderable"] for panel in panels] == [- "app",+ assert all(isinstance(panel["renderable"], Text) for panel in panels)+ assert [panel["renderable"].plain for panel in panels] == [+ "app [/Users/jinzhenj/.mineru]","access","stderr","stdout",@@ -548,6 +552,32 @@ def test_server_status_renders_separate_recent_log_panels(monkeypatch: Any) -> Nassert not any(getattr(item, "title", None) == "Recent Logs" for item in rendered)+def test_server_status_renders_markup_like_log_text_literally() -> None:+ rendered = list(+ server._render_server_status(+ ServerStatusResponse(+ running=True,+ pid=123,+ uptime_seconds=1,+ socket_path="/tmp/doclib.sock",+ data_dir="/tmp/mineru",+ sqlite_path="/tmp/doclib.db",+ log_path="/tmp/doclib.log",+ access_logs=["MinerU home [/Users/jinzhenj/.mineru]\n[bold]\n[/invalid]\n"],+ )+ )+ )+ panel = next(item for item in rendered if getattr(item, "title", None) == "Recent Access Logs")+ output = StringIO()++ Console(file=output, width=160, color_system=None).print(panel)++ rendered_text = output.getvalue()+ assert "MinerU home [/Users/jinzhenj/.mineru]" in rendered_text+ assert "[bold]" in rendered_text+ assert "[/invalid]" in rendered_text++def test_telemetry_status_command_prints_installation_id(monkeypatch: Any) -> None:class _Client:def __init__(self, *, timeout: int) -> None:@@ -2194,10 +2224,9 @@ def test_wait_for_server_stop_requires_ownership_release(monkeypatch: Any) -> Nomonkeypatch.setattr(server, "_server_running", lambda: False)monkeypatch.setattr(server, "doclib_home_lock", _home_lock)- monkeypatch.setattr(server, "_cleanup_local_endpoint_files", lambda: events.append("cleanup"))assert server._wait_for_server_stop(timeout=1) is True- assert events == ["lock", "cleanup"]+ assert events == ["lock"]def test_server_stop_waits_until_shutdown_completes(monkeypatch: Any) -> None:diff --git a/tests/unittest/test_cli_output_markup.py b/tests/unittest/test_cli_output_markup.pynew file mode 100644index 00000000..f367d9b9--- /dev/null+++ b/tests/unittest/test_cli_output_markup.py@@ -0,0 +1,46 @@+from __future__ import annotations++from rich.table import Table+from rich.text import Text++from mineru.cli import output+++MARKUP_LIKE_TEXT = "MinerU home [/Users/jinzhenj/.mineru] [bold] [/invalid]"+++def test_stdout_console_renders_markup_like_strings_literally() -> None:+ with output.console.capture() as capture:+ output.console.print(MARKUP_LIKE_TEXT)++ assert MARKUP_LIKE_TEXT in capture.get()+++def test_stderr_notice_renders_markup_like_strings_literally() -> None:+ with output.stderr_console.capture() as capture:+ output.print_notice(MARKUP_LIKE_TEXT)++ assert MARKUP_LIKE_TEXT in capture.get()+++def test_rich_table_renders_markup_like_title_and_cell_literally() -> None:+ table = Table(title=MARKUP_LIKE_TEXT)+ table.add_column("Value")+ table.add_row(MARKUP_LIKE_TEXT)++ with output.console.capture() as capture:+ output.print_rich(table)++ rendered = capture.get()+ assert "[/Users/jinzhenj/.mineru]" in rendered+ assert "[bold]" in rendered+ assert "[/invalid]" in rendered+++def test_explicit_rich_text_remains_renderable() -> None:+ text = Text("styled", style="green")++ with output.console.capture() as capture:+ output.print_rich(text)++ assert "styled" in capture.get()diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.pyindex 1b816480..87eed2c4 100644--- a/tests/unittest/test_doclib_app_startup.py+++ b/tests/unittest/test_doclib_app_startup.py@@ -346,6 +346,45 @@ def test_setup_logging_routes_loguru_records_to_application_log(tmp_path: Path)_clear_test_loggers()+def test_shutdown_removes_only_endpoint_owned_by_current_server(tmp_path: Path) -> None:+ endpoint_path = tmp_path / "doclib.endpoint.json"+ doclib_app.write_endpoint_file(endpoint_path, pid=123, server_id="current-server", transports=[])++ doclib_app._remove_owned_endpoint_file(str(endpoint_path), "old-server")+ assert endpoint_path.exists()++ doclib_app._remove_owned_endpoint_file(str(endpoint_path), "current-server")+ assert not endpoint_path.exists()+++def test_shutdown_removes_only_uds_path_with_bound_identity(tmp_path: Path) -> None:+ uds_path = tmp_path / "doclib.sock"+ uds_path.write_text("original", encoding="utf-8")+ original_identity = doclib_app._path_identity(str(uds_path))+ assert original_identity is not None++ uds_path.unlink()+ uds_path.write_text("replacement", encoding="utf-8")+ doclib_app._remove_owned_uds_path(str(uds_path), original_identity)+ assert uds_path.read_text(encoding="utf-8") == "replacement"++ replacement_identity = doclib_app._path_identity(str(uds_path))+ assert replacement_identity is not None+ doclib_app._remove_owned_uds_path(str(uds_path), replacement_identity)+ assert not uds_path.exists()+++def test_discovery_cleanup_runs_only_once() -> None:+ state = doclib_app.AppState()+ events: list[str] = []+ state.discovery_cleanup = lambda: events.append("cleanup")++ doclib_app._run_discovery_cleanup(state)+ doclib_app._run_discovery_cleanup(state)++ assert events == ["cleanup"]++def test_server_status_reports_configured_socket_path(monkeypatch, tmp_path) -> None:app_log_path = tmp_path / "doclib.log"access_log_path = tmp_path / "doclib.access.log"@@ -627,7 +666,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:10"]+ assert events == ["stdin.close", "wait:2.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.pyindex fda2e568..00634a18 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -620,8 +620,14 @@ def test_start_managed_parse_server_selects_port_and_writes_logs(monkeypatch: pyassert parse_stderr_log_path.read_text(encoding="utf-8").endswith("parse helper stderr\n")-def test_stop_managed_parse_server_closes_stdin_then_terminates_then_kills() -> None:- events: list[str] = []+def test_stop_managed_parse_server_uses_one_total_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ events: list[str | tuple[str, float]] = []+ now = 100.0++ def _monotonic() -> float:+ return now++ monkeypatch.setattr("mineru.doclib.background.parse_server_health.time.monotonic", _monotonic)class _Stdin:closed = False@@ -638,9 +644,11 @@ def test_stop_managed_parse_server_closes_stdin_then_terminates_then_kills() ->def poll(self) -> None:return None- def wait(self, timeout: int) -> None:+ def wait(self, timeout: float) -> None:+ nonlocal nowself.waits += 1- events.append(f"wait:{timeout}")+ events.append(("wait", timeout))+ now += timeoutif self.waits < 3:raise subprocess.TimeoutExpired(cmd=["parse-server"], timeout=timeout)@@ -652,7 +660,36 @@ def test_stop_managed_parse_server_closes_stdin_then_terminates_then_kills() ->stop_managed_parse_server(_Proc(), timeout_sec=4, reason="test")- assert events == ["stdin.close", "wait:4", "terminate", "wait:4", "kill", "wait:4"]+ 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 waits == pytest.approx([2.0, 1.2, 0.8])+ assert sum(waits) == pytest.approx(4.0)+++def test_stop_managed_parse_server_shortens_startup_grace(monkeypatch: pytest.MonkeyPatch) -> None:+ waits: list[float] = []++ class _Stdin:+ closed = False++ def close(self) -> None:+ self.closed = True++ class _Proc:+ pid = 12345+ stdin = _Stdin()++ def poll(self) -> None:+ return None++ def wait(self, timeout: float) -> None:+ waits.append(timeout)++ 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)++ assert waits == [2.0]def test_managed_parse_server_restart_writes_stdout_and_stderr_logs(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:@@ -773,10 +810,11 @@ def test_managed_parse_server_restart_stops_recorded_proc_before_start(monkeypatclass _Proc:pid = 67890- def _stop(proc: object, *, timeout_sec: int, reason: str) -> None:+ def _stop(proc: object, *, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:assert proc is old_procassert timeout_sec == 4assert reason == "restart"+ assert startup_in_progress is Trueevents.append("stop")def _popen(*args: Any, **kwargs: Any) -> _Proc:@@ -802,7 +840,7 @@ def test_managed_parse_server_restart_stops_recorded_proc_before_start(monkeypatstop_timeout_sec=4,managed_parse_server=ManagedParseServerConfig(host="127.0.0.2", port=16580, port_probe_count=3),)- health = ParseServerHealth(managed_proc=old_proc)+ health = ParseServerHealth(managed_proc=old_proc, local_starting=True)asyncio.run(checker._try_restart_managed(health))@@ -859,10 +897,11 @@ 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) -> None:+ def _stop(proc: object, *, timeout_sec: int, reason: str, startup_in_progress: bool) -> None:assert proc is old_procassert timeout_sec == 4assert reason == "tier-change"+ assert startup_in_progress is Falseevents.append("stop")def _start(