Skip to content

The agent that grows with you

feat(update): name the work a draining gateway is waiting on

teknium16a312fba54d9
diff --git a/cron/scheduler.py b/cron/scheduler.py
index be4b10ab0e5..96c8292d4be 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -496,6 +496,9 @@ _running_fire_owners: dict[str, dict[object, tuple[Optional[str], Path]]] = {}
# Shutdown must not misclassify these as ownerless in-process runs: the tool
# process sweep cannot reach the worker's transient scope.
_restart_safe_waiter_job_ids: set[str] = set()
+# job_id -> pid of the restart-safe external worker executing it (absent for in-process runs), so a
+# drain observer can name the process holding the gateway open.
+_running_worker_pids: dict[str, int] = {}
_running_lock = threading.Lock()
# Per in-flight id: time.time() claim instant + the future owning its release (``_FUTURE_PENDING``
@@ -564,6 +567,18 @@ def get_running_job_ids() -> "frozenset[str]":
return frozenset(_running_job_ids | _running_fire_owners.keys())
+def get_running_job_details() -> list[dict]:
+ """Per in-flight job: ``{"job_id", "elapsed_s", "worker_pid"}`` (``worker_pid`` None for in-process
+ runs). The drain wait publishes this so ``hermes update`` can say WHICH job it is waiting on."""
+ now = time.time()
+ with _running_lock:
+ return [
+ {"job_id": jid, "elapsed_s": round(now - _running_since[jid], 1) if jid in _running_since else None,
+ "worker_pid": _running_worker_pids.get(jid)}
+ for jid in sorted(_running_job_ids | _running_fire_owners.keys())
+ ]
+
+
def try_register_running_job(job_id: str) -> bool:
"""Atomically add ``job_id`` to the in-flight set; False (caller must skip) if already mid-run.
Single dedupe owner for ticker + manual runs (the fire claim's 300s TTL is outlived by real
@@ -593,6 +608,7 @@ def release_running_job(job_id: str) -> None:
_running_job_ids.discard(job_id)
_running_since.pop(job_id, None)
_running_futures.pop(job_id, None)
+ _running_worker_pids.pop(job_id, None)
def _inflight_min_allowance_minutes() -> float:
@@ -3222,6 +3238,8 @@ def _launch_external_cron_worker(job: dict) -> bool:
acknowledgement.get("pid"),
execution_id,
)
+ with _running_lock, contextlib.suppress(TypeError, ValueError):
+ _running_worker_pids[job_id] = int(acknowledgement.get("pid") or process.pid)
return _wait_for_external_cron_worker(
process,
execution_id=execution_id,
diff --git a/gateway/run.py b/gateway/run.py
index 302749ab8d9..4e982e242a1 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3907,9 +3907,13 @@ class GatewayRunner(
return "restarting" if self._restart_requested else "shutting down"
def _update_runtime_status(self, gateway_state: Optional[str] = None, exit_reason: Optional[str] = None) -> None:
+ # ``active_work`` names each unit only while draining — that is when an observer (``hermes
+ # update``) needs to know WHAT holds the gateway open; a per-turn write would be wasted I/O.
+ active_work = self._describe_active_work() if gateway_state == "draining" else None
_write_runtime_status_quiet(
gateway_state=gateway_state, exit_reason=exit_reason,
- restart_requested=self._restart_requested, active_agents=self._active_work_count())
+ restart_requested=self._restart_requested, active_agents=self._active_work_count(),
+ active_work=active_work)
def _persist_active_agents(self) -> None:
"""Persist the live in-flight agent count to ``gateway_state.json`` at every turn boundary.
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index 845ae0ce219..52bf07449ac 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1375,6 +1375,42 @@ class GatewayShutdownMixin:
"""Active work minus wedged turns — what the restart wait waits on."""
return max(0, self._active_work_count() - self._wedged_agent_count())
+ def _describe_active_work(self) -> list:
+ """One dict per in-flight work unit the restart wait is holding for, so an observer
+ (``hermes update``, ``hermes gateway status``) can name it instead of printing a bare count.
+
+ ``kind`` ∈ ``chat`` (session turn), ``cron`` (job id + external worker pid when the run was
+ handed to a restart-safe scope), ``api`` / ``deferred`` (count only — those sources expose
+ no identity). Best-effort: a source that can't be read is omitted, never raises.
+ """
+ from gateway.run import _AGENT_PENDING_SENTINEL
+ now = time.time()
+ units: list = []
+ for key, state in list(self._sessions_map().items()):
+ agent = state.turn.agent
+ if agent is None:
+ continue
+ unit: dict = {"kind": "chat", "session": key, "pid": os.getpid()}
+ if state.turn.started_ts:
+ unit["elapsed_s"] = round(now - state.turn.started_ts, 1)
+ if agent is not _AGENT_PENDING_SENTINEL:
+ unit["model"] = getattr(agent, "model", None)
+ summary_fn = getattr(agent, "get_activity_summary", None)
+ if callable(summary_fn):
+ with suppress(Exception):
+ summary = summary_fn()
+ unit["current_tool"] = summary.get("current_tool")
+ unit["idle_s"] = summary.get("seconds_since_activity")
+ units.append(unit)
+ with suppress(Exception):
+ from cron.scheduler import get_running_job_details
+ for job in get_running_job_details():
+ units.append({"kind": "cron", "job_id": job["job_id"], "elapsed_s": job["elapsed_s"],
+ "pid": job["worker_pid"] or os.getpid(), "external": bool(job["worker_pid"])})
+ for kind, count in (("api", self._active_api_run_count()), ("deferred", self._active_deferred_agent_worker_count())):
+ units.extend({"kind": kind, "pid": os.getpid()} for _ in range(count))
+ return units
+
async def _await_active_work_before_restart(self) -> bool:
"""Wait for in-flight work before ``stop()`` so the requesting turn isn't force-interrupted.
@@ -1419,8 +1455,9 @@ class GatewayShutdownMixin:
if (now - last_status_at) >= 30.0:
logger.info(
"Restart deferred: waiting on %d active work unit(s) "
- "(%d wedged and excluded; %.0fs remaining before force drain)",
+ "(%d wedged and excluded; %.0fs remaining before force drain): %s",
self._awaitable_work_count(), self._wedged_agent_count(), deadline - now,
+ self._describe_active_work(),
)
self._scale_to_zero_status("draining", "restart wait: status mark failed")
last_status_at = now
diff --git a/gateway/status.py b/gateway/status.py
index 2176a37f01b..9b197b33f16 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -801,7 +801,7 @@ def _coerce_session_store(session_store: Any) -> dict[str, str]:
def write_runtime_status(
*, gateway_state: Any = _UNSET, exit_reason: Any = _UNSET, restart_requested: Any = _UNSET,
- active_agents: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,
+ active_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,
error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,
retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,
ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,
@@ -832,6 +832,8 @@ def write_runtime_status(
("gateway_state", gateway_state, None), ("exit_reason", exit_reason, None),
("restart_requested", restart_requested, bool),
("active_agents", active_agents, parse_active_agents),
+ # Named in-flight units (see GatewayShutdownMixin._describe_active_work); None clears.
+ ("active_work", active_work, lambda v: list(v) if v else None),
# Multiplexed profiles; absent/empty for a single-profile gateway.
("served_profiles", served_profiles, lambda v: list(v or [])),
("session_store", session_store, _coerce_session_store),
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index fbb1dbba37e..c16e1f5603d 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -261,12 +261,13 @@ def _request_gateway_self_restart(pid: int) -> bool:
return True
-def _graceful_restart_via_sigusr1(pid: int, drain_timeout: float) -> bool:
+def _graceful_restart_via_sigusr1(pid: int, drain_timeout: float, *, on_progress=None) -> bool:
"""SIGUSR1 (drain-aware restart) a gateway PID and wait for exit; False if unsent or it outlived the timeout.
gateway/run.py maps SIGUSR1 to ``request_restart(via_service=True)``: refuse new turns, drain,
``stop()``, exit; the supervisor relaunches. ``drain_timeout`` must cover after-turn wait + drain
- — pass ``resolve_restart_exit_wait_budget(...)``.
+ — pass ``resolve_restart_exit_wait_budget(...)``. ``on_progress`` (zero-arg) runs on every poll so
+ a long wait can report what the gateway is still holding for (``update_cmd_drain_report``).
"""
if not hasattr(signal, "SIGUSR1") or pid <= 0:
return False
@@ -277,10 +278,10 @@ def _graceful_restart_via_sigusr1(pid: int, drain_timeout: float) -> bool:
except (PermissionError, OSError):
return False
- return _wait_for_pid_exit(pid, max(drain_timeout, 1.0))
+ return _wait_for_pid_exit(pid, max(drain_timeout, 1.0), on_progress=on_progress)
-def _wait_for_pid_exit(pid: int, timeout: float) -> bool:
+def _wait_for_pid_exit(pid: int, timeout: float, *, on_progress=None) -> bool:
"""Wait up to ``timeout``s for ``pid`` to exit; True once gone. (``launchctl bootstrap`` fails EIO
while the previous instance still drains, so teardown callers must wait for the real exit.)"""
if pid <= 0:
@@ -293,6 +294,8 @@ def _wait_for_pid_exit(pid: int, timeout: float) -> bool:
return True
if time.monotonic() >= deadline:
return False
+ if on_progress is not None:
+ on_progress()
time.sleep(0.5)
@@ -3414,7 +3417,8 @@ def _systemd_graceful_restart_action(system: bool, pid: int) -> str | None:
f"⏳ {scope_label} service restarting gracefully (PID {pid}) — "
f"waiting up to {wait_budget:.0f}s for in-flight turns + drain..."
)
- if not _graceful_restart_via_sigusr1(pid, wait_budget):
+ from hermes_cli.update_cmd_drain_report import drain_progress_reporter
+ if not _graceful_restart_via_sigusr1(pid, wait_budget, on_progress=drain_progress_reporter(budget_s=wait_budget)):
print(f"⚠ Graceful restart did not complete within {int(wait_budget)}s; forcing a service restart...")
return "restart"
@@ -4240,7 +4244,8 @@ def launchd_restart():
# surfaces with no other feedback (desktop updater) read silence as "update stuck".
wait_budget = _get_restart_exit_wait_budget()
print(f"→ Stopping gateway (PID {pid}) — draining in-flight runs (up to {wait_budget:.0f}s)...")
- if _graceful_restart_via_sigusr1(pid, wait_budget):
+ from hermes_cli.update_cmd_drain_report import drain_progress_reporter
+ if _graceful_restart_via_sigusr1(pid, wait_budget, on_progress=drain_progress_reporter(budget_s=wait_budget)):
# KeepAlive revives a planned exit, so do NOT kickstart (-k would kill the replacement) —
# but a clean exit doesn't prove supervision, so verify a replacement PID appears first.
if _wait_for_launchd_service_pid(label, pid, timeout=15.0, domain=domain):
@@ -4999,6 +5004,10 @@ def _runtime_health_lines() -> list[str]:
from gateway.status import parse_active_agents
count = parse_active_agents(state.get("active_agents"))
lines.append(f"⏳ Gateway draining for {action} ({count} active agent(s))")
+ work = state.get("active_work")
+ if isinstance(work, list) and work:
+ from hermes_cli.update_cmd_drain_report import describe_active_work_unit
+ lines.extend(f" • {describe_active_work_unit(u)}" for u in work if isinstance(u, dict))
elif gateway_state == "stopped" and exit_reason:
lines.append(f"⚠ Last shutdown reason: {exit_reason}")
diff --git a/hermes_cli/update_cmd_drain_report.py b/hermes_cli/update_cmd_drain_report.py
new file mode 100644
index 00000000000..bace46b7796
--- /dev/null
+++ b/hermes_cli/update_cmd_drain_report.py
@@ -0,0 +1,112 @@
+"""Name what a draining gateway is waiting on while ``hermes update`` blocks on it.
+
+The gateway's in-band restart (SIGUSR1 → ``request_restart``) defers ``stop()`` until in-flight
+work finishes, capped by ``agent.restart_after_turn_timeout`` (30 min by default). From the
+updater's side that was a bare "draining (up to 1875s)..." followed by silence, which reads as a
+hung update. The gateway publishes each unit it is holding for in ``gateway_state.json``
+(``active_work``, written by ``GatewayShutdownMixin._describe_active_work``); this module turns
+that into progress lines.
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+from typing import Callable, Optional
+
+# Progress cadence: the gateway refreshes ``active_work`` every 30s; printing faster only repeats it.
+DRAIN_REPORT_INTERVAL_S = 30.0
+
+
+def _fmt_elapsed(seconds: object) -> str:
+ try:
+ total = int(float(seconds)) # type: ignore[arg-type]
+ except (TypeError, ValueError):
+ return "?"
+ return f"{total // 60}m{total % 60:02d}s" if total >= 60 else f"{total}s"
+
+
+def _cron_job_name(job_id: str, home: Optional[Path]) -> Optional[str]:
+ """``name`` from the profile's ``jobs.json`` (None when unreadable — the id alone still identifies it)."""
+ try:
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+ from cron.jobs import load_jobs
+
+ token = set_hermes_home_override(home) if home else None
+ try:
+ for job in load_jobs():
+ if str(job.get("id")) == job_id:
+ return str(job.get("name") or "") or None
+ finally:
+ if token is not None:
+ reset_hermes_home_override(token)
+ except Exception:
+ return None
+ return None
+
+
+def describe_active_work_unit(unit: dict, home: Optional[Path] = None) -> str:
+ """One human line for one ``active_work`` entry; unknown shapes degrade to their ``kind``."""
+ kind = str(unit.get("kind") or "work")
+ pid = unit.get("pid")
+ pid_part = f" pid {pid}" if pid else ""
+ elapsed = unit.get("elapsed_s")
+ elapsed_part = f", running {_fmt_elapsed(elapsed)}" if elapsed is not None else ""
+ if kind == "cron":
+ job_id = str(unit.get("job_id") or "?")
+ name = _cron_job_name(job_id, home)
+ label = f"cron job {job_id}" + (f" ({name})" if name else "")
+ where = f" in external worker{pid_part}" if unit.get("external") else f" in-process{pid_part}"
+ return f"{label}{where}{elapsed_part}"
+ if kind == "chat":
+ session = str(unit.get("session") or "?")
+ model = unit.get("model")
+ tool = unit.get("current_tool")
+ detail = ", ".join(p for p in (f"model {model}" if model else "", f"tool {tool}" if tool else "") if p)
+ return f"chat turn {session}{pid_part}{elapsed_part}" + (f" [{detail}]" if detail else "")
+ return f"{kind} run{pid_part}{elapsed_part}"
+
+
+def read_active_work(home: Optional[Path] = None) -> Optional[list]:
+ """``active_work`` as the gateway last published it, or None (old gateway / not draining / unreadable)."""
+ try:
+ from gateway.status import read_runtime_status
+
+ record = read_runtime_status(home / "gateway_state.json" if home else None) or {}
+ work = record.get("active_work")
+ return list(work) if isinstance(work, list) else None
+ except Exception:
+ return None
+
+
+def format_drain_report(work: Optional[list], *, remaining_s: float, home: Optional[Path] = None) -> str:
+ """Multi-line progress block: what the gateway is waiting on plus how to stop waiting."""
+ lines = [f" ⏳ still draining — {int(max(remaining_s, 0))}s left before the forced restart"]
+ if work is None:
+ lines.append(" (gateway did not report what it is waiting on — pre-update gateway or unreadable state file)")
+ elif not work:
+ lines.append(" (no active work reported; the gateway should exit momentarily)")
+ else:
+ lines.append(f" waiting on {len(work)} active work unit(s):")
+ lines.extend(f" • {describe_active_work_unit(u, home)}" for u in work)
+ lines.append(" finish or kill the work above to release the drain now; "
+ "agent.restart_after_turn_timeout in config.yaml caps this wait")
+ return "\n".join(lines)
+
+
+def drain_progress_reporter(home: Optional[Path] = None, *, budget_s: float,
+ interval_s: float = DRAIN_REPORT_INTERVAL_S,
+ emit: Callable[[str], None] = print) -> Callable[[], None]:
+ """Return a zero-arg callback for ``_wait_for_pid_exit(on_progress=...)`` that prints the drain
+ report every ``interval_s`` while the wait is in progress."""
+ started = time.monotonic()
+ state = {"last": started}
+
+ def _tick() -> None:
+ now = time.monotonic()
+ if now - state["last"] < interval_s:
+ return
+ state["last"] = now
+ emit(format_drain_report(read_active_work(home), remaining_s=budget_s - (now - started), home=home))
+
+ return _tick
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index a3c1deafb28..0ffa745af28 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -602,7 +602,10 @@ def _restart_macos_launchd_gateways(
graceful_ok = False
if old_pid is not None and old_pid > 0:
print(f" → {label}: draining (up to {int(drain_budget)}s)...")
- graceful_ok = _graceful_restart_via_sigusr1(old_pid, drain_timeout=drain_budget)
+ from hermes_cli.update_cmd_drain_report import drain_progress_reporter
+ graceful_ok = _graceful_restart_via_sigusr1(
+ old_pid, drain_timeout=drain_budget,
+ on_progress=drain_progress_reporter(_gateway_home_for_pid(old_pid), budget_s=drain_budget))
if graceful_ok and _wait_for_launchd_service_pid(label, old_pid=old_pid, timeout=10.0, domain=domain):
# KeepAlive already respawned it on new code — a kickstart would kill it.
restarted_services.append(label)
@@ -753,7 +756,22 @@ def _drain_or_signal_gateway_for_update(pid: int, drain_budget: float, label: st
_escalate_wedged_gateway(pid)
return True
print(f" → {label}: draining (up to {int(drain_budget)}s)...")
- return _graceful_restart_via_sigusr1(pid, drain_timeout=drain_budget)
+ from hermes_cli.update_cmd_drain_report import drain_progress_reporter
+ return _graceful_restart_via_sigusr1(
+ pid, drain_timeout=drain_budget,
+ on_progress=drain_progress_reporter(_gateway_home_for_pid(pid), budget_s=drain_budget))
+
+
+def _gateway_home_for_pid(pid: int):
+ """HERMES_HOME of the gateway ``pid`` per the fleet inventory, else None (own profile's file)."""
+ with suppress(Exception):
+ from hermes_cli.update_receipt import _profile_homes
+ from gateway.status import read_runtime_status
+ for _profile, home in _profile_homes():
+ record = read_runtime_status(home / "gateway_state.json") or {}
+ if record.get("pid") == pid:
+ return home
+ return None
def _resolve_manage_cmd(cache: dict, scope_: str, scope_cmd_: list, svc_name_: str):
diff --git a/tests/gateway/test_drain_active_work_report.py b/tests/gateway/test_drain_active_work_report.py
new file mode 100644
index 00000000000..8e8568b4591
--- /dev/null
+++ b/tests/gateway/test_drain_active_work_report.py
@@ -0,0 +1,73 @@
+"""A draining gateway names the work it is waiting on, and the updater's wait prints it.
+
+Before: ``hermes update`` printed "draining (up to 1875s)..." and then nothing for up to 30 minutes
+while the gateway waited on one cron job; neither surface said WHAT was being waited on.
+"""
+
+import json
+import time
+
+import cron.scheduler as sched
+from gateway.run import GatewayRunner
+from gateway.session_state import SessionState
+from hermes_cli.update_cmd_drain_report import drain_progress_reporter
+
+
+class _FakeAgent:
+ model = "test/model"
+
+ def get_activity_summary(self):
+ return {"current_tool": "terminal", "seconds_since_activity": 1.0}
+
+
+def _runner():
+ runner = object.__new__(GatewayRunner)
+ runner._restart_requested = True
+ runner.adapters = {}
+ return runner
+
+
+def test_draining_status_names_chat_and_cron_units_and_clears_when_running(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ runner = _runner()
+ state = SessionState()
+ state.turn.agent = _FakeAgent()
+ state.turn.started_ts = time.time() - 10
+ runner._sessions_map()["telegram:dm:1"] = state
+ assert sched.try_register_running_job("job-a")
+ try:
+ with sched._running_lock:
+ sched._running_worker_pids["job-a"] = 4242
+ runner._update_runtime_status("draining")
+ record = json.loads((tmp_path / "gateway_state.json").read_text())
+ by_kind = {unit["kind"]: unit for unit in record["active_work"]}
+ assert by_kind["chat"]["session"] == "telegram:dm:1" and by_kind["chat"]["current_tool"] == "terminal"
+ assert by_kind["cron"]["job_id"] == "job-a" and by_kind["cron"]["pid"] == 4242 and by_kind["cron"]["external"]
+ assert record["active_agents"] == len(record["active_work"])
+ finally:
+ sched.release_running_job("job-a")
+ assert sched.get_running_job_details() == []
+ runner._update_runtime_status("running")
+ assert json.loads((tmp_path / "gateway_state.json").read_text())["active_work"] is None
+
+
+def test_drain_progress_reporter_prints_holder_and_config_knob(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "cron").mkdir()
+ (tmp_path / "cron" / "jobs.json").write_text(json.dumps({"jobs": [{"id": "job-a", "name": "nightly-scout"}]}))
+ (tmp_path / "gateway_state.json").write_text(json.dumps({
+ "pid": 1, "gateway_state": "draining",
+ "active_work": [{"kind": "cron", "job_id": "job-a", "pid": 4242, "external": True, "elapsed_s": 95}],
+ }))
+ out = []
+ tick = drain_progress_reporter(tmp_path, budget_s=600, interval_s=0.0, emit=out.append)
+ tick()
+ report = out[0]
+ assert "nightly-scout" in report and "job-a" in report and "pid 4242" in report and "1m35s" in report
+ assert "restart_after_turn_timeout" in report
+
+ # Pre-fix gateway (no active_work field): the wait still explains itself instead of going silent.
+ (tmp_path / "gateway_state.json").write_text(json.dumps({"pid": 1, "gateway_state": "draining"}))
+ out.clear()
+ tick()
+ assert "did not report" in out[0]
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 23594785733..5f91c8e81eb 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -678,7 +678,7 @@ class TestLaunchdServiceRecovery:
monkeypatch.setattr(
gateway_cli,
"_wait_for_pid_exit",
- lambda pid, timeout: waited.append((pid, timeout)) or True,
+ lambda pid, timeout, **_: waited.append((pid, timeout)) or True,
)
run_calls = []
@@ -874,7 +874,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(
gateway_cli,
"_graceful_restart_via_sigusr1",
- lambda pid, timeout: calls.append(("graceful", pid, timeout)) or True,
+ lambda pid, timeout, **_: calls.append(("graceful", pid, timeout)) or True,
)
# Once SIGUSR1 makes the gateway exit with the planned restart code,
@@ -913,7 +913,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(gateway_cli, "refresh_systemd_unit_if_needed", lambda system=False: None)
monkeypatch.setattr(gateway_cli, "_get_restart_exit_wait_budget", lambda: 27.0)
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 654)
- monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout: True)
+ monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout, **_: True)
waits = iter((False, True))
monkeypatch.setattr(
gateway_cli,
@@ -947,7 +947,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(gateway_cli, "refresh_systemd_unit_if_needed", lambda system=False: None)
monkeypatch.setattr(gateway_cli, "_get_restart_exit_wait_budget", lambda: 27.0)
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 654)
- monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout: True)
+ monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout, **_: True)
monkeypatch.setattr(
gateway_cli,
"_wait_for_systemd_service_restart",
@@ -974,7 +974,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(gateway_cli, "refresh_systemd_unit_if_needed", lambda system=False: None)
monkeypatch.setattr(gateway_cli, "_get_restart_exit_wait_budget", lambda: 27.0)
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 654)
- monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout: True)
+ monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout, **_: True)
def failed_replacement_wait(
system=False, previous_pid=None, replacement_observed=None
@@ -1004,7 +1004,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(gateway_cli, "refresh_systemd_unit_if_needed", lambda system=False: None)
monkeypatch.setattr(gateway_cli, "_get_restart_exit_wait_budget", lambda: 27.0)
monkeypatch.setattr("gateway.status.get_running_pid", lambda: 654)
- monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout: True)
+ monkeypatch.setattr(gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout, **_: True)
monkeypatch.setattr(
gateway_cli,
"_wait_for_systemd_service_restart",
@@ -1091,7 +1091,7 @@ class TestGatewaySystemServiceRouting:
monkeypatch.setattr(
gateway_cli,
"_graceful_restart_via_sigusr1",
- lambda pid, timeout: calls.append(("graceful", pid, timeout)) or True,
+ lambda pid, timeout, **_: calls.append(("graceful", pid, timeout)) or True,
)
monkeypatch.setattr(
gateway_cli,
@@ -1153,7 +1153,7 @@ class TestGatewaySystemServiceRouting:
)
monkeypatch.setattr(gateway_cli, "_get_restart_exit_wait_budget", lambda: 27.0)
monkeypatch.setattr(
- gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout: True
+ gateway_cli, "_graceful_restart_via_sigusr1", lambda pid, timeout, **_: True
)
monkeypatch.setattr(
gateway_cli,
diff --git a/tests/hermes_cli/test_update_cron_deadlock_guard.py b/tests/hermes_cli/test_update_cron_deadlock_guard.py
index d4cce9746ae..c20d7e3e5c1 100644
--- a/tests/hermes_cli/test_update_cron_deadlock_guard.py
+++ b/tests/hermes_cli/test_update_cron_deadlock_guard.py
@@ -97,7 +97,7 @@ class TestSelfRestartFireAndForget:
with patch.object(gw.os, "kill"), patch.object(
gw, "_wait_for_pid_exit",
- side_effect=lambda pid, t: waited.append((pid, t)) or True,
+ side_effect=lambda pid, t, **_: waited.append((pid, t)) or True,
):
ok = gw._graceful_restart_via_sigusr1(4242, drain_timeout=7.0)
@@ -131,7 +131,7 @@ class TestDrainOrSignalTriage:
monkeypatch.setattr(
gw,
"_graceful_restart_via_sigusr1",
- lambda pid, drain_timeout: calls["drain"].append((pid, drain_timeout))
+ lambda pid, drain_timeout, **_: calls["drain"].append((pid, drain_timeout))
or True,
)
return calls
diff --git a/tests/hermes_cli/test_update_launchd_fleet_restart.py b/tests/hermes_cli/test_update_launchd_fleet_restart.py
index 0f396a56814..26d0b9737c5 100644
--- a/tests/hermes_cli/test_update_launchd_fleet_restart.py
+++ b/tests/hermes_cli/test_update_launchd_fleet_restart.py
@@ -293,7 +293,7 @@ def _fleet(monkeypatch, tmp_path, *, current, labels, located,
monkeypatch.setattr(
gw,
"_graceful_restart_via_sigusr1",
- lambda pid, drain_timeout: (rec.drains.append(pid), (drain_results or {}).get(pid, False))[1],
+ lambda pid, drain_timeout, **_: (rec.drains.append(pid), (drain_results or {}).get(pid, False))[1],
)
def fake_kickstart(label, domain):
diff --git a/tests/hermes_cli/test_update_wedged_gateway.py b/tests/hermes_cli/test_update_wedged_gateway.py
index ece8ec3a669..f76d3203810 100644
--- a/tests/hermes_cli/test_update_wedged_gateway.py
+++ b/tests/hermes_cli/test_update_wedged_gateway.py
@@ -227,7 +227,7 @@ def _launchd_harness(monkeypatch, tmp_path, pid):
monkeypatch.setattr(
gateway_cli,
"_graceful_restart_via_sigusr1",
- lambda pid, timeout: events.append(("drain", pid, timeout)) or True,
+ lambda pid, timeout, **_: events.append(("drain", pid, timeout)) or True,
)
monkeypatch.setattr(
gateway_cli,
@@ -343,7 +343,7 @@ class TestEscalateWedgedGateway:
lambda pid, force=False, **kwargs: signals.append(("kill" if force else "term", pid)),
)
monkeypatch.setattr(
- gateway_cli, "_wait_for_pid_exit", lambda pid, timeout: True
+ gateway_cli, "_wait_for_pid_exit", lambda pid, timeout, **_: True
)
assert gateway_cli._escalate_wedged_gateway(4242) is True
@@ -375,7 +375,7 @@ class TestEscalateWedgedGateway:
monkeypatch.setattr(
gateway_cli,
"_wait_for_pid_exit",
- lambda pid, timeout: waits.append(timeout) or False,
+ lambda pid, timeout, **_: waits.append(timeout) or False,
)
assert gateway_cli._escalate_wedged_gateway(4242) is False
@@ -387,7 +387,7 @@ class TestEscalateWedgedGateway:
monkeypatch.setattr(gateway_cli, "terminate_pid", raise_gone)
monkeypatch.setattr(
- gateway_cli, "_wait_for_pid_exit", lambda pid, timeout: True
+ gateway_cli, "_wait_for_pid_exit", lambda pid, timeout, **_: True
)
assert gateway_cli._escalate_wedged_gateway(4242) is True
@@ -402,7 +402,7 @@ class TestEscalateWedgedGateway:
monkeypatch.setattr(gateway_cli, "terminate_pid", term)
monkeypatch.setattr(
- gateway_cli, "_wait_for_pid_exit", lambda pid, timeout: False
+ gateway_cli, "_wait_for_pid_exit", lambda pid, timeout, **_: False
)
assert gateway_cli._escalate_wedged_gateway(4242) is False
@@ -442,7 +442,7 @@ class TestLaunchdRestartWedgedIntegration:
monkeypatch.setattr(
gateway_cli,
"_graceful_restart_via_sigusr1",
- lambda pid, timeout: events.append(("drain", pid, timeout)) or True,
+ lambda pid, timeout, **_: events.append(("drain", pid, timeout)) or True,
)
# KeepAlive revival observed instantly — avoids the real 15s poll
# (mocked subprocess.run returns empty stdout, so the PID probe
@@ -609,7 +609,7 @@ class TestLoopTickWitness:
monkeypatch.setattr(
gateway_cli,
"_graceful_restart_via_sigusr1",
- lambda pid, timeout: events.append(("drain", pid, timeout)) or True,
+ lambda pid, timeout, **_: events.append(("drain", pid, timeout)) or True,
)
monkeypatch.setattr(
gateway_cli,
diff --git a/website/docs/getting-started/updating.md b/website/docs/getting-started/updating.md
index c843f849170..dee90d0e930 100644
--- a/website/docs/getting-started/updating.md
+++ b/website/docs/getting-started/updating.md
@@ -43,6 +43,20 @@ When you run `hermes update`, the following steps occur:
7. **Gateway auto-restart** — running gateways are refreshed after the update completes so the new code takes effect immediately. Service-managed gateways (systemd on Linux, launchd on macOS) are restarted through the service manager. Manual gateways are relaunched automatically when Hermes can map the running PID back to a profile. Manually-launched `hermes serve` / `hermes dashboard` backends (for example a network-bound serve powering a remote Desktop) are handled the same way: each backend records its bind address in the install's spawn ledger at startup, so the update stops it before the code swap and relaunches it afterward on the **same host and port** — a remote Desktop pointed at that endpoint reconnects instead of stranding. Backends owned by a running Desktop app are left to the app's own respawn.
8. **Multiplex migration (multi-profile installs)** — once the fleet is verified on the new code, an install with two or more profiles that still run **one gateway per profile** is folded into a single multiplexed default gateway when nothing blocks it (same as `hermes gateway migrate --multiplex --yes`); if a blocker exists (a bot token shared by two profiles, a secondary profile binding a port with no `/p/<profile>/` ingress) the update prints the blockers with their fixes and changes nothing. Single-profile installs are never touched. See [Migrating from per-profile gateways](../user-guide/multi-profile-gateways.md#migrating-from-per-profile-gateways).
+### Why the gateway restart can take a while
+
+The restart is drain-first: the running gateway refuses new turns, then waits for in-flight work (chat turns, cron jobs, API runs) to finish before exiting, capped by `agent.restart_after_turn_timeout` (30 minutes by default) so a long-running job is never cut off mid-run. While that wait is in progress the updater prints, every 30 seconds, what the gateway is still holding for — for example:
+
+```
+ → hermes-gateway: draining (up to 1875s)...
+ ⏳ still draining — 1560s left before the forced restart
+ waiting on 1 active work unit(s):
+ • cron job 6ba19dab68df (minimax-code-scout) in external worker pid 573597, running 6m40s
+ finish or kill the work above to release the drain now; agent.restart_after_turn_timeout in config.yaml caps this wait
+```
+
+Chat turns show their session key, model and current tool; cron jobs show the job id, name and the process running them (an external restart-safe worker on systemd installs, otherwise the gateway itself). `hermes gateway status` lists the same units while the gateway is draining. To stop waiting, finish or kill the listed work, or lower `agent.restart_after_turn_timeout` in `config.yaml` (`0` enters the forced drain immediately).
+
### Missing Windows updater files
If the maintained updater script is missing (for example after antivirus quarantine), the legacy update forwarder fails instead of reporting a successful hand-off. Repair the installation and review the security software's quarantine report before retrying; do not disable antivirus protection. Before reporting success, the maintained updater checks the CLI import, Windows executable header, ASAR header and packaged main entry, readable renderer HTML with a local module entry, initial module files, and current build stamp. These are minimum artifact checks, not a full dependency audit or an application/backend launch test. Missing Python is reported before waiting for Desktop shutdown; dependency repair is still allowed to run as part of the update. Electron checks maintained handoff prerequisites before stopping backends when that layout is present; genuine legacy-flat updater layouts remain supported, so not every missing updater file is detected before backend shutdown.