Skip to content

The agent that grows with you

fix(s6): read the supervised pid from s6-svstat -o, not the status line

Victor Kyriazakos38880bd2f1e9
diff --git a/hermes_cli/service_manager.py b/hermes_cli/service_manager.py
index 3e8d50762aa..f925c30b006 100644
--- a/hermes_cli/service_manager.py
+++ b/hermes_cli/service_manager.py
@@ -549,16 +549,27 @@ class S6ServiceManager:
self._run_svc("-u", "start", name)
_write_gateway_desired_state(name, "running")
+ def _svstat_fields(self, name: str, *fields: str) -> list[str] | None:
+ """``s6-svstat -o <fields>`` values for ``name``, or None on a nonzero rc or a count mismatch.
+
+ Never parse the human status line: s6 2.15 prints ``up (pid N pgid N) Ss``, which the old
+ ``(pid N)`` regex never matched, so the planned-stop marker was silently skipped.
+ """
+ result = _s6_run("s6-svstat", "-o", ",".join(fields), str(self.scandir / name))
+ if result.returncode != 0:
+ return None
+ values = result.stdout.split()
+ return values if len(values) == len(fields) else None
+
def _supervised_pid(self, name: str) -> int | None:
- """PID of the supervised gateway per ``s6-svstat``, or None on any failure."""
+ """PID of the supervised gateway per ``s6-svstat -o pid`` (``-1`` when down), or None on any
+ failure."""
try:
- result = _s6_run("s6-svstat", str(self.scandir / name))
- except (OSError, subprocess.SubprocessError):
- return None
- if result.returncode != 0:
+ values = self._svstat_fields(name, "pid")
+ pid = int(values[0]) if values else 0
+ except (OSError, subprocess.SubprocessError, ValueError):
return None
- m = re.search(r"\(pid (\d+)\)", result.stdout)
- return int(m.group(1)) if m else None
+ return pid if pid > 0 else None
def stop(self, name: str) -> None:
"""``s6-svc -d``, after writing a planned-stop marker for the supervised PID so the gateway's
@@ -580,8 +591,8 @@ class S6ServiceManager:
_write_gateway_desired_state(name, "running")
def is_running(self, name: str) -> bool:
- result = _s6_run("s6-svstat", str(self.scandir / name))
- return result.returncode == 0 and "up " in result.stdout
+ values = self._svstat_fields(name, "up")
+ return values == ["true"]
# -- runtime registration ---------------------------------------------
diff --git a/tests/docker/test_s6_gateway_planned_stop.py b/tests/docker/test_s6_gateway_planned_stop.py
new file mode 100644
index 00000000000..d7a7d8c5dca
--- /dev/null
+++ b/tests/docker/test_s6_gateway_planned_stop.py
@@ -0,0 +1,87 @@
+"""E2E: ``hermes gateway stop`` inside the s6 image is a PLANNED stop.
+
+``S6ServiceManager.stop()`` must find the supervised PID through the real s6
+binaries and write the planned-stop marker before ``s6-svc -d``. Otherwise the
+gateway reads the SIGTERM as an unexpected kill: it exits 1, persists
+``gateway_state=running`` (so the next boot auto-starts it, undoing the stop)
+and skips the clean-shutdown marker. Unit fakes cannot prove this; only the
+real ``s6-svstat`` shipped in the image can.
+
+Every ``docker exec`` runs as ``hermes`` per the conftest module docstring.
+"""
+from __future__ import annotations
+
+import json
+import time
+
+from tests.docker.conftest import docker_exec_sh, start_container, wait_for_docker_logs
+
+SLOT = "/run/service/gateway-default"
+
+
+def _svstat_field(container: str, field: str) -> str:
+ r = docker_exec_sh(container, f"/command/s6-svstat -o {field} {SLOT}")
+ return r.stdout.strip() if r.returncode == 0 else ""
+
+
+def _state(container: str) -> dict:
+ r = docker_exec_sh(container, "cat /opt/data/gateway_state.json 2>/dev/null")
+ if r.returncode != 0 or not r.stdout.strip():
+ return {}
+ try:
+ data = json.loads(r.stdout)
+ except json.JSONDecodeError:
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _gateway_state(container: str) -> str:
+ return str(_state(container).get("gateway_state", ""))
+
+
+def _agent_log(container: str) -> str:
+ return docker_exec_sh(container, "cat /opt/data/logs/agent.log 2>/dev/null").stdout
+
+
+def _wait(predicate, what: str, deadline_s: float = 90.0, interval_s: float = 0.5) -> None:
+ end = time.monotonic() + deadline_s
+ while time.monotonic() < end:
+ if predicate():
+ return
+ time.sleep(interval_s)
+ raise AssertionError(f"timed out after {deadline_s}s waiting for {what}")
+
+
+def test_gateway_stop_under_s6_is_planned(built_image: str, container_name: str) -> None:
+ start_container(built_image, container_name, cmd="gateway run")
+ wait_for_docker_logs(container_name, "s6 supervision", deadline_s=60.0)
+
+ # The supervised gateway (no platforms: it stays up for cron) must be up and
+ # past startup, so its signal handlers and planned-stop watcher are installed.
+ # Boot seeds gateway_state=running before the process exists, so readiness is
+ # the gateway's OWN state write (it stamps its pid) plus its startup-done line.
+ _wait(lambda: _svstat_field(container_name, "up") == "true", "gateway-default up")
+ supervised_pid = _svstat_field(container_name, "pid")
+ assert supervised_pid.isdigit() and int(supervised_pid) > 0, supervised_pid
+ _wait(
+ lambda: str(_state(container_name).get("pid")) == supervised_pid
+ and _gateway_state(container_name) == "running",
+ "supervised gateway's own gateway_state=running write",
+ )
+ _wait(lambda: "Press Ctrl+C to stop" in _agent_log(container_name), "gateway startup done")
+
+ r = docker_exec_sh(container_name, "hermes gateway stop", timeout=90)
+ assert r.returncode == 0, f"gateway stop failed: stdout={r.stdout!r} stderr={r.stderr!r}"
+
+ _wait(lambda: _svstat_field(container_name, "up") == "false", "gateway-default down")
+ logs = docker_exec_sh(
+ container_name, "cat /opt/data/logs/agent.log /opt/data/logs/gateway.log 2>/dev/null"
+ ).stdout
+
+ assert _svstat_field(container_name, "exitcode") == "0", (
+ f"supervised gateway exit: {_svstat_field(container_name, 'exitcode')!r}\n"
+ f"svstat: {docker_exec_sh(container_name, f'/command/s6-svstat {SLOT}').stdout!r}\n{logs[-4000:]}"
+ )
+ _wait(lambda: _gateway_state(container_name) == "stopped", "gateway_state=stopped", deadline_s=15.0)
+ assert "as a planned gateway stop" in logs, logs[-4000:]
+ assert "unexpected signal" not in logs, logs[-4000:]
diff --git a/tests/hermes_cli/test_service_manager.py b/tests/hermes_cli/test_service_manager.py
index 51474a810aa..0fe6ed9ebed 100644
--- a/tests/hermes_cli/test_service_manager.py
+++ b/tests/hermes_cli/test_service_manager.py
@@ -7,6 +7,8 @@ implementation in this same file once that phase ships.
"""
from __future__ import annotations
+import subprocess
+
import pytest
from hermes_cli.service_manager import (
@@ -274,8 +276,151 @@ def test_render_finish_script_does_not_restart_on_clean_exit(tmp_path) -> None:
# the marker, the gateway's shutdown handler can't tell an operator
# stop from a restart kill, and the gateway_state=stopped suppression
# (run.py) would never engage for explicit stops.
+#
+# The fake below replays what s6 2.15.0.0 (s6-overlay 3.2.3.0, pinned in the
+# Dockerfile) actually prints, captured from the real binary:
+# s6-svstat <dir> -> up (pid 26 pgid 26) 1 seconds
+# s6-svstat -o pid <dir> -> 26 (-1 when not up)
+# s6-svstat -o up <dir> -> true|false
+# after s6-svc -d -> down (signal SIGTERM) 1 seconds, normally up, ready 1 seconds
# ---------------------------------------------------------------------------
+_S6_PID = 4242
+
+
+def real_s6(monkeypatch: pytest.MonkeyPatch):
+ """Emulate s6 2.15 ``s6-svstat`` (legacy line and ``-o`` fields) plus ``s6-svc``.
+
+ ``state["up"]`` toggles the supervised process; ``state["svstat"]`` may be set
+ to a ``(returncode, stdout)`` override or an exception to raise.
+ """
+ _sp = subprocess
+ state: dict = {"up": True, "svstat": None, "calls": []}
+
+ def _fake(cmd, **kw):
+ seq = list(cmd)
+ name = seq[0].rsplit("/", 1)[-1]
+ state["calls"].append([name, *seq[1:]])
+ if name != "s6-svstat":
+ return _sp.CompletedProcess(cmd, 0, "", "")
+ override = state["svstat"]
+ if isinstance(override, BaseException):
+ raise override
+ if override is not None:
+ rc, out = override
+ return _sp.CompletedProcess(cmd, rc, out, "")
+ up = state["up"]
+ if "-o" in seq:
+ fields = seq[seq.index("-o") + 1].split(",")
+ table = {
+ "up": "true" if up else "false",
+ "pid": str(_S6_PID) if up else "-1",
+ "pgid": str(_S6_PID) if up else "-1",
+ "exitcode": "-1" if up else "0",
+ }
+ assert all(f in table for f in fields), f"unknown s6-svstat field in {fields}"
+ return _sp.CompletedProcess(cmd, 0, " ".join(table[f] for f in fields) + "\n", "")
+ line = (
+ f"up (pid {_S6_PID} pgid {_S6_PID}) 5 seconds\n"
+ if up
+ else "down (signal SIGTERM) 1 seconds, normally up, ready 1 seconds\n"
+ )
+ return _sp.CompletedProcess(cmd, 0, line, "")
+
+ monkeypatch.setattr("subprocess.run", _fake)
+ return state
+
+
+def marker_calls(monkeypatch: pytest.MonkeyPatch):
+ marked: list[int] = []
+ monkeypatch.setattr(
+ "gateway.status.write_planned_stop_marker", lambda pid: marked.append(pid) or True
+ )
+ return marked
+
+
+def _svc_down_issued(state) -> bool:
+ return any(c[:2] == ["s6-svc", "-d"] for c in state["calls"])
+
+
+def test_s6_stop_writes_planned_stop_marker_for_supervised_pid(
+ s6_scandir, real_s6, marker_calls
+) -> None:
+ (s6_scandir / "gateway-coder").mkdir()
+ mgr = S6ServiceManager(scandir=s6_scandir)
+
+ mgr.stop("gateway-coder")
+
+ assert marker_calls == [_S6_PID]
+ assert _svc_down_issued(real_s6)
+ svc_idx = next(i for i, c in enumerate(real_s6["calls"]) if c[:2] == ["s6-svc", "-d"])
+ assert any(c[0] == "s6-svstat" for c in real_s6["calls"][:svc_idx])
+
+
+def test_s6_stop_when_down_writes_no_marker_but_still_stops(
+ s6_scandir, real_s6, marker_calls
+) -> None:
+ (s6_scandir / "gateway-coder").mkdir()
+ real_s6["up"] = False
+
+ S6ServiceManager(scandir=s6_scandir).stop("gateway-coder")
+
+ assert marker_calls == []
+ assert _svc_down_issued(real_s6)
+
+
+def test_s6_stop_marker_write_failure_still_stops(
+ s6_scandir, real_s6, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ (s6_scandir / "gateway-coder").mkdir()
+ attempted: list[int] = []
+
+ def _boom(pid):
+ attempted.append(pid)
+ raise OSError("disk gone")
+
+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", _boom)
+
+ S6ServiceManager(scandir=s6_scandir).stop("gateway-coder")
+
+ assert attempted == [_S6_PID]
+ assert _svc_down_issued(real_s6)
+
+
+def test_s6_supervised_pid_reads_up_pid(s6_scandir, real_s6) -> None:
+ mgr = S6ServiceManager(scandir=s6_scandir)
+ assert mgr._supervised_pid("gateway-coder") == _S6_PID
+ real_s6["up"] = False
+ assert mgr._supervised_pid("gateway-coder") is None
+
+
+ "svstat",
+ [
+ (1, "s6-svstat: fatal: unable to read status\n"),
+ (0, "garbage\n"),
+ (0, ""),
+ (0, "4242 17\n"),
+ (0, "0\n"),
+ FileNotFoundError("/command/s6-svstat"),
+ subprocess.TimeoutExpired("s6-svstat", 5),
+ ],
+)
+def test_s6_supervised_pid_none_on_unusable_svstat(s6_scandir, real_s6, svstat) -> None:
+ real_s6["svstat"] = svstat
+ assert S6ServiceManager(scandir=s6_scandir)._supervised_pid("gateway-coder") is None
+
+
+def test_s6_is_running_follows_svstat_up_field(s6_scandir, real_s6) -> None:
+ mgr = S6ServiceManager(scandir=s6_scandir)
+ assert mgr.is_running("gateway-coder") is True
+ real_s6["up"] = False
+ assert mgr.is_running("gateway-coder") is False
+ real_s6["svstat"] = (1, "")
+ assert mgr.is_running("gateway-coder") is False
+
def _log_run_setup_fragment(rendered: str) -> str:
"""Keep mkdir/rm setup from ``_render_log_run``; stop before ``s6-log``."""