The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: reserve all gateway profiles before writable initialization
Tekniumc941b0e674c3
diff --git a/gateway/run.py b/gateway/run.pyindex 13341369e71..b1d9319a0c2 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -1631,6 +1631,9 @@ class HygieneTurnHoldExceeded(Exception):def _multiplex_profile_homes(config: object) -> list[tuple[str, "Path"]]:"""Return the authoritative profile set for one multiplex gateway config."""+ reserved = getattr(config, "_runtime_profile_homes", None)+ if reserved is not None:+ return list(reserved)from hermes_cli.profiles import profiles_to_servereturn list(profiles_to_serve(multiplex=True, profile_allowlist=getattr(config, "multiplex_profile_allowlist", None)))@@ -4577,142 +4580,159 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =and not await _start_gateway_replace_existing_instance(existing_pid, replace)):return False- _start_gateway_configure_logging(verbosity)-- runner = GatewayRunner(config)- # Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records- # land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.- # See #82936.- _enable_multiplex_log_routing(runner.config)- # ``--replace`` is explicit startup authority, not a durable reconnect policy: GatewayRunner scopes- # it to cold adapter connects and clears it before the background reconnect watcher starts.- runner._platform_lock_takeover_on_start = bool(replace)-- # Unexpected signals exit non-zero so service managers revive us; planned stops write a marker first.- _signal_initiated_shutdown = [False]-- shutdown_signal_handler = _start_gateway_make_shutdown_signal_handler(- runner, _signal_initiated_shutdown)-- def restart_signal_handler():- runner.request_restart(detached=False, via_service=True)-- loop = asyncio.get_running_loop()-- # Swallow transient network errors from background tasks; one unhandled httpx error would kill us.- # Issues #31066 / #31110: an unhandled ``telegram.error.TimedOut`` (or peer NetworkError / httpx- # connection error) in any awaited coroutine would propagate to the loop and kill the gateway process,- # taking down every profile attached to the same runner. systemd then restarts the service after ~5s but- # the active conversation turn is lost. The fix is intentionally narrow: only well-known transient- # network errors are swallowed (and logged with full traceback so the originating call site is still- # discoverable). Anything else is forwarded to the default handler so real bugs still surface.- loop.set_exception_handler(_gateway_loop_exception_handler)-- if threading.current_thread() is threading.main_thread():- # add_signal_handler raises NotImplementedError on Windows; SIGUSR1 is POSIX-only.- handlers = [(sig, shutdown_signal_handler, (sig,)) for sig in (signal.SIGINT, signal.SIGTERM)]- if hasattr(signal, "SIGUSR1"):- handlers.append((signal.SIGUSR1, restart_signal_handler, ())) # windows-footgun: ok — hasattr-guarded- for sig, handler, args in handlers:- with suppress(NotImplementedError):- loop.add_signal_handler(sig, handler, *args) # windows-footgun: ok — suppress(NotImplementedError)- else:- logger.info("Skipping signal handlers (not running in main thread).")-- # Windows has no add_signal_handler, so `hermes gateway stop`'s SIGTERM would never drain; poll the- # planned-stop marker (written BEFORE the kill) instead. Runs everywhere so masked-SIGTERM drains.- # Windows fallback: asyncio.add_signal_handler raises NotImplementedError on Windows, so `hermes gateway- # stop`'s SIGTERM (which Python maps to TerminateProcess on Windows) never invokes- # shutdown_signal_handler. That means the drain loop never runs, mark_resume_pending never fires, and- # sessions are silently lost across restarts (issue #33778). The fix is a marker-polling thread: `hermes- # gateway stop` writes the planned-stop marker BEFORE killing, and this thread notices it and drives the- # same shutdown path the signal handler would have. Runs on every platform (cheap, defensive) so- # non-signal-bearing environments (Windows native, sandboxed CI runners that mask SIGTERM) still get a- # clean drain.- _planned_stop_watcher_stop = threading.Event()- _planned_stop_watcher_thread = threading.Thread(- target=_run_planned_stop_watcher,- args=(_planned_stop_watcher_stop, runner, loop, shutdown_signal_handler), daemon=True,- name="planned-stop-watcher")- _planned_stop_watcher_thread.start()-- # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.+ from gateway.runtime_ownership import process_ownership, OwnershipConflict+ from gateway.status import remove_pid_file, release_gateway_runtime_lock+ 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 [])+ try:+ process_ownership.reserve([get_hermes_home(), *(home for _, home in profile_homes)])+ except (OwnershipConflict, OSError) as exc:+ logger.error("Cannot reserve gateway profiles: %s", exc)+ return False+ # Freeze discovery: later profile additions must restart and reserve before opening stores.+ if profile_homes:+ resolved_config._runtime_profile_homes = tuple(profile_homes)if not _start_gateway_claim_pid_file():+ release_gateway_runtime_lock()return False- # Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.- _control_server = await _start_gateway_start_control_socket(runner)+ try:+ _start_gateway_configure_logging(verbosity)- def _lifecycle_record_startup() -> None:- # Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the- # sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.- from gateway.lifecycle_ledger import record_startup- record_startup()+ runner = GatewayRunner(resolved_config)+ # Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records+ # land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.+ # See #82936.+ _enable_multiplex_log_routing(runner.config)+ # ``--replace`` is explicit startup authority, not a durable reconnect policy: GatewayRunner scopes+ # it to cold adapter connects and clears it before the background reconnect watcher starts.+ runner._platform_lock_takeover_on_start = bool(replace)- def _start_keepalive() -> None:- from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive- start_nous_auth_keepalive()+ # Unexpected signals exit non-zero so service managers revive us; planned stops write a marker first.+ _signal_initiated_shutdown = [False]- _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")- _best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")- _ensure_windows_gateway_venv_imports()+ shutdown_signal_handler = _start_gateway_make_shutdown_signal_handler(+ runner, _signal_initiated_shutdown)- # discover_mcp_tools() blocks up to 120s; on the loop thread it would freeze platform heartbeats.- try:- # MCP tool discovery — run in an executor so the asyncio event loop stays responsive even when a- # configured MCP server is slow or unreachable. discover_mcp_tools() uses a blocking 120s wait- # internally; calling it from the loop thread would freeze platform heartbeats (Discord shard,- # Telegram polling) until it returned. See #16856.- await _discover_gateway_mcp_tools(runner.config)- except Exception as e:- logger.debug("MCP tool discovery failed: %s", e)+ def restart_signal_handler():+ runner.request_restart(detached=False, via_service=True)- try:- success = await runner.start()- except BaseException:- _shutdown_gateway_health_export(runner)- raise- if not success:- _shutdown_gateway_health_export(runner)- return False+ loop = asyncio.get_running_loop()- def _recover_pending() -> None:- from gateway.shutdown_flush import recover_pending_to_db- recovered = recover_pending_to_db()- if recovered:- logger.info("Recovered %d pending message(s) from shutdown flush", recovered)-- _best_effort(_recover_pending)- if runner.should_exit_cleanly:- _shutdown_gateway_health_export(runner)- if runner.exit_reason:- logger.error("Gateway exiting cleanly: %s", runner.exit_reason)- # Explicit exit codes (GATEWAY_FATAL_CONFIG_EXIT_CODE) must propagate so s6 finish maps 78 → 125.- if runner.exit_code is not None:- raise SystemExit(runner.exit_code)- return True- if not runner._running:- # Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.+ # Swallow transient network errors from background tasks; one unhandled httpx error would kill us.+ # Issues #31066 / #31110: an unhandled ``telegram.error.TimedOut`` (or peer NetworkError / httpx+ # connection error) in any awaited coroutine would propagate to the loop and kill the gateway process,+ # taking down every profile attached to the same runner. systemd then restarts the service after ~5s but+ # the active conversation turn is lost. The fix is intentionally narrow: only well-known transient+ # network errors are swallowed (and logged with full traceback so the originating call site is still+ # discoverable). Anything else is forwarded to the default handler so real bugs still surface.+ loop.set_exception_handler(_gateway_loop_exception_handler)++ if threading.current_thread() is threading.main_thread():+ # add_signal_handler raises NotImplementedError on Windows; SIGUSR1 is POSIX-only.+ handlers = [(sig, shutdown_signal_handler, (sig,)) for sig in (signal.SIGINT, signal.SIGTERM)]+ if hasattr(signal, "SIGUSR1"):+ handlers.append((signal.SIGUSR1, restart_signal_handler, ())) # windows-footgun: ok — hasattr-guarded+ for sig, handler, args in handlers:+ with suppress(NotImplementedError):+ loop.add_signal_handler(sig, handler, *args) # windows-footgun: ok — suppress(NotImplementedError)+ else:+ logger.info("Skipping signal handlers (not running in main thread).")++ # Windows has no add_signal_handler, so `hermes gateway stop`'s SIGTERM would never drain; poll the+ # planned-stop marker (written BEFORE the kill) instead. Runs everywhere so masked-SIGTERM drains.+ # Windows fallback: asyncio.add_signal_handler raises NotImplementedError on Windows, so `hermes gateway+ # stop`'s SIGTERM (which Python maps to TerminateProcess on Windows) never invokes+ # shutdown_signal_handler. That means the drain loop never runs, mark_resume_pending never fires, and+ # sessions are silently lost across restarts (issue #33778). The fix is a marker-polling thread: `hermes+ # gateway stop` writes the planned-stop marker BEFORE killing, and this thread notices it and drives the+ # same shutdown path the signal handler would have. Runs on every platform (cheap, defensive) so+ # non-signal-bearing environments (Windows native, sandboxed CI runners that mask SIGTERM) still get a+ # clean drain.+ _planned_stop_watcher_stop = threading.Event()+ _planned_stop_watcher_thread = threading.Thread(+ target=_run_planned_stop_watcher,+ args=(_planned_stop_watcher_stop, runner, loop, shutdown_signal_handler), daemon=True,+ name="planned-stop-watcher")+ _planned_stop_watcher_thread.start()++ # Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.+ _control_server = await _start_gateway_start_control_socket(runner)++ def _lifecycle_record_startup() -> None:+ # Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the+ # sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.+ from gateway.lifecycle_ledger import record_startup+ record_startup()++ def _start_keepalive() -> None:+ from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive+ start_nous_auth_keepalive()++ _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")+ _best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")+ _ensure_windows_gateway_venv_imports()++ # discover_mcp_tools() blocks up to 120s; on the loop thread it would freeze platform heartbeats.try:- await runner.wait_for_shutdown()- with suppress(Exception):- await _shutdown_mcp_servers_nonblocking()- return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])- finally:+ # MCP tool discovery — run in an executor so the asyncio event loop stays responsive even when a+ # configured MCP server is slow or unreachable. discover_mcp_tools() uses a blocking 120s wait+ # internally; calling it from the loop thread would freeze platform heartbeats (Discord shard,+ # Telegram polling) until it returned. See #16856.+ await _discover_gateway_mcp_tools(runner.config)+ except Exception as e:+ logger.debug("MCP tool discovery failed: %s", e)++ try:+ success = await runner.start()+ except BaseException:+ _shutdown_gateway_health_export(runner)+ raise+ if not success:+ _shutdown_gateway_health_export(runner)+ return False++ def _recover_pending() -> None:+ from gateway.shutdown_flush import recover_pending_to_db+ recovered = recover_pending_to_db()+ if recovered:+ logger.info("Recovered %d pending message(s) from shutdown flush", recovered)++ _best_effort(_recover_pending)+ if runner.should_exit_cleanly:_shutdown_gateway_health_export(runner)+ if runner.exit_reason:+ logger.error("Gateway exiting cleanly: %s", runner.exit_reason)+ # Explicit exit codes (GATEWAY_FATAL_CONFIG_EXIT_CODE) must propagate so s6 finish maps 78 → 125.+ if runner.exit_code is not None:+ raise SystemExit(runner.exit_code)+ return True+ if not runner._running:+ # Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.+ try:+ await runner.wait_for_shutdown()+ with suppress(Exception):+ await _shutdown_mcp_servers_nonblocking()+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])+ finally:+ _shutdown_gateway_health_export(runner)- cron_stop, cron_provider, cron_thread, housekeeping_thread = (- _start_gateway_start_cron_and_housekeeping(runner))+ cron_stop, cron_provider, cron_thread, housekeeping_thread = (+ _start_gateway_start_cron_and_housekeeping(runner))- # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.- runner._start_systemd_watchdog()+ # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.+ runner._start_systemd_watchdog()- await runner.wait_for_shutdown()+ await runner.wait_for_shutdown()- return await _start_gateway_shutdown_tail(- runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,- _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)+ return await _start_gateway_shutdown_tail(+ runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,+ _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)+ finally:+ remove_pid_file()+ release_gateway_runtime_lock()def _guard_corrupt_user_config() -> None:"""Fail closed when the active profile's config.yaml cannot be parsed: nobody can repair it on thisdiff --git a/gateway/runtime_ownership.py b/gateway/runtime_ownership.pynew file mode 100644index 00000000000..71895d85676--- /dev/null+++ b/gateway/runtime_ownership.py@@ -0,0 +1,85 @@+"""Nonblocking, all-or-nothing reservations of canonical profile homes.++Lock inodes are never removed: unlinking a locked inode creates a second owner.+"""+from __future__ import annotations++import json+import os+from pathlib import Path+import stat+import threading+++class OwnershipConflict(RuntimeError):+ pass+++def canonical_home(home: Path) -> Path:+ return Path(os.path.normcase(str(Path(home).expanduser().resolve())))+++class ProfileOwnership:+ def __init__(self):+ self._handles: dict[Path, object] = {}+ self._mutex = threading.RLock()++ @property+ def homes(self) -> tuple[Path, ...]:+ with self._mutex:+ return tuple(self._handles)++ def reserve(self, homes) -> None:+ from gateway.status import _try_acquire_file_lock, _build_pid_record+ with self._mutex:+ added = []+ try:+ for home in sorted({canonical_home(p) for p in homes}):+ if home in self._handles:+ continue+ home.mkdir(parents=True, exist_ok=True)+ path = home / 'gateway.lock'+ flags = os.O_RDWR | os.O_CREAT | getattr(os, 'O_NOFOLLOW', 0)+ fd = os.open(path, flags, 0o600)+ handle = os.fdopen(fd, 'r+', encoding='utf-8')+ try:+ info = os.fstat(handle.fileno())+ if not stat.S_ISREG(info.st_mode) or (os.name != 'nt' and info.st_uid != os.getuid()):+ raise PermissionError('unsafe gateway lock owner or type')+ if not _try_acquire_file_lock(handle):+ raise OwnershipConflict(f'Gateway runtime already owns profile {home}')+ record = {**_build_pid_record(), 'hermes_home': str(home)}+ handle.seek(0)+ handle.truncate()+ json.dump(record, handle)+ handle.flush()+ os.fsync(handle.fileno())+ except BaseException:+ handle.close()+ raise+ self._handles[home] = handle+ added.append(home)+ except BaseException:+ for home in reversed(added):+ self.release(home)+ raise++ def owns(self, home: Path) -> bool:+ with self._mutex:+ return canonical_home(home) in self._handles++ def release(self, home: Path) -> None:+ from gateway.status import _release_file_lock+ with self._mutex:+ handle = self._handles.pop(canonical_home(home), None)+ if handle is not None:+ _release_file_lock(handle)+ handle.close()++ def close(self) -> None:+ with self._mutex:+ for home in reversed(self.homes):+ self.release(home)+++process_ownership = ProfileOwnership()diff --git a/gateway/status.py b/gateway/status.pyindex b356a938b69..ab53d15b501 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -537,7 +537,8 @@ def _cleanup_invalid_pid_path(pid_path: Path, *, cleanup_stale: bool) -> None:if not cleanup_stale:return_clear_running_pid_cache()- for path in (pid_path, _get_gateway_lock_path(pid_path)):+ # Keep the inode even when stale: another contender may already have opened it.+ for path in (pid_path,):with contextlib.suppress(Exception):path.unlink(missing_ok=True)@@ -657,53 +658,24 @@ def _release_file_lock(handle) -> None:def acquire_gateway_runtime_lock() -> bool:- """Claim the cross-process runtime lock; the OS releases it if the process dies."""- global _gateway_lock_handle- if _gateway_lock_handle is not None:- return True- path = _get_gateway_lock_path()- path.parent.mkdir(parents=True, exist_ok=True)+ """Reserve the launch profile without unlinking inaccessible lock inodes."""+ from gateway.runtime_ownership import process_ownership, OwnershipConflicttry:- handle = open(path, "a+", encoding="utf-8")- except PermissionError:- # Stale root-owned lock (launchd session that ran as root): the directory owner can- # unlink it; retry once with a fresh file.- try:- path.unlink()- handle = open(path, "a+", encoding="utf-8")- except OSError:- return False- if not _try_acquire_file_lock(handle):- handle.close()+ process_ownership.reserve([_get_process_hermes_home()])+ except (OwnershipConflict, OSError):return False- handle.seek(0)- handle.truncate()- json.dump(_build_pid_record(), handle)- handle.flush()- with contextlib.suppress(OSError):- os.fsync(handle.fileno())- _gateway_lock_handle = handle_clear_running_pid_cache()return True-def release_gateway_runtime_lock() -> None:- """Release the gateway runtime lock when owned by this process."""- global _gateway_lock_handle- handle, _gateway_lock_handle = _gateway_lock_handle, None- if handle is None:- return- _release_file_lock(handle)- with contextlib.suppress(OSError):- handle.close()+ """Release only this process's profile reservations, never their lock files."""+ from gateway.runtime_ownership import process_ownership+ process_ownership.close()_clear_running_pid_cache()-def owns_gateway_runtime_lock() -> bool:- """True when THIS process holds the runtime lock. ``is_gateway_runtime_lock_active`` answers- "does anyone?"; re-probing our own flock succeeds on POSIX, so only the handle discriminates."""- return _gateway_lock_handle is not None-+ from gateway.runtime_ownership import process_ownership+ return process_ownership.owns(_get_process_hermes_home())def _probe_lock_file(handle) -> bool:"""True when another process holds the lock (a won probe is released); closes ``handle``."""@@ -720,16 +692,15 @@ def _probe_lock_file(handle) -> bool:def is_gateway_runtime_lock_active(lock_path: Optional[Path] = None) -> bool:"""True when some process currently owns the gateway runtime lock."""resolved_lock_path = lock_path or _get_gateway_lock_path()- if _gateway_lock_handle is not None and resolved_lock_path == _get_gateway_lock_path():+ if owns_gateway_runtime_lock() and resolved_lock_path == _get_gateway_lock_path():return Trueif not resolved_lock_path.exists():return Falsetry:handle = open(resolved_lock_path, "a+", encoding="utf-8")except PermissionError:- # Stale root-owned lock (see acquire_gateway_runtime_lock): report inactive.- _unlink_quietly(resolved_lock_path)- return False+ # Unknown ownership is not permission to delete a potentially held inode.+ return Truereturn _probe_lock_file(handle)diff --git a/tests/gateway/test_runtime_ownership.py b/tests/gateway/test_runtime_ownership.pynew file mode 100644index 00000000000..cfe826f4f4d--- /dev/null+++ b/tests/gateway/test_runtime_ownership.py@@ -0,0 +1,64 @@+"""Real process exclusion before writable gateway construction."""+import os+from pathlib import Path+import subprocess+import sys++import pytest++[email protected]_only+def test_losing_start_never_constructs_writable_runner(tmp_path):+ from gateway.status import acquire_gateway_runtime_lock, release_gateway_runtime_lock+ assert acquire_gateway_runtime_lock()+ code = '''+import asyncio+from pathlib import Path+import os+import gateway.run as run+from gateway.config import GatewayConfig+class Witness:+ def __init__(self, config):+ Path(os.environ['WITNESS']).write_text('writable init reached')+ raise RuntimeError('initializer reached')+run.GatewayRunner = Witness+try:+ result = asyncio.run(run.start_gateway(GatewayConfig(), verbosity=None))+except RuntimeError:+ result = True+print('CLAIMED', result)+'''+ witness = tmp_path / 'witness'+ try:+ result = subprocess.run([sys.executable, '-c', code], env={**os.environ, 'WITNESS': str(witness)},+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30)+ assert result.returncode == 0, result.stderr+ assert not witness.exists(), result.stdout + result.stderr+ assert 'CLAIMED False' in result.stdout+ finally:+ release_gateway_runtime_lock()++[email protected]_only+def test_profile_reservations_unwind_without_releasing_another_owner(tmp_path):+ from gateway import runtime_ownership+ homes = [tmp_path / 'a', tmp_path / 'b']+ for home in homes:+ home.mkdir()+ blocker = runtime_ownership.ProfileOwnership()+ blocker.reserve([homes[1]])+ contender = runtime_ownership.ProfileOwnership()+ with pytest.raises(runtime_ownership.OwnershipConflict):+ contender.reserve(reversed(homes))+ free = runtime_ownership.ProfileOwnership()+ free.reserve([homes[0]])+ contender.close()+ with pytest.raises(runtime_ownership.OwnershipConflict):+ contender.reserve([homes[1]])+ blocker.close()+ contender.reserve([homes[1]])+ blocker.close() # late cleanup must not affect replacement+ with pytest.raises(runtime_ownership.OwnershipConflict):+ blocker.reserve([homes[1]])+ free.close()+ contender.close()