The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): publish parked profiles so their clients fail fast with profile_parked
teknium1b36858fd9cbd
diff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex ac82dfd7bd1..7e4b690daaf 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -232,7 +232,7 @@ async def _start_gateway_start_control_socket(runner):payload = build_identify_payload()payload.update({key: descriptor[key] for key in ("instance_id", "runtime_protocol", "authority_epoch", "state", "api_origin",- "served_profiles", "capabilities") if key in descriptor})+ "served_profiles", "parked_profiles", "capabilities") if key in descriptor})if getattr(runner, '_draining', False):payload.update(state='draining', capabilities=[])payload["supervisor"] = {"manual": "none", "desktop": "none"}.get(diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex cfcd1857ca9..29a3928c088 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -110,9 +110,10 @@ class GatewayProfileReconcileMixin:live = {str(name): Path(home) for name, home in profiles_to_serve(multiplex=True)}known = dict(self._served_profile_homes or {})sigs = self._served_profile_signatures or {}+ from gateway.run_runtime import park_profile, unpark_profile+ for name in [n for n in self._parked_profile_names() if n not in live]:+ unpark_profile(self, name)parked = self._parked_profile_names()- for name in [n for n in parked if n not in live]:- parked.remove(name)# The watcher never re-parks the same profile every cycle; a creator's explicit signal does.retry_parked = reason == "control-socket"added = [n for n in live if n not in known and n != active and (retry_parked or n not in parked)]@@ -126,13 +127,13 @@ class GatewayProfileReconcileMixin:result["removed"].append(name)current = {n: h for n, h in live.items() if n in known or n == active}for name in list(added):- if not await self._serve_profile_runtime(name, live[name]):+ reason = await self._serve_profile_runtime(name, live[name])+ if reason is not None:added.remove(name)- if name not in parked:- parked.append(name)+ park_profile(self, name, reason)result["parked"].append(name)continue- parked[:] = [n for n in parked if n != name]+ unpark_profile(self, name)current[name] = live[name]claimed = self._live_resource_claims(active)for name in added + changed:@@ -171,34 +172,32 @@ class GatewayProfileReconcileMixin:def _parked_profile_names(self) -> list:"""Profiles that exist but could not be served (unusable store, home owned elsewhere); boot's- ``initialize_gateway_runtime`` parks into the same descriptor list."""- descriptor = getattr(self, "session_runtime_descriptor", None)- if descriptor is None:- descriptor = self.session_runtime_descriptor = {}- return descriptor.setdefault("parked_profiles", [])+ ``initialize_gateway_runtime`` parks into the same published ``name -> reason`` map."""+ from gateway.run_runtime import parked_profile_map+ return list(parked_profile_map(self))- async def _serve_profile_runtime(self, name: str, home: "Path") -> bool:+ async def _serve_profile_runtime(self, name: str, home: "Path") -> Optional[str]:"""Grow the reservation by *home* and build its session authority (boot's per-secondary- steps). False — parked, reservation released — when another gateway owns the home (a stray- per-profile daemon) or its store cannot be opened. An adapters-only runner (no authority- registry) grows the reservation alone."""+ steps). Returns the park reason — reservation released — when another gateway owns the home+ (a stray per-profile daemon) or its store cannot be opened; None when served. An+ adapters-only runner (no authority registry) grows the reservation alone."""from gateway.run_runtime import release_profile_home, reserve_profile_home, serve_profile_runtimefrom gateway.runtime_ownership import OwnershipConflicttry:reserve_profile_home(self, name, home)except (OwnershipConflict, OSError) as exc:logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)- return False+ return f"home owned by another gateway: {exc}"if getattr(self, "session_authorities", None) is None:- return True+ return Nonetry:await serve_profile_runtime(self, name, home)except Exception as exc:logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",name, home, exc)release_profile_home(self, home)- return False- return True+ return f"session store unusable: {exc}"+ return Nonedef _live_resource_claims(self, active: str) -> Dict[tuple, str]:"""Startup's ``claimed`` map rebuilt from what is live now: primary claims plus every connecteddiff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 07fb758d56c..0d931d14d33 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -63,7 +63,37 @@ def _park_reserved_profile(runner, name, home, exc):logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",name, home, exc)release_profile_home(runner, home)- runner.session_runtime_descriptor.setdefault('parked_profiles', []).append(name)+ park_profile(runner, name, f'session store unusable: {exc}')+++def park_profile(runner, name, reason):+ """Publish *name* under ``parked_profiles`` (name -> reason) in the runtime descriptor and the+ root's ``gateway_state.json``: a client of that profile then gets a terminal ``profile_parked``+ verdict from ``ensure`` instead of waiting its whole deadline for a service that never comes."""+ parked = parked_profile_map(runner)+ parked[name] = str(reason)[:500]+ _record_parked_profiles(parked)+++def unpark_profile(runner, name):+ parked = parked_profile_map(runner)+ if parked.pop(name, None) is not None:+ _record_parked_profiles(parked)+++def parked_profile_map(runner):+ descriptor = getattr(runner, 'session_runtime_descriptor', None)+ if descriptor is None:+ descriptor = runner.session_runtime_descriptor = {}+ return descriptor.setdefault('parked_profiles', {})+++def _record_parked_profiles(parked):+ try:+ from gateway.status import write_runtime_status+ write_runtime_status(parked_profiles=dict(parked))+ except Exception:+ logger.debug('could not record parked_profiles', exc_info=True)async def initialize_gateway_runtime(runner):@@ -93,6 +123,8 @@ async def initialize_gateway_runtime(runner):_park_reserved_profile(runner, name, home, exc)descriptor['authority_epoch'] = registry.launch.epochdescriptor['served_profiles'] = registry.served_profiles()+ # Publish this boot's verdict (an empty map clears a previous run's parked set).+ _record_parked_profiles(parked_profile_map(runner))runner.session_ticket_store = TicketStore(instance_id, registry.profile_ids())diff --git a/gateway/status.py b/gateway/status.pyindex 5888efe88ea..72ef433fe1d 100644--- a/gateway/status.py+++ b/gateway/status.py@@ -792,7 +792,7 @@ def write_runtime_status(active_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,- multiplex_standalone_reason: Any = _UNSET,+ parked_profiles: Any = _UNSET, multiplex_standalone_reason: Any = _UNSET,ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,drop_profile_platforms: Optional[str] = None,) -> None:@@ -825,6 +825,8 @@ def write_runtime_status(("active_work", active_work, lambda v: list(v) if v else None),# Multiplexed profiles; absent/empty for a single-profile gateway.("served_profiles", served_profiles, lambda v: list(v or [])),+ # Profiles the multiplexer could not serve, name -> reason; clients fail fast on them.+ ("parked_profiles", parked_profiles, lambda v: {str(k): str(r) for k, r in dict(v or {}).items()}),# Why an unset-default (multiplex on) gateway is serving one profile; None clears it.("multiplex_standalone_reason", multiplex_standalone_reason, lambda v: str(v) if v else None),("session_store", session_store, _coerce_session_store),diff --git a/hermes_cli/gateway_client.py b/hermes_cli/gateway_client.pyindex b4a53a9837f..c8cb7732548 100644--- a/hermes_cli/gateway_client.py+++ b/hermes_cli/gateway_client.py@@ -124,7 +124,8 @@ async def connect_gateway():home = get_hermes_home().resolve()result = await asyncio.to_thread(ensure_gateway_runtime, home)if result.state != "ready" or result.endpoint is None:- raise GatewayClientError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}")+ detail = f" ({result.detail})" if getattr(result, "detail", None) else ""+ raise GatewayClientError(f"Gateway {result.state}: {result.reason_code or 'not_ready'}{detail}")endpoint = result.endpointticket = await asyncio.to_thread(_session_ticket, home, endpoint)url = endpoint.api_origin.replace("https:", "wss:").replace("http:", "ws:") + "/api/ws"diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.pyindex f45deaedb15..4f2213e1996 100644--- a/hermes_cli/gateway_runtime.py+++ b/hermes_cli/gateway_runtime.py@@ -32,6 +32,9 @@ class GatewayDiscovery:state: RuntimeStateendpoint: GatewayEndpoint | None = Nonereason_code: str | None = None+ # Human-readable cause behind a bounded ``reason_code`` when the owner published one (the+ # multiplexer's park reason); never raw peer data.+ detail: str | None = Nonedef _canonical_home(home: str | Path) -> str:@@ -100,6 +103,21 @@ def _multiplexer_starting(home: Path) -> bool:return root is not None and missing_owner_state(root) == "starting"+def _parked_by_multiplexer(payload: dict, home: Path) -> GatewayDiscovery | None:+ """A secondary the multiplexer could not serve (unusable store, home owned elsewhere) is+ published under ``parked_profiles`` (name -> reason). That is a terminal verdict for its+ clients: waiting for a ``served_profiles`` entry that will never appear is the wrong answer."""+ parked = payload.get("parked_profiles")+ if not isinstance(parked, dict):+ return None+ from hermes_cli.profiles import normalize_profile_name+ name = normalize_profile_name(home.name)+ reason = next((r for n, r in parked.items() if normalize_profile_name(str(n)) == name), None)+ if reason is None:+ return None+ return GatewayDiscovery("inaccessible", reason_code="profile_parked", detail=str(reason)[:500] or None)++def _served_by_multiplexer(home: Path, *, timeout: float) -> GatewayDiscovery | None:"""A served secondary has no socket of its own: the default multiplexer's control socketanswers for it, and its ``identify`` lists the home under ``served_profiles``. Only the@@ -116,7 +134,7 @@ def _served_by_multiplexer(home: Path, *, timeout: float) -> GatewayDiscovery |return Noneresult = _endpoint(payload, home, control_home=root)if result.state == "inaccessible" and result.reason_code == "profile_mismatch":- return None # the multiplexer does not serve this profile+ return _parked_by_multiplexer(payload, home) # else: the multiplexer does not serve this profilereturn resultdiff --git a/tests/gateway/test_multiplex_hot_serve_live.py b/tests/gateway/test_multiplex_hot_serve_live.pyindex 1587a936840..4a5bd2d9593 100644--- a/tests/gateway/test_multiplex_hot_serve_live.py+++ b/tests/gateway/test_multiplex_hot_serve_live.py@@ -245,6 +245,19 @@ def test_broken_secondary_state_db_parks_only_that_profile(mux):assert served_homes(desc) == {root.resolve(), mux['boot'].resolve()}, descassert recorded_served(root) == ['default', 'boot']assert "Profile 'broken' not served" in tail(mux), tail(mux)+ # The park is published (identify + gateway_state.json), so the profile's clients fail fast+ # with the real reason instead of waiting the whole deadline for a service that never comes.+ assert 'broken' in desc.get('parked_profiles', {}), desc+ recorded = json.loads((root / 'gateway_state.json').read_text(encoding='utf-8'))+ assert 'broken' in recorded.get('parked_profiles', {}), recorded+ started = time.monotonic()+ ensured = subprocess.run([sys.executable, '-m', 'hermes_cli.main', '-p', 'broken', 'gateway', 'ensure',+ '--json', '--timeout', '30'], cwd=ROOT, env=mux['env'], capture_output=True,+ text=True, timeout=60)+ payload = json.loads(ensured.stdout.strip().splitlines()[-1])+ assert (payload['state'], payload['reason_code']) == ('inaccessible', 'profile_parked'), (payload, ensured.stderr)+ assert 'unusable' in (payload.get('detail') or ''), payload+ assert ensured.returncode == 7 and time.monotonic() - started < 20, (ensured.returncode, ensured.stderr)stop(proc)finally:stop(proc, expect=None)