Skip to content

The agent that grows with you

test(e2e/handoff): processes running across hermes update (gateway, dashboard, cron, kanban)

teknium1c02f6b0f5c4e
diff --git a/tests/e2e/core/upgrade/handoff/__init__.py b/tests/e2e/core/upgrade/handoff/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/e2e/core/upgrade/handoff/_handoff.py b/tests/e2e/core/upgrade/handoff/_handoff.py
new file mode 100644
index 00000000000..c347359abd5
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/_handoff.py
@@ -0,0 +1,513 @@
+"""Staging for the hand-off suite: a real install at release N-1 (or HEAD), processes running
+from it, and the real ``hermes update`` to the next commit, all in one shared PID namespace.
+
+Two columns, both git-mode installs over a local bare ``origin`` (the official URL rewritten to it,
+so the updater takes the normal non-fork path and never touches the network):
+
+* ``n1``: ``main`` parked at release N-1 (``git describe --tags --abbrev=0 HEAD~1``, overridable with
+ ``HERMES_E2E_UPGRADE_BASE``), its venv built from N-1's own ``uv.lock`` (the installer's tier 0),
+ then ``main`` moves to HEAD;
+* ``head``: HEAD's ``scripts/install.sh`` into an empty HOME, then ``main`` gets NEXT, a synthetic
+ child commit adding a marker file.
+
+Every process (gateway, dashboard, cron ticker, kanban dispatcher, the updater) runs inside ONE
+``NamespaceHost`` sandbox, the way they share a user's machine.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import json
+import os
+import shutil
+import socket
+import sqlite3
+import subprocess
+import re
+import threading
+import time
+import tomllib
+import urllib.error
+import urllib.request
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import hermes_yaml as yaml
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.handoff._nshost import NamespaceHost
+
+TRACEBACK = I.TRACEBACK
+UPDATE_TIMEOUT = 1500
+API_KEY = "e2e-handoff-api-server-key"
+NEXT_MARKER = "docs/e2e-handoff-next-marker.txt"
+
+
+# -- refs ---------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Refs:
+ head: str
+ base_tag: str
+ base: str
+
+
+def refs() -> Refs:
+ """HEAD and release N-1, resolved on first use (collection runs no git)."""
+ head = I.head_sha()
+ try:
+ tag = os.environ.get("HERMES_E2E_UPGRADE_BASE") or I.git(
+ "describe", "--tags", "--match", "v20[0-9][0-9].*", "--abbrev=0", "HEAD~1", cwd=H.WORKTREE)
+ return Refs(head, tag, I.git("rev-parse", f"{tag}^{{commit}}", cwd=H.WORKTREE))
+ except AssertionError: # shallow checkout without tags
+ return Refs(head, "", "")
+
+
+def free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+# -- the install --------------------------------------------------------------------------------
+
+
+@dataclass
+class Install:
+ column: str
+ root: Path
+ origin: Path
+ env: dict[str, str]
+ host: NamespaceHost | None = None
+ target: str = ""
+ port: int = 0
+ logs: list[Path] = field(default_factory=list)
+
+ @property
+ def home(self) -> Path:
+ return Path(self.env["HOME"])
+
+ @property
+ def hermes_home(self) -> Path:
+ return Path(self.env["HERMES_HOME"])
+
+ @property
+ def checkout(self) -> Path:
+ return self.hermes_home / "hermes-agent"
+
+ @property
+ def hermes(self) -> str:
+ """The command on the user's PATH (``~/.local/bin/hermes``)."""
+ return str(self.home / ".local" / "bin" / "hermes")
+
+ def sha(self) -> str:
+ return I.git("rev-parse", "HEAD", cwd=self.checkout)
+
+ def cli(self, *args: str, timeout: float = 600, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
+ assert self.host is not None
+ return self.host.run([self.hermes, *args], timeout=timeout, env=env)
+
+ def spawn(self, name: str, *args: str, env: dict[str, str] | None = None) -> int:
+ assert self.host is not None
+ log = self.root / f"{name}.log"
+ self.logs.append(log)
+ return self.host.spawn([self.hermes, *args], log=log, env=env)
+
+ def update(self, *extra: str, timeout: float = UPDATE_TIMEOUT) -> subprocess.CompletedProcess:
+ return self.cli("update", "--yes", "--branch", "main", *extra, timeout=timeout)
+
+ def diagnostics(self, cp: subprocess.CompletedProcess | None = None) -> str:
+ """Everything a red cell needs: the command, the log tails, receipts, the process table."""
+ parts = []
+ if cp is not None:
+ parts.append(H.describe(cp, 8000))
+ for log in self.logs:
+ if log.exists():
+ parts.append(f"--- {log.name} (tail) ---\n{log.read_text(errors='replace')[-3000:]}")
+ logs = self.hermes_home / "logs"
+ for name in ("gateway.log", "errors.log", "update.log", "agent.log"):
+ p = logs / name
+ if p.exists():
+ parts.append(f"--- logs/{name} (tail) ---\n{p.read_text(errors='replace')[-3000:]}")
+ receipt = logs / "update_receipts" / "latest.json"
+ if receipt.exists():
+ parts.append(f"--- update receipt ---\n{receipt.read_text(errors='replace')[-4000:]}")
+ shims = self.root / "shims" / "shim-calls.log"
+ if shims.exists():
+ parts.append(f"--- supervisor shim calls ---\n{shims.read_text(errors='replace')[-2000:]}")
+ if self.host is not None:
+ try:
+ parts.append("--- sandbox process table ---\n" + self.host.ps_text())
+ except Exception as exc: # the table is a diagnostic; never mask the real failure
+ parts.append(f"--- sandbox process table unavailable: {exc} ---")
+ parts.append("--- sandbox transcript ---\n" + "\n".join(self.host.transcript[-40:]))
+ return "\n".join(parts)
+
+ def close(self) -> list[str]:
+ return self.host.close() if self.host is not None else []
+
+
+def _user_uv(env: dict[str, str], hermes_home: Path) -> None:
+ """Managed uv where the installer provisions it; ``uv self update`` is a no-op (no network)."""
+ real = I.real_uv()
+ assert real is not None
+ bin_dir = hermes_home / "bin"
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ uv = bin_dir / "uv"
+ uv.write_text("#!/bin/sh\n" 'if [ "$1" = self ]; then exit 0; fi\n' f'exec "{real}" "$@"\n', encoding="utf-8")
+ uv.chmod(0o755)
+
+
+def stage_n1(root: Path) -> Install:
+ """A git install at release N-1 with its own venv, as the N-1 installer left it."""
+ root.mkdir(parents=True, exist_ok=True)
+ origin = I.make_origin(root, refs().base)
+ sb = I.new_sandbox(root / "sb", origin)
+ env = sb.env
+ hermes_home = Path(env["HERMES_HOME"])
+ hermes_home.mkdir(parents=True, exist_ok=True)
+ checkout = hermes_home / "hermes-agent"
+ # Local-path clone (objects shared, nothing packed), then the official URL as the remote; the
+ # sandbox's ~/.gitconfig rewrites it to the local origin for every fetch the updater makes.
+ I.git("clone", "-q", "--shared", "-b", "main", str(origin), str(checkout), cwd=root)
+ I.git("remote", "set-url", "origin", I.OFFICIAL_HTTPS, cwd=checkout)
+ assert I.git("rev-parse", "HEAD", cwd=checkout) == refs().base
+ with (checkout / "pyproject.toml").open("rb") as fh:
+ base_python = tomllib.load(fh)["project"]["requires-python"]
+ no_cfg = root / "uv-config"
+ no_cfg.mkdir(exist_ok=True)
+ uv_env = {k: v for k, v in os.environ.items() if k not in ("VIRTUAL_ENV", "UV_NO_CONFIG", "UV_CONFIG_FILE")}
+ uv_env.update(UV_PROJECT_ENVIRONMENT=str(checkout / "venv"), XDG_CONFIG_HOME=str(no_cfg), XDG_CONFIG_DIRS=str(no_cfg))
+ cp = subprocess.run([I.real_uv(), "sync", "-q", "--locked", "--extra", "all", "--managed-python", "--python",
+ base_python], cwd=str(checkout), env=uv_env, capture_output=True, text=True, timeout=1800)
+ assert cp.returncode == 0, f"N-1 venv install from its uv.lock failed:\n{cp.stderr[-4000:]}"
+ local_bin = sb.home / ".local" / "bin"
+ local_bin.mkdir(parents=True, exist_ok=True)
+ (local_bin / "hermes").symlink_to(checkout / "venv" / "bin" / "hermes")
+ _user_uv(env, hermes_home)
+ env["PATH"] = os.pathsep.join([str(local_bin), env["PATH"]])
+ return Install("n1", root, origin, env)
+
+
+def stage_head(root: Path) -> Install:
+ """HEAD's installer into an empty HOME (the HEAD -> NEXT column)."""
+ root.mkdir(parents=True, exist_ok=True)
+ origin = I.make_origin(root, refs().head)
+ # Serve partial clones as GitHub does: the installer asks for ``--filter=blob:none``.
+ I.git("config", "uploadpack.allowFilter", "true", cwd=origin)
+ I.git("config", "uploadpack.allowAnySHA1InWant", "true", cwd=origin)
+ sb = I.new_sandbox(root / "sb", origin)
+ cp = I.run_installer(sb)
+ assert cp.returncode == 0 and TRACEBACK not in cp.stdout + cp.stderr, "HEAD install failed:\n" + I.describe(cp)
+ sb.env["PATH"] = os.pathsep.join([str(sb.home / ".local" / "bin"), sb.env["PATH"]])
+ return Install("head", root, origin, sb.env)
+
+
+def stage(column: str, root: Path) -> Install:
+ return stage_n1(root) if column == "n1" else stage_head(root)
+
+
+def publish_target(inst: Install) -> str:
+ """Upstream moves: N-1 -> HEAD, HEAD -> NEXT (a child commit adding a marker file)."""
+ if inst.column == "n1":
+ I.git("update-ref", "refs/heads/main", refs().head, cwd=inst.origin)
+ inst.target = refs().head
+ else:
+ inst.target = I.publish_commit(inst.origin, inst.root, "release: e2e handoff NEXT",
+ {NEXT_MARKER: f"NEXT above {refs().head}\n"})
+ return inst.target
+
+
+def start_host(inst: Install) -> NamespaceHost:
+ inst.host = NamespaceHost(inst.root, inst.env)
+ return inst.host
+
+
+# -- user configuration -------------------------------------------------------------------------
+
+
+def write_config(home: Path, provider_url: str, *, port: int | None = None, extra: dict | None = None) -> None:
+ """A user config on the fake provider; ``port`` enables the API server platform."""
+ home.mkdir(parents=True, exist_ok=True)
+ cfg: dict = {
+ "model": {"provider": "custom", "base_url": provider_url, "default": "fake-model", "context_length": 128000},
+ "agent": {"api_max_retries": 1},
+ "compression": {"enabled": False},
+ }
+ if port is not None:
+ cfg["platforms"] = {"api_server": {"enabled": True, "extra": {"host": "127.0.0.1", "port": port}}}
+ for k, v in (extra or {}).items():
+ cfg[k] = {**cfg.get(k, {}), **v} if isinstance(v, dict) and isinstance(cfg.get(k), dict) else v
+ (home / "config.yaml").write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")
+ (home / ".env").write_text(f"OPENAI_API_KEY={I.FAKE_KEY}\nAPI_SERVER_KEY={API_KEY}\n", encoding="utf-8")
+
+
+# -- talking to the gateway ---------------------------------------------------------------------
+
+
+def http(method: str, url: str, body: dict | None = None, *, key: str | None = API_KEY,
+ timeout: float = 120) -> tuple[int, dict | str]:
+ data = json.dumps(body).encode() if body is not None else None
+ req = urllib.request.Request(url, data=data, method=method)
+ req.add_header("Content-Type", "application/json")
+ if key:
+ req.add_header("Authorization", f"Bearer {key}")
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ raw = resp.read().decode("utf-8", errors="replace")
+ status = resp.status
+ except urllib.error.HTTPError as exc:
+ raw, status = exc.read().decode("utf-8", errors="replace"), exc.code
+ except (urllib.error.URLError, OSError) as exc:
+ return 0, f"{type(exc).__name__}: {exc}"
+ try:
+ return status, json.loads(raw)
+ except ValueError:
+ return status, raw
+
+
+def health(port: int) -> dict | None:
+ status, body = http("GET", f"http://127.0.0.1:{port}/health/detailed", timeout=5)
+ return body if status == 200 and isinstance(body, dict) else None
+
+
+def chat(port: int, text: str) -> tuple[int, dict | str]:
+ return http("POST", f"http://127.0.0.1:{port}/v1/chat/completions",
+ {"model": "hermes-agent", "messages": [{"role": "user", "content": text}]}, timeout=180)
+
+
+def reply_text(body) -> str:
+ try:
+ return body["choices"][0]["message"]["content"] or ""
+ except (TypeError, KeyError, IndexError):
+ return ""
+
+
+def identify(home: Path) -> dict | None:
+ """The live gateway's own answer to the control-socket ``identify`` verb: its pid (as the
+ sandbox sees it) and the code identity it booted with (per-process, not re-read from disk)."""
+ from gateway.control_socket import identify_gateway
+
+ return identify_gateway(home, timeout=5.0)
+
+
+def gateway_pids(inst: Install) -> list[dict]:
+ """Every gateway in the sandbox (the user's view: the process table). A gateway's own children
+ (forked helpers carrying the same argv) belong to it and are not counted as a second gateway."""
+ out = []
+ for p in inst.host.procs():
+ argv = p["cmdline"]
+ if p["state"] in ("Z", "X") or not argv:
+ continue
+ joined = " ".join(argv)
+ if "gateway" in argv and ("run" in argv or "start" in argv) and "hermes" in joined and "update" not in argv:
+ out.append(p)
+ pids = {p["pid"] for p in out}
+ return [p for p in out if p["ppid"] not in pids]
+
+
+def read_json(path: Path) -> dict | None:
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+
+
+def db_rows(db: Path, sql: str, args: tuple = ()) -> list[tuple]:
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=10)
+ try:
+ return con.execute(sql, args).fetchall()
+ finally:
+ con.close()
+
+
+def wait_for(pred, *, timeout: float, what: str, interval: float = 0.25):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ value = pred()
+ if value:
+ return value
+ time.sleep(interval)
+ raise AssertionError(f"timed out after {timeout:.0f}s waiting for {what}")
+
+
+def copy_tree(src: Path, dst: Path) -> None:
+ shutil.copytree(src, dst, symlinks=True)
+
+
+# -- a cell: install + provider + sandbox -------------------------------------------------------
+
+
+def cell(column: str, root: Path, provider_url: str, *, extra: dict | None = None):
+ """Stage ``column`` under ``root``, write a user config on the fake provider with the API server
+ platform on a free port, and start the shared-PID-namespace sandbox. Closing asserts that the
+ sandbox took every process with it."""
+ inst = stage(column, root / column)
+ inst.port = free_port()
+ write_config(inst.hermes_home, provider_url, port=inst.port, extra=extra)
+ start_host(inst)
+ leaked: list[str] = []
+ try:
+ yield inst
+ finally:
+ leaked = inst.close()
+ assert not leaked, f"processes outlived the sandbox: {leaked}"
+
+
+# -- the gateway, from the user's side ----------------------------------------------------------
+
+
+def start_gateway(inst: Install, *args: str) -> dict:
+ """``hermes gateway run`` as a user starts it by hand; returns its ``identify`` answer."""
+ inst.spawn("gateway", "gateway", "run", *args)
+ try:
+ wait_for(lambda: health(inst.port), timeout=240, what="the gateway API server /health")
+ ident = wait_for(lambda: identify(inst.hermes_home), timeout=60, what="control-socket identify")
+ except AssertionError as exc:
+ raise AssertionError(f"premise: the gateway never came up: {exc}\n{inst.diagnostics()}") from None
+ assert ident["code_sha"] == inst.sha(), f"premise: the gateway must serve the installed commit: {ident}"
+ return ident
+
+
+def gateway_starts(inst: Install) -> list[int]:
+ """PIDs of every gateway boot recorded in ``logs/gateway-exit-diag.log`` (one ``gateway.start`` each)."""
+ p = inst.hermes_home / "logs" / "gateway-exit-diag.log"
+ pids = []
+ for line in (p.read_text(errors="replace").splitlines() if p.exists() else []):
+ try:
+ rec = json.loads(line)
+ except ValueError:
+ continue
+ if rec.get("tag") == "gateway.start":
+ pids.append(int(rec.get("pid") or 0))
+ return pids
+
+
+def pid_file_pid(inst: Install) -> int | None:
+ """The PID ``$HERMES_HOME/gateway.pid`` names (JSON record or a bare number)."""
+ p = inst.hermes_home / "gateway.pid"
+ try:
+ raw = p.read_text(encoding="utf-8").strip()
+ except OSError:
+ return None
+ try:
+ data = json.loads(raw)
+ except ValueError:
+ return int(raw) if raw.isdigit() else None
+ if isinstance(data, dict):
+ return int(data["pid"]) if str(data.get("pid", "")).isdigit() else None
+ return int(data) if isinstance(data, int) else None
+
+
+def receipt(inst: Install) -> dict:
+ return read_json(inst.hermes_home / "logs" / "update_receipts" / "latest.json") or {}
+
+
+def settle_gateway(inst: Install, old_pid: int, *, timeout: float = 180) -> dict | None:
+ """Wait for a gateway serving ``inst.target`` under a new PID; None if none shows up."""
+ def serving():
+ ident = identify(inst.hermes_home)
+ return ident if ident and ident.get("pid") != old_pid and ident.get("code_sha") == inst.target else None
+ try:
+ return wait_for(serving, timeout=timeout, what="a relaunched gateway", interval=1.0)
+ except AssertionError:
+ return None
+
+
+# Which open issue explains a missing relaunch, per column (fix PRs delete their entry). ``n1``: the
+# restart watcher runs on the bare store Python and dies importing gateway.status. ``head``: the
+# updater does not recognise a gateway launched through the pm-runtime shim (``python3 -I -c
+# <bootstrap> gateway run``), so it stops it as an unsupervised stale survivor instead of relaunching.
+RELAUNCH_GATES = {
+ "n1": (r"relaunch armed but never started: no new gateway process booted",
+ "gated on #124649: the update restart watcher dies before relaunching a manual gateway"),
+ "head": (r"no relaunch: the update did not recognise gateway PID \d+ and stopped it as an unsupervised",
+ "gated on #124029: a pm-runtime-launched gateway is invisible to the updater's process scan"),
+}
+# A gateway started through the bootstrap launcher is misclassified and its gateway.pid is deleted
+# under it by the next status probe.
+PID_FILE_GATE = (r"gateway\.pid was deleted under the live gateway",
+ "gated on #123109: status probes delete a bootstrap-launched gateway's gateway.pid")
+
+_UNSUPERVISED_STOP = re.compile(r"Stopped \d+ manual gateway process\(es\) that had no supervisor")
+
+
+def relaunch_verdict(inst: Install, old_pid: int, boots_before: int, ident: dict | None,
+ up: subprocess.CompletedProcess | None = None) -> str:
+ """Why no gateway is serving the new commit, in words a gate can key on; '' when one is."""
+ if ident is not None:
+ return ""
+ boots = gateway_starts(inst)[boots_before:]
+ alive = [p["pid"] for p in gateway_pids(inst)]
+ armed = receipt(inst).get("gateway_restart", {})
+ out = (up.stdout + up.stderr) if up is not None else ""
+ if not boots and armed.get("relaunched_profiles"):
+ return (f"relaunch armed but never started: no new gateway process booted after the update stopped PID "
+ f"{old_pid} (receipt relaunched_profiles={armed.get('relaunched_profiles')}, live gateways={alive})")
+ if not boots and _UNSUPERVISED_STOP.search(out) and not armed.get("killed_pids"):
+ return (f"no relaunch: the update did not recognise gateway PID {old_pid} and stopped it as an unsupervised "
+ f"stale survivor (receipt gateway_restart={armed}, live gateways={alive})")
+ if not boots:
+ return (f"no relaunch: the update left no gateway running after PID {old_pid} and armed none "
+ f"(receipt gateway_restart={armed}, live gateways={alive})")
+ if not alive:
+ return f"relaunched gateway exited: boots {boots} after the update, none alive"
+ stale = identify(inst.hermes_home)
+ return f"gateway alive ({alive}) but not serving {inst.target[:12]}: identify={stale}"
+
+
+def pid_file_verdict(inst: Install, pid: int, history: list[tuple[float, str]]) -> str:
+ """'' when gateway.pid names ``pid``; otherwise how it went wrong (written then deleted under the
+ live gateway, never written, or naming someone else)."""
+ if pid_file_pid(inst) == pid:
+ return ""
+ wrote = any(re.search(rf'\b{pid}\b', v) for _, v in history)
+ now = history[-1][1] if history else "<unknown>"
+ if wrote and now == "<missing>" and pid in [p["pid"] for p in gateway_pids(inst)]:
+ return f"gateway.pid was deleted under the live gateway {pid} (history below)"
+ if not wrote:
+ return f"the relaunched gateway {pid} never wrote gateway.pid (now: {now[:120]})"
+ return f"gateway.pid names someone other than the live gateway {pid}: {now[:120]}"
+
+
+class FileWatch:
+ """Records every change to a file's content (timestamped) while the block runs: the history of
+ ``gateway.pid`` across an update is the evidence when it ends up naming nobody."""
+
+ def __init__(self, path: Path, interval: float = 0.25) -> None:
+ self.path, self.interval = path, interval
+ self.history: list[tuple[float, str]] = []
+ self._stop = threading.Event()
+ self._t0 = time.time()
+
+ def _snap(self) -> str:
+ try:
+ return self.path.read_text(errors="replace").strip()[:300]
+ except OSError:
+ return "<missing>"
+
+ def _run(self) -> None:
+ last = None
+ while not self._stop.is_set():
+ cur = self._snap()
+ if cur != last:
+ self.history.append((round(time.time() - self._t0, 2), cur))
+ last = cur
+ self._stop.wait(self.interval)
+
+ def __enter__(self) -> "FileWatch":
+ self._thread = threading.Thread(target=self._run, daemon=True)
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self._stop.set()
+ self._thread.join(timeout=5)
+
+ def render(self) -> str:
+ return "\n".join(f" +{t:>7}s {v}" for t, v in self.history)
diff --git a/tests/e2e/core/upgrade/handoff/_ns_agent.py b/tests/e2e/core/upgrade/handoff/_ns_agent.py
new file mode 100644
index 00000000000..f1a3914b1b0
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/_ns_agent.py
@@ -0,0 +1,157 @@
+"""In-sandbox command agent for the hand-off suite (stdlib only, run as a plain script).
+
+The hand-off cells need several long-lived processes (gateway, dashboard, cron ticker, kanban
+dispatcher) and the real ``hermes update`` to share ONE PID namespace, exactly as they share one
+machine for a user: the updater's process scans must see the gateway it restarts, and a relaunched
+gateway must be findable by the next ``hermes gateway status``. ``_helpers.sandbox_argv`` gives every
+command its own namespace, so this agent is started once inside the sandbox and runs every command
+of a cell on request.
+
+Protocol: one JSON object per line on stdin, one JSON reply per line on stdout, each carrying the
+request ``id``. Requests are served on their own threads, so a blocking ``run`` (the update) never
+stops the test from inspecting the process table meanwhile.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+
+_OUT = threading.Lock()
+_CHILDREN: dict[int, subprocess.Popen] = {}
+
+
+def _reply(rid, **payload) -> None:
+ line = json.dumps({"id": rid, **payload}) + "\n"
+ with _OUT:
+ sys.stdout.write(line)
+ sys.stdout.flush()
+
+
+def _stat(pid: int) -> list[str] | None:
+ try:
+ with open(f"/proc/{pid}/stat", encoding="utf-8", errors="replace") as fh:
+ return fh.read().rsplit(")", 1)[1].split()
+ except (OSError, IndexError):
+ return None
+
+
+def _read(path: str) -> bytes:
+ try:
+ with open(path, "rb") as fh:
+ return fh.read()
+ except OSError:
+ return b""
+
+
+def _procs() -> list[dict]:
+ rows = []
+ for entry in os.listdir("/proc"):
+ if not entry.isdigit():
+ continue
+ pid = int(entry)
+ fields = _stat(pid)
+ if fields is None:
+ continue
+ env = {}
+ for item in _read(f"/proc/{pid}/environ").split(b"\0"):
+ key, sep, value = item.partition(b"=")
+ if sep and key in (b"HERMES_HOME", b"INVOCATION_ID", b"HERMES_E2E_UNIT"):
+ env[key.decode()] = value.decode(errors="replace")
+ rows.append({
+ "pid": pid, "state": fields[0], "ppid": int(fields[1]), "start": int(fields[19]),
+ "cmdline": [a.decode(errors="replace") for a in _read(f"/proc/{pid}/cmdline").split(b"\0") if a],
+ "env": env,
+ })
+ return rows
+
+
+def _reap() -> None:
+ for pid, proc in list(_CHILDREN.items()):
+ if proc.poll() is not None:
+ _CHILDREN.pop(pid, None)
+
+
+def _reaper_loop() -> None:
+ """Reap spawned children the moment they exit, as the user's shell does: an unreaped zombie
+ still answers ``kill(pid, 0)``, so a restart watcher waiting for the old gateway to exit would
+ see it alive forever."""
+ while True:
+ _reap()
+ time.sleep(0.1)
+
+
+def _run(req: dict) -> dict:
+ stdin = subprocess.PIPE if req.get("input") is not None else subprocess.DEVNULL
+ proc = subprocess.Popen(req["argv"], env=req["env"], cwd=req["cwd"], text=True, stdin=stdin,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
+ started = time.monotonic()
+ try:
+ out, err = proc.communicate(input=req.get("input"), timeout=req.get("timeout") or 600)
+ return {"rc": proc.returncode, "stdout": out, "stderr": err, "timed_out": False,
+ "elapsed": time.monotonic() - started}
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except OSError:
+ pass
+ out, err = proc.communicate()
+ return {"rc": proc.returncode, "stdout": out, "stderr": err, "timed_out": True,
+ "elapsed": time.monotonic() - started}
+
+
+def _spawn(req: dict) -> dict:
+ log = open(req["log"], "ab") # noqa: SIM115 - handed to the child
+ try:
+ proc = subprocess.Popen(req["argv"], env=req["env"], cwd=req["cwd"], stdin=subprocess.DEVNULL,
+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ finally:
+ log.close()
+ _CHILDREN[proc.pid] = proc
+ return {"pid": proc.pid}
+
+
+def _kill(req: dict) -> dict:
+ try:
+ os.kill(int(req["pid"]), int(req.get("sig", signal.SIGTERM)))
+ return {"ok": True}
+ except OSError as exc:
+ return {"ok": False, "error": str(exc)}
+
+
+def _handle(req: dict) -> None:
+ rid = req.get("id")
+ try:
+ _reap()
+ op = req["op"]
+ if op == "run":
+ _reply(rid, **_run(req))
+ elif op == "spawn":
+ _reply(rid, **_spawn(req))
+ elif op == "procs":
+ _reply(rid, procs=_procs())
+ elif op == "kill":
+ _reply(rid, **_kill(req))
+ elif op == "ping":
+ _reply(rid, pid=os.getpid())
+ else:
+ _reply(rid, error=f"unknown op {op!r}")
+ except Exception as exc: # the agent must answer every request, whatever it was
+ _reply(rid, error=f"{type(exc).__name__}: {exc}")
+
+
+def main() -> None:
+ threading.Thread(target=_reaper_loop, daemon=True).start()
+ for raw in sys.stdin:
+ raw = raw.strip()
+ if raw:
+ threading.Thread(target=_handle, args=(json.loads(raw),), daemon=True).start()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/e2e/core/upgrade/handoff/_nshost.py b/tests/e2e/core/upgrade/handoff/_nshost.py
new file mode 100644
index 00000000000..88ef61215c5
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/_nshost.py
@@ -0,0 +1,133 @@
+"""Host side of the shared-PID-namespace sandbox (see ``_ns_agent.py``).
+
+``NamespaceHost(root)`` starts ONE ``bwrap`` sandbox (``_helpers.sandbox_argv``: own PID namespace,
+tmpfs over ``/run/user/<uid>``, real ``~/.hermes`` read-only, only ``root`` writable) running the
+agent, then runs and spawns every process of a cell inside it. Closing it kills the sandbox's init,
+which takes every process of the namespace with it, detached or not, so nothing a cell starts can
+outlive it; the dashboard lane's ``_reaper`` is armed around it as the leak check.
+"""
+
+from __future__ import annotations
+
+import itertools
+import json
+import os
+import signal
+import subprocess
+import sys
+import threading
+import time
+from concurrent.futures import Future
+from pathlib import Path
+from typing import Sequence
+
+from tests.e2e.core.dashboard import _reaper
+from tests.e2e.core.upgrade import _helpers as H
+
+_AGENT = Path(__file__).with_name("_ns_agent.py")
+
+
+class NamespaceHost:
+ def __init__(self, root: Path, env: dict[str, str]):
+ self.root = root
+ self.env = env
+ self.transcript: list[str] = []
+ self._ids = itertools.count(1)
+ self._pending: dict[int, Future] = {}
+ self._lock = threading.Lock()
+ self._wlock = threading.Lock() # one request line at a time: probes run from helper threads too
+ _reaper.adopt_orphans()
+ self._proc = subprocess.Popen(
+ H.sandbox_argv([sys.executable, "-u", str(_AGENT)], writable=[root]),
+ env=env, cwd=str(root), text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=open(root / "ns-agent.stderr", "w"), # noqa: SIM115 - lives as long as the sandbox
+ start_new_session=True,
+ )
+ self._reader = threading.Thread(target=self._read, daemon=True)
+ self._reader.start()
+ self.call({"op": "ping"}, timeout=60)
+
+ def _read(self) -> None:
+ assert self._proc.stdout is not None
+ for line in self._proc.stdout:
+ try:
+ msg = json.loads(line)
+ except ValueError:
+ continue
+ with self._lock:
+ fut = self._pending.pop(msg.get("id"), None)
+ if fut is not None:
+ fut.set_result(msg)
+ with self._lock:
+ pending, self._pending = self._pending, {}
+ for fut in pending.values():
+ fut.set_exception(AssertionError("sandbox agent exited:\n" + self.agent_stderr()))
+
+ def agent_stderr(self) -> str:
+ p = self.root / "ns-agent.stderr"
+ return p.read_text(errors="replace")[-3000:] if p.exists() else ""
+
+ def call(self, req: dict, *, timeout: float) -> dict:
+ rid = next(self._ids)
+ fut: Future = Future()
+ with self._lock:
+ self._pending[rid] = fut
+ assert self._proc.stdin is not None
+ with self._wlock:
+ self._proc.stdin.write(json.dumps({**req, "id": rid}) + "\n")
+ self._proc.stdin.flush()
+ msg = fut.result(timeout=timeout)
+ if "error" in msg:
+ raise AssertionError(f"sandbox agent refused {req.get('op')}: {msg['error']}")
+ return msg
+
+ # -- commands ------------------------------------------------------------------------------
+
+ def run(self, argv: Sequence[str], *, timeout: float = 600, env: dict[str, str] | None = None,
+ cwd: Path | None = None, input: str | None = None, quiet: bool = False) -> subprocess.CompletedProcess:
+ """Run to completion inside the namespace. ``quiet`` keeps a polling probe out of the transcript."""
+ started = time.strftime("%H:%M:%S")
+ msg = self.call({"op": "run", "argv": list(argv), "env": env or self.env, "cwd": str(cwd or self.root),
+ "timeout": timeout, "input": input}, timeout=timeout + 60)
+ cp = subprocess.CompletedProcess(list(argv), msg["rc"], msg["stdout"], msg["stderr"])
+ if not quiet:
+ self.transcript.append(f"[{started}] rc={cp.returncode} ({msg['elapsed']:.1f}s) {' '.join(argv)[:300]}")
+ if msg["timed_out"]:
+ raise AssertionError(f"{list(argv)} timed out after {timeout}s inside the sandbox\n" + H.describe(cp))
+ return cp
+
+ def spawn(self, argv: Sequence[str], *, log: Path, env: dict[str, str] | None = None,
+ cwd: Path | None = None) -> int:
+ msg = self.call({"op": "spawn", "argv": list(argv), "env": env or self.env, "cwd": str(cwd or self.root),
+ "log": str(log)}, timeout=60)
+ self.transcript.append(f"[{time.strftime('%H:%M:%S')}] spawned pid {msg['pid']}: {' '.join(argv)[:300]}")
+ return int(msg["pid"])
+
+ def procs(self) -> list[dict]:
+ """Every process in the namespace (pids as the sandbox sees them)."""
+ return self.call({"op": "procs"}, timeout=60)["procs"]
+
+ def kill(self, pid: int, sig: int = signal.SIGTERM) -> bool:
+ return bool(self.call({"op": "kill", "pid": pid, "sig": int(sig)}, timeout=60)["ok"])
+
+ def alive(self, pid: int) -> bool:
+ return any(p["pid"] == pid and p["state"] not in ("Z", "X") for p in self.procs())
+
+ def ps_text(self) -> str:
+ rows = [f"{p['pid']:>6} {p['ppid']:>6} {p['state']} {' '.join(p['cmdline'])[:220]}" for p in self.procs()]
+ return " PID PPID S CMD\n" + "\n".join(sorted(rows, key=lambda r: int(r.split()[0])))
+
+ def close(self) -> list[str]:
+ """Kill the sandbox (its init takes every namespace process with it); returns leaked host pids."""
+ try:
+ os.killpg(self._proc.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ try:
+ self._proc.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ pass
+ try:
+ return _reaper.reap(_reaper.with_home(Path(self.env["HOME"])), timeout=15)
+ finally:
+ _reaper.release_orphans()
diff --git a/tests/e2e/core/upgrade/handoff/_scenario.py b/tests/e2e/core/upgrade/handoff/_scenario.py
new file mode 100644
index 00000000000..1009d95801d
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/_scenario.py
@@ -0,0 +1,477 @@
+"""One user's machine across one real ``hermes update``, observed once per column.
+
+A manual gateway (with its cron ticker and embedded kanban dispatcher) and a manual dashboard run
+in one shared-PID-namespace sandbox. A kanban worker is in flight and a one-shot cron job comes due
+mid-update. The scenario runs once per column and records what the user would see; each property
+is its own test over that record, gated on its own issue. The expensive part (stage, boot, update,
+settle) is paid once per column, not once per property.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import json
+import os
+import re
+import secrets
+import shutil
+import sqlite3
+import sys
+import tempfile
+import threading
+import time
+from collections import Counter
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from tests.e2e.core._pending_fixes import known_failure, known_gate
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade.handoff import _handoff as X
+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall
+
+CRON_DUE_S = 65 # after the update starts: the checkout holds the new code, the old gateway still ticks
+_TASK_RE = re.compile(r"work kanban task (t_[0-9a-f]+)")
+_PORT_IN_USE = re.compile(r"address already in use|port \d+ is (already )?in use|errno 98", re.I)
+REPLY = "handoff reply"
+_IMPORT_ERR = re.compile(r"ModuleNotFoundError|ImportError|No module named|cannot import name")
+
+# Open issues behind a property, per column (a fix PR deletes its entry). Each pattern matches only the
+# verdict text its bug produces; any other failure of the same property propagates.
+DASHBOARD_GATES = {
+ "n1": (r"the respawned dashboard died parsing its launcher",
+ "gated on #124778: the update respawns a manual dashboard on a launcher the PM takeover made a shell shim"),
+}
+# The respawned dashboard can die after the updater already booked it "restarted": the receipt says
+# success and the update exits 0 with the dashboard dark (racy: an earlier death is "unaccounted", exit 1).
+FALSE_SUCCESS_GATE = (r"the update exited 0 though the dashboard did not come back",
+ "gated on #109290: a respawned dashboard that dies is booked as restarted and the update exits 0")
+CRON_GATES = {
+ "n1": (r"fired into the update swap window and failed importing",
+ "gated on #113293: a cron job due during an update fires into the swap window, fails, and loses its slot"),
+}
+
+
+class Model:
+ """The fake provider's brain. Chat turns get ``REPLY``; the cron job's prompt is counted; each
+ kanban worker completes its own card (``kanban_complete`` counted per card), and the first card's
+ worker blocks on its first call until ``release`` so it spans the whole update."""
+
+ def __init__(self, cron_marker: str) -> None:
+ self.cron_marker = cron_marker
+ self.cron_calls: list[float] = []
+ self.completes: Counter[str] = Counter()
+ self.hold: str | None = None
+ self.holding = threading.Event()
+ self.release = threading.Event()
+ self._lock = threading.Lock()
+
+ def __call__(self, rec: dict):
+ msgs = rec["body"].get("messages", [])
+ text = json.dumps(msgs)
+ tid = next((m.group(1) for m in (_TASK_RE.search(str(x.get("content"))) for x in msgs) if m), None)
+ if tid is not None:
+ if msgs[-1].get("role") == "tool":
+ return Text("card closed")
+ with self._lock:
+ if self.hold is None and not self.release.is_set():
+ self.hold = tid
+ if tid == self.hold and not self.release.is_set():
+ self.holding.set()
+ self.release.wait(timeout=1500)
+ with self._lock:
+ self.completes[tid] += 1
+ return ToolCall("kanban_complete", {"summary": f"done {tid}"})
+ if self.cron_marker in text:
+ with self._lock:
+ self.cron_calls.append(time.time())
+ return Text(f"cron ran {self.cron_marker}")
+ return Text(REPLY)
+
+
+# -- small views over the sandbox -------------------------------------------------------------------
+
+
+def _dashboard_health(port: int) -> dict | None:
+ status, body = X.http("GET", f"http://127.0.0.1:{port}/api/health", key=None, timeout=5)
+ return body if status == 200 and isinstance(body, dict) else None
+
+
+_LISTENER_PY = r"""
+import os, sys
+port = int(sys.argv[1]); inodes = set()
+for table in ("/proc/net/tcp", "/proc/net/tcp6"):
+ try:
+ rows = open(table).read().splitlines()[1:]
+ except OSError:
+ continue
+ for row in rows:
+ f = row.split()
+ if f[3] == "0A" and int(f[1].rsplit(":", 1)[1], 16) == port:
+ inodes.add(f[9])
+for pid in filter(str.isdigit, os.listdir("/proc")):
+ try:
+ for fd in os.listdir(f"/proc/{pid}/fd"):
+ link = os.readlink(f"/proc/{pid}/fd/{fd}")
+ if link.startswith("socket:[") and link[8:-1] in inodes:
+ print(pid); sys.exit(0)
+ except OSError:
+ pass
+"""
+
+
+def listener_pid(inst: X.Install, port: int) -> int | None:
+ """The sandbox PID owning the LISTEN socket on ``port`` (``/proc/net/tcp`` inode -> ``/proc/<pid>/fd``)."""
+ cp = inst.host.run([sys.executable, "-c", _LISTENER_PY, str(port)], timeout=60, quiet=True)
+ return int(cp.stdout.strip()) if cp.stdout.strip().isdigit() else None
+
+
+def dashboards(inst: X.Install) -> list[dict]:
+ """Top-level ``hermes dashboard`` processes (a dashboard's own helpers are not a second one)."""
+ out = [p for p in inst.host.procs()
+ if p["state"] not in ("Z", "X") and "dashboard" in p["cmdline"] and "update" not in p["cmdline"]
+ and any("hermes" in a for a in p["cmdline"])]
+ pids = {p["pid"] for p in out}
+ return [p for p in out if p["ppid"] not in pids]
+
+
+def _kanban(inst: X.Install, sql: str, args: tuple = ()) -> list[dict]:
+ db = inst.hermes_home / "kanban.db"
+ if not db.exists():
+ return []
+ con = sqlite3.connect(f"file:{db}?mode=ro", uri=True, timeout=30)
+ con.row_factory = sqlite3.Row
+ try:
+ return [dict(r) for r in con.execute(sql, args).fetchall()]
+ finally:
+ con.close()
+
+
+def card_status(inst: X.Install, tid: str) -> str:
+ rows = _kanban(inst, "SELECT status FROM tasks WHERE id = ?", (tid,))
+ return rows[0]["status"] if rows else ""
+
+
+def create_card(inst: X.Install, title: str) -> str:
+ cp = inst.cli("kanban", "create", title, "--assignee", "default", "--json", timeout=120)
+ assert cp.returncode == 0, "kanban create failed\n" + H.describe(cp)
+ return json.loads(cp.stdout[cp.stdout.index("{"):])["id"]
+
+
+def cron_jobs(inst: X.Install) -> list[dict]:
+ data = X.read_json(inst.hermes_home / "cron" / "jobs.json")
+ jobs = data.get("jobs", data) if isinstance(data, dict) else data
+ return [j for j in (jobs or []) if isinstance(j, dict)]
+
+
+def cron_outputs(inst: X.Install, job_id: str) -> list[str]:
+ d = inst.hermes_home / "cron" / "output" / job_id
+ return sorted(p.name for p in d.iterdir()) if d.is_dir() else []
+
+
+def worker_logs(inst: X.Install) -> str:
+ return "\n".join(f"--- {p.relative_to(inst.hermes_home)} ---\n{p.read_text(errors='replace')[-2500:]}"
+ for p in sorted(inst.hermes_home.rglob("t_*.log")))
+
+
+def cron_failure(inst: X.Install, name: str, job: dict | None) -> str:
+ """Why the job's run failed, as the scheduler logged it ('' when nothing failed)."""
+ if job and job.get("last_error"):
+ return str(job["last_error"])
+ pat = re.compile(rf"Job '{re.escape(name)}' failed: (.+)")
+ for log in (inst.root / "gateway.log", inst.hermes_home / "logs" / "gateway.log",
+ inst.hermes_home / "logs" / "errors.log"):
+ m = pat.search(log.read_text(errors="replace")) if log.exists() else None
+ if m:
+ return m.group(1).strip()
+ return ""
+
+
+def _run_segments(log: str) -> list[str]:
+ """A card's worker log, one segment per worker run (each starts with its ``Query:`` line)."""
+ return [s for s in re.split(r"(?m)^(?=Query: work kanban task )", log) if s.strip()]
+
+
+def _overlap(runs: list[dict]) -> list[tuple[int, int]]:
+ """Pairs of runs of ONE card that were live at the same time: a duplicate worker."""
+ out = []
+ for i, a in enumerate(runs):
+ for b in runs[i + 1:]:
+ a_end, b_end = a["ended_at"] or float("inf"), b["ended_at"] or float("inf")
+ if a["started_at"] < b_end and b["started_at"] < a_end:
+ out.append((a["id"], b["id"]))
+ return out
+
+
+class WorkerSampler:
+ """Samples the sandbox process table once a second while the block runs and records, per card,
+ the most kanban workers (``hermes ... chat -q "work kanban task <id>"``) alive at the same moment:
+ two at once is a duplicate spawn, whatever the board says afterwards."""
+
+ def __init__(self, inst: X.Install, interval: float = 1.0) -> None:
+ self.inst, self.interval = inst, interval
+ self.peak: Counter[str] = Counter()
+ self.evidence: dict[str, list] = {}
+ self._stop = threading.Event()
+
+ def _sample(self) -> None:
+ live = [p for p in self.inst.host.procs() if p["state"] not in ("Z", "X")]
+ by_card: dict[str, list[dict]] = {}
+ for p in live:
+ m = _TASK_RE.search(" ".join(p["cmdline"]))
+ if m:
+ by_card.setdefault(m.group(1), []).append(p)
+ for tid, procs in by_card.items():
+ pids = {p["pid"] for p in procs}
+ roots = sorted(p["pid"] for p in procs if p["ppid"] not in pids)
+ if len(roots) > self.peak[tid]:
+ self.peak[tid] = len(roots)
+ self.evidence[tid] = [round(time.time()), roots]
+
+ def _run(self) -> None:
+ while not self._stop.is_set():
+ try:
+ self._sample()
+ except Exception: # a probe racing sandbox teardown; the next sample decides
+ pass
+ self._stop.wait(self.interval)
+
+ def __enter__(self) -> "WorkerSampler":
+ self._thread = threading.Thread(target=self._run, daemon=True)
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc) -> None:
+ self._stop.set()
+ self._thread.join(timeout=70)
+
+
+def _quiet_wait(pred, *, timeout: float, what: str, interval: float = 1.0):
+ try:
+ return X.wait_for(pred, timeout=timeout, what=what, interval=interval)
+ except AssertionError:
+ return None
+
+
+# -- the scenario ---------------------------------------------------------------------------------
+
+
+def run(column: str, root: Path) -> SimpleNamespace:
+ """Boot the fleet, update, let everything settle, and record what the user would see."""
+ o = SimpleNamespace(column=column)
+ model = Model(f"CRON-HANDOFF-{secrets.token_hex(4)}")
+ with FakeLLMServer(model) as srv, X.cell(
+ column, root, srv.base_url, extra={"kanban": {"dispatch_interval_seconds": 3}}) as inst:
+ before = X.start_gateway(inst)
+ o.old_pid = before["pid"]
+ with X.FileWatch(inst.hermes_home / "gateway.pid") as watch:
+ assert X.pid_file_pid(inst) == o.old_pid, f"premise: gateway.pid names the gateway: {watch.render()}"
+ status, body = X.chat(inst.port, "hello before the update")
+ assert status == 200 and X.reply_text(body) == REPLY, f"premise: a turn works before: {body}"
+
+ o.dash_port = X.free_port()
+ inst.spawn("dashboard", "dashboard", "--no-open", "--host", "127.0.0.1", "--port", str(o.dash_port))
+ try: # the first ``hermes dashboard`` builds the web UI, as it does for the user
+ X.wait_for(lambda: _dashboard_health(o.dash_port), timeout=600, what="the dashboard /api/health")
+ except AssertionError as exc:
+ raise AssertionError(f"premise: the dashboard never came up: {exc}\n{inst.diagnostics()}") from None
+ o.dash_old = listener_pid(inst, o.dash_port)
+ assert o.dash_old, "premise: nothing listens on the dashboard port"
+
+ sampler = WorkerSampler(inst).__enter__()
+ o.card1 = create_card(inst, "in flight across the update")
+ assert model.holding.wait(timeout=240) and model.hold == o.card1, (
+ f"premise: the gateway's dispatcher never ran a worker for {o.card1}\n"
+ f"{worker_logs(inst)}\n{inst.diagnostics()}")
+
+ o.boots = len(X.gateway_starts(inst))
+ o.target = X.publish_target(inst)
+ due = dt.datetime.now(dt.timezone.utc).replace(microsecond=0) + dt.timedelta(seconds=CRON_DUE_S + 5)
+ cp = inst.cli("cron", "create", due.isoformat(), f"Reply with the word done. {model.cron_marker}",
+ "--name", model.cron_marker)
+ assert cp.returncode == 0, "premise: cron create failed\n" + H.describe(cp)
+ job = next((j for j in cron_jobs(inst) if j.get("name") == model.cron_marker), None)
+ assert job and job.get("id"), f"premise: the job is not in jobs.json: {cron_jobs(inst)}"
+ o.job_id = job["id"]
+ assert not model.cron_calls, "premise: the job ran before it was due"
+
+ o.up = inst.update()
+ o.sha_after = inst.sha()
+
+ o.ident = X.settle_gateway(inst, o.old_pid)
+ model.release.set()
+ o.chat_after = X.chat(inst.port, "hello after the update") if o.ident else (0, "")
+ o.card2 = create_card(inst, "created after the update")
+
+ gone_since: list[float] = []
+
+ def dash_back():
+ pid = listener_pid(inst, o.dash_port)
+ if pid and pid != o.dash_old and _dashboard_health(o.dash_port):
+ return pid
+ # No dashboard process at all for 20s: the respawn died (or never happened); stop waiting.
+ if dashboards(inst):
+ gone_since.clear()
+ elif not gone_since:
+ gone_since.append(time.monotonic())
+ return -1 if gone_since and time.monotonic() - gone_since[0] > 20 else None
+ back = _quiet_wait(dash_back, timeout=240, what="a new dashboard on its port")
+ o.dash_new = back if back and back > 0 else None
+
+ if o.ident: # the cron ticker and the kanban dispatcher live in the gateway
+ _quiet_wait(lambda: dt.datetime.now(dt.timezone.utc) > due + dt.timedelta(seconds=5), timeout=600,
+ what="the cron due time")
+ _quiet_wait(lambda: model.cron_calls, timeout=240, what="the cron job's provider call")
+ _quiet_wait(lambda: card_status(inst, o.card1) == "done" and card_status(inst, o.card2) == "done",
+ timeout=300, what="both kanban cards to finish")
+ # A re-fire or a duplicate worker shows up within a full ticker interval on the new gateway.
+ settle_until = max([time.time(), *model.cron_calls]) + 65
+ time.sleep(max(0.0, settle_until - time.time()))
+
+ sampler.__exit__()
+ o.worker_peak, o.worker_evidence = dict(sampler.peak), sampler.evidence
+ o.gateways = X.gateway_pids(inst)
+ o.status = inst.cli("gateway", "status", timeout=120)
+ o.cron_list = inst.cli("cron", "list", "--all", timeout=120)
+ time.sleep(2) # let the pid-file watch see what the status probes did
+ o.pid_history = watch.history
+ o.relaunch = X.relaunch_verdict(inst, o.old_pid, o.boots, o.ident, o.up)
+ o.pid_file = X.pid_file_verdict(inst, o.ident["pid"], watch.history) if o.ident else "no gateway"
+ o.dash_listener = listener_pid(inst, o.dash_port)
+ o.dash_roots = dashboards(inst)
+ restart_log = inst.hermes_home / "logs" / "dashboard-restart.log"
+ o.dash_restarts = restart_log.read_text(errors="replace") if restart_log.exists() else ""
+ o.cron_calls = list(model.cron_calls)
+ o.cron_outputs = cron_outputs(inst, o.job_id)
+ o.cron_job_after = next((j for j in cron_jobs(inst) if j.get("id") == o.job_id), None)
+ o.cron_error = cron_failure(inst, model.cron_marker, o.cron_job_after)
+ o.completes = dict(model.completes)
+ o.cards = {t: card_status(inst, t) for t in (o.card1, o.card2)}
+ o.runs = {t: _kanban(inst, "SELECT id, outcome, started_at, ended_at FROM task_runs WHERE task_id = ? "
+ "ORDER BY id", (t,)) for t in (o.card1, o.card2)}
+ o.worker_logs = worker_logs(inst)
+ card_log = {t: next((p.read_text(errors="replace") for p in inst.hermes_home.rglob(f"{t}.log")), "")
+ for t in (o.card1, o.card2)}
+ # Workers spawned after the update: every run of the new card, and every re-run of the in-flight one.
+ o.post_update_worker_logs = "\n".join(_run_segments(card_log[o.card2]) + _run_segments(card_log[o.card1])[1:])
+ inst.logs.append(restart_log)
+ o.diag = (inst.diagnostics(o.up) + f"\n--- gateway.pid history ---\n{watch.render()}"
+ f"\n--- cron job ---\n{json.dumps(o.cron_job_after, indent=1)[-2000:]}"
+ f"\n--- kanban ---\ncards={o.cards} provider kanban_complete calls={o.completes}\n"
+ f"peak live workers per card={o.worker_peak} (at, pids)={o.worker_evidence}\nruns={json.dumps(o.runs)}"
+ f"\n--- worker logs ---\n{o.worker_logs[-5000:]}")
+ return o
+
+
+# -- the properties -------------------------------------------------------------------------------
+
+
+class HandoffProperties:
+ """Every property of the hand-off, over one recorded scenario per column (``column`` on the
+ subclass). Each test is independent: a failure in one subsystem never hides another's."""
+
+ column: str = ""
+
+ @pytest.fixture(scope="class")
+ def fleet(self):
+ if self.column == "n1" and not X.refs().base:
+ pytest.skip("no release tag reachable (shallow checkout)")
+ base = os.environ.get("TMPDIR") or tempfile.gettempdir()
+ root = Path(tempfile.mkdtemp(prefix="ho", dir=base)) # short: AF_UNIX paths under $HERMES_HOME
+ try:
+ yield run(self.column, root)
+ finally:
+ shutil.rmtree(root, ignore_errors=True)
+
+ def _relaunched(self, o) -> None:
+ with known_gate(X.RELAUNCH_GATES, o.column):
+ assert not o.relaunch, f"{o.relaunch}\n{o.diag}"
+
+ def test_update_moves_the_checkout(self, fleet):
+ assert fleet.sha_after == fleet.target, f"the update did not move the checkout\n{fleet.diag}"
+
+ def test_gateway_is_relaunched_once_on_the_new_commit(self, fleet):
+ o = fleet
+ self._relaunched(o)
+ assert [p["pid"] for p in o.gateways] == [o.ident["pid"]], f"expected exactly one gateway: {o.gateways}\n{o.diag}"
+ status, body = o.chat_after
+ assert status == 200 and X.reply_text(body) == REPLY, f"no turn after the update: {body}\n{o.diag}"
+
+ def test_update_exit_status_matches_what_came_back(self, fleet):
+ """Nothing is reported as success when it failed, and a failure exit names something real."""
+ o = fleet
+ out = o.up.stdout + o.up.stderr
+ assert X.TRACEBACK not in out, f"the update crashed\n{o.diag}"
+ down = [name for name, ok in (("the gateway", o.ident), ("the dashboard", o.dash_new)) if not ok]
+ if o.up.returncode == 0:
+ with known_failure(*FALSE_SUCCESS_GATE):
+ assert not down, f"the update exited 0 though {' and '.join(down)} did not come back\n{o.diag}"
+ else:
+ assert down, (f"the update exited {o.up.returncode} though the gateway and the dashboard came back"
+ f"\n{o.diag}")
+
+ def test_gateway_pid_file_and_status_find_the_relaunched_gateway(self, fleet):
+ o = fleet
+ self._relaunched(o)
+ with known_failure(*X.PID_FILE_GATE):
+ assert not o.pid_file, f"{o.pid_file}\n{o.diag}"
+ assert f"Gateway is running (PID: {o.ident['pid']})" in o.status.stdout, (
+ f"`hermes gateway status` cannot find the relaunched gateway:\n{H.describe(o.status)}\n{o.diag}")
+
+ def test_dashboard_is_back_on_its_port(self, fleet):
+ o = fleet
+ out = o.up.stdout + o.up.stderr
+ assert "TypeError" not in out, f"the update tripped over the dashboard\n{o.diag}"
+ with known_gate(DASHBOARD_GATES, o.column):
+ assert o.dash_new is not None, f"{dashboard_verdict(o)}\n{o.diag}"
+ assert len(o.dash_roots) == 1, f"expected exactly one dashboard: {o.dash_roots}\n{o.diag}"
+ assert o.dash_listener == o.dash_new, f"the dashboard on port {o.dash_port} churned\n{o.diag}"
+ assert not _PORT_IN_USE.search(o.dash_restarts), f"the respawned dashboard hit port-in-use\n{o.diag}"
+
+ def test_cron_job_due_mid_update_runs_exactly_once(self, fleet):
+ o = fleet
+ self._relaunched(o)
+ with known_gate(CRON_GATES, o.column):
+ assert len(o.cron_calls) == 1, f"{cron_verdict(o)}\n{o.diag}"
+ assert len(o.cron_outputs) == 1, f"run records: {o.cron_outputs}\n{o.diag}"
+ assert o.cron_list.returncode == 0 and X.TRACEBACK not in o.cron_list.stdout + o.cron_list.stderr, (
+ f"the new code cannot read the job back:\n{H.describe(o.cron_list)}\n{o.diag}")
+ if o.cron_job_after is not None: # a spent one-shot may be dropped; a kept one records its run
+ job = o.cron_job_after
+ assert job.get("last_run_at") and job.get("last_status") == "ok", f"bookkeeping lost: {job}\n{o.diag}"
+
+ def test_kanban_inflight_worker_finishes_once_and_new_workers_import(self, fleet):
+ o = fleet
+ self._relaunched(o)
+ m = _IMPORT_ERR.search(o.post_update_worker_logs)
+ assert m is None, f"a kanban worker spawned after the update failed to import ({m and m.group(0)})\n{o.diag}"
+ assert o.cards[o.card2] == "done", f"the card created after the update never finished\n{o.diag}"
+ assert o.cards[o.card1] == "done", f"the in-flight card never finished\n{o.diag}"
+ for t in (o.card1, o.card2):
+ n = o.worker_peak.get(t, 0)
+ assert n <= 1, f"card {t} had {n} live workers at once {o.worker_evidence.get(t)}\n{o.diag}"
+ dup = _overlap(o.runs[t])
+ assert not dup, f"card {t} had two live workers at once (runs {dup})\n{o.diag}"
+ done = [r for r in o.runs[t] if r["outcome"] == "completed"]
+ assert len(done) == 1, f"card {t} has {len(done)} completed runs\n{o.diag}"
+ # The in-flight worker finishes, or the update interrupts it and it is re-queued exactly once.
+ assert len(o.runs[o.card1]) <= 2, f"the in-flight card ran {len(o.runs[o.card1])} times\n{o.diag}"
+ assert len(o.runs[o.card2]) == 1, f"the new card ran {len(o.runs[o.card2])} times\n{o.diag}"
+
+
+def dashboard_verdict(o) -> str:
+ """Why no new dashboard serves its port, in words a gate can key on."""
+ if re.search(r"^SyntaxError", o.dash_restarts, re.M) and "restarted:" in o.up.stdout:
+ return (f"the respawned dashboard died parsing its launcher: the update replayed the pre-update argv and "
+ f"Python read a shell script (SyntaxError in logs/dashboard-restart.log); port {o.dash_port} is dark")
+ return f"no new dashboard serves port {o.dash_port} (old pid {o.dash_old}, listener now {o.dash_listener})"
+
+
+def cron_verdict(o) -> str:
+ """How many times the job due mid-update reached the provider, and why not when it never did."""
+ n = len(o.cron_calls)
+ if n == 0 and _IMPORT_ERR.search(o.cron_error or ""):
+ return (f"the job due mid-update fired into the update swap window and failed importing "
+ f"({o.cron_error[:240]}); it never reached the provider")
+ return f"the job due mid-update ran {n} times" + (f" (last error: {o.cron_error[:240]})" if o.cron_error else "")
diff --git a/tests/e2e/core/upgrade/handoff/conftest.py b/tests/e2e/core/upgrade/handoff/conftest.py
new file mode 100644
index 00000000000..14bc6a253df
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/conftest.py
@@ -0,0 +1,24 @@
+"""Fixtures for the hand-off suite."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from pathlib import Path
+
+import pytest
+
+
+def root(tmp_path: Path):
+ """A SHORT cell root. A user's ``~/.hermes`` is a short path; pytest's ``tmp_path`` nests deep enough
+ that the gateway's AF_UNIX sockets under ``$HERMES_HOME`` overflow ``sun_path`` (108 bytes) and
+ silently degrade, which is a harness artifact, not the user's machine."""
+ base = os.environ.get("TMPDIR") or tempfile.gettempdir()
+ path = Path(tempfile.mkdtemp(prefix="ho", dir=base))
+ (tmp_path / "cell-root").write_text(str(path), encoding="utf-8")
+ try:
+ yield path
+ finally:
+ shutil.rmtree(path, ignore_errors=True)
diff --git a/tests/e2e/core/upgrade/handoff/test_handoff_from_head.py b/tests/e2e/core/upgrade/handoff/test_handoff_from_head.py
new file mode 100644
index 00000000000..a58c7ff62a6
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/test_handoff_from_head.py
@@ -0,0 +1,25 @@
+"""The hand-off suite, HEAD to NEXT.
+
+A HEAD install made by ``scripts/install.sh`` updated to NEXT, a synthetic child commit: the
+updater under test runs its own restart path end to end.
+
+Every property is a test over one recorded scenario (see ``_scenario.py``).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.handoff._scenario import HandoffProperties
+
+pytestmark = [
+ pytest.mark.skipif(not H.BWRAP_OK, reason="bubblewrap sandbox unavailable"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+ pytest.mark.live_system_guard_bypass, # one bwrap sandbox per column; killing it reaps everything
+]
+
+
+class TestFromHead(HandoffProperties):
+ column = "head"
diff --git a/tests/e2e/core/upgrade/handoff/test_handoff_from_n1.py b/tests/e2e/core/upgrade/handoff/test_handoff_from_n1.py
new file mode 100644
index 00000000000..9bafb3b9a76
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/test_handoff_from_n1.py
@@ -0,0 +1,25 @@
+"""The hand-off suite, release N-1 to HEAD.
+
+A git install of the previous release tag, set up as that release set it up, updated to HEAD:
+the N-1 updater fetches, pulls and hands off to HEAD's updater, which restarts everything.
+
+Every property is a test over one recorded scenario (see ``_scenario.py``).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.handoff._scenario import HandoffProperties
+
+pytestmark = [
+ pytest.mark.skipif(not H.BWRAP_OK, reason="bubblewrap sandbox unavailable"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+ pytest.mark.live_system_guard_bypass, # one bwrap sandbox per column; killing it reaps everything
+]
+
+
+class TestFromReleaseN1(HandoffProperties):
+ column = "n1"
diff --git a/tests/e2e/core/upgrade/handoff/test_update_network_failure.py b/tests/e2e/core/upgrade/handoff/test_update_network_failure.py
new file mode 100644
index 00000000000..cd6743e2e17
--- /dev/null
+++ b/tests/e2e/core/upgrade/handoff/test_update_network_failure.py
@@ -0,0 +1,60 @@
+"""A network failure during ``hermes update`` must never take down a healthy gateway (the exit-75
+class, #123370: keep it closed).
+
+The upstream is published, but the git transport is refused: the official URL is rewritten to a
+loopback port that nobody listens on, the way an offline laptop or a dead proxy looks. The update
+fails and says so. The gateway the user started keeps its PID, keeps serving the installed commit,
+and keeps answering turns. The checkout stays where it was.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tests.e2e.core.upgrade import _helpers as H
+from tests.e2e.core.upgrade import _install_helpers as I
+from tests.e2e.core.upgrade.handoff import _handoff as X
+from tests.fakes.fake_llm_provider import FakeLLMServer
+
+pytestmark = [
+ pytest.mark.skipif(not H.BWRAP_OK, reason="bubblewrap sandbox unavailable"),
+ pytest.mark.skipif(I.real_uv() is None, reason="uv required"),
+ pytest.mark.live_system_guard_bypass, # one bwrap sandbox per cell; killing it reaps everything
+]
+
+
+def _refuse_git_transport(inst: X.Install) -> str:
+ dead = f"http://127.0.0.1:{X.free_port()}/NousResearch/hermes-agent.git"
+ (inst.home / ".gitconfig").write_text(
+ f'[url "{dead}"]\n insteadOf = {I.OFFICIAL_HTTPS}\n insteadOf = {I.OFFICIAL_SSH}\n', encoding="utf-8")
+ return dead
+
+
[email protected]("column", ["n1", "head"])
+def test_refused_fetch_leaves_the_running_gateway_alone(root, column):
+ if column == "n1" and not X.refs().base:
+ pytest.skip("no release tag reachable (shallow checkout)")
+ with FakeLLMServer(default_text="still here") as srv, X.cell(column, root, srv.base_url) as inst:
+ before = X.start_gateway(inst)
+ installed = inst.sha()
+ boots = len(X.gateway_starts(inst))
+ X.publish_target(inst)
+ _refuse_git_transport(inst)
+
+ up = inst.update(timeout=600)
+
+ diag = inst.diagnostics(up)
+ assert up.returncode != 0, f"a refused fetch was reported as success\n{diag}"
+ out = (up.stdout + up.stderr).lower()
+ assert any(w in out for w in ("fetch", "network", "connect", "unable to access", "could not")), (
+ f"the failed update does not say why\n{diag}")
+ assert X.TRACEBACK not in up.stdout + up.stderr, f"the failed update crashed\n{diag}"
+ assert inst.sha() == installed, f"a failed fetch moved the checkout\n{diag}"
+ ident = X.identify(inst.hermes_home)
+ assert ident is not None and ident["pid"] == before["pid"], (
+ f"the running gateway was stopped or replaced by an update that never fetched: {ident}\n{diag}")
+ assert ident["code_sha"] == installed, f"gateway identity changed: {ident}\n{diag}"
+ assert len(X.gateway_starts(inst)) == boots, f"the gateway was restarted by a failed update\n{diag}"
+ assert [p["pid"] for p in X.gateway_pids(inst)] == [before["pid"]], f"gateway process set changed\n{diag}"
+ status, body = X.chat(inst.port, "are you still there?")
+ assert status == 200 and X.reply_text(body) == "still here", f"no turn after the failed update: {body}\n{diag}"