Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ service log at `~/.keepgpu/service-<host-with-dots-as-underscores>-<port>.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

Expand Down
4 changes: 3 additions & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --- | --- |
Expand Down
16 changes: 15 additions & 1 deletion src/keep_gpu/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
75 changes: 75 additions & 0 deletions tests/test_cli_service_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down