Skip to content

The agent that grows with you

fix(tui): a worker launched by a pre-update gateway keeps its parent-death guard

kshitijk4poor25f8dbfccba1
diff --git a/tests/tui_gateway/test_slash_worker_owned.py b/tests/tui_gateway/test_slash_worker_owned.py
index 0787766a960..a39c57128a3 100644
--- a/tests/tui_gateway/test_slash_worker_owned.py
+++ b/tests/tui_gateway/test_slash_worker_owned.py
@@ -166,9 +166,9 @@ def test_a_worker_that_already_died_is_never_group_signalled(monkeypatch):
os.killpg(leader.pid, signal.SIGKILL) # windows-footgun: ok — posix-marked test
-def test_main_imports_cli_before_runtime_prep_and_accepts_a_legacy_parent_pid(monkeypatch):
+def test_main_arms_the_legacy_watchdog_then_imports_cli_before_runtime_prep(monkeypatch):
"""``cli`` loads ~/.hermes/.env, which MCP discovery in the runtime prep needs. A gateway started
- before an update still passes ``--parent-pid``; the updated worker must still start."""
+ before an update still passes ``--parent-pid``; its death guard starts before the slow import."""
events = []
class FakeHermesCLI:
@@ -191,12 +191,13 @@ def test_main_imports_cli_before_runtime_prep_and_accepts_a_legacy_parent_pid(mo
monkeypatch.delitem(sys.modules, "cli")
monkeypatch.setattr(sys, "meta_path", [FakeCliFinder(), *sys.meta_path])
monkeypatch.setattr(slash_worker, "_prepare_slash_worker_runtime", lambda: events.append(("runtime",)))
+ monkeypatch.setattr(slash_worker, "_start_legacy_parent_watchdog", lambda pid: events.append(("watchdog", pid)))
monkeypatch.setattr(sys, "argv", ["slash_worker", "--session-key", "session-1", "--parent-pid", "424242"])
monkeypatch.setattr(sys, "stdin", io.StringIO(""))
slash_worker.main()
- assert events == [("cli-import",), ("runtime",), ("cli", "session-1")]
+ assert events == [("watchdog", 424242), ("cli-import",), ("runtime",), ("cli", "session-1")]
def test_slash_worker_close_reaps_zombie_and_closes_fds(monkeypatch):
@@ -245,3 +246,42 @@ def test_slash_worker_close_reaps_zombie_and_closes_fds(monkeypatch):
assert calls["terminate"] == calls["kill"] == 1
assert calls["wait"] >= 2 # reaped after both terminate and kill
assert calls["stdin"] == calls["stdout"] == calls["stderr"] == 1
+
+
+# A gateway started before the owned-child update: it runs its OLD code (plain Popen, --parent-pid,
+# no supervisor registration) against the updated worker on disk.
+_LEGACY_OWNER = r'''
+import os, subprocess, sys
+r = int(sys.argv[1])
+worker = subprocess.Popen([sys.executable, "-m", "tui_gateway.slash_worker", "--session-key", "legacy",
+ "--parent-pid", str(os.getpid())], stdin=r, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL, start_new_session=True, pass_fds=(r,))
+print(worker.pid, flush=True)
+sys.stdin.read()
+'''
+
+
[email protected]_system_guard_bypass # the worker reparents to init once its legacy owner dies
+def test_a_worker_launched_by_a_pre_update_gateway_still_dies_with_it(tmp_path):
+ """The test keeps the worker's stdin open, as a worker busy inside a command never reads EOF, so
+ only the legacy death guard can stop it after its old-code parent is SIGKILLed."""
+ r, w = os.pipe()
+ owner = subprocess.Popen([sys.executable, "-c", _LEGACY_OWNER, str(r)], env=_home(tmp_path, "legacy"),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, pass_fds=(r,))
+ os.close(r)
+ worker = None
+ try:
+ worker = psutil.Process(int(owner.stdout.readline()))
+ owner.kill()
+ owner.wait(timeout=10)
+ wait_until(lambda: not worker.is_running() or worker.status() == psutil.STATUS_ZOMBIE, timeout=30,
+ what="the legacy-launched worker to exit after its parent's kill -9")
+ finally:
+ os.close(w)
+ if worker is not None:
+ with contextlib.suppress(psutil.Error):
+ worker.kill()
+ if owner.poll() is None:
+ owner.kill()
+ owner.wait(timeout=10)
diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.py
index c8f5faa7980..a53b7285a0d 100644
--- a/tui_gateway/slash_worker.py
+++ b/tui_gateway/slash_worker.py
@@ -21,6 +21,8 @@ import json
import logging
import os
import sys
+import threading
+import time
from typing import TYPE_CHECKING
from tui_gateway._stdin_recovery import handle_spurious_eof
@@ -31,6 +33,34 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
+_in_flight = threading.Event() # set while a command executes (the legacy watchdog's grace)
+
+
+def _start_legacy_parent_watchdog(parent_pid: int, *, poll_s: float = 2.0, grace_s: float = 5.0) -> None:
+ """Keep the old death guard for a worker launched by a pre-update gateway.
+
+ A gateway started before the owned-child change still runs its old code. That code starts this
+ (updated) worker with a plain Popen and ``--parent-pid`` and never registers it with an
+ owner-death supervisor. If that gateway dies while the worker is inside a command, stdin EOF is
+ never read and nothing stops the worker. The watchdog compares the kernel's live ppid with the
+ pid passed at spawn, so a reused pid can never pass for the parent. An in-flight command gets
+ ``grace_s`` to finish. POSIX only: Windows never reparents, so the check could not fire there.
+ Current gateways don't pass ``--parent-pid`` (spawn_owned covers the worker), so it never starts.
+ """
+ if not parent_pid or os.name != "posix":
+ return
+
+ def _loop():
+ while os.getppid() == parent_pid:
+ time.sleep(poll_s)
+ deadline = time.monotonic() + grace_s
+ while _in_flight.is_set() and time.monotonic() < deadline:
+ time.sleep(0.05)
+ os._exit(0)
+
+ threading.Thread(target=_loop, daemon=True, name="slash-legacy-parent-watchdog").start()
+
+
def _prepare_slash_worker_runtime() -> None:
"""Start bounded MCP discovery before HermesCLI snapshots tools: each slash_worker child is its
own process — the parent ``hermes serve`` discovery thread does not populate this registry.
@@ -125,12 +155,13 @@ def main():
p.add_argument("--session-key", required=True)
p.add_argument("--model", default="")
p.add_argument("--provider", default="")
- # Accepted and ignored: a gateway started before an update still passes it to the updated worker
- # code on disk. The worker dies with its gateway through the gateway's owner-death supervisor.
+ # Passed only by a gateway started before the owned-child update (see the legacy watchdog).
p.add_argument("--parent-pid", type=int, default=0, help=argparse.SUPPRESS)
args = p.parse_args()
os.environ["HERMES_SESSION_KEY"] = args.session_key
os.environ["HERMES_INTERACTIVE"] = "1"
+ # Before the heavy cli import, so a legacy parent dying during startup is still noticed.
+ _start_legacy_parent_watchdog(args.parent_pid)
# Import cli ahead of MCP discovery: importing it loads ~/.hermes/.env and sets HERMES_QUIET,
# which MCP ``${VAR}`` interpolation in the runtime prep depends on.
from cli import HermesCLI
@@ -156,6 +187,7 @@ def main():
line = raw.strip()
if not line:
continue
+ _in_flight.set()
rid = None
try:
req = json.loads(line)
@@ -165,6 +197,7 @@ def main():
except Exception as e:
_reply(id=rid, ok=False, error=str(e))
finally:
+ _in_flight.clear()
# Workers persist for the TUI session: release allocator pages at the command boundary like
# other long-lived gateway processes (trim_memory's shared cooldown coalesces nearby activity).
try: