Skip to content

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

fix(doclib): bound managed parse-server recovery and clean up processes

myhloli9290a153b6fb
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.py
index 71ba4c96..4546618c 100644
--- a/mineru/doclib/app.py
+++ b/mineru/doclib/app.py
@@ -393,6 +393,7 @@ class AppState:
self.tcp_port: int | None = None
self.config: Config | None = None
self.discovery_cleanup: Callable[[], None] | None = None
+ self.shutdown: Callable[[], None] | None = None
REQUIRED_SCHEMA_TABLES = {
@@ -567,6 +568,12 @@ def _run_server(cfg: Config, *, log_source: ConfigSource | Literal["provided"] =
)
server = uvicorn.Server(uv_config)
+ def request_shutdown() -> None:
+ """通过 Uvicorn 正常退出,确保 Windows 也会执行生命周期清理。"""
+ server.should_exit = True
+
+ app.state.doclib_state.shutdown = request_shutdown
+
if uds_enabled:
uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
uds_sock.bind(uds_path)
diff --git a/mineru/doclib/background/parse_server_health.py b/mineru/doclib/background/parse_server_health.py
index 1e5f7a15..e1a0726a 100644
--- a/mineru/doclib/background/parse_server_health.py
+++ b/mineru/doclib/background/parse_server_health.py
@@ -78,6 +78,7 @@ def managed_parse_server_url(host: str, port: int) -> str:
def select_available_managed_port(host: str, port: int, *, strict_port: bool, port_probe_count: int) -> int:
+ """按配置探测端口,兼容 Windows 独占绑定及保留端口产生的访问拒绝。"""
last_exc: OSError | None = None
candidate_ports = (port,) if strict_port else range(port, port + port_probe_count)
for candidate_port in candidate_ports:
@@ -87,7 +88,7 @@ def select_available_managed_port(host: str, port: int, *, strict_port: bool, po
probe_sock.bind((host, candidate_port))
return int(probe_sock.getsockname()[1])
except OSError as exc:
- if exc.errno != errno.EADDRINUSE or strict_port:
+ if strict_port or (exc.errno != errno.EADDRINUSE and getattr(exc, "winerror", None) not in {10013, 10048}):
raise
last_exc = exc
finally:
@@ -147,6 +148,7 @@ def start_managed_parse_server(
log_cfg: LogConfig | None,
marker: str,
) -> tuple[subprocess.Popen, str, ManagedProcessControl]:
+ """创建托管子进程,监听线程或子进程启动失败时回收已创建的控制通道。"""
port = select_available_managed_port(
managed_cfg.host,
managed_cfg.port,
@@ -164,8 +166,8 @@ def start_managed_parse_server(
control = ManagedProcessControl.create()
env.update(control.child_env())
logger.info("Starting managed parse-server (%s): %s", marker, " ".join(cmd))
- control.start_accepting()
try:
+ control.start_accepting()
with open_managed_parse_server_logs(marker=marker, log_cfg=log_cfg) as (
stdout_log_file,
stderr_log_file,
@@ -185,6 +187,7 @@ def stop_managed_parse_server(
reason: str,
startup_in_progress: bool = False,
) -> None:
+ """在统一预算内关闭托管进程,最终仍未退出时抛错以保留调用方的进程归属。"""
if proc is None:
if control is not None:
control.close()
@@ -234,6 +237,8 @@ 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)
+ if proc.poll() is None:
+ raise RuntimeError(f"Managed parse-server did not stop (PID {pid}, reason={reason})") from exc
finally:
if control is not None:
control.close()
@@ -301,19 +306,29 @@ class ParseServerHealthCheck:
# 读取配置期间若发生切换,重新读取,避免用旧快照覆盖新的目标档位。
if config_generation != health.local_generation:
continue
+ if mode == "managed" and (health.local_mode != mode or health.managed_tier != desired_managed_tier):
+ health.restart_count = 0
+ health.managed_restart_exhausted = False
health.local_mode = mode
health.managed_tier = desired_managed_tier
health.self_hosted_url = self_hosted_url if self_hosted_url else None
# 档位切换先于探测和远程健康检查,旧服务不能在重启前重新变为可用。
tier_changed = False
- if health.local_mode == "managed":
+ if health.local_mode == "managed" and not health.managed_restart_exhausted:
tier_changed = await self._try_restart_managed_for_tier_change(health, desired_managed_tier)
+ elif health.local_mode != "managed" and (health.managed_proc is not None or health.managed_control is not None):
+ try:
+ self._stop_managed_process(health, reason="local mode changed")
+ except RuntimeError:
+ logger.exception("Failed to stop managed parse-server after local mode changed")
# probe local
probed_local = False
probe_generation = health.local_generation
- if health.local_mode != "disabled":
+ if health.local_mode == "managed" and health.managed_restart_exhausted:
+ self._exhaust_managed_restarts(health)
+ elif health.local_mode != "disabled":
url = self._local_url(health)
if url:
probed_local = True
@@ -364,7 +379,7 @@ class ParseServerHealthCheck:
if probe_generation != health.local_generation:
continue
- if health.local_mode == "managed":
+ if health.local_mode == "managed" and not health.managed_restart_exhausted:
proc = health.managed_proc
now = asyncio.get_event_loop().time()
startup_elapsed_sec = now - health.local_started_at
@@ -427,6 +442,9 @@ class ParseServerHealthCheck:
health: ParseServerHealth,
desired_managed_tier: ManagedServerTier,
) -> bool:
+ """目标档位变化时串行替换托管进程,熔断恢复由配置入口显式触发。"""
+ if health.managed_restart_exhausted:
+ return False
running_managed_tier = health.running_managed_tier
if running_managed_tier is None or running_managed_tier == desired_managed_tier:
return False
@@ -452,9 +470,9 @@ class ParseServerHealthCheck:
marker: str | None = None,
count_restart: bool = True,
) -> None:
- if count_restart and health.restart_count >= MAX_RESTART_ATTEMPTS:
- logger.error("Managed parse-server failed %d restarts, disabling", MAX_RESTART_ATTEMPTS)
- health.local_mode = "disabled"
+ """先确认旧进程已退出再启动新进程,连续失败达到预算后进入熔断。"""
+ if health.managed_restart_exhausted or (count_restart and health.restart_count >= MAX_RESTART_ATTEMPTS):
+ self._exhaust_managed_restarts(health)
return
config_generation = health.local_generation
@@ -464,18 +482,8 @@ class ParseServerHealthCheck:
if count_restart:
health.restart_count += 1
health.begin_managed_tier_transition(managed_tier)
- 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
- health.local_starting = False
try:
+ self._stop_managed_process(health, reason=reason)
proc, managed_url, control = start_managed_parse_server(
tier=managed_tier,
managed_cfg=self.managed_parse_server,
@@ -491,6 +499,47 @@ class ParseServerHealthCheck:
health.local_started_at = asyncio.get_event_loop().time()
except Exception as exc:
logger.error(f"Failed to restart managed parse-server: {exc}")
+ # 配置切换成功不消耗恢复预算,但切换失败仍须受连续失败上限约束。
+ if not count_restart:
+ health.restart_count += 1
+ if health.restart_count >= MAX_RESTART_ATTEMPTS:
+ self._exhaust_managed_restarts(health)
+
+ def _stop_managed_process(self, health: ParseServerHealth, *, reason: str) -> None:
+ """成功回收后释放进程归属,失败时保留引用供下一轮或应用退出重试。"""
+ 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
+ health.local_starting = False
+ health.local_started_at = 0.0
+
+ def _exhaust_managed_restarts(self, health: ParseServerHealth) -> None:
+ """锁定失败恢复并回收残留进程,后续轮次只重试未完成的回收。"""
+ if not health.managed_restart_exhausted:
+ logger.error("Managed parse-server failed %d restarts, disabling automatic restarts", MAX_RESTART_ATTEMPTS)
+ health.managed_restart_exhausted = True
+ health.local_generation += 1
+ health.local.probe = ProbeResult(
+ error_code="parse_server_unavailable",
+ error_msg=(
+ f"Managed parse-server failed {MAX_RESTART_ATTEMPTS} restarts. "
+ "Set managed mode or tier again, or restart MinerU server to retry."
+ ),
+ )
+ try:
+ if health.managed_proc is not None or health.managed_control is not None:
+ self._stop_managed_process(health, reason="restart budget exhausted")
+ except RuntimeError:
+ logger.exception("Failed to stop managed parse-server after restart budget exhausted")
+ health.local_starting = False
+ health.managed_tier_transition = False
async def _probe(self, base_url: str, *, api_key: str | None = None) -> ProbeResult:
headers = {"Authorization": f"Bearer {api_key}"} if api_key else None
@@ -529,18 +578,11 @@ class ParseServerHealthCheck:
return None
async def stop(self) -> None:
+ """结束健康检查并确认回收当前应用拥有的托管进程。"""
self.running = False
self.wakeup()
health = self.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
+ self._stop_managed_process(health, reason="health check stop")
def _probe_error(resp: httpx.Response) -> tuple[str, str]:
diff --git a/mineru/doclib/parse_server_state.py b/mineru/doclib/parse_server_state.py
index 30dd8c1b..8fb73527 100644
--- a/mineru/doclib/parse_server_state.py
+++ b/mineru/doclib/parse_server_state.py
@@ -48,6 +48,7 @@ class ParseServerHealth:
managed_tier: ManagedServerTier | None = None
running_managed_tier: ManagedServerTier | None = None
restart_count: int = 0
+ managed_restart_exhausted: bool = False # 运行时熔断独立于配置模式,避免热加载重新开启失败恢复。
managed_proc: subprocess.Popen | None = None
managed_control: ManagedProcessControl | None = None
managed_tier_transition: bool = False
diff --git a/mineru/doclib/server.py b/mineru/doclib/server.py
index 28be981c..78f2a5c6 100644
--- a/mineru/doclib/server.py
+++ b/mineru/doclib/server.py
@@ -2,9 +2,7 @@
from __future__ import annotations
-import asyncio
import os
-import signal
import sys
import time
from typing import Any, cast
@@ -37,7 +35,7 @@ from ..types import (
from ..version import __version__
from .auth import DoclibAuthMiddleware
from .background.parse_server_health import get_managed_parse_server_tier
-from .parse_server_state import ParseServerHealth
+from .parse_server_state import ParseServerHealth, ProbeResult
from .base import AsyncDoclibInterface
from .config_schema import validate_config_value
from .core.db import DatabaseManager
@@ -302,12 +300,13 @@ class DoclibServer(AsyncDoclibInterface):
@route("POST", "/server/shutdown", tags=("server",))
async def shutdown_server(self) -> ShutdownResponse:
- if hasattr(self.state, "shutdown"):
- result = self.state.shutdown()
- if hasattr(result, "__await__"):
- await result
- else:
- asyncio.create_task(_signal_shutdown())
+ """通过宿主回调请求优雅关闭,让应用生命周期完成资源回收。"""
+ shutdown = getattr(self.state, "shutdown", None)
+ if shutdown is None:
+ raise MineruError("service_unavailable", "Server shutdown is unavailable for this application host.")
+ result = shutdown()
+ if hasattr(result, "__await__"):
+ await result
return ShutdownResponse(accepted=True, message="Server shutting down...")
@route("POST", "/parses", tags=("parse",))
@@ -779,12 +778,27 @@ class DoclibServer(AsyncDoclibInterface):
async def _refresh_managed_tier_transition(self) -> None:
"""按最新有效配置撤销旧托管服务探测结果,并唤醒串行重启任务。"""
mode = await self.state.config_svc.get("parse_server.local.mode")
+ health = self.health
if mode != "managed":
+ if health.local_mode != mode:
+ health.local_generation += 1
+ health.local_mode = mode or "disabled"
+ health.local.probe = ProbeResult()
+ health.managed_tier_transition = False
+ health_check = getattr(self.state, "health_check", None)
+ if health_check is not None:
+ health_check.wakeup()
return
tier = await get_managed_parse_server_tier(self.state.config_svc)
- health = self.health
- if health.local_mode == "managed" and health.managed_tier == tier and health.running_managed_tier == tier:
+ if (
+ health.local_mode == "managed"
+ and health.managed_tier == tier
+ and health.running_managed_tier == tier
+ and not health.managed_restart_exhausted
+ ):
return
+ health.restart_count = 0
+ health.managed_restart_exhausted = False
health.begin_managed_tier_transition(tier)
health_check = getattr(self.state, "health_check", None)
if health_check is not None:
@@ -1157,11 +1171,6 @@ async def _unexpected_error_handler(_request: Request, exc: Exception) -> JSONRe
return JSONResponse(status_code=500, content=error_response(MineruError("internal_error", str(exc))))
-async def _signal_shutdown() -> None:
- await asyncio.sleep(0.1)
- os.kill(os.getpid(), signal.SIGTERM)
-
-
def _parse_server_status(
*,
local_mode: str,
diff --git a/mineru/parser/process_control.py b/mineru/parser/process_control.py
index d9a95283..21776245 100644
--- a/mineru/parser/process_control.py
+++ b/mineru/parser/process_control.py
@@ -149,6 +149,7 @@ class ManagedProcessControl:
cleanup_control_endpoint(self.family, self.address)
def _accept_connection(self) -> None:
+ """接收连接后在同一把锁内确认关闭状态,避免关闭完成后重新持有连接。"""
connection: Connection | None = None
while not self._closed.is_set():
try:
@@ -163,13 +164,12 @@ class ManagedProcessControl:
if connection is None:
return
- if self._closed.is_set():
- connection.close()
- return
with self._lock:
+ if self._closed.is_set():
+ connection.close()
+ return
self._connection = connection
- self._connection_ready.set()
- with self._lock:
+ self._connection_ready.set()
shutdown_requested = self._shutdown_requested
if shutdown_requested:
self._send_shutdown()
diff --git a/tests/conftest.py b/tests/conftest.py
index db3db0dd..5746a8c8 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -7,6 +7,9 @@ import os
import pytest
+# ONNX Runtime 1.30 的 1DS 遥测线程可能在解释器析构时崩溃,普通回归在导入前默认关闭遥测。
+os.environ.setdefault("ORT_DISABLE_TELEMETRY", "1")
+
# Typer 的 help 文案在 import 期求值,必须在任何 mineru 模块导入前固定 CLI 语言,
# 否则中文 locale 机器上既有的英文输出断言会失败。i18n 专项测试自行 monkeypatch 覆盖。
os.environ["MINERU_LANG"] = "en"
diff --git a/tests/unittest/test_doclib_app_startup.py b/tests/unittest/test_doclib_app_startup.py
index 55a2ba0d..c2ca2d43 100644
--- a/tests/unittest/test_doclib_app_startup.py
+++ b/tests/unittest/test_doclib_app_startup.py
@@ -621,6 +621,10 @@ def test_managed_parse_server_startup_ignores_invalid_tier_override(monkeypatch,
def poll(self) -> None:
return None
+ def terminate(self) -> None:
+ """模拟正常结束,使启动配置测试使用完整的进程生命周期替身。"""
+ return None
+
def wait(self, timeout: int) -> None:
return None
diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.py
index d66125bc..72137b58 100644
--- a/tests/unittest/test_doclib_cache_semantics.py
+++ b/tests/unittest/test_doclib_cache_semantics.py
@@ -779,7 +779,11 @@ def test_managed_parse_server_restart_writes_stdout_and_stderr_logs(monkeypatch:
)
health = ParseServerHealth()
- asyncio.run(checker._try_restart_managed(health))
+ try:
+ asyncio.run(checker._try_restart_managed(health))
+ finally:
+ if health.managed_control is not None:
+ health.managed_control.close()
assert health.managed_url == "http://127.0.0.2:16582"
assert parse_stdout_log_path.read_text(encoding="utf-8").endswith("parse restart stdout\n")
@@ -828,7 +832,11 @@ def test_managed_parse_server_restart_ignores_invalid_tier_override(monkeypatch:
)
health = ParseServerHealth()
- asyncio.run(checker._try_restart_managed(health))
+ try:
+ asyncio.run(checker._try_restart_managed(health))
+ finally:
+ if health.managed_control is not None:
+ health.managed_control.close()
assert events == ["start"]
assert config_svc.value == "ultra"
diff --git a/tests/unittest/test_doclib_lifespan.py b/tests/unittest/test_doclib_lifespan.py
index ac18b938..f75e59ad 100644
--- a/tests/unittest/test_doclib_lifespan.py
+++ b/tests/unittest/test_doclib_lifespan.py
@@ -2,13 +2,15 @@
from __future__ import annotations
-from doclib_test_utils import authenticated_doclib_config
+from doclib_test_utils import DOCLIB_AUTH_HEADERS, authenticated_doclib_config, create_doclib_server
import asyncio
from pathlib import Path
from types import SimpleNamespace
from typing import Any
+from unittest.mock import Mock
+import httpx
import pytest
from mineru.config import Config, LogConfig
@@ -243,3 +245,74 @@ def test_teardown_cancellation_waits_for_cleanup(tmp_path: Path, monkeypatch: py
assert events == ["watch.done", "db.close"]
asyncio.run(scenario())
+
+
[email protected]("complete_tier_restart", [True, False])
+def test_host_shutdown_after_tier_change_cleans_managed_process(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, complete_tier_restart: bool
+) -> None:
+ """标准宿主在档位切换前后收到停机请求时,均通过生命周期回收所属子进程。"""
+ cfg = authenticated_doclib_config(_configuration(tmp_path))
+ cfg.doclib.endpoint_path = str(tmp_path / "endpoint.json")
+ cfg.doclib.uds.enabled = False
+ cfg.doclib.tcp.enabled = True
+ cfg.doclib.tcp.port = 0
+ asyncio.run(_enable_managed(cfg))
+ processes = [Mock(pid=index) for index in (1, 2)]
+ start = Mock(side_effect=[(proc, "http://127.0.0.1:16580", None) for proc in processes])
+ stop = Mock()
+ kill = Mock()
+ monkeypatch.setattr(probes, "start_managed_parse_server", start)
+ monkeypatch.setattr(probes, "stop_managed_parse_server", stop)
+ monkeypatch.setattr("mineru.doclib.server.os.kill", kill)
+ monkeypatch.setattr("mineru.doclib.server._ensure_managed_parse_server_tier_available", Mock())
+ monkeypatch.setattr(doclib_app, "_create_background_task", Mock())
+
+ class Server:
+ """保留宿主与真实应用的组装路径,用受控循环替代网络服务等待。"""
+
+ def __init__(self, config: Any) -> None:
+ """保存标准入口传入的 ASGI 应用,等待停机回调设置退出标志。"""
+ self.app = config.app
+ self.should_exit = False
+
+ async def serve(self, *, sockets: list[object]) -> None:
+ """通过真实配置和停机路由触发关闭,再执行应用生命周期退出。"""
+ state = self.app.state.doclib_state
+ async with self.app.router.lifespan_context(self.app):
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=self.app), base_url="http://doclib", headers=DOCLIB_AUTH_HEADERS
+ ) as client:
+ changed = await client.put("/api/v1/configs/parse_server.local.managed_tier", json={"value": "advanced"})
+ assert changed.status_code == 200
+ if complete_tier_restart:
+ await state.health_check._try_restart_managed_for_tier_change(state.health, "advanced")
+ response = await client.post("/api/v1/server/shutdown")
+ assert response.status_code == 200
+ assert response.json()["accepted"] is True
+ assert self.should_exit is True
+ assert state.health.managed_proc is None
+ assert state.health.managed_control is None
+
+ monkeypatch.setattr(doclib_app.uvicorn, "Server", Server)
+ doclib_app._run_server(cfg)
+ assert start.call_count == (2 if complete_tier_restart else 1)
+ assert [call.args[0] for call in stop.call_args_list if call.args[0] is not None] == processes[: start.call_count]
+ assert not Path(cfg.doclib.endpoint_path).exists()
+ kill.assert_not_called()
+
+
+def test_embedded_shutdown_without_host_callback_reports_unavailable() -> None:
+ """未提供关闭回调的嵌入式宿主返回明确错误,避免终止承载它的 Python 进程。"""
+
+ async def scenario() -> None:
+ """通过真实 HTTP 路由检查缺少宿主回调时的公开错误响应。"""
+ server = create_doclib_server(SimpleNamespace(shutdown=None))
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=server.app), base_url="http://doclib", headers=DOCLIB_AUTH_HEADERS
+ ) as client:
+ response = await client.post("/api/v1/server/shutdown")
+ assert response.status_code == 500
+ assert response.json()["error"]["code"] == "service_unavailable"
+
+ asyncio.run(scenario())
diff --git a/tests/unittest/test_doclib_managed_tier_transition.py b/tests/unittest/test_doclib_managed_tier_transition.py
index c456b90e..847368f6 100644
--- a/tests/unittest/test_doclib_managed_tier_transition.py
+++ b/tests/unittest/test_doclib_managed_tier_transition.py
@@ -377,3 +377,68 @@ def test_transition_stays_unavailable_until_target_tier_is_ready(
assert exc.value.code == "engine_unavailable"
asyncio.run(_run())
+
+
[email protected]("retry", ["mode", "same_tier", "new_tier", "disable_enable"])
+def test_config_api_resets_exhausted_managed_recovery(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, retry: str) -> None:
+ """显式重设 managed 模式或档位可恢复熔断,重置预算后才允许新启动。"""
+
+ async def scenario() -> None:
+ """通过真实配置接口恢复故障服务,并验证启动采用当前有效档位。"""
+ _, server, _, health, checker = await _services(tmp_path, monkeypatch)
+ health.restart_count = 3
+ health.managed_restart_exhausted = True
+ health.local.probe = ProbeResult(error_code="parse_server_unavailable")
+ started = _mock_child_lifecycle(monkeypatch, health)
+ if retry == "disable_enable":
+ await server.set_config("parse_server.local.mode", ConfigSetRequest(value="disabled"))
+ if retry in {"mode", "disable_enable"}:
+ await server.set_config("parse_server.local.mode", ConfigSetRequest(value="managed"))
+ else:
+ tier = "standard" if retry == "new_tier" else "basic"
+ await server.set_config("parse_server.local.managed_tier", ConfigSetRequest(value=tier))
+ assert health.managed_restart_exhausted is False
+ assert health.restart_count == 0
+ assert checker._wakeup_event.is_set()
+ assert health.local.probe.healthy is False
+ await checker._try_restart_managed(health)
+ assert started == ["standard" if retry == "new_tier" else "basic"]
+ assert health.local_starting is True
+ assert health.restart_count == 1
+
+ asyncio.run(scenario())
+
+
[email protected]("mode", ["disabled", "self_hosted"])
+def test_leaving_managed_mode_invalidates_probe_and_releases_process(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str
+) -> None:
+ """模式切换立即撤销旧结果并唤醒回收,避免关闭 managed 后留下模型进程。"""
+
+ async def scenario() -> None:
+ """经配置 API 切换后运行真实健康循环,验证旧进程只回收一次。"""
+ _, server, _, health, checker = await _services(tmp_path, monkeypatch)
+ old_process = health.managed_proc
+ stopped: list[object] = []
+
+ def stop(process: object, **kwargs: object) -> None:
+ """记录模式切换交给清理入口的旧进程。"""
+ stopped.append(process)
+
+ async def probe(url: str, *, api_key: str | None = None) -> ProbeResult:
+ """探测完成后结束循环,验证停机清理先于后续探测。"""
+ checker.running = False
+ return ProbeResult()
+
+ monkeypatch.setattr("mineru.doclib.background.parse_server_health.stop_managed_parse_server", stop)
+ monkeypatch.setattr(checker, "_probe", probe)
+ await server.set_config("parse_server.local.mode", ConfigSetRequest(value=mode))
+ assert health.local_mode == mode
+ assert health.local.probe.healthy is False
+ assert checker._wakeup_event.is_set()
+ await checker.run()
+ assert stopped == [old_process]
+ assert health.managed_proc is None and health.managed_control is None
+ assert health.running_managed_tier is None
+
+ asyncio.run(scenario())
diff --git a/tests/unittest/test_managed_process_control.py b/tests/unittest/test_managed_process_control.py
index d92f7e00..3f3802c4 100644
--- a/tests/unittest/test_managed_process_control.py
+++ b/tests/unittest/test_managed_process_control.py
@@ -5,6 +5,8 @@ import subprocess
import sys
import threading
from pathlib import Path
+from types import TracebackType
+from unittest.mock import Mock
import pytest
@@ -101,3 +103,43 @@ watcher.close()
proc.kill()
proc.wait(timeout=2)
control.close()
+
+
+def test_managed_control_close_cannot_reinstall_accepted_connection() -> None:
+ """连接安装前关闭通道,监听线程恢复后必须关闭迟到连接并保持资源已释放。"""
+ entered = threading.Event()
+ release = threading.Event()
+ main_thread = threading.current_thread()
+ lock = threading.Lock()
+
+ class PausedWorkerLock:
+ """把监听线程暂停在加锁之前,让主线程确定性地先完成关闭。"""
+
+ def __enter__(self) -> None:
+ """监听线程首次加锁时等待,主线程关闭时可直接取得锁。"""
+ if threading.current_thread() is not main_thread and not entered.is_set():
+ entered.set()
+ assert release.wait(timeout=2)
+ lock.acquire()
+
+ def __exit__(
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None
+ ) -> None:
+ """释放底层锁,让关闭和安装连接继续按既定时序执行。"""
+ lock.release()
+
+ connection = Mock()
+ listener = Mock(accept=Mock(return_value=connection))
+ control = ManagedProcessControl(listener, "AF_PIPE", "test-only", b"test")
+ control._lock = PausedWorkerLock()
+ control.start_accepting()
+ try:
+ assert entered.wait(timeout=2)
+ control.close()
+ finally:
+ release.set()
+ control._accept_thread.join(timeout=2)
+ control.close()
+ assert not control._accept_thread.is_alive()
+ assert control._connection is None
+ connection.close.assert_called_once()
diff --git a/tests/unittest/test_parse_server_health.py b/tests/unittest/test_parse_server_health.py
index 841b44c5..eba550f3 100644
--- a/tests/unittest/test_parse_server_health.py
+++ b/tests/unittest/test_parse_server_health.py
@@ -3,7 +3,18 @@
from doclib_test_utils import create_health_check
+import asyncio
+import errno
+import logging
+import subprocess
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from mineru.doclib.background import parse_server_health as health_module
from mineru.doclib.background.parse_server_health import ParseServerHealthCheck
+from mineru.doclib.parse_server_state import ProbeResult
def _checker(interval_sec: int = 30) -> ParseServerHealthCheck:
@@ -41,3 +52,199 @@ def test_backoff_never_exceeds_normal_interval() -> None:
assert checker._next_interval_sec(1) == 5
assert checker._next_interval_sec(2) == 8
assert checker._next_interval_sec(0) == 8
+
+
[email protected]("failure", ["spawn", "readiness"])
+def test_restart_exhaustion_survives_config_reload_and_keeps_remote_probes(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, failure: str
+) -> None:
+ """真实循环连续失败后只熔断一次,后续配置刷新保留故障且远端探测继续。"""
+ checker = _checker(interval_sec=0)
+ checker.startup_timeout_sec = 0
+ health = checker.health
+ health.local_mode = "managed"
+ health.managed_tier = "standard"
+ config = {
+ "parse_server.local.mode": "managed",
+ "parse_server.local.managed_tier": "standard",
+ "parse_server.remote.url": "https://remote.example",
+ }
+ checker.config_svc = SimpleNamespace(get=AsyncMock(side_effect=config.get))
+ processes = [Mock(pid=index, poll=Mock(return_value=None)) for index in range(3)]
+ start = Mock(
+ side_effect=OSError(errno.EADDRINUSE, "occupied")
+ if failure == "spawn"
+ else [(proc, health.managed_url, None) for proc in processes]
+ )
+ stop = Mock()
+ monkeypatch.setattr(health_module, "start_managed_parse_server", start)
+ monkeypatch.setattr(health_module, "stop_managed_parse_server", stop)
+ remote_probes = 0
+ local_probes = 0
+
+ async def probe(url: str, *, api_key: str | None = None) -> ProbeResult:
+ """运行八轮后结束,远端始终可用且本地始终无法就绪。"""
+ nonlocal remote_probes, local_probes
+ if url == config["parse_server.remote.url"]:
+ remote_probes += 1
+ if remote_probes == 8:
+ checker.running = False
+ return ProbeResult(healthy=True, tiers=["standard"])
+ assert not health.managed_restart_exhausted
+ local_probes += 1
+ return ProbeResult(error_code="parse_server_unavailable", error_msg="simulated failure")
+
+ monkeypatch.setattr(checker, "_probe", probe)
+ with caplog.at_level(logging.ERROR, logger=health_module.logger.name):
+ asyncio.run(checker.run())
+
+ assert start.call_count == health_module.MAX_RESTART_ATTEMPTS
+ assert health.restart_count == health_module.MAX_RESTART_ATTEMPTS
+ assert health.managed_restart_exhausted is True
+ assert health.local_mode == config["parse_server.local.mode"] == "managed"
+ assert health.managed_proc is None and health.managed_control is None
+ assert health.running_managed_tier is None
+ assert health.local_starting is False and health.managed_tier_transition is False
+ assert health.local.probe.healthy is False
+ assert health.local.probe.error_code == "parse_server_unavailable"
+ assert "failed 3 restarts" in health.local.probe.error_msg
+ assert caplog.text.count("disabling automatic restarts") == 1
+ assert remote_probes == 8 and health.remote.probe.healthy is True
+ assert local_probes == (3 if failure == "spawn" else 4)
+ stopped = [call.args[0] for call in stop.call_args_list if call.args[0] is not None]
+ assert stopped == ([] if failure == "spawn" else processes)
+
+
+def test_exhausted_restart_retries_cleanup_without_losing_process(monkeypatch: pytest.MonkeyPatch) -> None:
+ """熔断回收失败时保留进程和控制通道,再次检查只回收残留资源。"""
+ checker = _checker()
+ health = checker.health
+ health.restart_count = health_module.MAX_RESTART_ATTEMPTS
+ process, control = Mock(), Mock()
+ health.managed_proc = process
+ health.managed_control = control
+ health.local_starting = True
+ health.managed_tier_transition = True
+ stop = Mock(side_effect=[RuntimeError("still alive"), None])
+ start = Mock()
+ monkeypatch.setattr(health_module, "stop_managed_parse_server", stop)
+ monkeypatch.setattr(health_module, "start_managed_parse_server", start)
+
+ asyncio.run(checker._try_restart_managed(health))
+ assert health.managed_restart_exhausted is True
+ assert health.managed_proc is process and health.managed_control is control
+ assert health.local_starting is False and health.managed_tier_transition is False
+ asyncio.run(checker._try_restart_managed(health))
+ assert health.managed_proc is None and health.managed_control is None
+ assert [call.args[0] for call in stop.call_args_list] == [process, process]
+ start.assert_not_called()
+
+
[email protected]("kill_fails", [True, False])
+def test_stop_managed_process_reports_unconfirmed_exit(kill_fails: bool) -> None:
+ """强杀失败或强杀后等待超时均向调用方报告失败,并关闭控制通道。"""
+ process = Mock(pid=123, poll=Mock(return_value=None))
+ process.wait.side_effect = subprocess.TimeoutExpired("parse-server", 0)
+ if kill_fails:
+ process.kill.side_effect = PermissionError("kill denied")
+ control = Mock(request_shutdown=Mock(return_value=False))
+
+ with pytest.raises(RuntimeError, match="did not stop"):
+ health_module.stop_managed_parse_server(process, control=control, timeout_sec=0, reason="test")
+
+ process.kill.assert_called_once()
+ control.close.assert_called_once()
+
+
+def test_failed_stop_retains_owned_process_and_prevents_replacement(monkeypatch: pytest.MonkeyPatch) -> None:
+ """旧进程回收失败时阻止创建新进程,应用退出仍能重试同一资源。"""
+ checker = _checker()
+ checker.config_svc = SimpleNamespace(get=AsyncMock(return_value="standard"))
+ health = checker.health
+ process, control = Mock(), Mock()
+ health.managed_proc = process
+ health.managed_control = control
+ start = Mock()
+ monkeypatch.setattr(health_module, "start_managed_parse_server", start)
+ monkeypatch.setattr(health_module, "stop_managed_parse_server", Mock(side_effect=RuntimeError("still alive")))
+
+ asyncio.run(checker._try_restart_managed(health))
+ start.assert_not_called()
+ assert health.managed_proc is process and health.managed_control is control
+ with pytest.raises(RuntimeError, match="still alive"):
+ asyncio.run(checker.stop())
+ assert health.managed_proc is process and health.managed_control is control
+
+
+def test_failed_tier_change_cleanup_is_bounded_by_restart_budget(monkeypatch: pytest.MonkeyPatch) -> None:
+ """切档回收失败也计入连续失败预算,避免旧进程仍在时无限绕过熔断。"""
+ checker = _checker()
+ checker.config_svc = SimpleNamespace(get=AsyncMock(return_value="advanced"))
+ health = checker.health
+ process = Mock()
+ health.managed_proc = process
+ health.running_managed_tier = "standard"
+ start = Mock()
+ monkeypatch.setattr(health_module, "start_managed_parse_server", start)
+ monkeypatch.setattr(health_module, "stop_managed_parse_server", Mock(side_effect=RuntimeError("still alive")))
+ for _attempt in range(health_module.MAX_RESTART_ATTEMPTS):
+ assert asyncio.run(checker._try_restart_managed_for_tier_change(health, "advanced")) is True
+ assert health.managed_restart_exhausted is True
+ assert health.restart_count == health_module.MAX_RESTART_ATTEMPTS
+ assert health.managed_proc is process
+ assert asyncio.run(checker._try_restart_managed_for_tier_change(health, "advanced")) is False
+ start.assert_not_called()
+
+
[email protected]("winerror", [10013, 10048, None])
[email protected]("strict_port", [True, False])
+def test_managed_port_selection_handles_windows_conflicts(
+ monkeypatch: pytest.MonkeyPatch, winerror: int | None, strict_port: bool
+) -> None:
+ """Windows 端口冲突在非严格模式下继续探测,普通权限错误仍直接报告。"""
+ error = PermissionError(errno.EACCES, "forbidden")
+ if winerror is not None:
+ error.winerror = winerror
+ sock = Mock()
+ sock.bind.side_effect = [error, None]
+ sock.getsockname.return_value = ("127.0.0.1", 16581)
+ monkeypatch.setattr(health_module.socket, "socket", Mock(return_value=sock))
+
+ if strict_port or winerror is None:
+ with pytest.raises(PermissionError) as caught:
+ health_module.select_available_managed_port("127.0.0.1", 16580, strict_port=strict_port, port_probe_count=3)
+ assert caught.value is error
+ assert sock.bind.call_count == 1
+ else:
+ selected = health_module.select_available_managed_port("127.0.0.1", 16580, strict_port=False, port_probe_count=3)
+ assert selected == 16581
+ assert [call.args[0][1] for call in sock.bind.call_args_list] == [16580, 16581]
+
+
+def test_managed_port_exhaustion_preserves_windows_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ """所有 Windows 候选端口被拒绝后报告范围耗尽,并保留最后的系统异常。"""
+ error = PermissionError(errno.EACCES, "forbidden")
+ error.winerror = 10013
+ sock = Mock(bind=Mock(side_effect=error))
+ monkeypatch.setattr(health_module.socket, "socket", Mock(return_value=sock))
+ with pytest.raises(RuntimeError, match="16580-16582") as caught:
+ health_module.select_available_managed_port("127.0.0.1", 16580, strict_port=False, port_probe_count=3)
+ assert caught.value.__cause__ is error
+ assert sock.bind.call_count == sock.close.call_count == 3
+
+
+def test_managed_start_closes_control_if_listener_thread_cannot_start(monkeypatch: pytest.MonkeyPatch) -> None:
+ """创建监听线程失败时也关闭控制通道,避免启动异常留下监听资源。"""
+ checker = _checker()
+ control = Mock(start_accepting=Mock(side_effect=RuntimeError("cannot start new thread")))
+ control.child_env.return_value = {}
+ monkeypatch.setattr(health_module, "select_available_managed_port", Mock(return_value=16580))
+ monkeypatch.setattr(health_module.ManagedProcessControl, "create", Mock(return_value=control))
+ popen = Mock()
+ monkeypatch.setattr(health_module.subprocess, "Popen", popen)
+ with pytest.raises(RuntimeError, match="cannot start new thread"):
+ health_module.start_managed_parse_server(
+ tier="standard", managed_cfg=checker.managed_parse_server, log_cfg=checker.log_cfg, marker="test"
+ )
+ control.close.assert_called_once()
+ popen.assert_not_called()