The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): the hot-serve reconcile grows and shrinks the profile reservation
teknium18cb6d0cea167
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex e1ec0c9511b..489d357ff6a 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -90,11 +90,15 @@ class GatewayProfileReconcileMixin:# ── reconcile ─────────────────────────────────────────────────────────────────────────────────async def reconcile_served_profiles(self, *, reason: str = "request") -> Dict[str, Any]:- """Diff ``profiles/`` against the served set: start adapters for new profiles, tear down and- unroute deleted ones, (re)build adapters for served profiles whose config/.env changed. Other- profiles' adapters are never touched. Returns ``{"added", "removed", "rescanned", "served_profiles"}``."""- from gateway.run import MultiplexConfigError, _multiplex_profile_homes- result: Dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "reason": reason}+ """Diff ``profiles/`` (what exists now) against the served set (the process reservation):+ reserve + build the runtime and start adapters for new profiles, tear down, unroute and+ unreserve deleted ones, (re)build adapters for served profiles whose config/.env changed.+ Other profiles' adapters are never touched. A new profile whose home another gateway owns or+ whose store is unusable is parked (logged, not served) and left for an explicit rescan.+ Returns ``{"added", "removed", "rescanned", "parked", "served_profiles"}``."""+ from gateway.run import MultiplexConfigError+ from hermes_cli.profiles import profiles_to_serve+ result: Dict[str, Any] = {"added": [], "removed": [], "rescanned": [], "parked": [], "reason": reason}if not self._multiplex_on():return {**result, "multiplex": False, "served_profiles": self.served_profile_names()}if not self._running or self._served_profile_homes is None:@@ -102,18 +106,33 @@ class GatewayProfileReconcileMixin:return {**result, "pending": True, "served_profiles": self.served_profile_names()}async with self._reconcile_lock():active = getattr(self, "_primary_profile_name", None) or "default"- current = {str(name): Path(home) for name, home in _multiplex_profile_homes(self.config)}+ 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 {}- added = [n for n in current if n not in known and n != active]- removed = [n for n in known if n not in current and n != active]- changed = [n for n in current if n in known and n != active and n not in added- and profile_serve_signature(current[n]) != sigs.get(n)]+ 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)]+ removed = [n for n in known if n not in live and n != active]+ changed = [n for n in live if n in known and n != active and n not in added+ and profile_serve_signature(live[n]) != sigs.get(n)]if not (added or removed or changed):return {**result, "served_profiles": self.served_profile_names()}for name in removed:await self._unserve_profile(name, known[name])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]):+ added.remove(name)+ if name not in parked:+ parked.append(name)+ result["parked"].append(name)+ continue+ parked[:] = [n for n in parked if n != name]+ current[name] = live[name]claimed = self._live_resource_claims(active)for name in added + changed:# Only acknowledge the configuration observed before connecting;@@ -138,7 +157,7 @@ class GatewayProfileReconcileMixin:self._served_profile_signatures = sigs# A profile deleted while an adapter above was still connecting must not be recorded back# (the deleter's signal timed out against this lock and rmtree already ran).- live_now = {str(name) for name, _home in _multiplex_profile_homes(self.config)}+ live_now = {str(name) for name, _home in profiles_to_serve(multiplex=True)}for name in [n for n in current if n not in live_now and n != active]:await self._unserve_profile(name, current.pop(name))result["removed"].append(name)@@ -149,6 +168,37 @@ class GatewayProfileReconcileMixin:result["served_profiles"] = self.served_profile_names()return result+ 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", [])++ async def _serve_profile_runtime(self, name: str, home: "Path") -> bool:+ """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."""+ from gateway.run_runtime import release_profile_home, reserve_profile_home, serve_profile_runtime+ from gateway.runtime_ownership import OwnershipConflict+ try:+ reserve_profile_home(self, name, home)+ except (OwnershipConflict, OSError) as exc:+ logger.error("[MULTIPLEX] Profile '%s' not served: %s", name, exc)+ return False+ if getattr(self, "session_authorities", None) is None:+ return True+ try:+ 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+def _live_resource_claims(self, active: str) -> Dict[tuple, str]:"""Startup's ``claimed`` map rebuilt from what is live now: primary claims plus every connectedsecondary's credential/listener, so a hot-added profile reusing a token is parked, never a@@ -207,6 +257,13 @@ class GatewayProfileReconcileMixin:for key in [k for k in list(cache or {}) if str(k).startswith(prefix)]:with _log_suppressed(logging.DEBUG, "agent eviction failed for %s", key, exc_info=True):self._evict_cached_agent(key)+ # Its session authority and reservation go before the store handles: the authority owns the+ # state.db writer, and the next restart must not try to reserve a home that no longer exists.+ from gateway.run_runtime import release_profile_home, unserve_profile_runtime+ if getattr(self, "session_authorities", None) is not None:+ with _log_suppressed(logging.WARNING, "session authority retirement failed for %s", name, exc_info=True):+ await unserve_profile_runtime(self, home)+ release_profile_home(self, home)with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):from hermes_state_registry import close_all_underclose_all_under(home)diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex e47609f90e7..13c691ded67 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -4,13 +4,19 @@ One SessionAuthority per reserved profile home. The launch home always has one;``gateway.multiplex_profiles`` every served secondary gets its own, built under thatprofile's runtime scope against that profile's ``state.db``. ``runner.session_authority``stays the launch profile's authority so single-profile behaviour is byte-identical.++The served set is not frozen at boot: ``serve_profile_runtime`` / ``unserve_profile_runtime``+grow and shrink it for the hot-serve reconcile."""from __future__ import annotationsimport asyncio+import loggingfrom pathlib import Pathimport uuid+logger = logging.getLogger(__name__)+def reserved_profile_homes(runner):"""``(name, home)`` pairs this process reserved: launch home first, then served secondaries."""@@ -26,12 +32,33 @@ def reserved_profile_homes(runner):return homes+async def _build_profile_authority(runner, name, home, *, register):+ """One profile's authority against its own ``state.db``; raises when that store is unusable."""+ from gateway.run import _profile_runtime_scope+ from gateway.session_authority import initialize_session_authority+ registry = runner.session_authorities+ instance_id = runner.session_runtime_descriptor['instance_id']+ # Each home's store resolves through the runner's scope-following handle cache, exactly+ # the handle every later scoped read of that profile uses (one writer per state.db).+ with _profile_runtime_scope(home, hydrate_secrets=False):+ db = getattr(runner._session_db, '_db', runner._session_db)+ if db is None or Path(db.db_path).resolve().parent != home:+ raise RuntimeError(f'session authority database does not belong to the reserved profile {home}')+ registry.add(home, None, name=name)+ try:+ authority = await initialize_session_authority(+ runner, profile_id=str(home), instance_id=instance_id, db=db, register=register)+ except BaseException:+ registry.remove(home)+ raise+ registry.replace(home, authority)+ return authority++async def initialize_gateway_runtime(runner):from gateway.runtime_bootstrap import TicketStorefrom gateway.runtime_ownership import process_ownership- from gateway.run import _profile_runtime_scopefrom gateway.session_authorities import SessionAuthorities- from gateway.session_authority import initialize_session_authorityhomes = reserved_profile_homes(runner)for _name, home in homes:@@ -47,22 +74,91 @@ async def initialize_gateway_runtime(runner):registry = SessionAuthorities(homes[0][1])runner.session_authorities = registryfor index, (name, home) in enumerate(homes):- # Each home's store resolves through the runner's scope-following handle cache, exactly- # the handle every later scoped read of that profile uses (one writer per state.db).- with _profile_runtime_scope(home, hydrate_secrets=False):- db = getattr(runner._session_db, '_db', runner._session_db)- if db is None or Path(db.db_path).resolve().parent != home:- raise RuntimeError(f'session authority database does not belong to the reserved profile {home}')- registry.add(home, None, name=name)- authority = await initialize_session_authority(- runner, profile_id=str(home), instance_id=instance_id, db=db,- register=index == 0)- registry.replace(home, authority)+ await _build_profile_authority(runner, name, home, register=index == 0)descriptor['authority_epoch'] = registry.launch.epochdescriptor['served_profiles'] = registry.served_profiles()runner.session_ticket_store = TicketStore(instance_id, registry.profile_ids())+def _publish_served_set(runner):+ registry = runner.session_authorities+ runner.session_runtime_descriptor['served_profiles'] = registry.served_profiles()+ runner.session_ticket_store.profile_ids = registry.profile_ids()+++def reserve_profile_home(runner, name, home):+ """Grow the process reservation by one profile (hot-serve): take its ``gateway.lock`` and add it+ to the frozen boot set, so every reader of the reservation — and the next restart's+ all-or-nothing reserve — sees it. ``OwnershipConflict`` when another gateway owns the home."""+ from gateway.runtime_ownership import process_ownership+ home = Path(home).resolve()+ process_ownership.reserve([home])+ reserved = getattr(runner.config, '_runtime_profile_homes', None)+ if reserved is not None and all(Path(h).resolve() != home for _n, h in reserved):+ runner.config._runtime_profile_homes = (*reserved, (name, home))+++def release_profile_home(runner, home):+ """Shrink the reservation by one profile (deleted, or parked because it cannot be served)."""+ from gateway.runtime_ownership import process_ownership+ home = Path(home).resolve()+ reserved = getattr(runner.config, '_runtime_profile_homes', None)+ if reserved is not None:+ runner.config._runtime_profile_homes = tuple(+ entry for entry in reserved if Path(entry[1]).resolve() != home)+ process_ownership.release(home)+++async def serve_profile_runtime(runner, name, home):+ """Hot-serve one reserved profile's runtime: build its authority, recover its durable state and+ publish it in the descriptor/ticket store — the steps boot performs per secondary. Raises when+ the profile's store is unusable; the caller parks it (and releases the reservation)."""+ from gateway.session_authorities import owner_scope+ from gateway.session_bot import recover_bot_deliveries+ from gateway.session_hosted_service import _ensure_hosted_service, start_ready_hosted_services+ from gateway.session_local_recovery import recover_local_sessions+ from gateway.platforms.webhook_ingress import recover_webhook_finalizations+ home = Path(home).resolve()+ registry = runner.session_authorities+ if registry.for_home(home) is not None:+ return registry.for_home(home)+ authority = await _build_profile_authority(runner, name, home, register=False)+ try:+ with owner_scope(authority):+ await recover_bot_deliveries(authority)+ recover_local_sessions(authority, schedule=True)+ await recover_webhook_finalizations(authority)+ if getattr(runner, 'session_control_server', None) is not None:+ await _ensure_hosted_service(runner, authority)+ except BaseException:+ registry.remove(home)+ raise+ _publish_served_set(runner)+ start_ready_hosted_services(runner)+ return authority+++async def unserve_profile_runtime(runner, home):+ """Retire one profile's authority (deleted while running) and shrink the published set.+ No-op for a profile this process never served."""+ from gateway.session_cron import unbind_owner+ home = Path(home).resolve()+ registry = runner.session_authorities+ authority = registry.remove(home) if home in registry else None+ if authority is None:+ return+ service = getattr(authority, 'hosted_room_service', None)+ if service is not None:+ await asyncio.to_thread(service.stop, timeout=5)+ tasks = [live.task for live in authority.sessions.values() if live.task is not None]+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ unbind_owner(authority)+ _publish_served_set(runner)++def _authorities(runner):from gateway.session_authorities import all_authoritiesreturn all_authorities(runner)diff --git a/gateway/session_authorities.py b/gateway/session_authorities.pyindex 1f7351d8b2e..1f067fc423b 100644--- a/gateway/session_authorities.py+++ b/gateway/session_authorities.py@@ -39,6 +39,15 @@ class SessionAuthorities:raise RuntimeError(f'no reserved session authority slot for {home}')self._by_key[key] = authority+ def remove(self, home):+ """Drop *home*'s slot (a parked boot, a hot-unserved profile); returns the authority or None.+ The launch slot is never removed."""+ key = hermes_home_key(home)+ if key == self.launch_key:+ raise RuntimeError('the launch session authority cannot be removed')+ self._names.pop(key, None)+ return self._by_key.pop(key, None)+def profile_name(self, authority):"""Served profile name for *authority*; None for the launch profile (its adapters are``runner.adapters``, its session keys the historical ``agent:main`` namespace)."""diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 688c722ab2c..f9ce60aa19a 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -95,8 +95,12 @@ class SessionAuthority:def logical_owner(self, session_id):"""The FIFO/admission identity of a route: the root of its compression lineage.- Compression advances the physical transcript, never the admission identity."""- return self.db.get_compression_lineage(session_id)[0] if session_id else session_id+ Compression advances the physical transcript, never the admission identity. A session this+ store does not hold (another served profile's, under multiplex) keeps its own id."""+ if not session_id:+ return session_id+ lineage = self.db.get_compression_lineage(session_id)+ return lineage[0] if lineage else session_iddef physical_target(self, ref):return self.db.get_compression_tip(ref.session_id) or ref.session_iddiff --git a/tests/gateway/test_multiplex_hot_serve.py b/tests/gateway/test_multiplex_hot_serve.pyindex 3f1f1674dc6..459c979ccee 100644--- a/tests/gateway/test_multiplex_hot_serve.py+++ b/tests/gateway/test_multiplex_hot_serve.py@@ -4,6 +4,11 @@ The multiplexer used to enumerate ``profiles/`` once at boot; these pin the runtprofile created afterwards is served, a deleted one is torn down and unrouted, a served profile whoseconfig/.env changed (bot token added after create) gets its adapters, and none of it touches the otherprofiles' live adapters. The cron ticker's live enumerator is covered in ``tests/cron``.++The runner is set up the way ``run_bootstrap.start_gateway`` leaves it: the boot set reserved through+``process_ownership`` and frozen into ``config._runtime_profile_homes``. The reconcile must diff the+LIVE ``profiles/`` against that reservation and grow/shrink it — a reconcile that reads the snapshot+back as "what exists" can never see a new profile (the regression these tests used to pass through)."""import asyncioimport json@@ -39,6 +44,7 @@ def _runner(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)runner = object.__new__(GatewayRunner)runner.config = GatewayConfig(multiplex_profiles=True)+ runner.session_authorities = None # adapters-only runner: no per-profile session authorityrunner._running = Truerunner._primary_profile_name = "default"runner.adapters = {}@@ -66,6 +72,28 @@ def _runner(tmp_path, monkeypatch):return runner, home+def _boot(runner, home):+ """What ``start_gateway`` does before the runner exists: reserve every profile that exists now and+ freeze that set as the reservation the process owns."""+ from gateway.run import _multiplex_profile_homes+ from gateway.runtime_ownership import process_ownership+ boot_set = _multiplex_profile_homes(runner.config)+ process_ownership.reserve([h for _n, h in boot_set])+ runner.config._runtime_profile_homes = tuple(boot_set)++[email protected](autouse=True)+def _release_reservations():+ from gateway.runtime_ownership import process_ownership+ yield+ for reserved in process_ownership.homes:+ process_ownership.release(reserved)+++def _reserved_names(runner):+ return sorted(name for name, _home in runner.config._runtime_profile_homes)++def _mkprofile(home, name, env=""):d = home / "profiles" / named.mkdir(parents=True, exist_ok=True)@@ -83,15 +111,20 @@ async def test_created_then_credentialed_profile_is_served_without_restart(tmp_prunner, home = _runner(tmp_path, monkeypatch)alpha_dir = _mkprofile(home, "alpha", "DISCORD_BOT_TOKEN=alpha-token\n")with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ _boot(runner, home)await runner._start_secondary_profile_adapters()alpha_adapter = runner._profile_adapters["alpha"][Platform.DISCORD]assert _served_record(home) == ["default", "alpha"]- # 1. Created while running, no token yet: served (routes/prefixes/cron), zero adapters.+ # 1. Created while running, no token yet: served (routes/prefixes/cron), zero adapters, and the+ # reservation grew to include it (the next restart's reserve, the served set, the cron ticker).gamma_dir = _mkprofile(home, "gamma")result = await runner.reconcile_served_profiles()assert result["added"] == ["gamma"]assert _served_record(home) == ["default", "alpha", "gamma"]+ assert _reserved_names(runner) == ["alpha", "default", "gamma"]+ from gateway.runtime_ownership import process_ownership+ assert process_ownership.owns(gamma_dir)assert "gamma" in runner.pairing_storesassert Platform.DISCORD not in runner._profile_adapters.get("gamma", {})@@ -103,7 +136,7 @@ async def test_created_then_credentialed_profile_is_served_without_restart(tmp_p# 3. A no-op rescan and the whole sequence never touched alpha's live adapter.assert await runner.reconcile_served_profiles() == {- "added": [], "removed": [], "rescanned": [], "reason": "request",+ "added": [], "removed": [], "rescanned": [], "parked": [], "reason": "request","served_profiles": ["default", "alpha", "gamma"],}assert runner._profile_adapters["alpha"][Platform.DISCORD] is alpha_adapter@@ -118,6 +151,7 @@ async def test_deleted_profile_is_torn_down_and_unrouted_others_untouched(tmp_pa_mkprofile(home, "alpha", "DISCORD_BOT_TOKEN=alpha-token\n")gamma_dir = _mkprofile(home, "gamma", "DISCORD_BOT_TOKEN=gamma-token\n")with patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ _boot(runner, home)await runner._start_secondary_profile_adapters()alpha_adapter = runner._profile_adapters["alpha"][Platform.DISCORD]gamma_adapter = runner._profile_adapters["gamma"][Platform.DISCORD]@@ -138,6 +172,10 @@ async def test_deleted_profile_is_torn_down_and_unrouted_others_untouched(tmp_paassert reconnect.cancelled()assert evicted == ["agent:gamma:discord:dm:1"]assert _served_record(home) == ["default", "alpha"]+ # The reservation shrank with it: the next restart must not reserve a home that is gone.+ assert _reserved_names(runner) == ["alpha", "default"]+ from gateway.runtime_ownership import process_ownership+ assert not process_ownership.owns(gamma_dir)assert runner._profile_adapters["alpha"][Platform.DISCORD] is alpha_adapterassert alpha_adapter.disconnected is False@@ -157,6 +195,7 @@ async def test_hot_added_profile_cannot_double_claim_a_live_secondary_token(tmp_runner._start_one_profile_adapters = _startwith patch("hermes_cli.profiles.get_active_profile_name", return_value="default"):+ _boot(runner, home)await runner._start_secondary_profile_adapters()_mkprofile(home, "dupe", "DISCORD_BOT_TOKEN=shared\n")await runner.reconcile_served_profiles()