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: enforce single doclib owner per home
jinzhenj096e6c05e897
diff --git a/docs/next/architecture.md b/docs/next/architecture.mdindex 6a952873..f517797f 100644--- a/docs/next/architecture.md+++ b/docs/next/architecture.md@@ -338,14 +338,17 @@ doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都启动顺序:-1. 创建 `data_dir`。-2. 初始化 SQLite schema、migration 和种子配置。-3. 清理 stale ingest 锁。-4. 将崩溃前 `parsing` 状态任务标记为 `failed` 并释放锁。-5. 创建 services。-6. managed 模式下启动 local parse-server。-7. 启动后台 asyncio tasks。-8. 启动 UDS 上的 uvicorn。+1. 获取 `$MINERU_HOME/doclib.lock`,独占当前 home。+2. 清理 stale endpoint 和 UDS socket。+3. 原子写入包含当前 PID、`server_id` 和空 transports 的 endpoint,供启动阶段诊断。+4. 启动本地 HTTP transport,并用实际 transports 原子更新 endpoint。+5. 创建 `data_dir`。+6. 初始化 SQLite schema、migration 和种子配置。+7. 清理 stale ingest 锁。+8. 将崩溃前 `parsing` 状态任务标记为 `failed` 并释放锁。+9. 创建 services。+10. managed 模式下启动 local parse-server。+11. 启动后台 asyncio tasks。### 6.2 关闭@@ -354,7 +357,11 @@ doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都1. 通知后台任务停止,等待当前任务收尾。2. managed 模式下终止 local parse-server。3. 关闭数据库资源。-4. 保留 socket 和 endpoint discovery 文件,由下一次 CLI 启动在确认没有存活实例后清理。+4. 在仍持有 `doclib.lock` 时尝试清理 socket 和 endpoint discovery 文件。+5. 释放 `doclib.lock`;lock 文件本身是否保留属于平台实现细节。++CLI 的 stop/restart 同时等待 endpoint 不可连接和 ownership lock 可重新获取,并在临时持有该锁时兜底清理 discovery 文件;+不能只用 endpoint 消失判断 shutdown 完成。### 6.3 崩溃恢复diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.mdindex d600d8dc..824f0a7a 100644--- a/docs/next/cli/mineru-e2e-test-cases.md+++ b/docs/next/cli/mineru-e2e-test-cases.md@@ -450,8 +450,8 @@ unset MINERU_DOCLIB_UDS_ENABLED MINERU_DOCLIB_TCP_ENABLED MINERU_DOCLIB_TCP_PORT- status JSON 中 `tcp.port` 是大于 0 的实际端口,不应为 0- endpoint JSON 的 `transports` 只需包含 TCP transport,`base_url` 端口必须等于 status JSON 的 `tcp.port`- stop exit code = 0-- stop 后 `$MINERU_HOME/doclib.endpoint.json` 可以保留,后续 `mineru server status --json` 返回 `running=false`-- 再次 start 时会清理残留 endpoint,并写入新的 version 2 endpoint+- stop 后 `$MINERU_HOME/doclib.endpoint.json` 被清理;不检查 `doclib.lock` 文件是否保留+- 后续 `mineru server status --json` 返回 `running=false`### SERVER-015 endpoint stale 清理@@ -482,7 +482,7 @@ export MINERU_HOME="$MAIN_MINERU_HOME"- stop exit code = 0- stop 输出 `Server is not running` 或等价信息- stop 后 stale endpoint 文件仍然存在-- 后续 start 在创建子进程前清理 stale endpoint 和 UDS socket+- 后续 start 创建的 server 在取得 `doclib.lock` 后清理 stale endpoint 和 UDS socket### SERVER-016 endpoint server identity 校验@@ -511,6 +511,29 @@ export MINERU_HOME="$MAIN_MINERU_HOME"- replacement 写入 version 2 endpoint 和新的 `server_id`。- version 1 endpoint PID 与 status PID 不同时返回 `server_instance_mismatch`,且不发送 shutdown。+### SERVER-018 doclib home ownership lock++前置:++- 使用独立 `MINERU_HOME`。++步骤:++1. 通过 `mineru server start` 启动第一个 doclib。+2. 确认 `$MINERU_HOME/doclib.lock` 存在。+3. 使用相同环境直接执行第二个 `python -m mineru.doclib.app`。+4. 确认第二个进程立即失败,第一个 server 仍可通过 status 访问。+5. 强制终止第一个 server 进程,再次执行 `mineru server start`。++预期:++- 第二个进程 exit code 非 0,stderr 包含当前 home,但不显示 `doclib.lock` 路径。+- 第二个进程不删除第一个实例的 endpoint 或 UDS socket。+- endpoint 不可连接但 ownership lock 被占用时,status/start/stop 返回 `service_unavailable` 和统一的 home ownership 消息,+ 不得报告普通未运行状态;endpoint 含有效 PID 时,错误中包含 `reported PID <pid>`,但不自动终止进程。+- 第一个进程退出后 OS lock 自动释放;replacement 能取得 ownership、清理 stale discovery 文件并正常启动。+- `doclib.lock` 文件是否存在不表示 server 是否正在运行,其保留行为可能因平台而异。+## 4A. Telemetry 命令### TELEMETRY-001 telemetry help@@ -3606,6 +3629,7 @@ mineru server start- SERVER-015 endpoint stale 清理- SERVER-016 endpoint server identity 校验- SERVER-017 version 1 endpoint 升级迁移+- SERVER-018 doclib home ownership lock- SERVER-012 error summary 与 recent logs- SERVER-010 停止 serverdiff --git a/docs/next/cli/mineru-server.md b/docs/next/cli/mineru-server.mdindex 98616fd7..69ed7729 100644--- a/docs/next/cli/mineru-server.md+++ b/docs/next/cli/mineru-server.md@@ -25,13 +25,15 @@启动时:-1. 初始化数据目录和 SQLite。-2. 运行 migration 和默认配置种子。-3. 清理 stale lock 和崩溃前未完成任务。-4. 创建 services。-5. managed 模式下拉起 local parse-server。-6. 启动 watch、ingest、parse、health check、device monitor 和 compaction。-7. 通过 UDS 或 TCP loopback 提供本地 HTTP + JSON 协议。+1. 获取 `$MINERU_HOME/doclib.lock`,确保当前 home 只有一个 doclib owner。+2. 清理 stale endpoint 和 UDS socket。+3. 写入包含当前 PID、`server_id` 和空 transports 的启动阶段 endpoint。+4. 绑定 UDS/TCP listener,并用实际 transports 更新 endpoint。+5. 初始化数据目录和 SQLite。+6. 运行 migration 和默认配置种子。+7. 清理 stale task lock 和崩溃前未完成任务。+8. 创建 services,并按需拉起 managed local parse-server。+9. 启动 watch、ingest、parse、health check、device monitor 和 compaction。默认情况下,UDS 可用时使用 `$MINERU_HOME/doclib.sock`;UDS 不可用时自动启用 TCP loopback fallback。server 启动成功后会写入 `$MINERU_HOME/doclib.endpoint.json`,供 CLI / SDK 发现实际 endpoint。@@ -42,10 +44,19 @@1. 停止后台任务。2. managed 模式下停止 local parse-server。3. 关闭数据库资源。-4. 保留 socket 文件和 endpoint discovery 文件,由下一次 `mineru server start` 在确认没有存活实例后清理。+4. 在 ownership 保护下清理 socket 文件和 endpoint discovery 文件;CLI stop 在取得已释放的锁后执行兜底清理。+5. 释放 ownership lock;`doclib.lock` 文件是否保留取决于平台锁实现。-`mineru server stop` 会等待 server 确实不可连接后才返回成功。`restart` 只有在 stop 完成后才启动 replacement,避免两个-server 同时操作一个 MinerU home。+`mineru server stop` 会等待 server 不可连接且 `doclib.lock` 已释放后才返回成功。`restart` 只有在 stop 完成后才启动+replacement,避免两个 server 同时操作一个 MinerU home。++`doclib.start.lock` 只序列化 CLI spawn;`doclib.lock` 由 server 进程持有整个生命周期,是判断 home ownership 的唯一权威锁。+直接执行 `python -m mineru.doclib.app` 也必须获取该锁。未取得 ownership 的进程不得清理 endpoint、socket 或数据库状态;+lock 文件是否存在不能用于判断 ownership。++如果 endpoint 不可连接但 `doclib.lock` 仍被占用,status/start/stop 返回 `service_unavailable`,说明当前 home 已由另一个 doclib+server process 持有;如果 endpoint 中存在有效 PID,错误会将其标记为 `reported PID` 供诊断。用户消息不显示 lock 路径,PID+不参与 ownership 判断,CLI 也不会据此自动终止进程。不能将该状态降级为普通的“server 未运行”,也不能自动抢占或清理。## 4. 状态输出diff --git a/docs/next/decisions/0021-doclib-local-transport-discovery.md b/docs/next/decisions/0021-doclib-local-transport-discovery.mdindex 4957c514..6459308c 100644--- a/docs/next/decisions/0021-doclib-local-transport-discovery.md+++ b/docs/next/decisions/0021-doclib-local-transport-discovery.md@@ -121,11 +121,13 @@ $MINERU_HOME/doclib.endpoint.json规则:-- 只写入实际成功绑定的 transports。+- server 取得 ownership 并清理 stale discovery 后,先写入 PID、`server_id` 和空 transports;绑定完成后只写入实际成功绑定的+ transports。- `server_id` 是每次 server 启动生成的随机 UUID,并由 `/server/status` 返回。- TCP 使用随机端口时,`base_url` 必须写入真实端口。- 文件写入应使用 atomic write: 先写临时文件,再 `replace`。-- server shutdown / stop 时保留 endpoint;下一次 start 确认没有存活 server 后再删除并重建。+- server 持有 `$MINERU_HOME/doclib.lock` 时才能写入或清理 endpoint;正常 shutdown 在释放 ownership 前清理 endpoint。+- 崩溃残留的 endpoint 由下一个成功取得 `doclib.lock` 的 server 删除并重建,CLI spawn 进程不直接清理。- stale endpoint 文件不能被视为 server 一定运行;client 连接失败后仍应报 `ServerNotRunningError`。### Client 连接策略@@ -255,7 +257,9 @@ Server 影响:- server 启动时按 `uds.enabled` 和 `tcp.enabled` 分别创建 socket。- server 允许只启 TCP。-- server 启动时写入 `doclib.endpoint.json`;停止时保留 discovery 文件,由下一次 CLI 启动清理 stale 文件。+- server 自身持有 `$MINERU_HOME/doclib.lock`,取得 ownership 后才清理 stale discovery 文件并写入新 endpoint。+- 正常停止在释放 ownership 前清理 discovery 文件;异常退出的残留文件由下一个 owner 清理。+- endpoint PID 只用于诊断,不作为 ownership 或自动终止进程的依据。- UDS 不可用不再导致 config import 失败。Client / CLI 影响:@@ -275,7 +279,7 @@ Client / CLI 影响:- 增加 UDS 可用时默认只启 UDS 的配置测试。- 增加 UDS 不可用时默认启 TCP 的配置测试。- 增加 server 只启 TCP 的启动测试。-- 增加 endpoint 文件写入、随机端口写入、shutdown 保留与下次启动清理测试。+- 增加 endpoint 文件写入、随机端口写入、ownership 内 shutdown 清理与崩溃后恢复测试。- 增加 client resolver 优先 UDS、fallback TCP、stale endpoint 失败测试。- 更新 `MINERU_DOCLIB_HTTP_*` 相关测试为 `MINERU_DOCLIB_TCP_*`。diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.pyindex 9b9c0399..ba823398 100644--- a/mineru/cli/commands/server.py+++ b/mineru/cli/commands/server.py@@ -16,6 +16,7 @@ from rich.table import Tablefrom ...config import configfrom ...doclib.endpoint import remove_endpoint_file+from ...doclib.instance_lock import DoclibLockUnavailable, build_doclib_home_owned_message, doclib_home_lockfrom ...doclib.types import ServerStatusResponse, TCPServerStatusfrom ...errors import MineruErrorfrom ...version import __version__@@ -153,24 +154,41 @@ def _server_running() -> bool:return False-def _wait_for_server(timeout: float = 15.0) -> bool:+def _doclib_lock_available() -> bool:+ try:+ with doclib_home_lock():+ return True+ except DoclibLockUnavailable:+ return False+++def _home_owner_unavailable_error() -> MineruError:+ return MineruError("service_unavailable", build_doclib_home_owned_message())+++def _wait_for_started_server(proc: subprocess.Popen[bytes], timeout: float = 15.0) -> bool:deadline = time.time() + timeoutwhile time.time() < deadline:if _server_running():return True+ if proc.poll() is not None:+ return Falsetime.sleep(0.3)return False-def _wait_for_sock(timeout: float = 15.0) -> bool:- return _wait_for_server(timeout)--def _wait_for_server_stop(timeout: float = 15.0) -> bool:deadline = time.time() + timeoutwhile time.time() < deadline:if not _server_running():- return True+ try:+ with doclib_home_lock():+ if _server_running():+ continue+ _cleanup_local_endpoint_files()+ return True+ except DoclibLockUnavailable:+ passtime.sleep(0.3)return False@@ -196,8 +214,8 @@ def _start() -> str:with _ServerStartLock(_server_start_lock_path()) as start_lock:if not start_lock.acquired or _server_running():return "Server is already running."-- _cleanup_local_endpoint_files()+ if not _doclib_lock_available():+ raise _home_owner_unavailable_error()with open(log_path, "a", encoding="utf-8") as log_file:log_file.write("\n--- mineru server start ---\n")@@ -217,8 +235,9 @@ def _start() -> str:start_new_session=True,)- if not _wait_for_server():- proc.kill()+ if not _wait_for_started_server(proc):+ if proc.poll() is None:+ proc.kill()raise MineruError("service_unavailable","Server failed to start within 15 seconds. "@@ -243,6 +262,8 @@ def stop() -> None:def _stop() -> str:if not _server_running():+ if not _doclib_lock_available():+ raise _home_owner_unavailable_error()return "Server is not running."try:@@ -285,6 +306,8 @@ def status(json_mode: bool = typer.Option(False, "--json", help="JSON output"))def _server_status() -> ServerStatusResponse:if not _server_running():+ if not _doclib_lock_available():+ raise _home_owner_unavailable_error()return _not_running_status()from ...doclib.client import DoclibClientdiff --git a/mineru/doclib/__init__.py b/mineru/doclib/__init__.pyindex 72084c98..28ad3e3b 100644--- a/mineru/doclib/__init__.py+++ b/mineru/doclib/__init__.py@@ -1 +1,3 @@-# The local mineru document library.+"""The local MinerU document library."""++__all__: list[str] = []diff --git a/mineru/doclib/app.py b/mineru/doclib/app.pyindex 0865ea51..c8f82238 100644--- a/mineru/doclib/app.py+++ b/mineru/doclib/app.py@@ -21,7 +21,8 @@ from loguru import logger as loguru_loggerfrom ..config import Config, LogConfig, _mineru_home, configfrom ..errors import MineruError, error_response, http_status_for-from .endpoint import EndpointTransport, uds_available, write_endpoint_file+from .endpoint import EndpointTransport, remove_endpoint_file, uds_available, write_endpoint_file+from .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@@ -428,7 +429,15 @@ def _bind_tcp_socket(host: str, port: int, *, strict_port: bool, port_probe_coundef main() -> None:"""Entry point: python -m mineru.doclib.app"""- cfg = config+ try:+ with doclib_home_lock():+ _run_server(config)+ except DoclibLockUnavailable:+ raise SystemExit(build_doclib_home_owned_message()) from None+++def _run_server(cfg: Config) -> None:+ """Run the doclib server while the caller holds the home ownership lock."""uds_path = os.path.expanduser(cfg.doclib.uds.path)endpoint_path = os.path.expanduser(cfg.doclib.endpoint_path)uds_enabled = cfg.doclib.resolved_uds_enabled@@ -442,66 +451,84 @@ def main() -> None:"Enable doclib.tcp or disable doclib.uds.")- app = create_app(cfg)- uv_config = uvicorn.Config(- app,- log_config=None,- lifespan="on",- timeout_keep_alive=cfg.doclib.tcp.timeout,- )- server = uvicorn.Server(uv_config)-- sockets: list[socket.socket] = []- transports: list[EndpointTransport] = []-+ remove_endpoint_file(endpoint_path)if uds_enabled:try:os.unlink(uds_path)except OSError:pass- uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- uds_sock.bind(uds_path)- os.chmod(uds_path, cfg.doclib.uds.permission)- uds_sock.listen(cfg.doclib.tcp.backlog)- sockets.append(uds_sock)- transports.append(EndpointTransport(type="uds", path=uds_path))-- if tcp_enabled:- tcp_sock, port = _bind_tcp_socket(- cfg.doclib.tcp.host,- cfg.doclib.tcp.port,- strict_port=cfg.doclib.tcp.strict_port,- port_probe_count=cfg.doclib.tcp.port_probe_count,+ sockets: list[socket.socket] = []+ transports: list[EndpointTransport] = []+ loop: asyncio.AbstractEventLoop | None = None+ try:+ app = create_app(cfg)+ write_endpoint_file(+ endpoint_path,+ pid=os.getpid(),+ server_id=app.state.doclib_state.server_id,+ transports=[],)- if cfg.doclib.tcp.port != 0 and port != cfg.doclib.tcp.port:- print(f"Port {cfg.doclib.tcp.port} in use, using {port}")- tcp_sock.listen(cfg.doclib.tcp.backlog)- sockets.append(tcp_sock)- app.state.doclib_state.tcp_port = port- transports.append(EndpointTransport(type="tcp", base_url=f"http://{cfg.doclib.tcp.host}:{port}"))- else:- app.state.doclib_state.tcp_port = None-- write_endpoint_file(- endpoint_path,- pid=os.getpid(),- server_id=app.state.doclib_state.server_id,- transports=transports,- )- print("MinerU server listening on " + " and ".join(_format_transport(transport) for transport in transports))+ uv_config = uvicorn.Config(+ app,+ log_config=None,+ lifespan="on",+ timeout_keep_alive=cfg.doclib.tcp.timeout,+ )+ server = uvicorn.Server(uv_config)++ if uds_enabled:+ uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ uds_sock.bind(uds_path)+ os.chmod(uds_path, cfg.doclib.uds.permission)+ uds_sock.listen(cfg.doclib.tcp.backlog)+ sockets.append(uds_sock)+ transports.append(EndpointTransport(type="uds", path=uds_path))++ if tcp_enabled:+ tcp_sock, port = _bind_tcp_socket(+ cfg.doclib.tcp.host,+ cfg.doclib.tcp.port,+ strict_port=cfg.doclib.tcp.strict_port,+ port_probe_count=cfg.doclib.tcp.port_probe_count,+ )+ if cfg.doclib.tcp.port != 0 and port != cfg.doclib.tcp.port:+ print(f"Port {cfg.doclib.tcp.port} in use, using {port}")+ tcp_sock.listen(cfg.doclib.tcp.backlog)+ sockets.append(tcp_sock)+ app.state.doclib_state.tcp_port = port+ transports.append(EndpointTransport(type="tcp", base_url=f"http://{cfg.doclib.tcp.host}:{port}"))+ else:+ app.state.doclib_state.tcp_port = None++ write_endpoint_file(+ endpoint_path,+ pid=os.getpid(),+ server_id=app.state.doclib_state.server_id,+ transports=transports,+ )+ print("MinerU server listening on " + " and ".join(_format_transport(transport) for transport in transports))- loop = asyncio.new_event_loop()+ loop = asyncio.new_event_loop()- async def serve() -> None:- await server.serve(sockets=sockets)+ async def serve() -> None:+ await server.serve(sockets=sockets)- try:- loop.run_until_complete(serve())- except KeyboardInterrupt:- pass+ try:+ loop.run_until_complete(serve())+ except KeyboardInterrupt:+ passfinally:- _cancel_pending_loop_tasks(loop)- loop.close()+ if loop is not None:+ _cancel_pending_loop_tasks(loop)+ 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)def _setup_logging(log_cfg: LogConfig) -> None:diff --git a/mineru/doclib/instance_lock.py b/mineru/doclib/instance_lock.pynew file mode 100644index 00000000..e45122bc--- /dev/null+++ b/mineru/doclib/instance_lock.py@@ -0,0 +1,57 @@+"""Process-held ownership lock for a MinerU doclib home."""++from __future__ import annotations++from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path++from filelock import FileLock, Timeout++from ..config import _mineru_home+from .endpoint import ENDPOINT_VERSION, default_endpoint_path, read_endpoint_file++DOCLIB_LOCK_FILENAME = "doclib.lock"+++def default_doclib_lock_path() -> Path:+ """Return the non-configurable ownership lock path for this MinerU home."""+ return Path(_mineru_home()).expanduser() / DOCLIB_LOCK_FILENAME+++def build_doclib_home_owned_message() -> str:+ """Build the user-facing ownership message from current diagnostics."""+ home = default_doclib_lock_path().parent+ endpoint = read_endpoint_file(default_endpoint_path())+ pid = endpoint.pid if endpoint is not None and endpoint.version == ENDPOINT_VERSION else None+ pid_detail = f" (reported PID {pid})" if pid is not None else ""+ return f"MinerU home [{home}] is currently owned by another doclib server process{pid_detail}."+++class DoclibLockUnavailable(RuntimeError):+ """Internal control-flow marker for a doclib ownership conflict."""+++@contextmanager+def doclib_home_lock() -> Iterator[Path]:+ """Acquire and retain exclusive ownership of the current MinerU home."""+ lock_path = default_doclib_lock_path()+ lock_path.parent.mkdir(parents=True, exist_ok=True)+ lock = FileLock(str(lock_path))+ try:+ lock.acquire(timeout=0)+ except Timeout as exc:+ raise DoclibLockUnavailable() from exc+ try:+ yield lock_path+ finally:+ lock.release()+++__all__ = [+ "DOCLIB_LOCK_FILENAME",+ "DoclibLockUnavailable",+ "build_doclib_home_owned_message",+ "default_doclib_lock_path",+ "doclib_home_lock",+]diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.pyindex 87aa4700..b46d600b 100644--- a/tests/unittest/test_cli_next_command_design.py+++ b/tests/unittest/test_cli_next_command_design.py@@ -4,6 +4,8 @@ import jsonimport osimport shleximport sys+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any@@ -2053,6 +2055,9 @@ def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(moclass _Proc:pid = 12345+ def poll(self) -> None:+ return None+def kill(self) -> None:popen_calls.append({"kill": True})@@ -2068,7 +2073,8 @@ def test_server_start_failure_points_to_log_and_does_not_discard_child_stderr(moreturn _Proc()monkeypatch.setattr(server, "_server_running", lambda: False)- monkeypatch.setattr(server, "_wait_for_server", lambda: False)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: True)+ monkeypatch.setattr(server, "_wait_for_started_server", lambda proc: False)monkeypatch.setattr(server, "_socket_path", lambda: str(tmp_path / "doclib.sock"))monkeypatch.setattr(server, "_endpoint_path", lambda: str(tmp_path / "doclib.endpoint.json"))monkeypatch.setattr(server, "_server_log_path", lambda: str(log_path))@@ -2104,7 +2110,7 @@ def test_server_start_lock_blocks_concurrent_start(monkeypatch: Any, tmp_path: Passert not lock_path.exists()-def test_server_start_cleans_stale_discovery_files_before_spawn(monkeypatch: Any, tmp_path: Path) -> None:+def test_server_start_leaves_stale_discovery_files_for_child_owner(monkeypatch: Any, tmp_path: Path) -> None:socket_path = tmp_path / "doclib.sock"endpoint_path = tmp_path / "doclib.endpoint.json"socket_path.write_text("stale", encoding="utf-8")@@ -2114,12 +2120,13 @@ def test_server_start_cleans_stale_discovery_files_before_spawn(monkeypatch: Anypid = 12345def _popen(*args: Any, **kwargs: Any) -> _Proc:- assert not socket_path.exists()- assert not endpoint_path.exists()+ assert socket_path.exists()+ assert endpoint_path.exists()return _Proc()monkeypatch.setattr(server, "_server_running", lambda: False)- monkeypatch.setattr(server, "_wait_for_server", lambda: True)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: True)+ monkeypatch.setattr(server, "_wait_for_started_server", lambda proc: True)monkeypatch.setattr(server, "_socket_path", lambda: str(socket_path))monkeypatch.setattr(server, "_endpoint_path", lambda: str(endpoint_path))monkeypatch.setattr(server, "_server_start_lock_path", lambda: str(tmp_path / "doclib.start.lock"))@@ -2137,6 +2144,7 @@ def test_server_stop_leaves_stale_discovery_files_when_not_running(monkeypatch:socket_path.write_text("stale", encoding="utf-8")endpoint_path.write_text("{}", encoding="utf-8")monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: True)monkeypatch.setattr(server, "_socket_path", lambda: str(socket_path))monkeypatch.setattr(server, "_endpoint_path", lambda: str(endpoint_path))@@ -2145,6 +2153,53 @@ def test_server_stop_leaves_stale_discovery_files_when_not_running(monkeypatch:assert endpoint_path.exists()+def test_server_start_rejects_unresponsive_home_owner(monkeypatch: Any, tmp_path: Path) -> None:+ popen_calls: list[bool] = []++ class _Endpoint:+ version = 2+ pid = 12345++ monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: False)+ monkeypatch.setattr(server, "_server_start_lock_path", lambda: str(tmp_path / "doclib.start.lock"))+ monkeypatch.setattr(server, "_server_log_path", lambda: str(tmp_path / "doclib.log"))+ monkeypatch.setattr(server, "_server_stdout_log_path", lambda: str(tmp_path / "doclib.stdout.log"))+ monkeypatch.setattr(server, "_server_stderr_log_path", lambda: str(tmp_path / "doclib.stderr.log"))+ monkeypatch.setattr("mineru.doclib.instance_lock._mineru_home", lambda: str(tmp_path))+ monkeypatch.setattr(+ "mineru.doclib.instance_lock.read_endpoint_file",+ lambda path: _Endpoint(),+ )+ monkeypatch.setattr(server.subprocess, "Popen", lambda *args, **kwargs: popen_calls.append(True))++ with pytest.raises(MineruError) as exc_info:+ server._start()++ assert exc_info.value.code == "service_unavailable"+ assert exc_info.value.message == (+ f"MinerU home [{tmp_path}] is currently owned by another doclib server process (reported PID 12345)."+ )+ assert "doclib.lock" not in exc_info.value.message+ assert popen_calls == []+++def test_wait_for_server_stop_requires_ownership_release(monkeypatch: Any) -> None:+ events: list[str] = []++ @contextmanager+ def _home_lock() -> Iterator[None]:+ events.append("lock")+ yield++ monkeypatch.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"]++def test_server_stop_waits_until_shutdown_completes(monkeypatch: Any) -> None:events: list[str] = []@@ -2697,6 +2752,7 @@ def test_cleanup_temp_json_error_output_is_machine_readable(monkeypatch: Any) ->def test_server_status_json_not_running_returns_state_json(monkeypatch: Any) -> None:monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: True)monkeypatch.setattr(server, "_socket_path", lambda: "/tmp/doclib.sock")monkeypatch.setattr(server.config.doclib, "data_dir", "~/.mineru")monkeypatch.setattr(server.config.doclib.sqlite, "path", "~/.mineru/doclib.db")@@ -2718,3 +2774,20 @@ def test_server_status_json_not_running_returns_state_json(monkeypatch: Any) ->assert payload["stderr_log_path"] == os.path.expanduser("~/.mineru/logs/doclib.stderr.log")assert payload["tcp"] == {"enabled": False, "host": None, "port": None}assert "Server is not running." not in result.output+++def test_server_status_json_reports_unresponsive_home_owner(monkeypatch: Any, tmp_path: Path) -> None:+ monkeypatch.setattr(server, "_server_running", lambda: False)+ monkeypatch.setattr(server, "_doclib_lock_available", lambda: False)+ monkeypatch.setattr("mineru.doclib.instance_lock._mineru_home", lambda: str(tmp_path))+ monkeypatch.setattr("mineru.doclib.instance_lock.read_endpoint_file", lambda path: None)++ result = runner.invoke(app, ["server", "status", "--json"])++ assert result.exit_code == 1+ payload = json.loads(result.output)+ assert payload["error"]["code"] == "service_unavailable"+ assert payload["error"]["message"] == (+ f"MinerU home [{tmp_path}] is currently owned by another doclib server process."+ )+ assert "doclib.lock" not in payload["error"]["message"]diff --git a/tests/unittest/test_doclib_endpoint.py b/tests/unittest/test_doclib_endpoint.pyindex 33fd7160..9d92f91f 100644--- a/tests/unittest/test_doclib_endpoint.py+++ b/tests/unittest/test_doclib_endpoint.py@@ -95,6 +95,19 @@ def test_endpoint_pid_is_diagnostic_only(tmp_path: Path) -> None:)+def test_endpoint_file_accepts_empty_transports_during_startup(tmp_path: Path) -> None:+ endpoint = tmp_path / "doclib.endpoint.json"++ write_endpoint_file(endpoint, pid=123, server_id="server-123", transports=[])++ assert read_endpoint_file(endpoint) == EndpointInfo(+ version=ENDPOINT_VERSION,+ pid=123,+ server_id="server-123",+ transports=[],+ )++def test_read_endpoint_file_accepts_legacy_v1_with_pid(tmp_path: Path) -> None:endpoint = tmp_path / "doclib.endpoint.json"endpoint.write_text(diff --git a/tests/unittest/test_doclib_instance_lock.py b/tests/unittest/test_doclib_instance_lock.pynew file mode 100644index 00000000..7c0894b0--- /dev/null+++ b/tests/unittest/test_doclib_instance_lock.py@@ -0,0 +1,131 @@+from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++from mineru.config import PatchedConfig+from mineru.doclib import app as doclib_app+from mineru.doclib import instance_lock+from mineru.doclib.endpoint import write_endpoint_file+++def test_default_doclib_lock_path_is_fixed_under_mineru_home(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(instance_lock, "_mineru_home", lambda: str(tmp_path))++ assert instance_lock.default_doclib_lock_path() == tmp_path / "doclib.lock"+++def test_doclib_home_lock_blocks_another_holder_and_releases(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(instance_lock, "_mineru_home", lambda: str(tmp_path))++ with instance_lock.doclib_home_lock() as lock_path:+ assert lock_path == tmp_path / "doclib.lock"+ assert lock_path.is_file()+ with pytest.raises(instance_lock.DoclibLockUnavailable) as exc_info:+ with instance_lock.doclib_home_lock():+ pass++ assert exc_info.value.args == ()+ with instance_lock.doclib_home_lock():+ pass+++def test_doclib_home_lock_is_released_after_owner_is_killed(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ script = """+from mineru.doclib.instance_lock import doclib_home_lock+with doclib_home_lock():+ print("locked", flush=True)+ input()+"""+ env = os.environ.copy()+ env["MINERU_HOME"] = str(tmp_path)+ monkeypatch.setenv("MINERU_HOME", str(tmp_path))+ proc = subprocess.Popen(+ [sys.executable, "-c", script],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ env=env,+ )+ try:+ assert proc.stdout is not None+ assert proc.stdout.readline().strip() == "locked"+ with pytest.raises(instance_lock.DoclibLockUnavailable):+ with instance_lock.doclib_home_lock():+ pass+ finally:+ proc.kill()+ proc.wait(timeout=5)++ with instance_lock.doclib_home_lock():+ pass+++def test_doclib_main_exits_before_startup_when_home_lock_is_held(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ monkeypatch.setattr(instance_lock, "_mineru_home", lambda: str(tmp_path))+ endpoint_path = tmp_path / "doclib.endpoint.json"+ socket_path = tmp_path / "doclib.sock"+ write_endpoint_file(endpoint_path, pid=12345, server_id="server-123", transports=[])+ endpoint_contents = endpoint_path.read_text(encoding="utf-8")+ socket_path.write_text("owned socket", encoding="utf-8")+ cfg = PatchedConfig(+ doclib={+ "endpoint_path": str(endpoint_path),+ "uds": {"path": str(socket_path)},+ }+ )+ monkeypatch.setattr(doclib_app, "config", cfg)+ monkeypatch.setattr(instance_lock, "default_endpoint_path", lambda: str(endpoint_path))++ with instance_lock.doclib_home_lock():+ with pytest.raises(SystemExit) as exc_info:+ doclib_app.main()++ message = str(exc_info.value)+ assert message == f"MinerU home [{tmp_path}] is currently owned by another doclib server process (reported PID 12345)."+ assert "doclib.lock" not in message+ assert endpoint_path.read_text(encoding="utf-8") == endpoint_contents+ assert socket_path.read_text(encoding="utf-8") == "owned socket"+++def test_run_server_writes_owner_endpoint_before_binding_transport(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ endpoint_path = tmp_path / "doclib.endpoint.json"+ cfg = PatchedConfig(+ doclib={+ "endpoint_path": str(endpoint_path),+ "uds": {"enabled": False, "path": str(tmp_path / "doclib.sock")},+ "tcp": {"enabled": True},+ }+ )+ app = SimpleNamespace(state=SimpleNamespace(doclib_state=SimpleNamespace(server_id="server-123")))+ writes: list[dict[str, object]] = []++ monkeypatch.setattr(doclib_app, "create_app", lambda cfg: app)+ monkeypatch.setattr(doclib_app.uvicorn, "Config", lambda *args, **kwargs: object())+ monkeypatch.setattr(doclib_app.uvicorn, "Server", lambda cfg: object())++ def _write_endpoint(path: str, *, pid: int, server_id: str, transports: list[object]) -> None:+ writes.append({"path": path, "pid": pid, "server_id": server_id, "transports": transports})++ def _fail_bind(*args: object, **kwargs: object) -> None:+ assert writes == [+ {+ "path": str(endpoint_path),+ "pid": os.getpid(),+ "server_id": "server-123",+ "transports": [],+ }+ ]+ raise RuntimeError("bind failed")++ monkeypatch.setattr(doclib_app, "write_endpoint_file", _write_endpoint)+ monkeypatch.setattr(doclib_app, "_bind_tcp_socket", _fail_bind)++ with pytest.raises(RuntimeError, match="bind failed"):+ doclib_app._run_server(cfg)