Skip to content

The agent that grows with you

fix(gateway): a restart over a SIGKILLed owner no longer loses the PID race to itself

teknium146819c45bbf8
diff --git a/gateway/host_attach.py b/gateway/host_attach.py
index 5de5e5670a3..82722bafea0 100644
--- a/gateway/host_attach.py
+++ b/gateway/host_attach.py
@@ -122,10 +122,21 @@ def _identify(home: Path) -> Optional[dict]:
def _served_from_identity(identity: dict) -> tuple[str, ...]:
"""Served set from a live ``identify``. A STANDALONE gateway publishes no ``served_profiles``;
- it serves its own profile and nothing else, which is not the same as "unknown"."""
+ it serves its own profile and nothing else, which is not the same as "unknown".
+
+ The unified runtime publishes each served profile as ``{"profile_id", "home"}`` (what
+ ``hermes_cli.gateway_runtime`` matches homes against); older gateways published bare names.
+ Both spell the same roster, so a dict entry is reduced to its profile name here."""
served = identity.get("served_profiles")
if isinstance(served, list) and served:
- return tuple(str(p) for p in served)
+ names = []
+ for entry in served:
+ if isinstance(entry, dict):
+ home = entry.get("home") or entry.get("profile_id")
+ names.append(profile_name_for_home(str(home)) if home else "default")
+ else:
+ names.append(str(entry))
+ return tuple(names)
return (str(identity.get("profile") or "default"),)
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index 6758f69b7c2..fa4be0780ab 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -446,15 +446,32 @@ async def _start_gateway_shutdown_tail(
-def _launch_home_may_multiplex() -> bool:
+def _launch_home_may_multiplex(config=None) -> bool:
"""A named profile serving ``default`` as a secondary splits default's local sessions between
the two stores (routing rows follow the launch home, receipts follow the authority), so the
- multiplexer is the default profile's job. Exits EX_CONFIG: a config verdict, never a retry."""
+ multiplexer is the default profile's job.
+
+ An EXPLICIT ``gateway.multiplex_profiles: true`` (config.yaml or ``GATEWAY_MULTIPLEX_PROFILES``)
+ on a named launch home exits EX_CONFIG: a config verdict, never a retry. The implicit default
+ (unset key, or the retired ``false`` that ``resolve_multiplex_mode`` settles like unset) is not
+ the operator's choice, so it is downgraded the way every other implicit-multiplex blocker is:
+ this process comes up standalone, says why, and *config* is flipped in place so the boot below
+ reserves and serves only the launch profile."""
from hermes_constants import profile_name_for_home
from gateway.run import get_hermes_home, logger
name = profile_name_for_home(get_hermes_home())
if name in (None, "default"):
return True
+ from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag
+ if config is not None and not explicit_multiplex_flag(get_hermes_home()):
+ from hermes_cli.gateway_multiplex_mode import MultiplexDecision, log_multiplex_decision
+ decision = MultiplexDecision(
+ False, "guard",
+ f"profile {name!r} launched the gateway, and only the default profile runs the multiplexer "
+ "(start it with `hermes gateway run` from the default profile to serve every profile)")
+ config.multiplex_profiles = False
+ log_multiplex_decision(decision)
+ return True
from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
from gateway.run import _write_runtime_status_quiet
logger.error(
@@ -510,8 +527,10 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =
resolved_config = config if config is not None else load_gateway_config_for_runner()
profile_homes = (_multiplex_profile_homes(resolved_config)
if getattr(resolved_config, 'multiplex_profiles', False) else [])
- if profile_homes and not _launch_home_may_multiplex():
+ if profile_homes and not _launch_home_may_multiplex(resolved_config):
return False
+ if profile_homes and not getattr(resolved_config, 'multiplex_profiles', False):
+ profile_homes = [] # implicit default downgraded: this named launch serves only itself
# Multiplex-only: the ONE host gateway decides first. Attach to it, make it serve this profile,
# replace it (--replace) or refuse — before anything below binds a port or claims a PID file.
diff --git a/gateway/status.py b/gateway/status.py
index b88720c8822..7b7f0cc40a5 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -522,9 +522,14 @@ def _gateway_command_subcommand(command: str | None) -> str | None:
# inside one AppleScript string; the gateway itself is its child and is matched on its own command line.
if basenames[0] == "osascript":
return None
- # Gateway-dedicated entrypoints carry no subcommand to inspect.
+ # Gateway-dedicated entrypoints carry no subcommand to inspect (``python -m gateway.run`` is the
+ # module spelling of the same script: its PID record renders argv as ``gateway/run.py``, and a
+ # liveness probe that read the live ``-m`` cmdline as "not a gateway" made every fixture-launched
+ # standalone owner invisible to the multiplex preflight).
if any(t == "gateway/run.py" or t.endswith("/gateway/run.py") for t in tokens):
return "run"
+ if any(tokens[i] == "-m" and tokens[i + 1] == "gateway.run" for i in range(len(tokens) - 1)):
+ return "run"
if any(b in ("hermes-gateway", "hermes-gateway.exe") for b in basenames):
return "run"
joined = " ".join(tokens)
@@ -1391,6 +1396,11 @@ def get_runtime_status_running_pid(
pid = _live_pid_from_record(payload)
if pid is None:
return None
+ # A record we wrote ourselves earlier in this boot (the multiplex verdict is persisted before
+ # the PID claim) is not a rival gateway; reporting it made a restart over a SIGKILLed owner
+ # lose the "PID file race" to its own process and skip the stale gateway.pid cleanup.
+ if pid == os.getpid():
+ return None
# Active-profile context: the record's hermes_home must match this process so a stale record
# cannot lend another profile's identity.
if expected_home is None and not _pid_record_belongs_to_current_profile(payload):
diff --git a/tests/conftest.py b/tests/conftest.py
index 40a65085bbf..6b37a4aa855 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1762,7 +1762,32 @@ def _live_system_guard(request, monkeypatch):
return True
return False
- def _check_subprocess_cmd(name, cmd):
+ def _sandboxed_gateway_child(cmd_str: str, env) -> bool:
+ """The disposable-daemon fixtures (``tests/gateway/fixtures/*``, the socket-path-length
+ probes) launch the bare ``python -m gateway.run`` module entry with an explicit ``env``
+ that re-homes BOTH ``HERMES_HOME`` and ``HOME`` away from the developer's account. Such a
+ child resolves no developer unit or config, holds no live port, and is reaped by its
+ test: the orphan class the guard exists for is the ``hermes gateway run|start|restart``
+ CLI spawn against the real home, which the fixtures never use."""
+ if not isinstance(env, dict):
+ return False
+ try:
+ tokens = _shlex.split(cmd_str)
+ except ValueError:
+ tokens = cmd_str.split()
+ if "-m" not in tokens or tokens[tokens.index("-m") + 1:][:1] != ["gateway.run"]:
+ return False
+ hermes_home, home = env.get("HERMES_HOME"), env.get("HOME")
+ if not hermes_home or not home:
+ return False
+ real_home = Path.home().resolve()
+ try:
+ return (Path(home).resolve() != real_home
+ and not Path(hermes_home).resolve().is_relative_to(real_home))
+ except Exception:
+ return False
+
+ def _check_subprocess_cmd(name, cmd, env=None):
if _is_blocked_systemctl(cmd):
raise RuntimeError(
f"tests/conftest.py live-system guard: blocked "
@@ -1831,6 +1856,7 @@ def _live_system_guard(request, monkeypatch):
not lookalike_ok
and not in_container
and _gateway_command_subcommand(cmd_str) in ("run", "start", "restart")
+ and not _sandboxed_gateway_child(cmd_str, env)
):
raise RuntimeError(
f"tests/conftest.py live-system guard: blocked "
@@ -1846,7 +1872,7 @@ def _live_system_guard(request, monkeypatch):
def _wrap_subprocess(name, real):
def _guarded(cmd, *args, **kwargs):
- _check_subprocess_cmd(name, cmd)
+ _check_subprocess_cmd(name, cmd, kwargs.get("env"))
return real(cmd, *args, **kwargs)
_guarded.__name__ = f"_guarded_{name}"
# Make the wrapper subscriptable like the wrapped callable when
@@ -1864,7 +1890,7 @@ def _live_system_guard(request, monkeypatch):
class _GuardedPopen(real): # type: ignore[misc, valid-type]
def __init__(self, cmd, *args, **kwargs):
- _check_subprocess_cmd("Popen", cmd)
+ _check_subprocess_cmd("Popen", cmd, kwargs.get("env"))
super().__init__(cmd, *args, **kwargs)
_GuardedPopen.__name__ = "Popen"
diff --git a/tests/gateway/test_gateway_command_line_matcher.py b/tests/gateway/test_gateway_command_line_matcher.py
index 88867a58a5f..7a932f4cf4f 100644
--- a/tests/gateway/test_gateway_command_line_matcher.py
+++ b/tests/gateway/test_gateway_command_line_matcher.py
@@ -24,6 +24,7 @@ ACCEPT = [
"python -m hermes_cli.main gateway run --replace",
"python -m hermes_cli/main.py gateway run",
"python gateway/run.py",
+ "python -m gateway.run", # module spelling of the dedicated entrypoint
"hermes-gateway.exe",
"hermes gateway", # bare `hermes gateway` defaults to run
"hermes gateway run",
diff --git a/tests/gateway/test_reload_signal_logs_graceful_restart.py b/tests/gateway/test_reload_signal_logs_graceful_restart.py
index a80f70d9548..ba6556740b4 100644
--- a/tests/gateway/test_reload_signal_logs_graceful_restart.py
+++ b/tests/gateway/test_reload_signal_logs_graceful_restart.py
@@ -16,6 +16,15 @@ class _AbortedStartupRunner:
"""Aborts before running mode so start_gateway() returns right after installing signal handlers."""
def __init__(self, config):
+ # The unified bootstrap builds the session authority against the runner's real store
+ # and stops it on every exit path (same shape as test_startup_restart_race.py).
+ from gateway.session import SessionStore
+ from hermes_state import SessionDB
+ from hermes_constants import get_hermes_home
+ self.session_store = SessionStore(get_hermes_home() / 'sessions', config)
+ self._session_db = SessionDB(get_hermes_home() / 'state.db')
+ self.session_store._db = self._session_db
+ self._draining = False
self.config = config
self.adapters = {}
self._running = False
@@ -33,6 +42,10 @@ class _AbortedStartupRunner:
async def wait_for_shutdown(self):
return None
+ async def stop(self):
+ self.session_store.close_all_db_handles()
+ self._session_db.close()
+
def request_restart(self, *, detached=False, via_service=False):
self.restart_calls.append({"detached": detached, "via_service": via_service})
return True
diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.py
index 76aebf44c52..957174d505b 100644
--- a/tests/gateway/test_session_authority_cancel_settlement.py
+++ b/tests/gateway/test_session_authority_cancel_settlement.py
@@ -138,6 +138,7 @@ def _wire_turn_agent(authority, generation, agent):
"""Run the real per-turn agent wiring with this authority as the turn's approval owner."""
from gateway.run_turn_runner import TurnRunner
ctx = SimpleNamespace(
+ source=SimpleNamespace(platform=None), # main's notification presentation reads ctx.source.platform
progress_callback=None, native_tool_start_callback=None, voice_ack_callback=None,
_voice_ack_guild=[None], _native_slack_task_cards=False, native_tool_complete_callback=None,
_step_callback_sync=None, _hooks_ref=SimpleNamespace(loaded_hooks=[]), _status_callback_sync=None,
diff --git a/tests/gateway/test_shutdown_runtime_ownership.py b/tests/gateway/test_shutdown_runtime_ownership.py
index 4e786dac591..b7368098243 100644
--- a/tests/gateway/test_shutdown_runtime_ownership.py
+++ b/tests/gateway/test_shutdown_runtime_ownership.py
@@ -1,4 +1,5 @@
"""Exit-state persistence is not the end of canonical writer lifetime."""
+import asyncio
import os
import subprocess
import sys
@@ -20,7 +21,8 @@ def test_exit_state_keeps_runtime_reserved_until_final_cleanup(tmp_path, monkeyp
monkeypatch.setattr(run, '_hermes_home', home)
states = []
runner = SimpleNamespace(
- _restart_requested=False, _exit_reason=None,
+ _restart_requested=False, _exit_reason=None, _restart_command_source=None,
+ _restart_via_service=False, _restart_detached=False, _draining=True,
_update_runtime_status=lambda *args: states.append(args),
)
ctx = SimpleNamespace(timed_out=timed_out, active_agents={}, elapsed=lambda: 0)
@@ -44,7 +46,8 @@ if claimed:
write_pid_file()
try:
assert contender() == 'CLAIMED False'
- GatewayShutdownMixin._stop_persist_exit_state(runner, ctx)
+ # Async since main's launchd-budgeted status flush; ownership semantics are unchanged.
+ asyncio.run(GatewayShutdownMixin._stop_persist_exit_state(runner, ctx))
assert contender() == 'CLAIMED False', 'exit-state phase released ownership before writer drain'
assert (home / 'gateway.pid').exists()
assert (home / '.clean_shutdown').exists() is not timed_out
diff --git a/tests/gateway/test_unified_gateway_native_live.py b/tests/gateway/test_unified_gateway_native_live.py
index f1e485cf2a1..02b9504f3b5 100644
--- a/tests/gateway/test_unified_gateway_native_live.py
+++ b/tests/gateway/test_unified_gateway_native_live.py
@@ -392,11 +392,14 @@ def test_native_gateway_runtime_live(harness):
raise AssertionError('second gateway did not refuse while the first owns gateway.lock')
log.flush(); log.seek(0)
text = log.read()
- assert code != 0, text
- # The refusal is logged before the stderr handler exists (gap: silent on the console);
- # the durable errors.log carries the ownership refusal.
+ # One gateway per host: a second `gateway run` for a profile the live owner already serves
+ # ATTACHES (exit 0, spawns nothing) rather than starting a second process; only a launch the
+ # owner cannot serve is refused non-zero. Either way the owner keeps the lock and its identity.
errors = (home / 'logs' / 'errors.log').read_text(encoding='utf-8', errors='replace')
- assert 'already running' in text + errors or 'Cannot reserve gateway profiles' in text + errors, (text, errors[-2000:])
+ attached = code == 0 and 'already serves' in text
+ refused = code != 0 and ('already running' in text + errors or 'Cannot reserve gateway profiles' in text + errors
+ or 'Another gateway already owns this host' in text + errors)
+ assert attached or refused, (code, text, errors[-2000:])
assert owner.poll() is None
assert control(home, 'identify')['instance_id'] == desc['instance_id']
return code
diff --git a/tests/gateway/test_warning_wiring_conservation.py b/tests/gateway/test_warning_wiring_conservation.py
index 6544350e712..ff5a903c892 100644
--- a/tests/gateway/test_warning_wiring_conservation.py
+++ b/tests/gateway/test_warning_wiring_conservation.py
@@ -22,7 +22,9 @@ def test_actual_wiring_retains_observers_and_controls_across_muted_turn():
_merge_turn_request_overrides=TurnRunner._merge_turn_request_overrides,
_clarify_callback_sync=lambda *a: "yes",
_notice_callback_sync=lambda *a: observed.append(("notice", a)),
- _attach_session_title_callback=lambda *a: None)
+ _attach_session_title_callback=lambda *a: None,
+ # Standalone turn (no session-authority approval owner adopted this agent).
+ _approval_owner=None)
agent = StatusOutputMixin()
agent.suppress_status_output = True
TurnRunner._wire_turn_agent_callbacks(holder, agent, {}, None, None, None, False)
diff --git a/tests/gateway/test_worker_compression_admission.py b/tests/gateway/test_worker_compression_admission.py
index 2502ffe662a..11f7b6d9c2b 100644
--- a/tests/gateway/test_worker_compression_admission.py
+++ b/tests/gateway/test_worker_compression_admission.py
@@ -29,7 +29,11 @@ class OverflowModel(BaseHTTPRequestHandler):
if body.get('messages'):
self.server.requests.append(body)
if body.get('model') == 'original' and len(json.dumps(body.get('messages', []))) > 50000:
- payload = json.dumps({'error': {'message': 'maximum context length exceeded',
+ # Quote the server's own measurement the way real providers do: a rejection with no
+ # count that sits far below the known window is treated as transient (another request
+ # holding a single-slot server), never as a reason to compress (#114644).
+ payload = json.dumps({'error': {'message': "This model's maximum context length is 64000 tokens. "
+ 'However, your messages resulted in 70000 tokens.',
'type': 'invalid_request_error', 'code': 'context_length_exceeded'}}).encode()
self.send_response(400)
self.send_header('Content-Type', 'application/json')