From 83967a4f0096470dabe03d59c15bbd9f942c178d Mon Sep 17 00:00:00 2001 From: Wangmerlyn Date: Fri, 3 Jul 2026 07:16:13 +0000 Subject: [PATCH] fix(cli): tolerate ps-split daemon executable paths --- AGENTS.md | 8 +++- docs/guides/cli.md | 5 +- docs/reference/cli.md | 4 +- src/keep_gpu/cli.py | 16 ++++++- tests/test_cli_service_commands.py | 75 ++++++++++++++++++++++++++++++ 5 files changed, 103 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1971608..2fc89f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -300,7 +300,11 @@ This file defines how coding agents should work in this repository. verified and must not be signaled as a managed daemon. Process probes should use guarded platform fallbacks when `/proc` is unavailable, but only known matching identity values may authorize a signal; UID must be a plain integer - and start identity must be a non-empty string. + and start identity must be a non-empty string. If a non-`/proc` command-line + fallback loses quoting around an executable path with spaces, ownership may + still verify only when the live command suffix matches the recorded KeepGPU + service command and the split executable prefix rejoins to the recorded + executable path. - MCP executable HTTP endpoint inputs (`--host`, `--port`) must be validated before socket bind, matching the CLI service endpoint contract. The MCP argparse layer must pass raw `--port` values to the shared validator so @@ -442,7 +446,7 @@ This file defines how coding agents should work in this repository. - Single-GPU `keep()` must reject a restart while a previous worker thread is still alive with its stop event already set; returning success in that state hides a stopping keeper as if a fresh keep succeeded. -- Keep service daemon ownership safe: no stop, force-stop, or fallback path may signal a PID unless the auto-start ownership record verifies the running process. PID records must store exact plain JSON integer `pid`, `port`, and `uid` values plus a non-empty string `start_time`; lossy numeric coercions such as floats or booleans are not ownership-verified. Non-`/proc` process metadata fallbacks are allowed only when they recover known UID and start-identity values. If auto-start spawns a daemon but cannot write a trustworthy ownership record, it must best-effort terminate that just-spawned process and fail instead of leaving an unmanaged daemon behind. +- Keep service daemon ownership safe: no stop, force-stop, or fallback path may signal a PID unless the auto-start ownership record verifies the running process. PID records must store exact plain JSON integer `pid`, `port`, and `uid` values plus a non-empty string `start_time`; lossy numeric coercions such as floats or booleans are not ownership-verified. Non-`/proc` process metadata fallbacks are allowed only when they recover known UID and start-identity values, and command-line fallbacks may tolerate only lost quoting around the recorded executable path, not a different executable or service command. If auto-start spawns a daemon but cannot write a trustworthy ownership record, it must best-effort terminate that just-spawned process and fail instead of leaving an unmanaged daemon behind. - Auto-start must not overwrite the PID record for an ownership-verified live KeepGPU daemon whose health endpoint is unavailable; fail with an actionable message so the user can inspect logs or explicitly force-stop it. diff --git a/docs/guides/cli.md b/docs/guides/cli.md index e80a2d7..114ed36 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -103,7 +103,10 @@ service log at `~/.keepgpu/service--.log` or use the printed `keep-gpu service-stop --force` command before trying again. Recovery hints include custom `--host`/`--port` flags when needed. On systems without `/proc`, KeepGPU may recover daemon identity from platform process -metadata, but unknown identity still refuses to signal. +metadata, including command lines whose executable path with spaces lost shell +quoting in `ps` output. That fallback still requires the KeepGPU service command +suffix, rejoined executable prefix, UID, and start identity to match the trusted +PID record; unknown or mismatched identity still refuses to signal. ### List telemetry diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 059cdf2..6b0349f 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -174,7 +174,9 @@ signaling. Auto-start cleans up and fails if it cannot create a trustworthy ownership record for the daemon it just spawned. On systems without `/proc`, KeepGPU may recover daemon identity from platform process metadata, but it still signals only when recovered identity is known and exactly matches the stored -ownership record. +ownership record. If `ps` output splits an executable path that contains spaces, +KeepGPU accepts only a live command whose suffix and rejoined executable prefix +match the recorded service command. | Option | Description | | --- | --- | diff --git a/src/keep_gpu/cli.py b/src/keep_gpu/cli.py index c5b4dbc..d9ac385 100644 --- a/src/keep_gpu/cli.py +++ b/src/keep_gpu/cli.py @@ -224,6 +224,20 @@ def _is_keepgpu_service_argv( return argv[1:] == expected_tail +def _service_argv_matches_running_cmdline( + recorded_argv: List[str], running_argv: List[str] +) -> bool: + if running_argv == recorded_argv: + return True + if len(recorded_argv) < 2 or len(running_argv) <= len(recorded_argv[1:]): + return False + running_prefix_len = len(running_argv) - len(recorded_argv[1:]) + return ( + running_argv[running_prefix_len:] == recorded_argv[1:] + and " ".join(running_argv[:running_prefix_len]) == recorded_argv[0] + ) + + def _build_service_pid_record(host: str, port: int, pid: int) -> Dict[str, Any]: uid = _process_uid(pid) start_time = _process_start_identity(pid) @@ -729,7 +743,7 @@ def _record_matches_running_process( if not _is_keepgpu_service_argv(argv, host, port): return False pid = record["pid"] - if _process_cmdline(pid) != argv: + if not _service_argv_matches_running_cmdline(argv, _process_cmdline(pid)): return False recorded_uid = record.get("uid") diff --git a/tests/test_cli_service_commands.py b/tests/test_cli_service_commands.py index 2d7dc2b..46b853c 100644 --- a/tests/test_cli_service_commands.py +++ b/tests/test_cli_service_commands.py @@ -3523,6 +3523,81 @@ def fake_kill(pid, sig): assert not cli._service_pid_path("127.0.0.1", 8765).exists() +@pytest.mark.parametrize( + ("live_executable_prefix", "live_suffix", "expected_stopped", "expected_kills"), + [ + ( + ["/Applications/Python", "3.12/bin/python"], + None, + True, + [(4321, cli.signal.SIGTERM)], + ), + (["/Applications/Different", "Python/bin/python"], None, False, []), + ( + ["/Applications/Python", "3.12/bin/python"], + ["-m", "other.module", "--mode", "http", "--host", "127.0.0.1"], + False, + [], + ), + ], +) +def test_stop_service_process_handles_ps_split_executable_path_with_spaces( + monkeypatch, + tmp_path, + live_executable_prefix, + live_suffix, + expected_stopped, + expected_kills, +): + monkeypatch.setattr(cli, "_runtime_dir", lambda: tmp_path) + host, port = "127.0.0.1", 8765 + recorded_argv = [ + "/Applications/Python 3.12/bin/python", + "-m", + "keep_gpu.mcp.server", + "--mode", + "http", + "--host", + host, + "--port", + str(port), + ] + payload = { + "pid": 4321, + "host": host, + "port": port, + "argv": recorded_argv, + "uid": 1000, + "start_time": "Wed Jul 1 05:00:00 2026", + "created_at": 1.0, + } + cli._service_pid_path(host, port).write_text(json.dumps(payload), encoding="utf-8") + monkeypatch.setattr( + cli, + "_process_cmdline", + lambda pid: [*live_executable_prefix, *(live_suffix or recorded_argv[1:])], + ) + monkeypatch.setattr(cli, "_process_uid", lambda pid: 1000) + monkeypatch.setattr( + cli, "_process_start_identity", lambda pid: "Wed Jul 1 05:00:00 2026" + ) + alive = {"value": True} + monkeypatch.setattr(cli, "_pid_alive", lambda pid: alive["value"]) + kills = [] + + def fake_kill(pid, sig): + kills.append((pid, sig)) + alive["value"] = False + + monkeypatch.setattr(cli.os, "kill", fake_kill) + + stopped = cli._stop_service_process(host, port, timeout=0.5) + + assert stopped is expected_stopped + assert kills == expected_kills + assert not cli._service_pid_path(host, port).exists() + + def test_stop_service_process_uses_monotonic_deadlines(monkeypatch, tmp_path): monkeypatch.setattr(cli, "_runtime_dir", lambda: tmp_path) payload = {