Files
hermes-agent/tests/hermes_cli/test_gateway_run_hard_exit.py
teknium1 a10620a669 fix(gateway): a record alone never means "attach", and --replace/--force work
Review fixes on the lifecycle-verbs PR. Three of them were escape hatches that
looked implemented and were dead code, and one turned a boot race into a
permanently parked unit.

- ATTACH now requires a LIVE `identify` answer. The claim-time record is
  published with NO served set (the runner settles multiplex a moment later),
  and `host_gateway()` reports `served_known=False` when nothing answers. An
  owner whose served set is unknown yields a TRANSIENT refusal, never an
  attach: previously `default`'s claim published "default,other" before its
  socket bound, `other`'s systemd unit read that as "I am served", exited 78,
  and systemd parked it for good.
- `served_profiles()` honours the actual `gateway.multiplex_profiles` setting
  instead of forcing `multiplex=True`, so a standalone gateway stops claiming
  the whole roster.
- `--replace` is threaded through the CLI guard into `start_gateway`, and
  `--force` into `_host_attach_or_none`. Both previously exited in the guard
  before the code that implements them ever ran ("nothing to start", rc=0).
- A supervised attach exits 75 (EX_TEMPFAIL), not 78. 78 is the PERMANENT
  config refusal every supervisor parks on; "someone else serves me right now"
  is a runtime observation that ends when that process does. No unit files
  change: systemd already has RestartForceExitStatus=75/RestartSec=5, the s6
  finish script passes 75 through, launchd relaunches a non-78 failure. Exit 0
  would not do — s6 parks a clean exit too.
- `restart --all` retracts the stopped owner's record (`discard_dead_record`)
  and re-enters with `replace=True`, so it can no longer attach to the corpse
  it just stopped and exit 0.
- Rendezvous hardening: the dir is created/repaired 0o700, a record whose
  `st_uid` is not ours is ignored, liveness is proven BEFORE we dial the home
  it names, and a live `identify` must agree about `hermes_home`.
- `-p X gateway restart --all` reaches the `--all`-aware branch instead of the
  generic guard's `hermes -p default gateway restart` one-liner.
- `host_gateway()` is memoized (2s TTL, invalidated on every record write), so
  `gateway status`/doctor across N profiles pays one probe, not N.

Tests: the two new files build the record as raw JSON, so they COLLECT and RUN
against a tree without the `home` field and fail on the outcome. A/B against
the PR head: 9 failed / 6 passed → 15 passed. conftest's per-test
HERMES_GATEWAY_LOCK_DIR now defers to a caller-supplied value (and
run_tests.sh forwards it through `env -i`), and the per-process dir is a
deterministic self-sweeping per-PID path instead of an atexit-only mkdtemp.
`test_runner_startup_failures.py` stubs the new attach gate and releases the
host role it claims.
2026-09-21 05:02:29 -07:00

79 lines
2.7 KiB
Python

"""Regression tests for CLI gateway run exit behavior.
``hermes gateway run`` enters through hermes_cli.gateway, not gateway.run.main().
After graceful teardown it must use the same hard-exit backstop as gateway.run.main()
so Python finalization does not wait on non-daemon worker threads (for example
in-flight cron ThreadPoolExecutor jobs) and delay service-managed restarts.
"""
from __future__ import annotations
import types
import pytest
class _HardExitObserved(BaseException):
def __init__(self, code: int):
super().__init__(code)
self.code = code
def _prepare(monkeypatch):
import hermes_cli.gateway as gateway_cli
import gateway.run as gateway_run
monkeypatch.setattr(gateway_cli, "_guard_official_docker_root_gateway", lambda: None)
monkeypatch.setattr(gateway_cli, "_guard_named_profile_under_multiplexer", lambda force=False: None)
monkeypatch.setattr(gateway_cli, "_attach_to_host_gateway_or_guard", lambda **kwargs: None)
monkeypatch.setattr(gateway_cli, "_guard_supervised_gateway_conflict", lambda force=False: None)
monkeypatch.setattr(gateway_cli, "_guard_existing_gateway_process_conflict", lambda replace=False: None)
monkeypatch.setattr(gateway_cli, "supports_systemd_services", lambda: False)
monkeypatch.setattr(gateway_cli.sys, "stdin", types.SimpleNamespace(isatty=lambda: False))
monkeypatch.setenv("HERMES_GATEWAY_EXIT_DIAG", "0")
async def _start_gateway(*args, **kwargs): # pragma: no cover - never awaited by fake run
return True
def _hard_exit(code: int) -> None:
raise _HardExitObserved(code)
monkeypatch.setattr(gateway_run, "start_gateway", _start_gateway)
monkeypatch.setattr(gateway_run, "_exit_after_graceful_shutdown", _hard_exit)
return gateway_cli
def test_run_gateway_hard_exits_after_clean_return(monkeypatch):
gateway_cli = _prepare(monkeypatch)
def _fake_run(coro):
coro.close()
return True
monkeypatch.setattr(gateway_cli.asyncio, "run", _fake_run)
with pytest.raises(_HardExitObserved) as excinfo:
gateway_cli.run_gateway()
assert excinfo.value.code == 0
def test_run_gateway_hard_exits_after_keyboard_interrupt(monkeypatch):
"""KeyboardInterrupt (console Ctrl+C) must also hard-exit, not return.
A bare ``return`` would let Python finalization join non-daemon worker
threads, the same wedge this backstop prevents on the other exit paths.
"""
gateway_cli = _prepare(monkeypatch)
def _fake_run(coro):
coro.close()
raise KeyboardInterrupt()
monkeypatch.setattr(gateway_cli.asyncio, "run", _fake_run)
with pytest.raises(_HardExitObserved) as excinfo:
gateway_cli.run_gateway()
assert excinfo.value.code == 0