Skip to content

The agent that grows with you

fix(gateway): mark supervisor-ordered stops as planned so direct systemctl restart exits cleanly

joaomarcosba3b1eb3c316
diff --git a/gateway/systemd_stop_mark.py b/gateway/systemd_stop_mark.py
new file mode 100644
index 00000000000..d487ef90774
--- /dev/null
+++ b/gateway/systemd_stop_mark.py
@@ -0,0 +1,56 @@
+"""Mark a supervisor-ordered stop as planned so SIGTERM exits cleanly.
+
+Runs as systemd ``ExecStop=`` before ``KillSignal=SIGTERM``. A raw
+``systemctl restart/stop hermes-gateway`` bypasses the ``hermes gateway``
+CLI, so no takeover (``--replace``) or planned-stop marker exists when the
+SIGTERM lands; the gateway classifies it as an unexpected kill, exits
+non-zero, and the journal records ``Failed with result exit-code`` even
+though the restart was intentional.
+
+The unit's ``Environment=HERMES_HOME=`` is inherited here, so the shared
+:func:`gateway.status.write_planned_stop_marker` helper lands the marker in
+the right profile home with PID + start-time identity. Best-effort and
+never blocking: any failure returns 0 so the stop/restart proceeds.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+
+
+def _resolve_target_pid(argv: list[str] | tuple[str, ...]) -> int | None:
+ """Explicit ``argv[1]``, else systemd's ``$MAINPID``. None when unknown.
+
+ No PID-file fallback on purpose: marking the recorded PID without proof
+ it is the process systemd is about to signal could mislabel an unrelated
+ shutdown as planned.
+ """
+ raw: object = None
+ if len(argv) > 1 and argv[1]:
+ raw = argv[1]
+ else:
+ raw = os.environ.get("MAINPID")
+ try:
+ pid = int(str(raw).strip())
+ except (TypeError, ValueError, AttributeError):
+ return None
+ return pid if pid > 0 else None
+
+
+def main(argv: list[str] | tuple[str, ...] | None = None) -> int:
+ """Write the planned-stop marker for the supervised PID. Always 0."""
+ try:
+ pid = _resolve_target_pid(list(argv) if argv is not None else sys.argv)
+ if pid is None:
+ return 0
+ from gateway.status import write_planned_stop_marker
+
+ write_planned_stop_marker(pid)
+ except Exception:
+ pass
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 6d3746f4090..f5abc7d4032 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -3092,6 +3092,7 @@ RestartPreventExitStatus={GATEWAY_FATAL_CONFIG_EXIT_CODE}
KillMode=mixed
KillSignal=SIGTERM
ExecReload=/bin/kill -USR1 $MAINPID
+ExecStop=-{python_path} -m gateway.systemd_stop_mark
ExecStopPost=-{python_path} -m gateway.cgroup_cleanup
TimeoutStopSec={restart_timeout}
StandardOutput=journal
diff --git a/tests/gateway/test_systemd_stop_mark.py b/tests/gateway/test_systemd_stop_mark.py
new file mode 100644
index 00000000000..2a73feef449
--- /dev/null
+++ b/tests/gateway/test_systemd_stop_mark.py
@@ -0,0 +1,58 @@
+"""Supervisor-ordered stops exit cleanly instead of logging a failure.
+
+Raw ``systemctl restart/stop`` sends SIGTERM with no marker, so the gateway
+used to classify it as an unexpected kill (exit 1, ``Failed with result
+exit-code``). The generated unit now marks the stop via ``ExecStop=`` first.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from gateway import systemd_stop_mark
+
+
+def test_stop_mark_writes_planned_stop_for_supervised_pid(monkeypatch):
+ """MAINPID (or an explicit argv PID) is marked; the helper owns identity."""
+ marked: list[int] = []
+ monkeypatch.setattr(
+ "gateway.status.write_planned_stop_marker",
+ lambda pid: marked.append(pid) or True,
+ )
+ monkeypatch.setenv("MAINPID", "4242")
+ assert systemd_stop_mark.main(["systemd_stop_mark"]) == 0
+ assert marked == [4242]
+
+ marked.clear()
+ monkeypatch.delenv("MAINPID")
+ assert systemd_stop_mark.main(["systemd_stop_mark", "7777"]) == 0
+ assert marked == [7777]
+
+
+def test_stop_mark_never_blocks_restart_and_unit_wires_exec_stop(monkeypatch):
+ """Unknown PIDs mark nothing but still exit 0; the unit runs the marker."""
+ marked: list[int] = []
+ monkeypatch.setattr(
+ "gateway.status.write_planned_stop_marker",
+ lambda pid: marked.append(pid) or True,
+ )
+ for argv, env in ((["m"], None), (["m", "0"], None), (["m", "abc"], None)):
+ if env is None:
+ monkeypatch.delenv("MAINPID", raising=False)
+ assert systemd_stop_mark.main(argv) == 0
+ assert marked == []
+
+ def _boom(_pid):
+ raise OSError("disk gone")
+
+ monkeypatch.setattr("gateway.status.write_planned_stop_marker", _boom)
+ monkeypatch.setenv("MAINPID", "4242")
+ assert systemd_stop_mark.main(["m"]) == 0
+
+ from hermes_cli import gateway as gateway_cli
+
+ unit = gateway_cli.generate_systemd_unit(system=False)
+ assert "ExecStop=-" in unit and "-m gateway.systemd_stop_mark" in unit
+ # The cgroup reaper still runs after the main process exits.
+ assert "-m gateway.cgroup_cleanup" in unit
+ assert unit.index("systemd_stop_mark") < unit.index("cgroup_cleanup")
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index e8a15e8c171..c856a1f7e85 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -604,6 +604,16 @@ Use the user service on laptops and dev boxes. Use the system service on VPS or
The unit Hermes installs already shuts the gateway down cleanly with `KillMode=mixed` + `KillSignal=SIGTERM`, and uses `Restart=always` with `RestartForceExitStatus` so updates and `/restart` respawn correctly. Do **not** add a systemd drop-in such as `ExecStopPost=/bin/kill -9 $MAINPID` — `ExecStopPost` fires on *every* stop, including clean restarts, so it `SIGKILL`s the freshly spawned instance before it stabilizes and `Restart=always` immediately respawns it. The result is an infinite restart loop (and, on Telegram, a flood of restart messages). If you've added such a drop-in, remove it: `systemctl --user edit hermes-gateway` (or `sudo systemctl edit hermes-gateway` for a system service) and delete the `ExecStopPost` line, then `systemctl --user daemon-reload`.
:::
+### Direct `systemctl restart` / `stop` exits cleanly
+
+The installed unit declares `ExecStop=` to record a planned-stop marker for `$MAINPID` before `SIGTERM` is delivered, so stopping or restarting the service directly is classified as intentional: the gateway drains, persists `gateway_state=stopped`, and exits `0` — the journal shows a clean stop/start with no `Failed with result exit-code` line.
+
+```bash
+systemctl --user restart hermes-gateway # or: sudo systemctl restart hermes-gateway
+```
+
+Prefer `hermes gateway restart` when in-flight agent turns matter: it asks the gateway to drain first (`SIGUSR1`, honoring the restart wait budget) and waits for the replacement, while a raw `systemctl restart` stops the current process on systemd's schedule. After updating Hermes, run `hermes gateway restart` once so the running service picks up the regenerated unit that contains the `ExecStop=` line (`hermes gateway status` warns while the installed unit is outdated).
+
:::tip Headless VMs: user service + linger avoids root prompts
A system service needs root for every restart — including the automatic gateway restart at the end of `hermes update`. When `hermes update` runs as a non-root user, it tries passwordless `sudo systemctl`; if that's unavailable, it skips the restart and prints the manual `sudo systemctl restart hermes-gateway` command (it never blocks on an interactive password prompt).