Skip to content

The agent that grows with you

fix(terminal): fully-qualified .scope unit name, exit-code check, already_exited cleanup (#70716)

toprakeker21de22a4ec4c
diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py
index d744042f53a..c3692bcb221 100644
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@ -1650,7 +1650,7 @@ class TestSystemdCgroupIsolation:
assert "--unit" in argv
unit_idx = argv.index("--unit")
assert argv[unit_idx + 1].startswith("hermes-worker-"), argv
- assert argv[unit_idx + 1] == f"hermes-worker-{session.id}", argv
+ assert argv[unit_idx + 1] == f"hermes-worker-{session.id}", argv # _build_systemd_scope_argv uses bare name
# The original shell command must still be present at the tail,
# after the ``--`` separator that prevents systemd-run from
# interpreting command flags as its own.
@@ -1661,7 +1661,7 @@ class TestSystemdCgroupIsolation:
# systemd-run owns session/cgroup creation — no start_new_session.
assert captured["start_new_session"] is False
# The session must record the unit name so kill_process can stop it.
- assert session.systemd_unit == f"hermes-worker-{session.id}"
+ assert session.systemd_unit == f"hermes-worker-{session.id}.scope"
def test_falls_back_when_systemd_run_unavailable(
self, registry, monkeypatch
@@ -1717,6 +1717,36 @@ class TestSystemdCgroupIsolation:
assert argv == ["/bin/bash", "-lic", "set +m; echo hello"], argv
assert captured["start_new_session"] is True
+ def test_kill_recovered_detached_already_exited_stops_persisted_scope(
+ self, registry, monkeypatch
+ ):
+ """Recovered detached sessions whose wrapper PID is gone/recycled must
+ still stop their persisted systemd scope before the already_exited
+ return, while retaining the PID-reuse guard (no PID tree kill)."""
+ session = _make_session(sid="proc_recovered_scope", command="daemonize")
+ session.detached = True
+ session.pid_scope = "host"
+ session.pid = 12345
+ session.host_start_time = 67890
+ session.systemd_unit = "hermes-worker-proc_recovered_scope.scope"
+ registry._running[session.id] = session
+
+ stopped = []
+ terminated = []
+ monkeypatch.setattr(registry, "_host_pid_is_ours", lambda pid, start: False)
+ monkeypatch.setattr(registry, "_terminate_host_pid", lambda pid, start: terminated.append((pid, start)))
+ monkeypatch.setattr("tools.process_registry._stop_systemd_unit", lambda unit: stopped.append(unit) or True)
+
+ with patch.object(registry, "_write_checkpoint"):
+ result = registry.kill_process(session.id)
+
+ assert result["status"] == "already_exited"
+ assert stopped == ["hermes-worker-proc_recovered_scope.scope"]
+ assert terminated == []
+ assert session.exited is True
+ assert session.id in registry._finished
+ assert session.id not in registry._running
+
def test_systemd_run_user_scope_available_caches_after_probe(
self, registry, monkeypatch
):
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 5492531429a..0da6b498f6e 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -190,8 +190,8 @@ def _stop_systemd_unit(unit_name: str) -> bool:
SIGTERM to every process in the unit's cgroup and escalates to SIGKILL
after the unit's ``TimeoutStopSec``.
- Returns True if the command ran (regardless of exit code — the unit may
- already be gone), False if ``systemctl`` is unavailable.
+ Returns True if the unit was successfully stopped (or was already gone),
+ False if ``systemctl`` is unavailable or the stop command failed.
"""
import shutil
@@ -199,11 +199,18 @@ def _stop_systemd_unit(unit_name: str) -> bool:
if binary is None:
return False
try:
- subprocess.run(
+ result = subprocess.run(
[binary, "--user", "stop", unit_name],
capture_output=True,
timeout=15,
)
+ if result.returncode != 0:
+ logger.debug(
+ "systemctl --user stop %s exited %d: %s",
+ unit_name, result.returncode,
+ result.stderr.decode(errors="replace").strip(),
+ )
+ return False
return True
except Exception as exc:
logger.debug("systemctl --user stop %s failed: %s", unit_name, exc)
@@ -890,7 +897,7 @@ class ProcessRegistry:
pty_argv = _build_systemd_scope_argv(
pty_argv, unit_suffix=session.id,
)
- session.systemd_unit = f"hermes-worker-{session.id}"
+ session.systemd_unit = f"hermes-worker-{session.id}.scope"
elif not _IS_WINDOWS:
try:
from gateway.restart import is_gateway_supervisor_process as _sup
@@ -972,7 +979,7 @@ class ProcessRegistry:
spawn_argv = _build_systemd_scope_argv(
shell_argv, unit_suffix=session.id,
)
- session.systemd_unit = f"hermes-worker-{session.id}"
+ session.systemd_unit = f"hermes-worker-{session.id}.scope"
# systemd-run creates the new session/cgroup for us; do NOT also
# set start_new_session (harmless, but redundant and it can mask
# scope-creation failures in some systemd versions).
@@ -1864,6 +1871,12 @@ class ProcessRegistry:
return {"status": "not_found", "error": f"No process with ID {session_id}"}
if session.exited:
+ # Even if the main process already exited, a double-forked
+ # descendant may still be alive in the systemd scope (#70716,
+ # reviewer gap #2 — the ``already_exited`` early return skipped
+ # unit cleanup). Stop the scope to reap any survivors.
+ if session.systemd_unit:
+ _stop_systemd_unit(session.systemd_unit)
with session._lock:
result = {
"status": "already_exited",
@@ -1899,8 +1912,14 @@ class ProcessRegistry:
elif session.detached and session.pid_scope == "host" and session.pid:
# Identity check, not bare liveness: if the PID is gone OR was
# recycled onto an unrelated process, treat our process as
- # exited and never tree-kill the stranger.
+ # exited and never tree-kill the stranger. If this recovered
+ # session also carries an owned systemd scope, stop that scope
+ # before returning: a daemonized descendant may still be alive
+ # there even though the wrapper PID exited or was recycled
+ # across the gateway restart (#70716, teknium1 review).
if not self._host_pid_is_ours(session.pid, session.host_start_time):
+ if session.systemd_unit:
+ _stop_systemd_unit(session.systemd_unit)
with session._lock:
session.exited = True
session.exit_code = None