Skip to content

The agent that grows with you

fix(gateway): serialize the in-place multiplex switch with reconcile

Tekniumcf7087d5cdb8
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.py
index ec78d7d0ed6..9789bfc0de0 100644
--- a/gateway/run_profile_reconcile.py
+++ b/gateway/run_profile_reconcile.py
@@ -348,43 +348,50 @@ class GatewayProfileReconcileMixin:
record_multiplex_decision, recorded_standalone_reason)
from hermes_cli.profiles import profiles_to_serve
from hermes_constants import get_default_hermes_root, get_process_hermes_home
- if not self._running or getattr(self, "_draining", False):
- return False # shutdown began: never arm fail-closed secrets under drain-time work
- if recorded_standalone_reason() not in (SINGLE_PROFILE_REASON, AUTO_MIGRATION_OPTED_OUT_REASON):
- return False
- launch = get_process_hermes_home().resolve()
- if launch != get_default_hermes_root().resolve():
- return False # only the default home runs the multiplexer (``_launch_home_may_multiplex``)
- if len(profiles_to_serve(multiplex=True, include_parked=True)) < 2:
- return False
- blocker = await self._run_housekeeping_in_executor(_added_profile_blocker, launch)
- if blocker is not None:
- if blocker != self._single_profile_blocker_logged:
- logger.warning("[MULTIPLEX] A new profile exists but this gateway stays standalone: %s", blocker)
- self._single_profile_blocker_logged = blocker
- if blocker == AUTO_MIGRATION_OPTED_OUT_REASON:
- # Published so `gateway ensure` refuses the new profile naming the opt-out (Desktop shows
- # that detail) instead of "only one profile exists".
- record_multiplex_decision(MultiplexDecision(False, "guard", blocker))
- return False
- from hermes_constants import hermes_home_key
- from tools.mcp_tool_scope import rekey_unscoped_connections
- from tui_gateway.launch_profile_policy import activate_multi_profile_hosting
- activate_multi_profile_hosting()
- rekey_unscoped_connections(hermes_home_key(launch))
- self.config.multiplex_profiles = True
- self.config._runtime_profile_homes = (("default", launch),)
- registry = getattr(self, "session_authorities", None)
- if registry is not None:
- registry.multiplexed = True
- for adapter in list(self.adapters.values()):
- adapter.set_message_handler(self._primary_message_handler())
- adapter.set_busy_session_handler(self._primary_busy_session_handler())
- adapter.set_platform_event_handler(self._primary_platform_event_handler())
- self._record_served_profiles("default", [("default", launch)])
- log_multiplex_decision(MultiplexDecision(True, "default", "a second profile was created"))
- logger.info("[MULTIPLEX] A second profile exists; serving every profile from this process (no restart)")
- return True
+ # Serialized with reconcile: a second rescan (watcher + creator) resuming mid-activation
+ # reset the reservation the first one's reconcile had already grown.
+ async with self._reconcile_lock():
+ if self._multiplex_on():
+ return True # a concurrent rescan activated while this one waited
+ if not self._running or getattr(self, "_draining", False):
+ return False # shutdown began: never arm fail-closed secrets under drain-time work
+ if recorded_standalone_reason() not in (SINGLE_PROFILE_REASON, AUTO_MIGRATION_OPTED_OUT_REASON):
+ return False
+ launch = get_process_hermes_home().resolve()
+ if launch != get_default_hermes_root().resolve():
+ return False # only the default home runs the multiplexer (``_launch_home_may_multiplex``)
+ if len(profiles_to_serve(multiplex=True, include_parked=True)) < 2:
+ return False
+ blocker = await self._run_housekeeping_in_executor(_added_profile_blocker, launch)
+ if blocker is not None:
+ if blocker != self._single_profile_blocker_logged:
+ logger.warning("[MULTIPLEX] A new profile exists but this gateway stays standalone: %s", blocker)
+ self._single_profile_blocker_logged = blocker
+ if blocker == AUTO_MIGRATION_OPTED_OUT_REASON:
+ # Published so `gateway ensure` refuses the new profile naming the opt-out (Desktop shows
+ # that detail) instead of "only one profile exists".
+ record_multiplex_decision(MultiplexDecision(False, "guard", blocker))
+ return False
+ if not self._running or getattr(self, "_draining", False):
+ return False # shutdown began during the preflight await
+ from hermes_constants import hermes_home_key
+ from tools.mcp_tool_scope import rekey_unscoped_connections
+ from tui_gateway.launch_profile_policy import activate_multi_profile_hosting
+ activate_multi_profile_hosting()
+ rekey_unscoped_connections(hermes_home_key(launch))
+ self.config.multiplex_profiles = True
+ self.config._runtime_profile_homes = (("default", launch),)
+ registry = getattr(self, "session_authorities", None)
+ if registry is not None:
+ registry.multiplexed = True
+ for adapter in list(self.adapters.values()):
+ adapter.set_message_handler(self._primary_message_handler())
+ adapter.set_busy_session_handler(self._primary_busy_session_handler())
+ adapter.set_platform_event_handler(self._primary_platform_event_handler())
+ self._record_served_profiles("default", [("default", launch)])
+ log_multiplex_decision(MultiplexDecision(True, "default", "a second profile was created"))
+ logger.info("[MULTIPLEX] A second profile exists; serving every profile from this process (no restart)")
+ return True
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
diff --git a/tests/gateway/test_single_profile_flip_keeps_launch_work.py b/tests/gateway/test_single_profile_flip_keeps_launch_work.py
index c33c1850554..a14fa33dec4 100644
--- a/tests/gateway/test_single_profile_flip_keeps_launch_work.py
+++ b/tests/gateway/test_single_profile_flip_keeps_launch_work.py
@@ -140,3 +140,51 @@ async def test_activation_does_not_run_once_shutdown_began(standalone_host):
runner._running = False # stop() flips this first
await runner.reconcile_served_profiles(reason="control-socket")
assert not is_multiplex_active(), "a shutting-down gateway armed fail-closed secrets"
+
+
+async def test_concurrent_rescans_keep_the_new_profiles_reservation(standalone_host, monkeypatch):
+ """A watcher tick and a creator's rescan both start the switch. The slower preflight resuming
+ while the faster rescan is still serving the bot must not reset the reservation to just the
+ default home (routing and cron would then miss a bot whose authority is live)."""
+ from gateway import run_profile_reconcile as rpr
+ runner, home = standalone_host
+ preflights = []
+ housekeeping = runner._run_housekeeping_in_executor
+
+ async def run_housekeeping(func, *args):
+ if func is rpr._added_profile_blocker:
+ preflights.append(func)
+ if len(preflights) > 1:
+ await reserved_bot.wait() # resumes while the first rescan is mid-serve
+ return None
+ return await housekeeping(func, *args)
+
+ serve = runner._serve_profile_runtime
+ reserved_bot = asyncio.Event()
+
+ async def slow_serve(name, path):
+ reason = await serve(name, path)
+ reserved_bot.set()
+ for _ in range(20): # adapters still connecting: the other rescan gets the loop
+ await asyncio.sleep(0)
+ return reason
+
+ runner._run_housekeeping_in_executor = run_housekeeping
+ runner._serve_profile_runtime = slow_serve
+ bot = _mkprofile(home, "daily-news-bot").resolve()
+ await asyncio.gather(runner.reconcile_served_profiles(reason="control-socket"),
+ runner.reconcile_served_profiles(reason="watcher"))
+ reserved = {name: path for name, path in runner.config._runtime_profile_homes}
+ assert reserved.get("daily-news-bot") == bot, reserved
+
+
+async def test_activation_rechecks_shutdown_after_the_preflight(standalone_host, monkeypatch):
+ from agent.secret_scope import is_multiplex_active
+ from gateway import run_profile_reconcile as rpr
+ runner, home = standalone_host
+ monkeypatch.setattr(rpr, "_added_profile_blocker", lambda _launch: setattr(runner, "_running", False))
+ _mkprofile(home, "daily-news-bot")
+ await runner.reconcile_served_profiles(reason="control-socket")
+ assert not is_multiplex_active(), "stop() began during the preflight, yet fail-closed secrets were armed"