Skip to content

The agent that grows with you

refactor(gateway): fold the runner's duplicated identity stamps into one seam

teknium1a554fcbe2d5e
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 8c1ad3834fc..1c9b07afdcb 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -1348,40 +1348,49 @@ class GatewayAdapterLifecycleMixin:
"""``scope_factory(profile_home)`` or a nullcontext when the profile home is unknown."""
return scope_factory(profile_home) if profile_home is not None else contextlib.nullcontext()
- def _stamp_event_profile(self, event, profile_name: str) -> None:
- """Best-effort: pin the secondary's identity on an inbound event (stamps ``source.profile``
- when none yet). A source that cannot resolve keeps today's fallback readers."""
- source = getattr(event, "source", None)
+ def _canonicalize(self, source, *, transport_profile: Optional[str] = None,
+ primary_home: Optional[Path] = None):
+ """Runner-side identity seam: the pinned :class:`RoutingIdentity` of *source*, resolving it
+ once when absent. ``transport_profile`` names a secondary's own bot (its handlers know it by
+ construction); ``None`` = the primary/shared bot. ``None`` result = rejected route under
+ multiplexing (the caller drops; the ingress gate warns once) or a source that cannot resolve
+ (bare test rigs) — the legacy readers then stay in force."""
if source is None:
- return
- with suppress(Exception):
- from gateway.session_identity import resolve_identity
- resolve_identity(source, runner=self, transport_profile=profile_name)
- with suppress(Exception):
- if not source.profile:
- source.profile = profile_name
+ return None
+ from gateway.session_identity import canonical_identity
+ try:
+ identity = canonical_identity(
+ source, runner=self, transport_profile=transport_profile, primary_home=primary_home)
+ except Exception:
+ logger.debug("identity resolution failed; legacy readers stay in force", exc_info=True)
+ return None
+ if transport_profile and not getattr(source, "profile", None):
+ with suppress(Exception):
+ source.profile = transport_profile # a secondary's own event is at least its own
+ return identity
def _make_profile_message_handler(self, profile_name: str):
- """Message handler that stamps source.profile, then delegates under the profile scope
- (auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be visible here)."""
+ """Message handler that canonicalizes the event's identity FIRST, then delegates under the
+ profile scope (auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be
+ visible here)."""
from gateway.run import _async_profile_runtime_scope
profile_home = self._profile_home_or_none(profile_name)
async def _handler(event):
- self._stamp_event_profile(event, profile_name)
+ self._canonicalize(getattr(event, "source", None), transport_profile=profile_name)
async with self._scope_or_null(_async_profile_runtime_scope, profile_home):
return await self._handle_message(event)
return _handler
def _make_profile_busy_session_handler(self, profile_name: str):
- """Stamp an owning adapter's profile, then resolve busy policy under the profile scope
+ """Busy-path twin: canonicalize FIRST, then resolve busy policy under the profile scope
(auth runs against the profile's own allowlist, same as the cold-path message handler)."""
from gateway.run import _async_profile_runtime_scope
profile_home = self._profile_home_or_none(profile_name)
async def _handler(event, _session_key):
- self._stamp_event_profile(event, profile_name)
+ self._canonicalize(event.source, transport_profile=profile_name)
async with self._scope_or_null(_async_profile_runtime_scope, profile_home):
return await self._handle_active_session_busy_message(event, self._session_key_for_source(event.source))
@@ -1421,27 +1430,13 @@ class GatewayAdapterLifecycleMixin:
return _handler
def _admit_primary_source(self, source, default_home: Path) -> Optional[Path]:
- """Resolve the primary-adapter source's identity (transport home for authorization, routed
- profile for the runtime) and return the runtime home to scope the turn under; ``None`` when
- the route targets an unserved profile. Route ≠ admitting bot."""
- from gateway.session_identity import IdentityUnresolved, resolve_identity
- try:
- return resolve_identity(source, runner=self, primary_home=default_home).runtime_home
- except IdentityUnresolved:
- return None
-
- def _stamp_routed_profile(self, source, adapter_profile: Optional[str] = None) -> bool:
- """Stamp ``source.profile`` from ``profile_routes``; False when the route is rejected.
-
- ``adapter_profile`` owns the receiving bot: routes are scoped to it and it is the
- fallback when none matches, so re-stamping a source never crosses a bot boundary.
- """
- from gateway.profile_routing import ProfileRouteRejected
- try:
- source.profile = self._profile_name_for_source(source, adapter_profile=adapter_profile) or adapter_profile
- except ProfileRouteRejected:
- return False
- return True
+ """Canonicalize a primary-adapter source (transport home for authorization, routed profile
+ for the runtime) and return the runtime home to scope the turn under; ``None`` when the
+ route targets an unserved profile. Route ≠ admitting bot."""
+ identity = self._canonicalize(source, primary_home=default_home)
+ if identity is not None:
+ return identity.runtime_home
+ return None if getattr(source, "profile_route_rejected", False) is True else default_home
def _primary_message_handler(self):
"""Return the correctly scoped handler for a primary adapter."""
@@ -1483,8 +1478,7 @@ class GatewayAdapterLifecycleMixin:
profile_home = self._profile_home_or_none(profile_name)
async def _handler(event, source):
- if getattr(source, "profile", None) is None:
- source.profile = profile_name
+ self._canonicalize(source, transport_profile=profile_name)
with self._scope_or_null(_profile_runtime_scope, profile_home):
return await self._handle_gateway_platform_event(event, source)
@@ -1496,8 +1490,10 @@ class GatewayAdapterLifecycleMixin:
default_home = Path(get_hermes_home())
async def _handler(event, source):
- source._authorization_profile_home = default_home
- with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
+ profile_home = self._admit_primary_source(source, default_home)
+ if profile_home is None:
+ return None # rejected route: same disposition as the message ingress gate
+ with _profile_runtime_scope(profile_home):
return await self._handle_gateway_platform_event(event, source)
return _handler
@@ -1609,8 +1605,9 @@ class GatewayAdapterLifecycleMixin:
source._transport_adapter_ref = _weakref.ref(adapter)
if transport_home is None:
return self._is_user_authorized(source)
- source._authorization_profile_home = transport_home
- if not self._stamp_routed_profile(source):
+ # Canonicalize FIRST (callback sources never went through ``build_source``): the routed
+ # profile's pairing store is consulted, allowlists read under the transport home.
+ if self._canonicalize(source, primary_home=transport_home) is None:
return False # fail-closed, like the ``_handle_message`` ingress gate
return self._is_user_authorized_for_source(source)
return check
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 0cee8372988..3e03b3f3739 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -176,21 +176,12 @@ class GatewayInboundMixin:
except Exception:
logger.debug("reset_session_vars failed at handler entry", exc_info=True)
- # Most adapters resolve profile routes in build_source(); internal/voice paths construct
- # SessionSource directly, so resolve those here as the shared fail-closed ingress gate.
- # Strict boolean marker: require the literal True so duck-typed test/internal sources with
- # dynamic attributes are not mistaken for a rejection.
- if (
- getattr(_config, "multiplex_profiles", False)
- and not getattr(source, "profile", None)
- and getattr(source, "profile_route_rejected", False) is not True
- ):
- from gateway.profile_routing import ProfileRouteRejected
-
- try:
- source.profile = self._profile_name_for_source(source)
- except ProfileRouteRejected:
- source.profile_route_rejected = True
+ # Identity FIRST. Most adapters canonicalize at their own ingress; internal/voice paths
+ # construct SessionSource directly, so this is the shared fail-closed gate. Strict boolean
+ # marker: require the literal True so duck-typed test/internal sources with dynamic
+ # attributes are not mistaken for a rejection.
+ if getattr(_config, "multiplex_profiles", False):
+ self._canonicalize(source)
if getattr(source, "profile_route_rejected", False) is True:
logger.warning(
"Dropping inbound message because its explicit profile route "
diff --git a/gateway/run_voice.py b/gateway/run_voice.py
index 2e0ddcb5019..c78283fdd98 100644
--- a/gateway/run_voice.py
+++ b/gateway/run_voice.py
@@ -249,8 +249,11 @@ class GatewayVoiceMixin:
if not text_ch_id:
return
source = self._voice_input_source(adapter, guild_id, user_id, text_ch_id)
- # Cached source still carries the previous speaker's routed profile.
- if not self._stamp_routed_profile(source, getattr(adapter, "_owner_profile", None)):
+ # The cached source still carries the previous speaker's identity (per-sender routes,
+ # #106019): drop the pin so the seam re-resolves for THIS speaker.
+ from gateway.session_identity import clear_identity
+ clear_identity(source)
+ if self._canonicalize(source, transport_profile=getattr(adapter, "_owner_profile", None)) is None:
logger.warning("Dropping voice input: its profile route targets an unserved profile")
return
# Validate the session owner against the current allowlist before auto-resuming. A session created
diff --git a/gateway/session_identity.py b/gateway/session_identity.py
index 54e7f81212e..67cf389fef8 100644
--- a/gateway/session_identity.py
+++ b/gateway/session_identity.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import dataclasses
import logging
+from contextlib import suppress
import weakref
from dataclasses import dataclass, field
from pathlib import Path
@@ -85,6 +86,15 @@ def identity_of(source: Any) -> Optional[RoutingIdentity]:
return identity if isinstance(identity, RoutingIdentity) else None
+def clear_identity(source: Any) -> None:
+ """Drop the pinned identity so the next :func:`canonical_identity` re-resolves — for sources a
+ caller reuses across events whose routing may differ (a guild's cached voice source is shared by
+ every speaker, and ``profile_routes[].user_id`` routes per speaker)."""
+ for attr in (_IDENTITY_ATTR, "profile_route_rejected"):
+ with suppress(AttributeError):
+ delattr(source, attr)
+
+
def replace_source(source: "SessionSource", **changes: Any) -> "SessionSource":
""":func:`dataclasses.replace` that keeps the wire-invisible provenance (transport ref,
authorization home, identity). A plain ``replace`` silently produces a source the runner
diff --git a/tests/gateway/test_profile_resolution.py b/tests/gateway/test_profile_resolution.py
index d3dbc2031cc..8356dcd0331 100644
--- a/tests/gateway/test_profile_resolution.py
+++ b/tests/gateway/test_profile_resolution.py
@@ -24,6 +24,10 @@ def mock_runner():
runner._resolve_profile_home_for_source = GatewayRunner._resolve_profile_home_for_source.__get__(runner)
# _handle_message's ingress gates (profile route rejection) live in this helper.
runner._hm_admit_event = GatewayRunner._hm_admit_event.__get__(runner)
+ # The identity seam the gate canonicalizes through; a hand-built source has no transport owner.
+ runner._canonicalize = GatewayRunner._canonicalize.__get__(runner)
+ runner._transport_owner = lambda _source: None
+ runner._primary_profile_name = "default"
return runner