The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): unify shutdown exit verdicts
YuYigenge24047d8bd2e
diff --git a/gateway/run.py b/gateway/run.pyindex c5c9cd91633..8215224446c 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2046,7 +2046,8 @@ from gateway.restart import (DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT,DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT,DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,- DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT)+ DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,+ GATEWAY_SERVICE_RESTART_EXIT_CODE as _GATEWAY_SERVICE_RESTART_EXIT_CODE)logger = logging.getLogger(__name__)@@ -5096,14 +5097,26 @@ def _exit_with_failure_verdict(runner) -> bool:return True-def _unexpected_signal_requires_restart(runner, signal_initiated_shutdown: bool) -> bool:- """True when an unplanned signal should make the supervisor revive the gateway."""- if not signal_initiated_shutdown or runner._restart_requested:+def _resolve_gateway_exit_verdict(runner, signal_initiated_shutdown: bool) -> bool:+ """Resolve the process verdict after either startup abort or normal shutdown."""+ if _exit_with_failure_verdict(runner):+ return False+ if runner.exit_code is not None:+ raise SystemExit(runner.exit_code)+ if signal_initiated_shutdown and not runner._restart_requested:+ logger.info(+ "Exiting with code 1 (signal-initiated shutdown without restart "+ "request) so the service manager can revive the gateway."+ )return False- logger.info(- "Exiting with code 1 (signal-initiated shutdown without restart "- "request) so the service manager can revive the gateway."- )+ # Older restart paths may not set ``runner.exit_code``; retain the service-restart fallback.+ if runner._restart_via_service:+ logger.info(+ "Exiting with code %d (service-restart requested) so the service "+ "manager relaunches the gateway.",+ _GATEWAY_SERVICE_RESTART_EXIT_CODE,+ )+ raise SystemExit(_GATEWAY_SERVICE_RESTART_EXIT_CODE)return True@@ -5126,8 +5139,6 @@ async def _start_gateway_shutdown_tail(stop_nous_auth_keepalive()_best_effort(_stop_keepalive)- if _exit_with_failure_verdict(runner):- return False# Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.# Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron@@ -5150,20 +5161,7 @@ async def _start_gateway_shutdown_tail(with suppress(Exception):await _shutdown_mcp_servers_nonblocking()- if runner.exit_code is not None:- raise SystemExit(runner.exit_code)-- # Unplanned SIGTERM exits non-zero so the service manager revives us; planned stops must not.- if _unexpected_signal_requires_restart(runner, _signal_initiated_shutdown[0]):- return False # → sys.exit(1) in the caller-- # Older restart paths may reach here without ``runner.exit_code``; keep the non-zero fallback.- if runner._restart_via_service:- logger.info("Exiting with code 75 (service-restart requested) so the service "- "manager relaunches the gateway.")- raise SystemExit(75)-- return True+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False, verbosity: Optional[int] = 0) -> bool:@@ -5304,15 +5302,9 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =# Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.try:await runner.wait_for_shutdown()- if _exit_with_failure_verdict(runner):- return Falsewith suppress(Exception):await _shutdown_mcp_servers_nonblocking()- if runner.exit_code is not None:- raise SystemExit(runner.exit_code)- if _unexpected_signal_requires_restart(runner, _signal_initiated_shutdown[0]):- return False- return True+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])finally:_shutdown_gateway_health_export(runner)diff --git a/tests/gateway/test_startup_restart_race.py b/tests/gateway/test_startup_restart_race.pyindex 015b4bd9f65..df67751518c 100644--- a/tests/gateway/test_startup_restart_race.py+++ b/tests/gateway/test_startup_restart_race.py@@ -218,6 +218,56 @@ async def test_start_gateway_does_not_start_cron_after_aborted_startup(tmp_path,assert export_shutdown_calls == 1+async def test_start_gateway_preserves_service_restart_fallback_after_aborted_startup(+ tmp_path, monkeypatch+):+ """A legacy service restart without an explicit exit code still exits with EX_TEMPFAIL."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ cron_started = False++ class AbortedStartupRunner:+ def __init__(self, config):+ self.config = config+ self.adapters = {}+ self._running = False+ self._restart_requested = True+ self._restart_via_service = True+ self.should_exit_cleanly = False+ self.should_exit_with_failure = False+ self.exit_reason = None+ self.exit_code = None++ async def start(self):+ return True++ async def wait_for_shutdown(self):+ return None++ def fail_if_cron_starts(*args, **kwargs):+ nonlocal cron_started+ cron_started = True++ monkeypatch.setattr("gateway.status.get_running_pid", lambda: None)+ monkeypatch.setattr("gateway.status.acquire_gateway_runtime_lock", lambda: True)+ monkeypatch.setattr("gateway.status.write_pid_file", lambda: None)+ monkeypatch.setattr("gateway.status.remove_pid_file", lambda: None)+ monkeypatch.setattr("gateway.status.release_gateway_runtime_lock", lambda: None)+ monkeypatch.setattr("tools.skills_sync.sync_skills", lambda quiet=True: None)+ monkeypatch.setattr("hermes_logging.setup_logging", lambda hermes_home, mode: None)+ monkeypatch.setattr("gateway.run.GatewayRunner", AbortedStartupRunner)+ monkeypatch.setattr("gateway.run._start_cron_ticker", fail_if_cron_starts)+ monkeypatch.setattr("tools.mcp_tool_lifecycle.shutdown_mcp_servers", lambda: None)++ with pytest.raises(SystemExit) as exc:+ await gateway_run.start_gateway(+ config=GatewayConfig(), replace=False, verbosity=None+ )++ assert exc.value.code == GATEWAY_SERVICE_RESTART_EXIT_CODE+ assert cron_started is False++@pytest.mark.asyncio@pytest.mark.parametrize(("unexpected_signal", "expected_success"),@@ -238,6 +288,7 @@ async def test_start_gateway_classifies_startup_signal_exit(self.adapters = {}self._running = Falseself._restart_requested = False+ self._restart_via_service = Falseself.should_exit_cleanly = Falseself.should_exit_with_failure = Falseself.exit_reason = None