The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a systemctl timeout on a slow-stopping gateway unit is unknown, not failed
Teknium1436c8cdd398
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.pyindex 4ce7a469cfb..d96b5bdfd69 100644--- a/hermes_cli/update_cmd_fleet.py+++ b/hermes_cli/update_cmd_fleet.py@@ -701,10 +701,11 @@ def _systemctl_reset_and_restart(manage_cmd: list, svc_name: str, *, scope_cmd:auto-restart can wedge a plain ``restart`` against RestartSec backoff and stay dead."""# Property reads need no manage-units privileges: narrow sudoers may permit# restart/reset-failed but deny show. Keep the same user/system manager scope.- from hermes_cli.update_cmd_fleet_unit_budget import systemd_restart_timeout- timeout = systemd_restart_timeout(scope_cmd if scope_cmd is not None else manage_cmd, svc_name)+ from hermes_cli.update_cmd_fleet_unit_budget import run_unit_job, systemd_restart_timeout+ scope_cmd = scope_cmd if scope_cmd is not None else manage_cmd+ timeout = systemd_restart_timeout(scope_cmd, svc_name)_systemctl(manage_cmd + ["reset-failed", svc_name], timeout=10)- return _systemctl(manage_cmd + ["restart", svc_name], timeout=timeout)+ return run_unit_job(manage_cmd, scope_cmd, "restart", svc_name, timeout=timeout)def _systemd_unit_owned_by_update(scope_cmd: list, svc_name: str) -> bool:@@ -1268,17 +1269,15 @@ def _restart_one_systemd_gateway_unit(_main_pid, drain_budget, svc_name, self_restart_pending=self_restart_pending)if _graceful_ok:- from hermes_cli.update_cmd_fleet_unit_budget import service_restart_sec, systemd_restart_timeout+ from hermes_cli.update_cmd_fleet_unit_budget import run_unit_job, service_restart_sec, systemd_restart_timeout# ``Restart=always`` respawns only after RestartSec (60s in our unit; dead time for a# voluntary restart). ``reset-failed`` + ``start`` skips it (~1-3s); if RestartSec already# elapsed, ``start`` is a no-op and we fall through to the poll. Needs manage-units# privileges; without them auto-restart still fires after RestartSec.if _manage_cmd is not None:_systemctl(_manage_cmd + ["reset-failed", svc_name], timeout=10)- _systemctl(- _manage_cmd + ["start", svc_name],- timeout=systemd_restart_timeout(scope_cmd, svc_name, start_only=True),- )+ run_unit_job(_manage_cmd, scope_cmd, "start", svc_name,+ timeout=systemd_restart_timeout(scope_cmd, svc_name, start_only=True))if _wait_for_service_active(scope_cmd, svc_name, timeout=10.0):restarted_services.append(svc_name)returndiff --git a/hermes_cli/update_cmd_fleet_unit_budget.py b/hermes_cli/update_cmd_fleet_unit_budget.pyindex 24542213be3..4dfd8326a4c 100644--- a/hermes_cli/update_cmd_fleet_unit_budget.py+++ b/hermes_cli/update_cmd_fleet_unit_budget.py@@ -8,33 +8,27 @@ poller must outwait the unit's ``RestartSec`` cooldown. Both read unit propertiefrom __future__ import annotationsimport subprocess+import timefrom contextlib import suppress# poll() takes signed 32-bit milliseconds; keep headroom for rounding in communicate()._SYSTEMCTL_RESTART_TIMEOUT_MAX = (2**31 - 1) // 1000 - 1-def systemd_restart_timeout(scope_cmd: list, svc_name: str, *, start_only: bool = False) -> float:- """Outwait the unit's stop + start budgets, not just the systemctl client.-- A client timeout does not cancel the manager's queued restart. Unknown or- infinite limits use systemd's usual 90s per phase so automation stays bounded.- Custom ExecStop chains or EXTEND_TIMEOUT_USEC can still exceed this budget;- genuine timeouts must continue through the existing per-unit failure path.- """+def _unit_stop_start_budgets(scope_cmd: list, svc_name: str) -> tuple[float, float]:+ """``(TimeoutStopUSec, TimeoutStartUSec)`` in seconds. Unknown or infinite limits use+ systemd's usual 90s per phase so automation stays bounded."""from gateway.shutdown_forensics import parse_systemd_duration_to_usfrom hermes_cli.update_cmd_fleet import _systemctl- budgets = {"TimeoutStartUSec": 90.0}- if not start_only:- budgets["TimeoutStopUSec"] = 90.0+ budgets = {"TimeoutStopUSec": 90.0, "TimeoutStartUSec": 90.0}try:show = _systemctl(scope_cmd + ["show", svc_name, "--property=TimeoutStopUSec,TimeoutStartUSec"],timeout=5,)except (FileNotFoundError, subprocess.TimeoutExpired):- return sum(budgets.values()) + 15.0+ return budgets["TimeoutStopUSec"], budgets["TimeoutStartUSec"]if show.returncode == 0:for line in (show.stdout or "").splitlines():key, _, raw = line.partition("=")@@ -47,7 +41,84 @@ def systemd_restart_timeout(scope_cmd: list, svc_name: str, *, start_only: boolbudgets[key] = duration / 1_000_000except (ValueError, OverflowError):pass- return min(sum(budgets.values()) + 15.0, _SYSTEMCTL_RESTART_TIMEOUT_MAX)+ return budgets["TimeoutStopUSec"], budgets["TimeoutStartUSec"]+++def systemd_restart_timeout(scope_cmd: list, svc_name: str, *, start_only: bool = False) -> float:+ """Outwait the unit's stop + start budgets, not just the systemctl client.++ A client timeout does not cancel the manager's queued restart: ``run_unit_job`` then+ waits for that job instead of calling the restart failed.+ """+ stop, start = _unit_stop_start_budgets(scope_cmd, svc_name)+ return min((0.0 if start_only else stop) + start + 15.0, _SYSTEMCTL_RESTART_TIMEOUT_MAX)+++#: A wait on a unit's own job never runs past this, whatever its timeouts say.+_UNIT_JOB_HARD_CAP_S = 900.0+#: Exit status ``run_unit_job`` reports when systemd's job for the unit is still running.+UNIT_JOB_STILL_RUNNING = 124+_TRANSITIONAL_STATES = ("activating", "deactivating", "reloading", "refreshing")+++def unit_job_budget(scope_cmd: list, svc_name: str, verb: str) -> float:+ """How long systemd may legitimately take to finish *verb* on the unit: TimeoutStopUSec+ twice (the SIGTERM wait, then the final-SIGKILL wait systemd bounds by the same value; a+ cgroup child stuck in D state takes both), plus TimeoutStartUSec for a start, plus slack."""+ stop, start = _unit_stop_start_budgets(scope_cmd, svc_name)+ budget = 2 * stop + (start if verb in ("start", "restart") else 0.0) + 30.0+ return min(budget, _UNIT_JOB_HARD_CAP_S)+++def unit_job_state(scope_cmd: list, svc_name: str) -> dict[str, str]:+ """``ActiveState``/``SubState``/``MainPID``/``Job`` of the unit; ``{}`` when unreadable."""+ from hermes_cli.update_cmd_fleet import _systemctl++ try:+ show = _systemctl(scope_cmd + ["show", svc_name, "--property=ActiveState,SubState,MainPID,Job"], timeout=10)+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return {}+ if show.returncode != 0:+ return {}+ return dict(line.partition("=")[::2] for line in (show.stdout or "").splitlines() if "=" in line)+++def _settled(state: dict[str, str]) -> bool:+ return state.get("ActiveState") not in (None, "", *_TRANSITIONAL_STATES) and not state.get("Job")+++def run_unit_job(manage_cmd: list, scope_cmd: list, verb: str, svc_name: str, *, timeout: float):+ """``systemctl <verb> <unit>``, where a client timeout is UNKNOWN, not failed.++ The timeout cancels nothing: systemd keeps running the job (a ``start`` queued behind a+ slow stop included), so judging it failed reports a restart that then happens, and a+ rollback ``start`` queues behind the stop and boots the unit later, unasked. Past the+ timeout this waits for the unit's job to settle, bounded by ``unit_job_budget`` from the+ call, and reports the settled state: exit 0 when the unit reached what *verb* asked for+ (``active`` for start/restart, stopped for stop), else ``UNIT_JOB_STILL_RUNNING`` while+ the job still runs, 1 when it settled elsewhere. A call that returns in time is untouched.+ """+ from hermes_cli.update_cmd_fleet import _systemctl++ started = time.monotonic()+ try:+ return _systemctl(manage_cmd + [verb, svc_name], timeout=timeout)+ except subprocess.TimeoutExpired as exc:+ argv = exc.cmd+ deadline = started + max(unit_job_budget(scope_cmd, svc_name, verb), timeout)+ state = unit_job_state(scope_cmd, svc_name)+ while not _settled(state) and time.monotonic() < deadline:+ time.sleep(1.0)+ state = unit_job_state(scope_cmd, svc_name)+ waited, active = time.monotonic() - started, state.get("ActiveState", "unknown")+ if not _settled(state):+ print(f" ⏳ systemctl {verb} {svc_name} timed out after {timeout:.0f}s; systemd's job is still "+ f"running after {waited:.0f}s ({active}/{state.get('SubState', '?')})")+ return subprocess.CompletedProcess(argv, UNIT_JOB_STILL_RUNNING, "", f"systemd's {verb} job still running")+ reached = active == "active" if verb in ("start", "restart") else active in ("inactive", "failed")+ print(f" ⏳ systemctl {verb} {svc_name} timed out after {timeout:.0f}s; systemd finished the job "+ f"after {waited:.0f}s ({active})")+ return subprocess.CompletedProcess(argv, 0 if reached else 1, "", "" if reached else f"unit settled {active}")_RESTART_SEC_UNITS = (("ms", 0.001), ("us", 0.000001), ("min", 60.0), ("s", 1.0))diff --git a/hermes_cli/update_cmd_posix_pause.py b/hermes_cli/update_cmd_posix_pause.pyindex 0f71d8b8a2e..db28b22781b 100644--- a/hermes_cli/update_cmd_posix_pause.py+++ b/hermes_cli/update_cmd_posix_pause.py@@ -323,12 +323,25 @@ def _manage_cmd(scope: str) -> list | None:return cmd+def _scope_cmd(unit: dict) -> list:+ return ["systemctl", "--user"] if unit["scope"] == "user" else ["systemctl"]++def _stop_unit(unit: dict) -> None:- from hermes_cli.update_cmd_fleet import _systemctl+ """Stop *unit* through systemd. A stop job systemd is still running holds the pause unless+ the gateway is provably still up: its job outlives our client timeout (a cgroup child that+ ignores SIGTERM keeps it in ``deactivating`` for up to twice TimeoutStopSec), it keeps the+ supervisor from respawning the gateway, and a rollback ``start`` would only queue behind it+ and boot the gateway seconds before the checkout moves."""+ from hermes_cli.update_cmd_fleet import _unit_main_pid+ from hermes_cli.update_cmd_fleet_unit_budget import UNIT_JOB_STILL_RUNNING, run_unit_jobcmd = _manage_cmd(unit["scope"])if cmd is None:raise PauseRefused(f"no privilege to stop system unit {unit['unit']}")- result = _systemctl(cmd + ["stop", unit["unit"]], timeout=_STOP_TIMEOUT_S)+ result = run_unit_job(cmd, _scope_cmd(unit), "stop", unit["unit"], timeout=_STOP_TIMEOUT_S)+ if result.returncode == UNIT_JOB_STILL_RUNNING and not _alive(unit["pid"], unit.get("ct")) \+ and _unit_main_pid(_scope_cmd(unit), unit["unit"]) <= 0:+ returnif result.returncode != 0:raise PauseRefused(f"systemctl stop {unit['unit']} failed: {(result.stderr or '').strip()}")@@ -339,13 +352,14 @@ def _start_unit(unit: dict) -> int:from hermes_cli.update_cmd_fleet import (_repair_unit_without_fatal_exit_park, _systemctl, _unit_main_pid, _wait_for_service_active,)+ from hermes_cli.update_cmd_fleet_unit_budget import run_unit_jobcmd = _manage_cmd(unit["scope"])if cmd is None:raise RuntimeError(f"no privilege to start system unit {unit['unit']}")_repair_unit_without_fatal_exit_park(unit["unit"], unit["scope"])_systemctl(cmd + ["reset-failed", unit["unit"]], timeout=10)- result = _systemctl(cmd + ["start", unit["unit"]], timeout=_STOP_TIMEOUT_S)- scope_cmd = ["systemctl", "--user"] if unit["scope"] == "user" else ["systemctl"]+ scope_cmd = _scope_cmd(unit)+ result = run_unit_job(cmd, scope_cmd, "start", unit["unit"], timeout=_STOP_TIMEOUT_S)if result.returncode != 0 or not _wait_for_service_active(scope_cmd, unit["unit"], timeout=15.0):raise RuntimeError(f"{unit['unit']} did not start: {(result.stderr or '').strip() or 'not active'}")return _unit_main_pid(scope_cmd, unit["unit"])diff --git a/tests/hermes_cli/test_update_slow_unit_stop.py b/tests/hermes_cli/test_update_slow_unit_stop.pynew file mode 100644index 00000000000..a2a7da57f31--- /dev/null+++ b/tests/hermes_cli/test_update_slow_unit_stop.py@@ -0,0 +1,90 @@+"""A systemd unit whose stop outlives the updater's ``systemctl`` timeout.++systemd keeps running a job after its client gives up, so a timed-out ``stop``/``start`` is+unknown until the unit's state is read: the pause must hold while the gateway is gone, and the+restart must count a unit that finished coming up on its own job.+"""+import subprocess+import types++import pytest++from hermes_cli import update_cmd_fleet as fleet+from hermes_cli import update_cmd_fleet_unit_budget as budget+from hermes_cli import update_cmd_posix_pause as pause++UNIT = "hermes-gateway"+SCOPE = ["systemctl", "--user"]+MANAGE = [*SCOPE, "--no-ask-password"]+++class _SlowUnit:+ """A unit whose queued job finishes ``job_s`` (fake) seconds after it is issued, into+ ``settled`` (ActiveState, MainPID)."""++ def __init__(self, monkeypatch, *, job_s: float, settled: tuple[str, int]):+ self.now, self.job_s, self.settled, self.done_at, self.verbs = 0.0, job_s, settled, None, []+ clock = types.SimpleNamespace(monotonic=lambda: self.now, sleep=self._sleep)+ monkeypatch.setattr(budget, "time", clock, raising=False) # base has no clock here+ monkeypatch.setattr(fleet, "_systemctl", self.systemctl)++ def _sleep(self, seconds):+ self.now += seconds++ def _state(self):+ if self.done_at is not None and self.now >= self.done_at:+ return self.settled[0], self.settled[1], ""+ return "deactivating", 0, "7"++ def systemctl(self, cmd, *, timeout):+ verb = next((v for v in ("stop", "start", "restart", "reset-failed", "show", "is-active") if v in cmd), None)+ if verb in ("stop", "start", "restart"):+ self.verbs.append(verb)+ self.done_at = self.now + self.job_s+ self.now += timeout # the client waits out its timeout, the job keeps running+ raise subprocess.TimeoutExpired(cmd, timeout)+ active, main_pid, job = self._state()+ if verb == "is-active":+ return subprocess.CompletedProcess(cmd, 0, active, "")+ prop = next((c for c in cmd if c.startswith("--property=")), "")+ if "TimeoutStopUSec" in prop:+ return subprocess.CompletedProcess(cmd, 0, "TimeoutStopUSec=90s\nTimeoutStartUSec=90s", "")+ if prop == "--property=MainPID":+ return subprocess.CompletedProcess(cmd, 0, str(main_pid), "")+ return subprocess.CompletedProcess(+ cmd, 0, f"ActiveState={active}\nSubState=x\nMainPID={main_pid}\nJob={job}", "")++[email protected]("serving", [False, True], ids=["gateway-gone", "gateway-serving"])+def test_pause_holds_while_systemd_finishes_a_slow_stop(monkeypatch, serving):+ """The incident: the drained gateway already exited, ``systemctl stop`` timed out at 120 s while+ systemd needed ~181 s (SIGTERM wait + final-SIGKILL wait) for a stuck cgroup child. Base raised,+ and the pause's rollback ``start`` queued behind the stop and booted the gateway mid-swap."""+ unit = _SlowUnit(monkeypatch, job_s=181.0, settled=("active", 4242) if serving else ("failed", 0))+ monkeypatch.setattr(pause, "_alive", lambda pid, ct: False)+ entry = {"kind": "systemd", "scope": "user", "unit": UNIT, "pid": 1234, "ct": None}+ if serving:+ with pytest.raises(pause.PauseRefused):+ pause._stop_unit(entry)+ else:+ pause._stop_unit(entry)+ assert unit.verbs == ["stop"]+++def test_restart_counts_a_unit_whose_start_job_outlived_the_client(monkeypatch):+ """After the drain, ``systemctl start`` queues behind the unit's still-running stop and times+ out; systemd then brings the gateway up on the new code. That is a restart, not a failure."""+ unit = _SlowUnit(monkeypatch, job_s=190.0, settled=("active", 5555))+ calls = iter([subprocess.CompletedProcess([], 0, "active", ""), subprocess.CompletedProcess([], 0, "42", "")])+ real = unit.systemctl+ monkeypatch.setattr(fleet, "_systemctl", lambda cmd, *, timeout: next(calls) if not unit.verbs and (+ "is-active" in cmd or "--property=MainPID" in cmd) else real(cmd, timeout=timeout))+ monkeypatch.setattr(fleet, "_systemd_unit_owned_by_update", lambda scope_cmd, svc: True)+ monkeypatch.setattr(fleet, "_repair_unit_without_fatal_exit_park", lambda svc, scope: None)+ monkeypatch.setattr(fleet, "_drain_or_signal_gateway_for_update", lambda *a, **kw: True)+ restarted, failed = [], []+ fleet._restart_one_systemd_gateway_unit(+ UNIT, scope="user", scope_cmd=SCOPE, drain_budget=45, _manage_cmd_cache={"user": MANAGE},+ restarted_services=restarted, failed_or_stale_units=failed,+ )+ assert (restarted, failed, unit.verbs) == ([UNIT], [], ["start"])diff --git a/tests/hermes_cli/test_update_unit_client_budget.py b/tests/hermes_cli/test_update_unit_client_budget.pyindex 0ab9b29a2d0..79de4faeb13 100644--- a/tests/hermes_cli/test_update_unit_client_budget.py+++ b/tests/hermes_cli/test_update_unit_client_budget.py@@ -1,9 +1,11 @@"""Update clients cover unit transactions without hiding manager failures."""import subprocess+import typesimport pytestfrom hermes_cli import update_cmd_fleet as fleet+from hermes_cli import update_cmd_fleet_unit_budget as budget@pytest.fixture(autouse=True)@@ -101,8 +103,14 @@ def test_budget_fallback_keeps_real_errors(monkeypatch, limits, outcome):monkeypatch.setattr(fleet, "_systemctl", systemctl)if outcome == "timeout":- with pytest.raises(subprocess.TimeoutExpired):- fleet._systemctl_reset_and_restart(["systemctl"], "hermes-serve-test")+ # A client timeout is unknown, not failed: the unit's state never settles here, so the+ # bounded wait for systemd's job ends in a non-zero result, never a raise or a hang.+ clock = [0.0]+ monkeypatch.setattr(budget, "time", types.SimpleNamespace(+ monotonic=lambda: clock[0], sleep=lambda s: clock.__setitem__(0, clock[0] + s)))+ result = fleet._systemctl_reset_and_restart(["systemctl"], "hermes-serve-test")+ assert result.returncode == budget.UNIT_JOB_STILL_RUNNING+ assert clock[0] <= budget._UNIT_JOB_HARD_CAP_Selse:result = fleet._systemctl_reset_and_restart(["systemctl"], "hermes-serve-test")assert result.returncode == outcome