Skip to content

The agent that grows with you

refactor(gateway): retire the --replace drop-in in one step, two invariant tests

teknium141f0bd942d36
diff --git a/hermes_cli/gateway_service_unit.py b/hermes_cli/gateway_service_unit.py
index 17476fda56f..ebb08bbbcf4 100644
--- a/hermes_cli/gateway_service_unit.py
+++ b/hermes_cli/gateway_service_unit.py
@@ -283,8 +283,6 @@ def systemd_unit_is_current(system: bool = False) -> bool:
unit_path = _gw().get_systemd_unit_path(system=system)
if not unit_path.exists():
return False
- if _is_hermes_replace_dropin(_systemd_replace_dropin_path(system=system)):
- return False
installed = unit_path.read_text(encoding="utf-8")
expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None
@@ -328,32 +326,25 @@ def _refuse_temp_home_service_write(definition: str, kind: str) -> bool:
return True
-def _systemd_replace_dropin_path(system: bool = False) -> Path:
- unit_path = _gw().get_systemd_unit_path(system=system)
- return unit_path.parent / f"{unit_path.name}.d" / "20-replace.conf"
-
+def _retire_hermes_replace_dropin(system: bool = False) -> bool:
+ """Unlink the ``20-replace.conf`` drop-in an older Hermes wrote to end a respawn storm; True if removed.
-def _is_hermes_replace_dropin(dropin: Path) -> bool:
- if not dropin.is_file():
+ It appends ``--replace`` to a supervised ExecStart the generator no longer emits, and since the
+ cross-profile ownership guard that override turns a per-profile fleet into a unit that can never
+ start (#119467). Only the Hermes-authored file (recognised by its own comment) is touched.
+ """
+ unit_path = _gw().get_systemd_unit_path(system=system)
+ dropin = unit_path.parent / f"{unit_path.name}.d" / "20-replace.conf"
+ try:
+ text = dropin.read_text(encoding="utf-8")
+ except OSError:
return False
- text = dropin.read_text(encoding="utf-8")
- return all(token in text for token in ("Added to end the gateway respawn storm", "--replace", "ExecStart="))
-
-
-def _retire_hermes_replace_dropin(system: bool = False) -> bool:
- dropin = _systemd_replace_dropin_path(system=system)
- if not _is_hermes_replace_dropin(dropin):
+ if not all(token in text for token in ("Added to end the gateway respawn storm", "--replace", "ExecStart=")):
return False
- # Retire only the old Hermes-authored takeover override.
dropin.unlink()
return True
-def _report_retired_hermes_replace_dropin(system: bool = False) -> None:
- _gw()._run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)
- print("↻ Removed stale Hermes --replace drop-in from the gateway service")
-
-
def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
"""Rewrite the installed systemd unit when the generated definition has changed."""
unit_path = _gw().get_systemd_unit_path(system=system)
@@ -361,13 +352,14 @@ def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
return False
# _gw().systemd_unit_is_current is the HERMES_HOME-sync chokepoint; its env mutation persists for the regenerate below.
- was_current = _gw().systemd_unit_is_current(system=system)
- dropin_removed = _retire_hermes_replace_dropin(system=system)
- if was_current and not dropin_removed:
+ current = _gw().systemd_unit_is_current(system=system)
+ if _retire_hermes_replace_dropin(system=system):
+ _gw()._run_systemctl(["daemon-reload"], system=system, check=True, timeout=30)
+ print(f"↻ Removed the stale Hermes --replace drop-in from the gateway {_gw()._service_scope_label(system)} service")
+ if current:
+ return True
+ elif current:
return False
- if dropin_removed and _gw().systemd_unit_is_current(system=system):
- _report_retired_hermes_replace_dropin(system=system)
- return True
expected_user = _gw()._read_systemd_user_from_unit(unit_path) if system else None
new_unit = _gw().generate_systemd_unit(system=system, run_as_user=expected_user)
@@ -375,14 +367,10 @@ def refresh_systemd_unit_if_needed(system: bool = False) -> bool:
# Test safety belt: the user unit path is under Path.home(), which conftest does NOT sandbox, and a
# pytest-tmp HERMES_HOME baked into the developer's real unit breaks their gateway on next reboot.
if not system and any(m in new_unit for m in ("/pytest-of-", '/hermes_test"', "/hermes_test/")):
- if dropin_removed:
- _report_retired_hermes_replace_dropin(system=system)
return False
# Structural variant: refuse ANY temp-dir HERMES_HOME (manual E2E homes lack the pytest markers).
if _gw()._refuse_temp_home_service_write(new_unit, "systemd unit"):
- if dropin_removed:
- _report_retired_hermes_replace_dropin(system=system)
return False
unit_path.write_text(new_unit, encoding="utf-8")
diff --git a/tests/hermes_cli/test_systemd_replace_dropin.py b/tests/hermes_cli/test_systemd_replace_dropin.py
index 08136d1a2e7..88ccd41283f 100644
--- a/tests/hermes_cli/test_systemd_replace_dropin.py
+++ b/tests/hermes_cli/test_systemd_replace_dropin.py
@@ -1,121 +1,57 @@
-"""Hermes-authored systemd --replace drop-ins must not survive unit refresh.
+"""A Hermes-authored systemd ``--replace`` drop-in must not survive unit refresh.
-The generator emits ``gateway run`` without ``--replace``. A leftover
-``20-replace.conf`` overrides that ExecStart, so refresh has to retire the
-Hermes file even when the base unit text already matches.
+An older Hermes wrote ``<unit>.d/20-replace.conf`` to end a respawn storm; it overrides ExecStart
+with ``gateway run --replace``. Combined with the cross-profile ownership guard, that override turns
+a per-profile fleet's unit into one that can never start (#119467). Refresh retires the Hermes file,
+and only that file: a drop-in the operator wrote is theirs.
"""
-import pytest
-
import hermes_cli.gateway as gateway_cli
-
-class TestSystemdReplaceDropinRetirement:
- POSITIVE = (
- "# Added to end the gateway respawn storm: a stray lock-holder used to make the\n"
- "# plain `gateway run` exit 1, and Restart=always turned that into thousands of\n"
- "# restarts. `--replace` makes systemd's start reclaim the lock instead of\n"
- "# crash-looping. Remove this file (and daemon-reload) to revert.\n"
- "[Service]\n"
- "ExecStart=\n"
- "ExecStart=/usr/bin/python -m hermes_cli.main gateway run --replace\n"
- )
-
- def _setup(self, tmp_path, monkeypatch, *, dropin=None):
- unit = tmp_path / "hermes-gateway.service"
- unit.write_bytes(b"[Unit]\nDescription=current\n")
- monkeypatch.setattr(gateway_cli, "get_systemd_unit_path", lambda system=False: unit)
- monkeypatch.setattr(
- gateway_cli, "generate_systemd_unit", lambda **_: "[Unit]\nDescription=current\n"
- )
- monkeypatch.setattr(gateway_cli, "_sync_hermes_home_from_systemd_unit", lambda **_: None)
- calls = []
- monkeypatch.setattr(
- gateway_cli, "_run_systemctl", lambda args, **kwargs: calls.append((args, kwargs))
- )
- if dropin is not None:
- dropin_path = unit.parent / f"{unit.name}.d" / "20-replace.conf"
- dropin_path.parent.mkdir()
- dropin_path.write_text(dropin, encoding="utf-8")
- return unit, calls
-
- def test_current_unit_retire_dropin_and_reload_once(self, tmp_path, monkeypatch, capsys):
- unit, calls = self._setup(tmp_path, monkeypatch, dropin=self.POSITIVE)
- before = unit.read_bytes()
- assert gateway_cli.systemd_unit_is_current() is False
- assert gateway_cli.refresh_systemd_unit_if_needed() is True
- assert unit.read_bytes() == before
- assert not (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert [args for args, _kwargs in calls] == [["daemon-reload"]]
- assert calls[0][1]["system"] is False
- assert "Removed stale Hermes --replace drop-in" in capsys.readouterr().out
-
- def test_retired_dropin_is_reloaded_when_unit_write_is_refused(
- self, tmp_path, monkeypatch, capsys
- ):
- unit, calls = self._setup(tmp_path, monkeypatch, dropin=self.POSITIVE)
- before = unit.read_bytes()
- monkeypatch.setattr(
- gateway_cli,
- "generate_systemd_unit",
- lambda **_: "[Unit]\nHERMES_HOME=/tmp/pytest-of-example/hermes_test\n",
- )
-
- assert gateway_cli.refresh_systemd_unit_if_needed() is False
- assert not (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert unit.read_bytes() == before
- assert [args for args, _kwargs in calls] == [["daemon-reload"]]
- assert "Removed stale Hermes --replace drop-in" in capsys.readouterr().out
-
- def test_stale_unit_rewrites_and_retires_dropin_once(self, tmp_path, monkeypatch):
- unit, calls = self._setup(tmp_path, monkeypatch, dropin=self.POSITIVE)
- replacement = "[Unit]\nDescription=rewritten\n"
- monkeypatch.setattr(gateway_cli, "generate_systemd_unit", lambda **_: replacement)
-
- assert gateway_cli.refresh_systemd_unit_if_needed() is True
- assert unit.read_text(encoding="utf-8") == replacement
- assert not (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert [args for args, _kwargs in calls] == [["daemon-reload"]]
-
- def test_same_filename_without_marker_is_kept(self, tmp_path, monkeypatch):
- unit, calls = self._setup(
- tmp_path, monkeypatch, dropin="[Service]\nExecStart=foo --replace\n"
- )
- assert gateway_cli.systemd_unit_is_current() is True
- assert gateway_cli.refresh_systemd_unit_if_needed() is False
- assert (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert calls == []
-
- def test_other_dropin_name_is_kept(self, tmp_path, monkeypatch):
- unit, calls = self._setup(tmp_path, monkeypatch)
- other = unit.parent / f"{unit.name}.d" / "10-custom.conf"
- other.parent.mkdir(parents=True)
- other.write_text(self.POSITIVE, encoding="utf-8")
- assert gateway_cli.refresh_systemd_unit_if_needed() is False
- assert other.exists() and calls == []
-
- @pytest.mark.parametrize(
- "text",
- [
- "# Added to end the gateway respawn storm\n[Service]\n",
- "# Added to end the gateway respawn storm\n[Service]\nExecStart=\n",
- "# Added to end the gateway respawn storm\n[Service]\nExecStart=foo\n",
- ],
- )
- def test_incomplete_marker_is_kept(self, tmp_path, monkeypatch, text):
- unit, calls = self._setup(tmp_path, monkeypatch, dropin=text)
- assert gateway_cli.refresh_systemd_unit_if_needed() is False
- assert (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert calls == []
-
- def test_no_dropin_current_unit_is_unchanged(self, tmp_path, monkeypatch):
- unit, calls = self._setup(tmp_path, monkeypatch)
- assert gateway_cli.refresh_systemd_unit_if_needed() is False
- assert unit.read_bytes() == b"[Unit]\nDescription=current\n"
- assert calls == []
-
- def test_system_scope_uses_patched_unit_path(self, tmp_path, monkeypatch):
- unit, calls = self._setup(tmp_path, monkeypatch, dropin=self.POSITIVE)
- assert gateway_cli.refresh_systemd_unit_if_needed(system=True) is True
- assert not (unit.parent / f"{unit.name}.d" / "20-replace.conf").exists()
- assert calls == [(["daemon-reload"], {"system": True, "check": True, "timeout": 30})]
+HERMES_DROPIN = (
+ "# Added to end the gateway respawn storm: a stray lock-holder used to make the\n"
+ "# plain `gateway run` exit 1, and Restart=always turned that into thousands of\n"
+ "# restarts. `--replace` makes systemd's start reclaim the lock instead of\n"
+ "# crash-looping. Remove this file (and daemon-reload) to revert.\n"
+ "[Service]\n"
+ "ExecStart=\n"
+ "ExecStart=/usr/bin/python -m hermes_cli.main gateway run --replace\n"
+)
+
+
+def _current_unit_with_dropin(tmp_path, monkeypatch, dropin_text: str):
+ unit = tmp_path / "hermes-gateway.service"
+ unit.write_text("[Unit]\nDescription=current\n", encoding="utf-8")
+ monkeypatch.setattr(gateway_cli, "get_systemd_unit_path", lambda system=False: unit)
+ monkeypatch.setattr(gateway_cli, "generate_systemd_unit", lambda **_: "[Unit]\nDescription=current\n")
+ monkeypatch.setattr(gateway_cli, "_sync_hermes_home_from_systemd_unit", lambda **_: None)
+ calls = []
+ monkeypatch.setattr(gateway_cli, "_run_systemctl", lambda args, **kwargs: calls.append((args, kwargs)))
+ dropin = unit.parent / f"{unit.name}.d" / "20-replace.conf"
+ dropin.parent.mkdir()
+ dropin.write_text(dropin_text, encoding="utf-8")
+ return unit, dropin, calls
+
+
+def test_refresh_retires_the_hermes_replace_dropin_even_when_the_unit_text_is_current(tmp_path, monkeypatch, capsys):
+ """The base unit already matches the generator, so the old gate said "nothing to do" and the
+ drop-in kept re-arming ``--replace`` on every restart."""
+ unit, dropin, calls = _current_unit_with_dropin(tmp_path, monkeypatch, HERMES_DROPIN)
+ before = unit.read_bytes()
+
+ assert gateway_cli.refresh_systemd_unit_if_needed(system=True) is True
+
+ assert not dropin.exists()
+ assert unit.read_bytes() == before, "the current unit itself is left alone"
+ assert [args for args, _ in calls] == [["daemon-reload"]] and calls[0][1]["system"] is True
+ assert "--replace drop-in" in capsys.readouterr().out
+
+
+def test_refresh_keeps_an_operator_written_dropin_of_the_same_name(tmp_path, monkeypatch):
+ """Only the file Hermes authored (recognised by its own comment) is retired."""
+ unit, dropin, calls = _current_unit_with_dropin(
+ tmp_path, monkeypatch, "[Service]\nExecStart=\nExecStart=/opt/hermes gateway run --replace\n")
+
+ assert gateway_cli.refresh_systemd_unit_if_needed() is False
+
+ assert dropin.exists() and calls == []