The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stop once the checkout is moved back to a release that predates the gateway runtime
Tekniumc9b519cc0367
diff --git a/gateway/run_startup.py b/gateway/run_startup.pyindex 423552e40a9..286136d53b3 100644--- a/gateway/run_startup.py+++ b/gateway/run_startup.py@@ -1599,6 +1599,8 @@ class GatewayStartupMixin:self._spawn_reconnect_watcher()for method in self._POST_RECONNECT_WATCHERS:self._spawn_supervised(getattr(self, method), method[1:])+ from gateway.runtime_downgrade_exit import runtime_downgrade_watcher+ self._spawn_supervised(lambda: runtime_downgrade_watcher(self), "runtime_downgrade_watcher")# Scale-to-zero watcher ONLY when opted in, messaging is relay-only/absent, and a wakeUrl exists.try:if self._scale_to_zero_should_arm():diff --git a/gateway/runtime_downgrade_exit.py b/gateway/runtime_downgrade_exit.pynew file mode 100644index 00000000000..b95cc276187--- /dev/null+++ b/gateway/runtime_downgrade_exit.py@@ -0,0 +1,91 @@+"""Stop a gateway whose checkout was moved back to a release that predates the gateway runtime.++Downgrading is unsupported, but a manual ``git checkout <older release>`` under a running gateway+leaves this process serving every local session from code the tree no longer has. Older clients+cannot attach to it, and older ``hermes gateway run`` refuses because this process still holds the+profile. Nothing on the older side knows how to stop it. So the gateway watches its own tree, using the boot+revision ``gateway.code_skew`` records. Once the checkout has provably moved (two consecutive+reads, never while an update holds the tree) to code whose state-store modules lack the runtime+ledger, it logs why and stops with the normal drain (a hard exit if that stop fails on the older+tree). It never asks for a restart, so a service manager that relaunches it starts the older+release's own gateway. Every uncertain read keeps it up.+"""++from __future__ import annotations++import asyncio+import logging+import os+from pathlib import Path+from typing import Callable, Optional++logger = logging.getLogger(__name__)++POLL_S = 30.0+_CONFIRMATIONS = 2+_RUNTIME_SCHEMA_MARKER = "CREATE TABLE IF NOT EXISTS session_admissions"+_PROJECT_ROOT = Path(__file__).resolve().parent.parent+++def tree_predates_runtime(root: Path = _PROJECT_ROOT) -> bool:+ """True only when the checkout's state-store modules are readable and none defines the ledger."""+ try:+ sources = [path.read_text(encoding="utf-8", errors="replace") for path in root.glob("hermes_state*.py")]+ except OSError:+ return False # mid-checkout or unreadable: proves nothing+ return bool(sources) and not any(_RUNTIME_SCHEMA_MARKER in text for text in sources)+++def downgrade_reason(skew, *, update_in_progress: bool, predates: Callable[[], bool]) -> Optional[str]:+ """The log line when this gateway must stop for a downgraded tree, else None."""+ if not skew or update_in_progress or not predates():+ return None+ return ("This gateway loaded %s, but its checkout is now at %s, a release that predates the gateway "+ "runtime. Downgrading is unsupported; stopping (no restart) so the older release can run its "+ "own gateway." % tuple(skew))+++async def _stop_or_exit(runner, *, hard_exit: Callable[[int], None] = os._exit) -> None:+ """The normal drain, and a hard exit if it raises. The stop path lazily imports modules that+ the older tree on disk no longer has; a stop that raised never sets the shutdown event and has+ already disarmed its own watchdog, so without this the process idles on forever."""+ try:+ await runner.stop()+ except Exception: # health: allow BLE001 -- any failure of the stop on a downgraded tree ends the same way+ logger.exception("Gateway stop failed on the downgraded checkout; exiting now")+ hard_exit(1)+++async def runtime_downgrade_watcher(runner, *, poll_s: float = POLL_S, skew_fn=None, update_probe=None,+ predates=tree_predates_runtime, max_polls: Optional[int] = None) -> None:+ """Supervised gateway watcher: ``runner.stop()`` after ``_CONFIRMATIONS`` consecutive downgrade reads.++ The probes are bound here, at gateway start: a lazy import after the tree moved would load the+ older release's module into this process."""+ if skew_fn is None:+ from gateway.code_skew import detect_code_skew as skew_fn+ if update_probe is None:+ from hermes_cli.update_lock import update_in_progress as update_probe+ observe_skew: Callable = skew_fn+ observe_update: Callable[[], bool] = update_probe++ def _read() -> Optional[str]:+ try:+ busy = observe_update()+ except Exception: # health: allow BLE001 -- an unreadable update lock cannot prove the swap is over+ busy = True+ return downgrade_reason(observe_skew(), update_in_progress=busy, predates=predates)++ seen = polls = 0+ while getattr(runner, "_running", False) and (max_polls is None or polls < max_polls):+ polls += 1+ reason = await asyncio.to_thread(_read)+ seen = seen + 1 if reason else 0+ if seen >= _CONFIRMATIONS:+ logger.error("%s", reason)+ runner._exit_reason = reason+ # Detached, strongly held: stop() cancels every background task, this watcher included,+ # and a stop awaited from here would be cancelled with it (the #12875 class).+ runner._runtime_downgrade_stop = asyncio.get_running_loop().create_task(_stop_or_exit(runner))+ return+ await asyncio.sleep(poll_s)diff --git a/tests/gateway/test_runtime_downgrade_exit.py b/tests/gateway/test_runtime_downgrade_exit.pynew file mode 100644index 00000000000..9defa955bd4--- /dev/null+++ b/tests/gateway/test_runtime_downgrade_exit.py@@ -0,0 +1,76 @@+"""A gateway stops once its checkout is moved back to a release that predates the gateway runtime.++Downgrading is unsupported (#106742, jquesnelle item 6). After a manual ``git checkout <older+release>`` under a running head gateway, the older client cannot attach to it, and older+``gateway run`` refuses because this process still holds the profile. Nothing on the older side+can stop it, so it stops itself: only on a proven, confirmed move to pre-runtime code, never+mid-update, and without asking for a restart.+"""+import asyncio+import subprocess++from gateway import runtime_downgrade_exit as rde++_SKEW = ("aaaaaaaaaa", "bbbbbbbbbb")+++class _Runner:+ def __init__(self):+ self._running, self.stopped, self.restart_kwargs = True, 0, None++ async def stop(self, **kwargs):+ self.stopped += 1+ self.restart_kwargs = kwargs+ self._running = False+++def _watch(skews, *, update=False, predates=lambda: True):+ runner, seq = _Runner(), iter(skews)++ async def run():+ await rde.runtime_downgrade_watcher(+ runner, poll_s=0, skew_fn=lambda: next(seq, None), update_probe=lambda: update,+ predates=predates, max_polls=len(skews) + 1)+ await asyncio.sleep(0) # let the detached stop task run+ asyncio.run(run())+ return runner+++def test_a_confirmed_move_to_a_pre_runtime_tree_stops_without_a_restart(tmp_path):+ runner = _watch([_SKEW, _SKEW])+ assert runner.stopped == 1 and runner.restart_kwargs == {} # a plain stop: no exit-75 respawn of this code+ assert "predates the gateway runtime" in runner._exit_reason+ # A single blip, a live update, or a move to code that still has the runtime keep it up.+ assert _watch([_SKEW, None, _SKEW, None]).stopped == 0+ assert _watch([_SKEW, _SKEW, _SKEW], update=True).stopped == 0+ assert _watch([_SKEW, _SKEW], predates=lambda: False).stopped == 0+ # Live: the stop lazily imported gateway.session_acp_lifecycle, absent at v0.21.6, and raised;+ # the shutdown event was never set and the process idled on holding its profile lock.+ exits = []++ class _Broken(_Runner):+ async def stop(self, **kwargs):+ raise ModuleNotFoundError("No module named 'gateway.session_acp_lifecycle'")++ asyncio.run(rde._stop_or_exit(_Broken(), hard_exit=exits.append))+ asyncio.run(rde._stop_or_exit(_Runner(), hard_exit=exits.append))+ assert exits == [1]+++def test_the_tree_probe_reads_the_checkout_on_disk(tmp_path):+ def git(*args):+ subprocess.run(["git", *args], cwd=tmp_path, check=True, capture_output=True)++ git("init", "-b", "main")+ git("config", "user.email", "[email protected]")+ git("config", "user.name", "T")+ (tmp_path / "hermes_state_common.py").write_text("SCHEMA = 'CREATE TABLE IF NOT EXISTS sessions'\n")+ git("add", ".")+ git("commit", "-m", "old release")+ git("tag", "old")+ (tmp_path / "hermes_state_common.py").write_text("SCHEMA = 'CREATE TABLE IF NOT EXISTS session_admissions'\n")+ git("commit", "-am", "runtime")+ assert rde.tree_predates_runtime(tmp_path) is False+ git("checkout", "-q", "--detach", "old")+ assert rde.tree_predates_runtime(tmp_path) is True+ assert rde.tree_predates_runtime(tmp_path / "missing") is False # nothing readable proves nothing