Skip to content

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

fix: handle legacy doclib server shutdown

jinzhenj9535a7bcf65d
diff --git a/docs/next/architecture.md b/docs/next/architecture.md
index 624c068e..6a952873 100644
--- a/docs/next/architecture.md
+++ b/docs/next/architecture.md
@@ -354,7 +354,7 @@ doclib 不在 `parsed/` 中保存 Markdown、Content List 或 HTML。它们都
1. 通知后台任务停止,等待当前任务收尾。
2. managed 模式下终止 local parse-server。
3. 关闭数据库资源。
-4. 删除 socket 文件。
+4. 保留 socket 和 endpoint discovery 文件,由下一次 CLI 启动在确认没有存活实例后清理。
### 6.3 崩溃恢复
diff --git a/docs/next/cli/mineru-e2e-test-cases.md b/docs/next/cli/mineru-e2e-test-cases.md
index bbd0e909..d600d8dc 100644
--- a/docs/next/cli/mineru-e2e-test-cases.md
+++ b/docs/next/cli/mineru-e2e-test-cases.md
@@ -450,7 +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`
+- stop 后 `$MINERU_HOME/doclib.endpoint.json` 可以保留,后续 `mineru server status --json` 返回 `running=false`
+- 再次 start 时会清理残留 endpoint,并写入新的 version 2 endpoint
### SERVER-015 endpoint stale 清理
@@ -480,7 +481,8 @@ export MINERU_HOME="$MAIN_MINERU_HOME"
- status JSON 返回 `running=false`,不因 stale endpoint 输出 Python traceback
- stop exit code = 0
- stop 输出 `Server is not running` 或等价信息
-- stop 后 stale endpoint 文件被 best-effort 清理
+- stop 后 stale endpoint 文件仍然存在
+- 后续 start 在创建子进程前清理 stale endpoint 和 UDS socket
### SERVER-016 endpoint server identity 校验
@@ -495,6 +497,20 @@ export MINERU_HOME="$MAIN_MINERU_HOME"
- 不向主测试 HOME 的 server 发送业务请求或 shutdown 请求。
- 没有其他匹配 transport 时返回 `server_instance_mismatch`,或由 `server status` 表示当前 HOME 的 server 未运行。
+### SERVER-017 version 1 endpoint 升级迁移
+
+前置:
+
+- 使用独立 `MINERU_HOME` 启动 server。
+- 将 endpoint 改写为 version 1,保留原 PID 和 transports,删除 `server_id`。
+
+预期:
+
+- `mineru server status --json` 通过 endpoint/status PID 对应关系识别旧格式 server。
+- `mineru server restart` 先等待旧实例完全退出,再启动 replacement。
+- replacement 写入 version 2 endpoint 和新的 `server_id`。
+- version 1 endpoint PID 与 status PID 不同时返回 `server_instance_mismatch`,且不发送 shutdown。
+
## 4A. Telemetry 命令
### TELEMETRY-001 telemetry help
@@ -3589,6 +3605,7 @@ mineru server start
- SERVER-014 TCP-only fallback
- SERVER-015 endpoint stale 清理
- SERVER-016 endpoint server identity 校验
+- SERVER-017 version 1 endpoint 升级迁移
- SERVER-012 error summary 与 recent logs
- SERVER-010 停止 server
diff --git a/docs/next/cli/mineru-server.md b/docs/next/cli/mineru-server.md
index 0a0e4726..98616fd7 100644
--- a/docs/next/cli/mineru-server.md
+++ b/docs/next/cli/mineru-server.md
@@ -42,7 +42,10 @@
1. 停止后台任务。
2. managed 模式下停止 local parse-server。
3. 关闭数据库资源。
-4. 删除 socket 文件和 endpoint discovery 文件。
+4. 保留 socket 文件和 endpoint discovery 文件,由下一次 `mineru server start` 在确认没有存活实例后清理。
+
+`mineru server stop` 会等待 server 确实不可连接后才返回成功。`restart` 只有在 stop 完成后才启动 replacement,避免两个
+server 同时操作一个 MinerU home。
## 4. 状态输出
diff --git a/docs/next/decisions/0021-doclib-local-transport-discovery.md b/docs/next/decisions/0021-doclib-local-transport-discovery.md
index 4ad4b28c..4957c514 100644
--- a/docs/next/decisions/0021-doclib-local-transport-discovery.md
+++ b/docs/next/decisions/0021-doclib-local-transport-discovery.md
@@ -125,7 +125,7 @@ $MINERU_HOME/doclib.endpoint.json
- `server_id` 是每次 server 启动生成的随机 UUID,并由 `/server/status` 返回。
- TCP 使用随机端口时,`base_url` 必须写入真实端口。
- 文件写入应使用 atomic write: 先写临时文件,再 `replace`。
-- server shutdown / stop 时 best-effort 删除该文件。
+- server shutdown / stop 时保留 endpoint;下一次 start 确认没有存活 server 后再删除并重建。
- stale endpoint 文件不能被视为 server 一定运行;client 连接失败后仍应报 `ServerNotRunningError`。
### Client 连接策略
@@ -173,7 +173,8 @@ DOCLIB_UDS_BASE_URL = "http://mineru"
4. endpoint 中同时存在 UDS 和 TCP 时,优先尝试 UDS。
5. UDS 不存在、不可用或连接失败时,尝试 TCP。
6. endpoint 不存在、无效或不包含可用 transport 时,不根据当前 config 推导 transport。
-7. 第一次使用候选 transport 前,通过 `/server/status` 校验其 `server_id` 与 endpoint 一致。
+7. 第一次使用候选 transport 前,通过 `/server/status` 校验身份:version 2 比较 `server_id`;version 1
+ 仅作为升级迁移格式,比较 endpoint PID 与 status PID。
8. 身份不匹配时继续尝试下一个 transport;所有候选均不匹配时抛出 `server_instance_mismatch`。
9. 没有候选 endpoint 或所有候选 endpoint 都无法连接时,抛 `ServerNotRunningError`。
@@ -185,6 +186,7 @@ CLI 的 `server status`、`server stop` 和业务命令都应使用同一套 res
状态模型中的 `http` 字段改为 `tcp`,CLI human-readable 输出也显示 `TCP`。状态中的 `server_id` 标识当前
server 进程,并用于默认 endpoint discovery 的身份校验;`pid` 和 `mineru_home` 只用于诊断。
+version 1 endpoint 是例外:由于旧格式没有 `server_id`,PID 仅在停止和迁移旧 server 时承担临时身份校验。
`server status --json` 应继续返回:
@@ -253,7 +255,7 @@ Server 影响:
- server 启动时按 `uds.enabled` 和 `tcp.enabled` 分别创建 socket。
- server 允许只启 TCP。
-- server 写入并清理 `doclib.endpoint.json`。
+- server 启动时写入 `doclib.endpoint.json`;停止时保留 discovery 文件,由下一次 CLI 启动清理 stale 文件。
- UDS 不可用不再导致 config import 失败。
Client / CLI 影响:
@@ -273,7 +275,7 @@ Client / CLI 影响:
- 增加 UDS 可用时默认只启 UDS 的配置测试。
- 增加 UDS 不可用时默认启 TCP 的配置测试。
- 增加 server 只启 TCP 的启动测试。
-- 增加 endpoint 文件写入、随机端口写入、shutdown 清理测试。
+- 增加 endpoint 文件写入、随机端口写入、shutdown 保留与下次启动清理测试。
- 增加 client resolver 优先 UDS、fallback TCP、stale endpoint 失败测试。
- 更新 `MINERU_DOCLIB_HTTP_*` 相关测试为 `MINERU_DOCLIB_TCP_*`。
diff --git a/docs/next/sdk/doclib-client.md b/docs/next/sdk/doclib-client.md
index c8c383c1..c4f04dd4 100644
--- a/docs/next/sdk/doclib-client.md
+++ b/docs/next/sdk/doclib-client.md
@@ -48,6 +48,7 @@ class DoclibClient:
- 默认通过 `$MINERU_HOME/doclib.endpoint.json` 发现 doclib endpoint。
- 默认发现不从启动配置推导 UDS 或 TCP;endpoint 文件不存在或无效时,方法调用抛出 `ServerNotRunningError`。
- 默认发现会在首次请求前校验 endpoint 与 `/server/status` 的 `server_id`;不匹配的 transport 不会承载业务请求。
+- version 1 endpoint 仅用于升级迁移,通过 endpoint/status PID 对应关系识别旧 server;version 2 的 PID 不参与身份判断。
- `socket_path` 表示显式 UDS endpoint;`base_url` 只表示显式 TCP endpoint,例如 `http://127.0.0.1:15980`。
- 显式 `socket_path` / `base_url` 代表调用方明确选择的 server,不执行 endpoint `server_id` 校验。
- `socket_path` 和 `base_url` 不能同时传入。
diff --git a/docs/plans/2026-07-21-doclib-legacy-server-shutdown-design.md b/docs/plans/2026-07-21-doclib-legacy-server-shutdown-design.md
index 84688b00..ebc0f725 100644
--- a/docs/plans/2026-07-21-doclib-legacy-server-shutdown-design.md
+++ b/docs/plans/2026-07-21-doclib-legacy-server-shutdown-design.md
@@ -32,7 +32,7 @@ then binds its socket and atomically writes a fresh version 2 endpoint.
A version 1 endpoint whose PID differs from server status is rejected as
`server_instance_mismatch`. A shutdown that does not complete within the
-configured wait period fails with `service_unavailable` and does not start a
+15-second wait period fails with `service_unavailable` and does not start a
replacement.
## Verification
diff --git a/mineru/cli/commands/server.py b/mineru/cli/commands/server.py
index cedc8253..9b9c0399 100644
--- a/mineru/cli/commands/server.py
+++ b/mineru/cli/commands/server.py
@@ -166,6 +166,15 @@ 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() + timeout
+ while time.time() < deadline:
+ if not _server_running():
+ return True
+ time.sleep(0.3)
+ return False
+
+
@app.command()
def start() -> None:
"""Start the mineru server in the background."""
@@ -188,13 +197,7 @@ def _start() -> str:
if not start_lock.acquired or _server_running():
return "Server is already running."
- socket_path = _socket_path()
- # Clean stale socket
- try:
- os.unlink(socket_path)
- except OSError:
- pass
- remove_endpoint_file(_endpoint_path())
+ _cleanup_local_endpoint_files()
with open(log_path, "a", encoding="utf-8") as log_file:
log_file.write("\n--- mineru server start ---\n")
@@ -240,7 +243,6 @@ def stop() -> None:
def _stop() -> str:
if not _server_running():
- _cleanup_local_endpoint_files()
return "Server is not running."
try:
@@ -248,11 +250,14 @@ def _stop() -> str:
c = DoclibClient(timeout=5)
c.shutdown_server()
- except Exception:
- pass
+ except Exception as exc:
+ raise MineruError("service_unavailable", f"Failed to request MinerU server shutdown: {exc}") from exc
- time.sleep(0.5)
- _cleanup_local_endpoint_files()
+ if not _wait_for_server_stop():
+ raise MineruError(
+ "service_unavailable",
+ "MinerU server did not stop within 15 seconds. The server was not restarted.",
+ )
return "Server stopped."
@@ -266,7 +271,6 @@ def restart() -> None:
def _restart() -> str:
if _server_running():
stop_message = _stop()
- time.sleep(1)
start_message = _start()
return f"{stop_message}\n{start_message}"
return _start()
diff --git a/mineru/doclib/app.py b/mineru/doclib/app.py
index dd8cf47e..0865ea51 100644
--- a/mineru/doclib/app.py
+++ b/mineru/doclib/app.py
@@ -21,7 +21,7 @@ from loguru import logger as loguru_logger
from ..config import Config, LogConfig, _mineru_home, config
from ..errors import MineruError, error_response, http_status_for
-from .endpoint import EndpointTransport, remove_endpoint_file, uds_available, write_endpoint_file
+from .endpoint import EndpointTransport, uds_available, write_endpoint_file
from .server import DoclibServer
from .types import PARSE_STATUS_FAILED, PARSE_STATUS_PARSING, SCAN_STATUS_FAILED, SCAN_STATUS_RUNNING
@@ -500,12 +500,6 @@ def main() -> None:
except KeyboardInterrupt:
pass
finally:
- if uds_enabled:
- try:
- os.unlink(uds_path)
- except OSError:
- pass
- remove_endpoint_file(endpoint_path)
_cancel_pending_loop_tasks(loop)
loop.close()
diff --git a/mineru/doclib/client.py b/mineru/doclib/client.py
index 6a1d3fc7..de73196a 100644
--- a/mineru/doclib/client.py
+++ b/mineru/doclib/client.py
@@ -15,6 +15,7 @@ from ..types import Tier
from .base import DoclibInterface
from .endpoint import (
DOCLIB_UDS_BASE_URL,
+ EndpointInfo,
EndpointTransport,
default_endpoint_path,
read_endpoint_file,
@@ -102,7 +103,7 @@ class DoclibClient(DoclibInterface):
) -> None:
if socket_path is not None and base_url is not None:
raise ValueError("socket_path and base_url cannot both be provided.")
- self._clients, self._expected_server_id = _build_clients(
+ self._clients, self._expected_endpoint = _build_clients(
endpoint_path=endpoint_path,
socket_path=socket_path,
base_url=base_url,
@@ -456,9 +457,9 @@ class DoclibClient(DoclibInterface):
raise ServerNotRunningError() from None
def _validate_server_instance(self, client: httpx.Client) -> None:
- expected_server_id = self._expected_server_id
+ expected_endpoint = self._expected_endpoint
client_id = id(client)
- if expected_server_id is None or client_id in self._validated_client_ids:
+ if expected_endpoint is None or client_id in self._validated_client_ids:
return
resp = client.get(
@@ -467,8 +468,11 @@ class DoclibClient(DoclibInterface):
headers=self._telemetry_headers(),
)
data = _decode_response(resp)
- actual_server_id = data.get("server_id")
- if actual_server_id != expected_server_id:
+ if expected_endpoint.server_id is not None:
+ identity_matches = data.get("server_id") == expected_endpoint.server_id
+ else:
+ identity_matches = data.get("pid") == expected_endpoint.pid
+ if not identity_matches:
raise _ServerInstanceMismatch()
self._validated_client_ids.add(client_id)
@@ -512,7 +516,7 @@ def _build_clients(
socket_path: str | Path | None,
base_url: str | None,
timeout: int,
-) -> tuple[list[httpx.Client], str | None]:
+) -> tuple[list[httpx.Client], EndpointInfo | None]:
if socket_path is not None:
client = _client_for_transport(EndpointTransport(type="uds", path=str(socket_path)), timeout=timeout)
return ([client] if client is not None else [], None)
@@ -530,7 +534,7 @@ def _build_clients(
client = _client_for_transport(transport, timeout=timeout)
if client is not None:
clients.append(client)
- return clients, endpoint.server_id
+ return clients, endpoint
def _client_for_transport(transport: EndpointTransport, *, timeout: int) -> httpx.Client | None:
diff --git a/mineru/doclib/endpoint.py b/mineru/doclib/endpoint.py
index 70785c30..e2cd63c4 100644
--- a/mineru/doclib/endpoint.py
+++ b/mineru/doclib/endpoint.py
@@ -25,12 +25,13 @@ class EndpointTransport:
class EndpointInfo:
version: int
pid: int | None
- server_id: str
+ server_id: str | None
transports: list[EndpointTransport]
DOCLIB_UDS_BASE_URL = "http://mineru"
ENDPOINT_VERSION = 2
+LEGACY_ENDPOINT_VERSION = 1
def uds_available() -> bool:
@@ -83,12 +84,23 @@ def read_endpoint_file(path: str | os.PathLike[str]) -> EndpointInfo | None:
pid = payload.get("pid")
server_id = payload.get("server_id")
transports = payload.get("transports")
- if version != ENDPOINT_VERSION or not isinstance(server_id, str) or not server_id or not isinstance(transports, list):
+ if not isinstance(transports, list):
+ return None
+ parsed_pid = pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None
+ if version == LEGACY_ENDPOINT_VERSION:
+ if parsed_pid is None:
+ return None
+ parsed_server_id = None
+ elif version == ENDPOINT_VERSION:
+ if not isinstance(server_id, str) or not server_id:
+ return None
+ parsed_server_id = server_id
+ else:
return None
return EndpointInfo(
version=version,
- pid=pid if isinstance(pid, int) and not isinstance(pid, bool) and pid > 0 else None,
- server_id=server_id,
+ pid=parsed_pid,
+ server_id=parsed_server_id,
transports=[_parse_transport(item) for item in transports if isinstance(item, dict)],
)
@@ -113,6 +125,7 @@ def _parse_transport(item: dict[str, Any]) -> EndpointTransport:
__all__ = [
"DOCLIB_UDS_BASE_URL",
"ENDPOINT_VERSION",
+ "LEGACY_ENDPOINT_VERSION",
"EndpointInfo",
"EndpointTransport",
"default_endpoint_path",
diff --git a/tests/unittest/test_cli_next_command_design.py b/tests/unittest/test_cli_next_command_design.py
index 88370675..87aa4700 100644
--- a/tests/unittest/test_cli_next_command_design.py
+++ b/tests/unittest/test_cli_next_command_design.py
@@ -54,7 +54,7 @@ from mineru.doclib.types import (
WatchInfo,
WatchListResponse,
)
-from mineru.errors import ServerNotRunningError
+from mineru.errors import MineruError, ServerNotRunningError
from mineru.filetypes import FILE_TYPE_BY_EXTENSION
from mineru.version import __version__
@@ -2104,6 +2104,87 @@ def test_server_start_lock_blocks_concurrent_start(monkeypatch: Any, tmp_path: P
assert not lock_path.exists()
+def test_server_start_cleans_stale_discovery_files_before_spawn(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")
+ endpoint_path.write_text("{}", encoding="utf-8")
+
+ class _Proc:
+ pid = 12345
+
+ def _popen(*args: Any, **kwargs: Any) -> _Proc:
+ assert not socket_path.exists()
+ assert not endpoint_path.exists()
+ return _Proc()
+
+ monkeypatch.setattr(server, "_server_running", lambda: False)
+ monkeypatch.setattr(server, "_wait_for_server", lambda: 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"))
+ 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(server.subprocess, "Popen", _popen)
+
+ assert server._start() == "Server started (PID 12345)."
+
+
+def test_server_stop_leaves_stale_discovery_files_when_not_running(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")
+ endpoint_path.write_text("{}", encoding="utf-8")
+ monkeypatch.setattr(server, "_server_running", lambda: False)
+ monkeypatch.setattr(server, "_socket_path", lambda: str(socket_path))
+ monkeypatch.setattr(server, "_endpoint_path", lambda: str(endpoint_path))
+
+ assert server._stop() == "Server is not running."
+ assert socket_path.exists()
+ assert endpoint_path.exists()
+
+
+def test_server_stop_waits_until_shutdown_completes(monkeypatch: Any) -> None:
+ events: list[str] = []
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ assert timeout == 5
+
+ def shutdown_server(self) -> None:
+ events.append("shutdown")
+
+ monkeypatch.setattr(server, "_server_running", lambda: True)
+ monkeypatch.setattr(server, "_wait_for_server_stop", lambda: events.append("wait") or True)
+ monkeypatch.setattr("mineru.doclib.client.DoclibClient", _Client)
+
+ assert server._stop() == "Server stopped."
+ assert events == ["shutdown", "wait"]
+
+
+def test_server_stop_timeout_does_not_start_replacement(monkeypatch: Any) -> None:
+ starts: list[bool] = []
+
+ class _Client:
+ def __init__(self, *, timeout: int) -> None:
+ pass
+
+ def shutdown_server(self) -> None:
+ pass
+
+ monkeypatch.setattr(server, "_server_running", lambda: True)
+ monkeypatch.setattr(server, "_wait_for_server_stop", lambda: False)
+ monkeypatch.setattr(server, "_start", lambda: starts.append(True) or "started")
+ monkeypatch.setattr("mineru.doclib.client.DoclibClient", _Client)
+
+ with pytest.raises(MineruError) as exc_info:
+ server._restart()
+
+ assert exc_info.value.code == "service_unavailable"
+ assert starts == []
+
+
def test_parse_content_read_failure_exits_nonzero(monkeypatch: Any, tmp_path: Path) -> None:
source = tmp_path / "demo.txt"
source.write_text("hello", encoding="utf-8")
diff --git a/tests/unittest/test_doclib_endpoint.py b/tests/unittest/test_doclib_endpoint.py
index f8be46b0..33fd7160 100644
--- a/tests/unittest/test_doclib_endpoint.py
+++ b/tests/unittest/test_doclib_endpoint.py
@@ -19,9 +19,10 @@ from mineru.doclib.endpoint import (
from mineru.errors import MineruError, ServerNotRunningError
-def _status_payload(server_id: str) -> dict[str, object]:
+def _status_payload(server_id: str, pid: int) -> dict[str, object]:
return {
"running": True,
+ "pid": pid,
"server_id": server_id,
"socket_path": "",
"data_dir": "",
@@ -31,13 +32,14 @@ def _status_payload(server_id: str) -> dict[str, object]:
class _FakeClient:
- def __init__(self, server_id: str) -> None:
+ def __init__(self, server_id: str, *, pid: int = 123) -> None:
self.server_id = server_id
+ self.pid = pid
self.paths: list[str] = []
def get(self, path: str, *, params: dict | None = None, headers: dict | None = None) -> httpx.Response:
self.paths.append(path)
- return httpx.Response(200, json=_status_payload(self.server_id), request=httpx.Request("GET", path))
+ return httpx.Response(200, json=_status_payload(self.server_id, self.pid), request=httpx.Request("GET", path))
def close(self) -> None:
pass
@@ -93,6 +95,27 @@ def test_endpoint_pid_is_diagnostic_only(tmp_path: Path) -> None:
)
+def test_read_endpoint_file_accepts_legacy_v1_with_pid(tmp_path: Path) -> None:
+ endpoint = tmp_path / "doclib.endpoint.json"
+ endpoint.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "pid": 123,
+ "transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}],
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ assert read_endpoint_file(endpoint) == EndpointInfo(
+ version=1,
+ pid=123,
+ server_id=None,
+ transports=[EndpointTransport(type="tcp", base_url="http://127.0.0.1:15980")],
+ )
+
+
def test_doclib_client_rejects_explicit_uds_and_tcp() -> None:
with pytest.raises(ValueError, match="socket_path and base_url"):
DoclibClient(socket_path="/tmp/doclib.sock", base_url="http://127.0.0.1:15980")
@@ -166,7 +189,7 @@ def test_doclib_client_discovers_uds_then_tcp(monkeypatch: pytest.MonkeyPatch, t
None,
"{}",
"not json",
- json.dumps({"version": 1, "pid": 123, "transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}]}),
+ json.dumps({"version": 1, "pid": "not-a-pid", "transports": []}),
],
)
def test_doclib_client_does_not_infer_transports_without_valid_endpoint(
@@ -198,7 +221,7 @@ def test_doclib_client_lazily_validates_discovered_server_id(monkeypatch: pytest
server_id="expected-server",
transports=[EndpointTransport(type="tcp", base_url="http://127.0.0.1:15980")],
)
- fake_client = _FakeClient("expected-server")
+ fake_client = _FakeClient("expected-server", pid=456)
monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)
client = DoclibClient(endpoint_path=endpoint)
@@ -209,6 +232,49 @@ def test_doclib_client_lazily_validates_discovered_server_id(monkeypatch: pytest
assert fake_client.paths == ["/api/v1/server/status", "/api/v1/server/status"]
+def test_doclib_client_validates_legacy_endpoint_pid(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ endpoint = tmp_path / "doclib.endpoint.json"
+ endpoint.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "pid": 123,
+ "transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ fake_client = _FakeClient("", pid=123)
+ monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)
+
+ status = DoclibClient(endpoint_path=endpoint).get_server_status()
+
+ assert status.pid == 123
+ assert fake_client.paths == ["/api/v1/server/status", "/api/v1/server/status"]
+
+
+def test_doclib_client_rejects_legacy_endpoint_pid_mismatch(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ endpoint = tmp_path / "doclib.endpoint.json"
+ endpoint.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "pid": 123,
+ "transports": [{"type": "tcp", "base_url": "http://127.0.0.1:15980"}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ fake_client = _FakeClient("", pid=456)
+ monkeypatch.setattr(client_module, "_client_for_transport", lambda transport, timeout: fake_client)
+
+ with pytest.raises(MineruError) as exc_info:
+ DoclibClient(endpoint_path=endpoint).get_server_status()
+
+ assert exc_info.value.code == "server_instance_mismatch"
+ assert fake_client.paths == ["/api/v1/server/status"]
+
+
def test_doclib_client_rejects_discovered_server_id_mismatch(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
endpoint = tmp_path / "doclib.endpoint.json"
write_endpoint_file(