fix(gateway): restart-when-idle waits for real work only, and the update watcher never takes over a busy gateway
Four gaps in restart-when-idle (review on #155532): - A manual gateway `hermes update` left running with its restart pending still had the detached restart watcher armed; at its 120 s deadline the watcher launched `gateway run --replace`, which SIGTERMs/SIGKILLs the still-busy old gateway: the live work the update declined to stop was killed anyway. On POSIX the watcher now waits for the old PID to exit, however long (the gateway exits on its own once idle; every gateway the update stopped exits, and the survivor sweep SIGKILLs one ignoring SIGTERM). Windows keeps its deadline (no SIGUSR1, nothing is left pending). - A saved async-delegation completion for a platform with no adapter here was requeued by the watcher every pass without spending a delivery attempt, and queued_notice_units() kept counting it, so the gateway never went idle. _completion_delivery_ready() now marks such a notice (_no_transport) and the restart wait does not count it; it stays durable in the ledger and is replayed after the restart. The mark clears as soon as a transport is found. - A managed worker turn whose tool or model call never returns held the restart forever: the inactivity escape (agent.gateway_timeout) only looked at in-process chat turns. ManagedWorker now stamps last_frame_at on every frame the owner receives, and a worker silent past the timeout with no open approval/clarify prompt is excluded from the awaitable count like a wedged chat turn. - test_drain_waits_for_in_flight_delegation passed even if the drain returned at once. It now holds the delegation on an Event, asserts the drain is still pending after polling it, releases, and asserts completion.
This commit is contained in:
@@ -62,7 +62,9 @@ def process_units(runner, now: float) -> list[dict]:
|
||||
|
||||
def queued_notice_units(runner) -> list[dict]:
|
||||
"""Completion notices queued for delivery, or dequeued by the watcher and not yet admitted
|
||||
(``_async_notices_in_delivery``): their turn has not started, but it will."""
|
||||
(``_async_notices_in_delivery``): their turn has not started, but it will. One the watcher found
|
||||
no transport for here (``_no_transport``: a disabled or unavailable platform) is not counted: it
|
||||
would hold the restart forever, and its ledger row replays it after the restart."""
|
||||
from tools.process_registry import process_registry
|
||||
queue = process_registry.completion_queue
|
||||
with queue.mutex:
|
||||
@@ -73,7 +75,8 @@ def queued_notice_units(runner) -> list[dict]:
|
||||
"session": evt.get("parent_session_id") or evt.get("session_key") or None}
|
||||
# Only delegation completions: process completion events are re-queued by the shared
|
||||
# watcher until their own per-process watcher (counted above) consumes them.
|
||||
for evt in events if isinstance(evt, dict) and evt.get("type") == "async_delegation"]
|
||||
for evt in events if isinstance(evt, dict) and evt.get("type") == "async_delegation"
|
||||
and not evt.get("_no_transport")]
|
||||
|
||||
|
||||
def background_units(runner) -> list[dict]:
|
||||
|
||||
@@ -1173,12 +1173,14 @@ class GatewayNotificationsMixin(GatewayUpdateNotificationsMixin, GatewayNotifica
|
||||
key = (getattr(source, "profile", None), platform) if source is not None else None
|
||||
if adapter is None:
|
||||
# The watcher requeues silently every tick; say once per outage which lane has no transport.
|
||||
evt["_no_transport"] = True # stays durable; a restart wait does not hold for it
|
||||
if key is not None and key not in warned:
|
||||
warned.add(key)
|
||||
logger.warning("Async completion held: %s", _held_reason(
|
||||
source, platform, getattr(getattr(self, "config", None), "multiplex_profiles", False)))
|
||||
return False
|
||||
warned.discard(key)
|
||||
evt.pop("_no_transport", None)
|
||||
if not adapter_supports_push(adapter):
|
||||
ensure = getattr(adapter, "_ensure_session_db", None)
|
||||
try:
|
||||
|
||||
@@ -29,7 +29,7 @@ from gateway.restart import (
|
||||
)
|
||||
from gateway.run_common import _UNSET
|
||||
from gateway.run_runtime import interrupt_side_agents, managed_turn_count, stop_managed_turns
|
||||
from gateway.session_runtime_workers import uncounted_runtime_work_units
|
||||
from gateway.session_runtime_workers import uncounted_runtime_work_units, wedged_managed_turn_count
|
||||
from gateway.run_shutdown_home_notice import (
|
||||
HOME_NOTICE_MUTED,
|
||||
GatewayHomeShutdownNoticeMixin,
|
||||
@@ -1529,7 +1529,7 @@ class GatewayShutdownMixin(GatewaySessionEndMixin, GatewayHomeShutdownNoticeMixi
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
return sum(
|
||||
return wedged_managed_turn_count(self, timeout) + sum( # + managed worker turns (no frame)
|
||||
1
|
||||
for agent in list((getattr(self, "_running_agents", None) or {}).values())
|
||||
if agent is not None and agent is not _AGENT_PENDING_SENTINEL
|
||||
|
||||
@@ -159,6 +159,8 @@ class ManagedWorker:
|
||||
self.write_lock = threading.Lock()
|
||||
self.commands = queue.Queue(maxsize=16)
|
||||
self.closed = threading.Event()
|
||||
# Owner-side activity clock: a turn with no frame past agent.gateway_timeout is wedged.
|
||||
self.last_frame_at = time.monotonic()
|
||||
# Latched the moment Stop is admitted, before any pipe write: the owner's read loop
|
||||
# supervises it even while the child has not yet said hello or read its bootstrap.
|
||||
self.stop = asyncio.Event()
|
||||
@@ -209,6 +211,7 @@ class ManagedWorker:
|
||||
self.process.stdout.close()
|
||||
|
||||
def _deliver(self, item):
|
||||
self.last_frame_at = time.monotonic()
|
||||
self._frames.append(item)
|
||||
self._arrived.set()
|
||||
|
||||
|
||||
@@ -29,6 +29,22 @@ def managed_worker_units(authority):
|
||||
for sid, worker in list(getattr(authority, '_managed_workers', {}).items()) if not worker.closed.is_set()]
|
||||
|
||||
|
||||
def wedged_managed_turn_count(runner, timeout):
|
||||
"""Live managed workers that sent no frame for ``timeout`` seconds and hold no open approval or
|
||||
clarify prompt (a human may answer it any time): the restart wait must not hold for them."""
|
||||
import time
|
||||
now = time.monotonic()
|
||||
return sum(1 for authority in all_authorities(runner)
|
||||
for sid, worker in list(getattr(authority, '_managed_workers', {}).items())
|
||||
if not worker.closed.is_set() and now - getattr(worker, 'last_frame_at', now) >= timeout
|
||||
and not _open_prompts(authority, sid))
|
||||
|
||||
|
||||
def _open_prompts(authority, sid):
|
||||
live = getattr(authority, 'sessions', {}).get(sid)
|
||||
return bool(getattr(getattr(live, 'controls', None), 'remote_responders', None))
|
||||
|
||||
|
||||
def uncounted_runtime_work_units(runner):
|
||||
"""One ``active_work`` entry per unit ``uncounted_runtime_work`` counts, each naming the real
|
||||
unit: a managed worker's session and process, an executing session's id and route, a tracked
|
||||
|
||||
@@ -999,7 +999,7 @@ def launch_detached_profile_gateway_restart(profile: str, old_pid: int) -> bool:
|
||||
|
||||
|
||||
GATEWAY_RESTART_WATCHER_TIMEOUT_S = 120
|
||||
"""How long the detached restart watcher waits for the old PID to exit before giving up.
|
||||
"""Windows only: the watcher's wait for the old PID (POSIX waits for exit: a restart-pending gateway is busy).
|
||||
|
||||
``hermes update``'s post-relaunch liveness check budgets against this: the watcher spawns the new
|
||||
gateway only AFTER the old PID is gone, so a verification window shorter than this can expire
|
||||
@@ -1100,8 +1100,8 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: b
|
||||
cmd = sys.argv[2:]
|
||||
_respawn_cwd = {respawn_cwd_literal}
|
||||
_respawn_env_overlay = {respawn_env_literal}
|
||||
deadline = time.monotonic() + {watcher_timeout_literal}
|
||||
while time.monotonic() < deadline:
|
||||
deadline = time.monotonic() + {watcher_timeout_literal} if sys.platform == "win32" else None
|
||||
while deadline is None or time.monotonic() < deadline:
|
||||
# ``os.kill(pid, 0)`` is not a no-op on Windows — use the cross-platform existence check.
|
||||
if not pid_exists_stdlib(pid):
|
||||
break
|
||||
|
||||
@@ -41,17 +41,23 @@ class TestDrainWaitsForBackgroundDelegations:
|
||||
instantly) -- the exact repro from the upgrade-killed-subagent incident."""
|
||||
import tools.async_delegation as ad
|
||||
|
||||
from tests.waiting import async_wait_until
|
||||
|
||||
runner, _adapter = make_restart_runner()
|
||||
state = {"n": 1}
|
||||
monkeypatch.setattr(ad, "active_count", lambda: state["n"])
|
||||
finished = asyncio.Event()
|
||||
polls = {"n": 0}
|
||||
|
||||
async def finish_delegation():
|
||||
await asyncio.sleep(0.12) # health: allow HX013 -- the delegation must outlive the drain start
|
||||
state["n"] = 0
|
||||
def active_count():
|
||||
polls["n"] += 1
|
||||
return 0 if finished.is_set() else 1
|
||||
|
||||
task = asyncio.create_task(finish_delegation())
|
||||
_snapshot, timed_out = await runner._drain_active_agents(2.0)
|
||||
await task
|
||||
monkeypatch.setattr(ad, "active_count", active_count)
|
||||
drain = asyncio.create_task(runner._drain_active_agents(30.0))
|
||||
# The drain has seen the delegation more than once (past its entry check) and is still waiting.
|
||||
await async_wait_until(lambda: polls["n"] >= 3 or drain.done(), what="drain polled the live delegation")
|
||||
assert not drain.done(), "drain returned while a background delegation was still in flight"
|
||||
finished.set()
|
||||
_snapshot, timed_out = await asyncio.wait_for(drain, 10.0)
|
||||
|
||||
assert timed_out is False, (
|
||||
"drain must wait for the in-flight background delegation to finish, "
|
||||
|
||||
52
tests/gateway/test_restart_wait_unreal_work.py
Normal file
52
tests/gateway/test_restart_wait_unreal_work.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""A restart waits for real work only. Two units used to hold it forever:
|
||||
|
||||
- a saved async-delegation completion for a platform this gateway has no adapter for: the watcher
|
||||
requeues it every pass (``_completion_delivery_ready`` is False before any delivery attempt is
|
||||
spent), so the queued-notice count never reached zero;
|
||||
- a managed worker turn whose tool or model call never returns: the inactivity escape covered
|
||||
in-process chat turns only.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from gateway.config import Platform
|
||||
from gateway.restart_when_idle import queued_notice_units
|
||||
from gateway.session import SessionSource
|
||||
from tests.gateway.restart_test_helpers import make_restart_runner
|
||||
|
||||
|
||||
def test_a_completion_with_no_transport_here_does_not_hold_the_restart():
|
||||
runner, _adapter = make_restart_runner() # serves Telegram only
|
||||
evt = {"type": "async_delegation", "delegation_id": "d1", "session_key": "agent:main:discord:dm:9"}
|
||||
runner._build_process_event_source = lambda _evt: SessionSource(
|
||||
platform=Platform.DISCORD, chat_id="9", chat_type="dm", user_id="u1")
|
||||
runner._resolve_injection_adapter = lambda _platform, _source: runner.adapters.get(Platform.DISCORD)
|
||||
runner._async_notices_in_delivery = [evt]
|
||||
assert len(queued_notice_units(runner)) == 1 # not yet tried: a turn may still come of it
|
||||
|
||||
assert asyncio.run(runner._completion_delivery_ready(evt)) is False
|
||||
assert queued_notice_units(runner) == []
|
||||
|
||||
# The platform connects: the same notice is deliverable here again, and holds the restart.
|
||||
runner.adapters[Platform.DISCORD] = MagicMock(supports_async_delivery=True)
|
||||
assert asyncio.run(runner._completion_delivery_ready(evt)) is True
|
||||
assert len(queued_notice_units(runner)) == 1
|
||||
|
||||
|
||||
def test_a_managed_turn_silent_past_the_gateway_timeout_does_not_hold_the_restart(monkeypatch):
|
||||
from gateway.session_managed_worker import ManagedWorker
|
||||
monkeypatch.delenv("HERMES_AGENT_TIMEOUT", raising=False) # 1800 s
|
||||
runner, _adapter = make_restart_runner()
|
||||
worker = ManagedWorker(MagicMock(pid=4242))
|
||||
worker._arrived = asyncio.Event()
|
||||
runner.session_authority = SimpleNamespace(_managed_workers={"s1": worker}, sessions={})
|
||||
assert runner._awaitable_work_count() == 1
|
||||
|
||||
worker.last_frame_at = time.monotonic() - 4000 # no frame for longer than agent.gateway_timeout
|
||||
assert runner._awaitable_work_count() == 0
|
||||
|
||||
worker._deliver({"type": "delta", "text": "x"}) # a frame arrives: it is live work again
|
||||
assert runner._awaitable_work_count() == 1
|
||||
@@ -0,0 +1,55 @@
|
||||
"""``hermes update`` leaves a busy manual gateway running with its restart pending, after arming the
|
||||
detached restart watcher. The watcher used to respawn ``gateway run --replace`` at its 120 s
|
||||
deadline, and ``--replace`` SIGTERMs/SIGKILLs the still-busy gateway: the live work the update had
|
||||
just declined to stop was killed anyway. On POSIX the watcher now waits for the old PID to exit.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from hermes_cli import gateway
|
||||
from tests.waiting import wait_until
|
||||
|
||||
|
||||
@pytest.mark.platforms("posix")
|
||||
def test_watcher_never_respawns_while_the_old_gateway_is_still_running(tmp_path, monkeypatch):
|
||||
release, exited, marker = tmp_path / "release", tmp_path / "old-exited", tmp_path / "respawned"
|
||||
home = tmp_path / "home"
|
||||
home.mkdir()
|
||||
monkeypatch.setenv("HERMES_HOME", str(home))
|
||||
# The busy gateway: runs until released, and records its own exit.
|
||||
old = subprocess.Popen([sys.executable, "-c", (
|
||||
"import os, time\n"
|
||||
f"while not os.path.exists({str(release)!r}): time.sleep(0.05)\n"
|
||||
f"open({str(exited)!r}, 'w').close()\n")])
|
||||
# The respawn records whether the old gateway was already gone when it started.
|
||||
relaunch = [sys.executable, "-c",
|
||||
f"import os; open({str(marker)!r}, 'w').write(str(os.path.exists({str(exited)!r})))"]
|
||||
# Its deadline has already passed: the old watcher respawned at once.
|
||||
monkeypatch.setattr(gateway, "GATEWAY_RESTART_WATCHER_TIMEOUT_S", 0)
|
||||
spawned = []
|
||||
real_popen = subprocess.Popen
|
||||
|
||||
def _capture(argv, **kwargs):
|
||||
proc = real_popen(argv, **kwargs)
|
||||
spawned.append(proc)
|
||||
return proc
|
||||
|
||||
monkeypatch.setattr(subprocess, "Popen", _capture)
|
||||
try:
|
||||
assert gateway._spawn_gateway_restart_watcher(old.pid, relaunch, host=False)
|
||||
watcher, started = spawned[0], time.monotonic()
|
||||
# Either the watcher respawned (old code), or it has been waiting well past its deadline.
|
||||
wait_until(lambda: marker.exists() or (watcher.poll() is None and time.monotonic() - started >= 2.0),
|
||||
timeout=30, what="watcher respawned or kept waiting")
|
||||
release.touch()
|
||||
wait_until(lambda: marker.exists() and marker.read_text(), timeout=30, what="respawn after exit")
|
||||
assert marker.read_text() == "True", "the watcher respawned while the old gateway was still running"
|
||||
finally:
|
||||
release.touch()
|
||||
old.wait(timeout=30)
|
||||
Reference in New Issue
Block a user