Skip to content

The agent that grows with you

fix(gateway): an auto-started gateway that cannot load a lazy install retires for a fresh one

Tekniuma2a602af6923
diff --git a/gateway/run_idle_exit.py b/gateway/run_idle_exit.py
index 12cce08a179..7f0e2615c5e 100644
--- a/gateway/run_idle_exit.py
+++ b/gateway/run_idle_exit.py
@@ -149,18 +149,28 @@ def _store_gates_busy(homes) -> str | None:
return None
-def busy_reason(runner, *, window: float) -> str | None:
- """Why the gateway must stay up, or None when it may exit. Fails closed on any error."""
+def _client_busy(runner, window: float) -> str | None:
+ clients = getattr(runner, "_idle_exit_clients", 0)
+ if clients:
+ return f"{clients} client(s) attached"
+ tickets = getattr(runner, "session_ticket_store", None)
+ if tickets is not None and tickets.outstanding():
+ return "client attaching"
+ quiet = time.monotonic() - getattr(runner, "_idle_exit_last_activity", 0.0)
+ if quiet < window:
+ return f"client activity {quiet:.0f}s ago"
+ return None
+
+
+def busy_reason(runner, *, window: float, count_clients: bool = True) -> str | None:
+ """Why the gateway must stay up, or None when it may exit. Fails closed on any error.
+
+ ``count_clients=False``: a restart is pending, and an attached or returning client is exactly who
+ needs the fresh gateway; every duty nothing would restart (adapters, cron, admissions) still counts.
+ """
try:
- clients = getattr(runner, "_idle_exit_clients", 0)
- if clients:
- return f"{clients} client(s) attached"
- tickets = getattr(runner, "session_ticket_store", None)
- if tickets is not None and tickets.outstanding():
- return "client attaching"
- quiet = time.monotonic() - getattr(runner, "_idle_exit_last_activity", 0.0)
- if quiet < window:
- return f"client activity {quiet:.0f}s ago"
+ if count_clients and (reason := _client_busy(runner, window)):
+ return reason
if runner._draining or not runner._running:
return "already stopping"
if runner._active_work_count():
@@ -175,15 +185,43 @@ def busy_reason(runner, *, window: float) -> str | None:
return f"idle probe failed ({type(exc).__name__})"
-def _begin_idle_exit(runner, window: float) -> None:
+def _begin_idle_exit(runner, window: float, restart: str | None = None) -> None:
"""Withdraw admission synchronously (no await between the last idle check and here), then stop."""
runner._draining = True
runner.session_runtime_descriptor.update(state="draining", capabilities=[], drain_reason=IDLE_EXIT_REASON)
- runner._exit_reason = f"{IDLE_EXIT_STOP_PREFIX} for {window:.0f}s (gateway.unmanaged_idle_exit_seconds)"
+ runner._exit_reason = (f"{IDLE_EXIT_STOP_PREFIX}; restarting to load {restart}" if restart else
+ f"{IDLE_EXIT_STOP_PREFIX} for {window:.0f}s (gateway.unmanaged_idle_exit_seconds)")
logger.info("Exiting: %s; the next client starts a fresh gateway", runner._exit_reason)
runner._idle_exit_stop_task = asyncio.ensure_future(runner.stop())
+async def _sleep_unless_restart_pending(interval: float) -> None:
+ """Sleep ``interval``, waking within a second of a pending restart: a user retrying right after
+ the failed turn must reach a fresh gateway, not this one. Always sleeps at least one slice, so a
+ pending restart held up by other work is re-probed once a second, never in a spin."""
+ from pm.environments_adopt import restart_pending
+ deadline = time.monotonic() + interval
+ while True:
+ await asyncio.sleep(min(1.0, max(0.0, deadline - time.monotonic())))
+ if restart_pending() or time.monotonic() >= deadline:
+ return
+
+
+async def _retired_for_restart(runner, window: float) -> bool:
+ """Retire as soon as nothing but clients holds the gateway when a dependency install this process
+ ran can only load in a new one (``pm.environments_adopt.restart_pending``). Its clients wait out the
+ ``idle_exit`` drain and start a fresh gateway, which boots the new generation."""
+ from pm.environments_adopt import restart_pending
+ if not (restart := restart_pending()):
+ return False
+ if await asyncio.to_thread(busy_reason, runner, window=window, count_clients=False) is not None:
+ return False
+ if busy_reason(runner, window=window, count_clients=False) is not None:
+ return False
+ _begin_idle_exit(runner, window, restart=restart)
+ return True
+
+
async def unmanaged_idle_exit_watcher(runner) -> None:
window = idle_exit_seconds(runner)
if window <= 0:
@@ -194,11 +232,13 @@ async def unmanaged_idle_exit_watcher(runner) -> None:
interval = min(30.0, max(0.5, window / 4))
idle_since = None
while runner._running and not runner._draining:
- await asyncio.sleep(interval)
+ await _sleep_unless_restart_pending(interval)
window = idle_exit_seconds(runner)
if window <= 0:
idle_since = None
continue
+ if await _retired_for_restart(runner, window):
+ return
# The store/cron/kanban reads touch disk; keep them off the loop, then re-check the
# loop-only facts (clients, tickets, draining) synchronously right before acting.
reason = await asyncio.to_thread(busy_reason, runner, window=window)
diff --git a/pm/environments_adopt.py b/pm/environments_adopt.py
index 6c3b9a003e7..4e48efd6303 100644
--- a/pm/environments_adopt.py
+++ b/pm/environments_adopt.py
@@ -110,6 +110,23 @@ def restart_needed(project_root: Path) -> str | None:
f"loaded {running.parent.name}")
+_restart_pending: str | None = None
+
+
+def note_restart_pending(reason: str) -> None:
+ """Record that an install this process ran can only load in a new process.
+
+ An auto-started gateway that nothing restarts reads it (``gateway.run_idle_exit``) and retires,
+ so the next client starts one that boots the new generation instead of reattaching to this one.
+ """
+ global _restart_pending
+ _restart_pending = reason
+
+
+def restart_pending() -> str | None:
+ return _restart_pending
+
+
def adopt_selected(project_root: Path) -> bool:
"""Move this process onto the selected generation. True when it already runs it, adopted it,
or runs from no generation of this install at all (there is nothing to adopt)."""
diff --git a/pm/extras.py b/pm/extras.py
index fe72c69164e..69bc080411c 100644
--- a/pm/extras.py
+++ b/pm/extras.py
@@ -220,7 +220,7 @@ def ensure_import(extra: str) -> None:
# already imported would change underneath it (adopt_selected); otherwise only
# a restart can load it.
from pm.environments import selected_venv, site_packages
- from pm.environments_adopt import adopt_selected, restart_needed
+ from pm.environments_adopt import adopt_selected, note_restart_pending, restart_needed
from pm.paths import repo_root, runtime_facts_path
import sys
from pathlib import Path
@@ -231,6 +231,7 @@ def ensure_import(extra: str) -> None:
selected = site_packages(selected_venv(root)).resolve()
if selected not in {Path(entry).resolve() for entry in sys.path}:
reason = restart_needed(root) or "this process does not run from the install's dependency environment"
+ note_restart_pending(f"{extra} installed ({reason})")
raise InstallError("venv", f"{extra} installed; restart Hermes to activate it ({reason})")
diff --git a/tests/gateway/test_unmanaged_idle_exit_restart_pending.py b/tests/gateway/test_unmanaged_idle_exit_restart_pending.py
new file mode 100644
index 00000000000..24022506982
--- /dev/null
+++ b/tests/gateway/test_unmanaged_idle_exit_restart_pending.py
@@ -0,0 +1,81 @@
+"""An auto-started gateway that installed a dependency it cannot load retires once its turn ends.
+
+Without this the CLI's next attempt (or a fresh ``hermes chat``) reattached to the same process and
+failed the same way until the idle window ran out. Real asyncio and a real ticket store; the runner
+is a stand-in exposing only what the idle predicate reads.
+"""
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import run_idle_exit
+from gateway.config import Platform
+from gateway.runtime_bootstrap import TicketStore
+from pm import environments_adopt
+from tests.waiting import async_wait_until
+
+
+def _runner(tmp_path, monkeypatch, *, work):
+ """``work[0]``: agent turns in flight; ``work[1]``: how often the watcher has probed for them."""
+ home = tmp_path / "home"
+ home.mkdir()
+ stops = []
+
+ def active_work_count():
+ work[1] += 1
+ return work[0]
+
+ async def stop():
+ stops.append(True)
+ runner._running = False
+ runner = SimpleNamespace(
+ _running=True, _draining=False, adapters={Platform.LOCAL: object()},
+ _profile_adapters={}, _profile_failed_platforms={}, _failed_platforms={},
+ config=SimpleNamespace(platforms={}), session_ticket_store=TicketStore("i", frozenset({str(home)})),
+ session_runtime_descriptor={"state": "ready", "capabilities": ["x"]}, _exit_reason=None,
+ _active_work_count=active_work_count, _scale_to_zero_has_live_background_work=lambda: False, stop=stop)
+ # The default 600 s window: only a pending restart may end it within this test.
+ monkeypatch.setattr(run_idle_exit, "idle_exit_seconds", lambda r: 600.0)
+ for probe in ("_ledger_busy", "_cron_busy", "_store_gates_busy"):
+ monkeypatch.setattr(run_idle_exit, probe, lambda *_a: None)
+ monkeypatch.setattr(run_idle_exit, "_kanban_busy", lambda: None)
+ monkeypatch.setattr(run_idle_exit, "_served_homes", lambda r: [home])
+ monkeypatch.setattr(environments_adopt, "_restart_pending", None)
+ return runner, stops
+
+
+async def test_pending_restart_retires_once_the_turn_ends_even_with_a_client_attached(tmp_path, monkeypatch):
+ work = [1, 0]
+ runner, stops = _runner(tmp_path, monkeypatch, work=work)
+ with run_idle_exit.attached_client(runner):
+ watcher = asyncio.ensure_future(run_idle_exit.unmanaged_idle_exit_watcher(runner))
+ environments_adopt.note_restart_pending("anthropic installed (dependency generation g2 was published)")
+ await async_wait_until(lambda: work[1] >= 4, timeout=10, what="two restart probes")
+ assert not watcher.done() and runner.session_runtime_descriptor["state"] == "ready" # turn in flight
+
+ work[0] = 0
+ await asyncio.wait_for(watcher, 5)
+ await runner._idle_exit_stop_task
+ assert stops == [True]
+ # The drain clients already wait out before starting a fresh gateway.
+ assert runner.session_runtime_descriptor["drain_reason"] == run_idle_exit.IDLE_EXIT_REASON
+ assert runner._exit_reason.startswith(run_idle_exit.IDLE_EXIT_STOP_PREFIX)
+ assert "anthropic installed" in runner._exit_reason
+
+
+async def test_pending_restart_never_drops_a_duty_nothing_would_restart(tmp_path, monkeypatch):
+ """Clients come back and start a fresh gateway; a messaging adapter would just go dark."""
+ work = [0, 0]
+ runner, stops = _runner(tmp_path, monkeypatch, work=work)
+ runner.config.platforms[Platform.TELEGRAM] = SimpleNamespace(enabled=True)
+ watcher = asyncio.ensure_future(run_idle_exit.unmanaged_idle_exit_watcher(runner))
+ environments_adopt.note_restart_pending("anthropic installed")
+ await async_wait_until(lambda: work[1] >= 4, timeout=10, what="two restart probes")
+ assert not watcher.done() and stops == []
+ assert runner.session_runtime_descriptor["state"] == "ready"
+ watcher.cancel()