Skip to content

The agent that grows with you

fix(gateway): only the runtime-lock owner records the multiplex decision

Tekniumb37c5d8dd8e4
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.py
index 9487af7cf5b..520f8939719 100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@ -230,6 +230,8 @@ def _start_gateway_claim_pid_file(force: bool = False) -> bool:
return False
atexit.register(remove_pid_file)
atexit.register(release_gateway_runtime_lock)
+ from hermes_cli.gateway_multiplex_mode import publish_pending_multiplex_decision
+ publish_pending_multiplex_decision()
_claim_host_gateway_role(force=force)
return True
diff --git a/hermes_cli/gateway_multiplex_mode.py b/hermes_cli/gateway_multiplex_mode.py
index 48cce2c6de8..885369f374f 100644
--- a/hermes_cli/gateway_multiplex_mode.py
+++ b/hermes_cli/gateway_multiplex_mode.py
@@ -275,16 +275,35 @@ def resolve_multiplex_mode(config) -> MultiplexDecision:
return decision
+_pending_decision: list[MultiplexDecision] = []
+
+
def record_multiplex_decision(decision: MultiplexDecision) -> None:
"""Persist a guard refusal into ``gateway_state.json`` so `hermes gateway status` can show why this
- gateway serves one profile while the default says multiplex; any other verdict clears the field."""
+ gateway serves one profile while the default says multiplex; any other verdict clears the field.
+
+ Only the runtime-lock owner writes that file. The decision is made while the config loads, before
+ the lock claim, and a pre-lock write published this process's pid as a live ``starting`` gateway:
+ a launch racing it read that as an owner and refused, leaving no gateway at all. Until this process
+ holds the lock the decision stays pending; ``publish_pending_multiplex_decision`` writes it once
+ the claim succeeds, and a launch that loses the claim never writes it."""
try:
- from gateway.status import write_runtime_status
+ from gateway.status import owns_gateway_runtime_lock, write_runtime_status
+ if not owns_gateway_runtime_lock():
+ _pending_decision[:] = [decision]
+ return
+ _pending_decision.clear()
write_runtime_status(multiplex_standalone_reason=decision.reason if decision.source == "guard" else None)
except Exception:
logger.debug("could not record the multiplex decision", exc_info=True)
+def publish_pending_multiplex_decision() -> None:
+ """Write the decision held back before the runtime-lock claim (called right after the claim)."""
+ if _pending_decision:
+ record_multiplex_decision(_pending_decision[-1])
+
+
def log_multiplex_decision(decision: MultiplexDecision) -> None:
record_multiplex_decision(decision)
if decision.source == "retired-opt-out":
diff --git a/tests/hermes_cli/test_gateway_multiplex_mode.py b/tests/hermes_cli/test_gateway_multiplex_mode.py
index 575eaed4a42..3f6c70d00a7 100644
--- a/tests/hermes_cli/test_gateway_multiplex_mode.py
+++ b/tests/hermes_cli/test_gateway_multiplex_mode.py
@@ -182,12 +182,67 @@ def test_guard_refusal_is_recorded_in_runtime_status_and_cleared_on_default(tmp_
from gateway import status as gw_status
from hermes_cli.gateway_multiplex_mode import MultiplexDecision, record_multiplex_decision
monkeypatch.setattr(gw_status, "_get_runtime_status_path", lambda: tmp_path / "gateway_state.json")
+ monkeypatch.setattr(gw_status, "owns_gateway_runtime_lock", lambda: True) # the serving gateway records
record_multiplex_decision(MultiplexDecision(False, "guard", "profile(s) 'coder' still run their own gateway"))
assert "coder" in gw_status.read_runtime_status(tmp_path / "gateway_state.json")["multiplex_standalone_reason"]
record_multiplex_decision(MultiplexDecision(True, "default", "unset; default applies"))
assert gw_status.read_runtime_status(tmp_path / "gateway_state.json")["multiplex_standalone_reason"] is None
[email protected]_gateway_lookalike # a stub that records a decision and takes the lock; reaped below
+def test_pre_lock_decision_never_publishes_a_rival_gateway_owner(tmp_path):
+ """The multiplex decision is made while the config loads, before the runtime-lock claim. Writing
+ it then published that launch's pid in gateway_state.json, and a launch racing it read that pid as
+ a live gateway and refused, so neither served (the cron e2e's "A gateway already owns this host").
+ A real `hermes gateway run`-shaped child records its decision without the lock; the rival must
+ still see no owner, and the decision lands only once that child holds the lock."""
+ import subprocess
+ import sys
+ import textwrap
+
+ home = tmp_path / "home"
+ home.mkdir()
+ entry = tmp_path / "bin" / "hermes" # the argv a gateway identity check accepts
+ entry.parent.mkdir()
+ entry.write_text(textwrap.dedent("""
+ import sys
+ from gateway import status
+ from hermes_cli.gateway_multiplex_mode import MultiplexDecision, record_multiplex_decision
+ record_multiplex_decision(MultiplexDecision(False, "guard", "profile 'coder' runs its own gateway"))
+ print("decided", flush=True)
+ sys.stdin.readline()
+ assert status.acquire_gateway_runtime_lock()
+ from hermes_cli.gateway_multiplex_mode import publish_pending_multiplex_decision
+ publish_pending_multiplex_decision()
+ print("claimed", flush=True)
+ sys.stdin.readline()
+ """), encoding="utf-8")
+ env = {**os.environ, "HERMES_HOME": str(home), "PYTHONPATH": str(Path(__file__).resolve().parents[2])}
+ child = subprocess.Popen([sys.executable, str(entry), "gateway", "run"], env=env, text=True,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ probe = textwrap.dedent("""
+ import json
+ from gateway import status
+ record = status.read_runtime_status() or {}
+ print(json.dumps([status.get_running_pid(), record.get("multiplex_standalone_reason")]))
+ """)
+
+ def rival() -> list:
+ out = subprocess.run([sys.executable, "-c", probe], env=env, text=True, capture_output=True, timeout=60)
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout)
+ try:
+ assert child.stdout.readline().strip() == "decided"
+ assert rival() == [None, None] # nothing claims to own the home before the lock does
+ child.stdin.write("\n")
+ child.stdin.flush()
+ assert child.stdout.readline().strip() == "claimed"
+ assert rival() == [child.pid, "profile 'coder' runs its own gateway"]
+ finally:
+ child.kill()
+ child.wait(timeout=30)
+
+
def test_recorded_standalone_warning_lines_suppressed_for_dead_or_stale_record(tmp_path, monkeypatch):
"""Dead or stale gateway_state.json must not emit standalone warnings (#120991)."""
import gateway.status as gw_status