Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

perf(agent-bridge): stop the connection pool being held by work that isn't using it (#351)

Louis Amaudruz46e52a5b712b
diff --git a/core/switch_core/bridges/agent/api_key_cache.py b/core/switch_core/bridges/agent/api_key_cache.py
new file mode 100644
index 000000000..73e2d7de1
--- /dev/null
+++ b/core/switch_core/bridges/agent/api_key_cache.py
@@ -0,0 +1,86 @@
+from __future__ import annotations
+
+import time
+from collections import OrderedDict
+
+from switch_core.bridges.agent.protocol.connections import HEARTBEAT_TTL_SECONDS
+from switch_core.db.models import Agent, ApiKey
+
+
+class ApiKeyCache:
+ """A short-lived memo of resolved agent bearer tokens.
+
+ Every authenticated request resolves its token against Postgres before the
+ handler runs, and an agent connection beats every couple of seconds, so
+ that one lookup is the bulk of the traffic through the connection pool —
+ including the heartbeats whose deadline the pool is capable of missing.
+
+ What it deliberately does not do:
+
+ - **Cache a failure.** Only a token that resolved to a live agent is
+ stored, so an unknown, revoked or malformed token always reaches the
+ database and can never be answered from memory.
+ - **Hold a plaintext token.** Entries are keyed on the same SHA-256 digest
+ the database stores.
+ - **Outlive a rotation.** ``invalidate_agent`` is called when a key is
+ rotated or an agent deleted; expiry is the backstop, not the mechanism.
+
+ A ``ttl_seconds`` of 0 disables it: every read misses and nothing is ever
+ stored. The TTL bounds how long an already-issued credential survives its
+ revocation, and it is refused at or above the heartbeat TTL — past that a
+ credential could authenticate a connection the server has already given up
+ on, which is longer than any of this is worth.
+ """
+
+ def __init__(self, *, ttl_seconds: float, max_entries: int) -> None:
+ if ttl_seconds < 0:
+ raise ValueError(f"ttl_seconds must not be negative, got {ttl_seconds!r}")
+ if ttl_seconds >= HEARTBEAT_TTL_SECONDS:
+ raise ValueError(
+ f"ttl_seconds must stay below the agent heartbeat TTL of "
+ f"{HEARTBEAT_TTL_SECONDS}s, got {ttl_seconds!r}"
+ )
+ if max_entries < 1:
+ raise ValueError(f"max_entries must be at least 1, got {max_entries!r}")
+ self._ttl = ttl_seconds
+ self._max_entries = max_entries
+ self._entries: OrderedDict[str, tuple[float, ApiKey, Agent]] = OrderedDict()
+
+ @property
+ def enabled(self) -> bool:
+ return self._ttl > 0
+
+ def get(self, token_hash: str) -> tuple[ApiKey, Agent] | None:
+ entry = self._entries.get(token_hash)
+ if entry is None:
+ return None
+ expires_at, api_key, agent = entry
+ if expires_at <= time.monotonic():
+ del self._entries[token_hash]
+ return None
+ self._entries.move_to_end(token_hash)
+ return api_key, agent
+
+ def put(self, token_hash: str, api_key: ApiKey, agent: Agent) -> None:
+ if not self.enabled:
+ return
+ self._entries[token_hash] = (time.monotonic() + self._ttl, api_key, agent)
+ self._entries.move_to_end(token_hash)
+ while len(self._entries) > self._max_entries:
+ self._entries.popitem(last=False)
+
+ def invalidate(self, token_hash: str) -> None:
+ self._entries.pop(token_hash, None)
+
+ def invalidate_agent(self, agent_id: str) -> None:
+ """Drop every entry resolving to `agent_id`, whatever its token."""
+ stale = [
+ token_hash
+ for token_hash, (_, _, agent) in self._entries.items()
+ if agent.id == agent_id
+ ]
+ for token_hash in stale:
+ del self._entries[token_hash]
+
+ def clear(self) -> None:
+ self._entries.clear()
diff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.py
index a440c675b..e744bbf93 100644
--- a/core/switch_core/bridges/agent/app.py
+++ b/core/switch_core/bridges/agent/app.py
@@ -9,6 +9,7 @@ from fastapi.responses import JSONResponse
from switch_core.bridges.agent.api.handlers import router as api_router
from switch_core.bridges.agent.api.operations import router as operations_router
from switch_core.bridges.agent.api.version_routes import router as version_router
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.auth import BearerAuthMiddleware
from switch_core.bridges.agent.deeplink import router as deeplink_router
from switch_core.bridges.agent.dependencies import init_dependencies
@@ -63,6 +64,14 @@ def create_agent_bridge_app(
if connections is None:
connections = ConnectionRegistry()
+ # One cache for the whole process, for the same reason as `connections`:
+ # the HTTP door and the MCP door each carry their own auth middleware, and
+ # a rotated key must stop working on both the moment it is rotated.
+ api_key_cache = ApiKeyCache(
+ ttl_seconds=config.agent_auth_cache_ttl_seconds,
+ max_entries=config.agent_auth_cache_max_entries,
+ )
+
init_dependencies(
agent_store=agent_store,
agent_session_store=agent_session_store,
@@ -77,6 +86,7 @@ def create_agent_bridge_app(
resource_request_tracker=resource_request_tracker,
resource_service=resource_service,
api_key_store=api_key_store,
+ api_key_cache=api_key_cache,
external_user_store=external_user_store,
bridge_store=bridge_store,
session_factory=session_factory,
@@ -97,6 +107,7 @@ def create_agent_bridge_app(
resource_request_tracker=resource_request_tracker,
resource_service=resource_service,
api_key_store=api_key_store,
+ api_key_cache=api_key_cache,
external_user_store=external_user_store,
bridge_store=bridge_store,
session_factory=session_factory, # type: ignore[arg-type]
@@ -153,6 +164,7 @@ def create_agent_bridge_app(
BearerAuthMiddleware,
agent_store=agent_store,
api_key_store=api_key_store,
+ api_key_cache=api_key_cache,
session_factory=session_factory, # type: ignore[arg-type]
)
diff --git a/core/switch_core/bridges/agent/auth.py b/core/switch_core/bridges/agent/auth.py
index 6368ce4e8..712ef320b 100644
--- a/core/switch_core/bridges/agent/auth.py
+++ b/core/switch_core/bridges/agent/auth.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import hashlib
import logging
-from typing import Any
import jwt
from fastapi import HTTPException, Request
@@ -11,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from starlette.responses import Response
from starlette.types import ASGIApp, Receive, Scope, Send
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.db.models import Agent, ApiKey
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.api_key_store import ApiKeyStore
@@ -87,12 +87,14 @@ class BearerAuthMiddleware:
*,
agent_store: AgentStore,
api_key_store: ApiKeyStore,
+ api_key_cache: ApiKeyCache,
session_factory: async_sessionmaker[AsyncSession],
oidc_validator: OIDCTokenValidator | None = None,
) -> None:
self.app = app
self._agent_store = agent_store
self._api_key_store = api_key_store
+ self._api_key_cache = api_key_cache
self._session_factory = session_factory
self._oidc_validator = oidc_validator
@@ -145,25 +147,40 @@ class BearerAuthMiddleware:
response = Response("Invalid credentials", status_code=401)
await response(scope, receive, send)
- async def _resolve_api_key(self, token: str) -> tuple[ApiKey | None, Any | None]:
+ async def _resolve_api_key(self, token: str) -> tuple[ApiKey | None, Agent | None]:
"""Look up the token in api_keys once; return (api_key_row, agent_or_None).
``agent`` is populated only when the row is an ``agent``-type key that
resolves to an Agent. For registration tokens (or any key with no
backing Agent), ``agent`` is ``None`` but ``api_key`` carries the row
so the caller can decide what to do with it.
+
+ A resolved agent is memoised for a few seconds (see
+ :class:`ApiKeyCache`); everything else — an unknown token, a
+ registration token, an agent key with no agent — always reads the
+ database.
"""
token_hash = hashlib.sha256(token.encode()).hexdigest()
+ cached = self._api_key_cache.get(token_hash)
+ if cached is not None:
+ return cached
+
async with self._session_factory() as session:
- api_key = await self._api_key_store.get_by_hash(session, token_hash)
- if api_key is None:
+ found = await self._api_key_store.get_with_agent_by_hash(
+ session, token_hash
+ )
+ if found is None:
return None, None
- if api_key.type == "agent":
- agent = await self._agent_store.get_by_api_key_id(session, api_key.id)
- return api_key, agent
- return api_key, None
+ api_key, agent = found
+ if api_key.type != "agent":
+ agent = None
+ session.expunge_all()
+
+ if agent is not None:
+ self._api_key_cache.put(token_hash, api_key, agent)
+ return api_key, agent
- async def _try_oidc(self, token: str) -> Any | None:
+ async def _try_oidc(self, token: str) -> Agent | None:
assert self._oidc_validator is not None
try:
claims = self._oidc_validator.validate(token)
diff --git a/core/switch_core/bridges/agent/dependencies.py b/core/switch_core/bridges/agent/dependencies.py
index 217a12473..1c5aedc0a 100644
--- a/core/switch_core/bridges/agent/dependencies.py
+++ b/core/switch_core/bridges/agent/dependencies.py
@@ -5,6 +5,7 @@ from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
from switch_core.bridges.agent.protocol.event_buffer import EventBuffer
from switch_core.bridges.agent.protocol.service import ProtocolService
@@ -43,6 +44,7 @@ def init_dependencies(
resource_request_tracker: ResourceRequestTracker,
resource_service: ResourceService,
api_key_store: ApiKeyStore,
+ api_key_cache: ApiKeyCache,
external_user_store: ExternalUserStore,
bridge_store: CollaborationBridgeStore,
session_factory: Any,
@@ -61,6 +63,7 @@ def init_dependencies(
_state["resource_request_tracker"] = resource_request_tracker
_state["resource_service"] = resource_service
_state["api_key_store"] = api_key_store
+ _state["api_key_cache"] = api_key_cache
_state["external_user_store"] = external_user_store
_state["bridge_store"] = bridge_store
_state["session_factory"] = session_factory
@@ -80,6 +83,7 @@ def init_dependencies(
resource_request_tracker=resource_request_tracker,
resource_service=resource_service,
api_key_store=api_key_store,
+ api_key_cache=api_key_cache,
external_user_store=external_user_store,
bridge_store=bridge_store,
session_factory=session_factory,
@@ -136,6 +140,10 @@ def get_api_key_store() -> ApiKeyStore:
return _state["api_key_store"] # type: ignore[no-any-return]
+def get_api_key_cache() -> ApiKeyCache:
+ return _state["api_key_cache"] # type: ignore[no-any-return]
+
+
def get_config() -> SwitchConfig:
return _state["config"] # type: ignore[no-any-return]
diff --git a/core/switch_core/bridges/agent/mcp/server.py b/core/switch_core/bridges/agent/mcp/server.py
index 2b2ef6db6..8bd62fbfc 100644
--- a/core/switch_core/bridges/agent/mcp/server.py
+++ b/core/switch_core/bridges/agent/mcp/server.py
@@ -115,6 +115,7 @@ def create_mcp_app(
starlette_app,
agent_store=agent_store,
api_key_store=api_key_store,
+ api_key_cache=protocol.api_key_cache,
session_factory=protocol.session_factory,
oidc_validator=oidc_validator,
)
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.py
index 3ef00b2cd..8673462ca 100644
--- a/core/switch_core/bridges/agent/protocol/service.py
+++ b/core/switch_core/bridges/agent/protocol/service.py
@@ -30,6 +30,7 @@ from switch_core.agent_display_name import normalise_display_name
from switch_core.agent_icon import normalise_icon_url, validate_icon_url
from switch_core.aliases import check_alias_collisions, validate_alias_format
from switch_core.authz import Action, Principal, require, require_manage
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.protocol.agent_detail import (
apply_agent_options,
assemble_agent_detail,
@@ -136,6 +137,17 @@ class AgentExistsError(Exception):
caller did not opt into re-registration via ``overwrite=True``."""
+def _describe_room(room: Room) -> RoomDescriptor:
+ return RoomDescriptor(
+ id=room.id,
+ name=room.name,
+ description=room.description,
+ matrix_room_id=room.matrix_room_id,
+ archived=room.archived_at is not None,
+ bridge_id=room.bridge_id,
+ )
+
+
class ProtocolService:
def __init__(
self,
@@ -153,6 +165,7 @@ class ProtocolService:
resource_request_tracker: ResourceRequestTracker,
resource_service: ResourceService,
api_key_store: ApiKeyStore,
+ api_key_cache: ApiKeyCache,
external_user_store: ExternalUserStore,
bridge_store: CollaborationBridgeStore,
session_factory: async_sessionmaker[AsyncSession],
@@ -179,6 +192,10 @@ class ProtocolService:
self.resource_request_tracker = resource_request_tracker
self.resource_service = resource_service
self.api_key_store = api_key_store
+ # Shared with the bearer-auth middleware for the same reason as
+ # `connections`: a key this service rotates must stop authenticating
+ # requests on every door at once.
+ self.api_key_cache = api_key_cache
self.external_user_store = external_user_store
self.bridge_store = bridge_store
self.session_factory = session_factory
@@ -532,6 +549,7 @@ class ProtocolService:
)
await session.commit()
+ self.api_key_cache.invalidate_agent(existing.id)
return existing.id
async def _create_bridge_identities(
@@ -686,6 +704,7 @@ class ProtocolService:
async with self.session_factory() as session:
await self.agent_store.delete(session, resolved_id)
await session.commit()
+ self.api_key_cache.invalidate_agent(resolved_id)
await self.client_lifecycle.remove(client_id)
@@ -697,21 +716,20 @@ class ProtocolService:
room = await self.room_store.get(session, room_id)
if room is None:
raise ValueError(f"Room not found: {room_id}")
- return RoomDescriptor(
- id=room.id,
- name=room.name,
- description=room.description,
- matrix_room_id=room.matrix_room_id,
- )
+ return _describe_room(room)
async def require_room_member(self, agent_id: str, room_id: str) -> RoomDescriptor:
"""Get room and verify agent is a member. Raises PermissionError if not."""
- room = await self.get_room(room_id)
async with self.session_factory() as session:
- agent_ids = await self.room_store.get_agent_ids(session, room_id)
- if agent_id not in agent_ids:
+ found = await self.room_store.get_with_membership(
+ session, room_id, agent_id
+ )
+ if found is None:
+ raise ValueError(f"Room not found: {room_id}")
+ room, is_member = found
+ if not is_member:
raise PermissionError("Agent is not a member of this room")
- return room
+ return _describe_room(room)
async def list_rooms(
self, agent_id: str, *, include_archived: bool = False
@@ -724,16 +742,7 @@ class ProtocolService:
rooms = await self.room_store.get_rooms_for_agent(
session, agent_id, include_archived=include_archived
)
- return [
- RoomDescriptor(
- id=r.id,
- name=r.name,
- description=r.description,
- matrix_room_id=r.matrix_room_id,
- archived=r.archived_at is not None,
- )
- for r in rooms
- ]
+ return [_describe_room(r) for r in rooms]
async def list_participants(self, room_id: str) -> list[ParticipantDescriptor]:
"""List all agents and users in a room."""
@@ -820,9 +829,27 @@ class ProtocolService:
if not agent_ids:
return {}
async with self.session_factory() as session:
- result = await session.execute(select(Agent).where(Agent.id.in_(agent_ids)))
- agents = list(result.scalars().all())
- return await self._compute_statuses(session, agents, room_id)
+ return await self.get_agent_statuses_by_ids_in_session(
+ session, room_id, agent_ids
+ )
+
+ async def get_agent_statuses_by_ids_in_session(
+ self,
+ session: AsyncSession,
+ room_id: str,
+ agent_ids: list[str],
+ ) -> dict[str, AgentStatus]:
+ """`get_agent_statuses_by_ids` for a caller that already holds a session.
+
+ A request handler with its own open transaction must use this: taking a
+ second checkout while holding the first makes the request queue against
+ the pool for a slot it is itself occupying.
+ """
+ if not agent_ids:
+ return {}
+ result = await session.execute(select(Agent).where(Agent.id.in_(agent_ids)))
+ agents = list(result.scalars().all())
+ return await self._compute_statuses(session, agents, room_id)
async def get_agent_status(self, agent_id: str, room_id: str) -> AgentStatus:
async with self.session_factory() as session:
@@ -923,7 +950,7 @@ class ProtocolService:
# inbound message arrived. The message itself is already delivered, so a
# failure here is degraded-but-functional, not a reason to fail the send.
try:
- await self.set_typing(agent_id, room_id, False)
+ await self._set_typing(agent_id, room, False)
except Exception:
logger.warning(
"Failed to clear typing indicator for room %s", room_id, exc_info=True
@@ -1005,7 +1032,7 @@ class ProtocolService:
raise ValueError(f"Failed to send media message for '{filename}'")
posted.append({"event_id": event_id, "mxc": mxc, "filename": filename})
try:
- await self.set_typing(agent_id, room_id, False)
+ await self._set_typing(agent_id, room, False)
except Exception:
logger.warning(
"Failed to clear typing indicator for room %s", room_id, exc_info=True
@@ -1018,6 +1045,7 @@ class ProtocolService:
async def _require_can_address(
self,
+ session: AsyncSession,
target: Agent,
*,
room_id: str,
@@ -1031,6 +1059,7 @@ class ProtocolService:
:meth:`_can_address` and reported instead.
"""
if await self._can_address(
+ session,
target,
room_id=room_id,
group_id=group_id,
@@ -1044,6 +1073,7 @@ class ProtocolService:
async def _can_address(
self,
+ session: AsyncSession,
target: Agent,
*,
room_id: str,
@@ -1057,12 +1087,15 @@ class ProtocolService:
the `agents` dimension, or through an `owner_agents` rule when both are
owned by the same person. The sender is looked up only once the target
is actually restricted, so the open case stays a single read.
+
+ Reads through the caller's `session`: every caller already holds one,
+ and taking a second while the first is open queues a request behind
+ the pool for its own slot.
"""
policy = parse_policy(target.addressing_policy)
if policy.is_open():
return True
- async with self.session_factory() as session:
- sender = await self.agent_store.get(session, sender_agent_id)
+ sender = await self.agent_store.get(session, sender_agent_id)
return can_address(
policy,
room_id=room_id,
@@ -1175,6 +1208,7 @@ class ProtocolService:
if target_agent is None:
continue
if not await self._can_address(
+ session,
target_agent,
room_id=room_id,
group_id=group_id,
@@ -1224,29 +1258,35 @@ class ProtocolService:
bridge) are a no-op — there is no external channel to surface the
indicator to.
"""
- await self.require_room_member(agent_id, room_id)
- async with self.session_factory() as session:
- agent = await self.agent_store.get(session, agent_id)
- room = await self.room_store.get(session, room_id)
- if agent is None:
- raise ValueError(f"Agent not found: {agent_id}")
- if room is None:
- raise ValueError(f"Room not found: {room_id}")
+ room = await self.require_room_member(agent_id, room_id)
+ await self._set_typing(agent_id, room, is_typing)
+
+ async def _set_typing(
+ self, agent_id: str, room: RoomDescriptor, is_typing: bool
+ ) -> None:
+ """Surface a typing indicator for a room the caller already resolved.
+ Membership is the caller's to establish; an internal-only room costs
+ no query at all, since the bridge is already known to be absent.
+ """
if room.bridge_id is None:
logger.debug(
"Room %s has no collaboration bridge; skipping typing indicator",
- room_id,
+ room.id,
)
return
bridge_core = self.collab_lifecycle.get(room.bridge_id)
if bridge_core is None:
raise ValueError(
- f"Collaboration bridge {room.bridge_id} for room {room_id} "
+ f"Collaboration bridge {room.bridge_id} for room {room.id} "
"is not running"
)
- await bridge_core.handle_outbound_typing(room_id, agent.name, is_typing)
+ async with self.session_factory() as session:
+ agent = await self.agent_store.get(session, agent_id)
+ if agent is None:
+ raise ValueError(f"Agent not found: {agent_id}")
+ await bridge_core.handle_outbound_typing(room.id, agent.name, is_typing)
async def update_status(self, agent_id: str, room_id: str, detail: str) -> None:
"""Send a status message to a room."""
@@ -1930,12 +1970,14 @@ class ProtocolService:
# so it is subject to the same allow-list as a message. Unlike the
# message path (which demotes to unaddressed) a task is explicit, so a
# denied delegation fails loud rather than silently vanishing.
- await self._require_can_address(
- performer,
- room_id=room.id,
- group_id=room_row.group_id if room_row is not None else None,
- sender_agent_id=requester_id,
- )
+ async with self.session_factory() as session:
+ await self._require_can_address(
+ session,
+ performer,
+ room_id=room.id,
+ group_id=room_row.group_id if room_row is not None else None,
+ sender_agent_id=requester_id,
+ )
async with self.session_factory() as session:
task = Task(
diff --git a/core/switch_core/bridges/agent/protocol/types.py b/core/switch_core/bridges/agent/protocol/types.py
index f861f1031..6dcc89e98 100644
--- a/core/switch_core/bridges/agent/protocol/types.py
+++ b/core/switch_core/bridges/agent/protocol/types.py
@@ -94,6 +94,10 @@ class RoomDescriptor(BaseModel):
description: str
matrix_room_id: str
archived: bool = False
+ # The room's collaboration bridge, or None for an internal-only room.
+ # Carried so a caller that already resolved the room does not have to read
+ # it again to decide whether an outbound signal has anywhere to go.
+ bridge_id: str | None = None
class AgentStatus(StrEnum):
diff --git a/core/switch_core/config.py b/core/switch_core/config.py
index 7f8f100b6..1709ffe53 100644
--- a/core/switch_core/config.py
+++ b/core/switch_core/config.py
@@ -1,8 +1,12 @@
+import re
from urllib.parse import urlsplit
from pydantic import model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
+# A Postgres time value: a bare count of milliseconds, or a count with a unit.
+_PG_INTERVAL_RE = re.compile(r"^\d+\s*(us|ms|s|min|h|d)?$")
+
class SwitchConfig(BaseSettings):
model_config = SettingsConfigDict(env_prefix="")
@@ -86,6 +90,33 @@ class SwitchConfig(BaseSettings):
# unexplained latency rather than an error. Fail fast and loudly instead.
db_pool_timeout: float = 5.0
+ # Resolving a bearer token to its agent is the highest-frequency query in
+ # the system — it runs before every authenticated request, and a fleet of
+ # agents beats continuously — so a successful resolution is memoised in
+ # process for this long. Only successes are cached; an unknown or revoked
+ # token always reaches Postgres, and a rotation or an agent deletion drops
+ # the entry immediately rather than waiting for it to expire. This is the
+ # window in which an already-issued credential outlives its revocation, so
+ # it is deliberately shorter than the agent heartbeat TTL. Set to 0 to
+ # disable the cache and read the database on every request.
+ agent_auth_cache_ttl_seconds: float = 5.0
+ # Bound on the memo. One entry per distinct live token; the oldest is
+ # evicted past this, so a flood of tokens cannot grow the process.
+ agent_auth_cache_max_entries: int = 4096
+
+ # Postgres terminates a connection that sits inside an open transaction
+ # without executing anything for longer than this (a Postgres interval such
+ # as "15s"), turning a slot that never comes back into a loud, attributable
+ # error. Disabled by default, and it must stay that way until Matrix I/O
+ # moves out of the RoomService transactions: `add_agents_to_room`,
+ # `remove_agents_from_room` and `delete_room` currently hold a transaction
+ # across invite/kick round trips, so enabling this today would trade a
+ # latency problem for a consistency one — Matrix membership changed, the
+ # rows that record it rolled back. Applies to the application engine only;
+ # Alembic builds its own engine from `db_connect_args`, so a migration is
+ # never killed mid-transaction.
+ db_idle_in_transaction_session_timeout: str | None = None
+
# libpq-style TLS mode for the Postgres connection, forwarded to asyncpg.
# "disable" (the default) keeps in-cluster / local-dev connections plain,
# matching current behaviour. Managed Postgres (RDS / Cloud SQL / Azure)
@@ -93,6 +124,31 @@ class SwitchConfig(BaseSettings):
# certificate, or "verify-ca" / "verify-full" to also validate it.
db_ssl_mode: str = "disable"
+ @model_validator(mode="after")
+ def _validate_agent_auth_cache(self) -> "SwitchConfig":
+ if self.agent_auth_cache_ttl_seconds < 0:
+ raise ValueError(
+ "AGENT_AUTH_CACHE_TTL_SECONDS must not be negative (0 disables "
+ f"the cache), got {self.agent_auth_cache_ttl_seconds!r}."
+ )
+ if self.agent_auth_cache_max_entries < 1:
+ raise ValueError(
+ "AGENT_AUTH_CACHE_MAX_ENTRIES must be at least 1, got "
+ f"{self.agent_auth_cache_max_entries!r}."
+ )
+ return self
+
+ @model_validator(mode="after")
+ def _validate_idle_in_transaction_session_timeout(self) -> "SwitchConfig":
+ value = self.db_idle_in_transaction_session_timeout
+ if value is not None and not _PG_INTERVAL_RE.match(value):
+ raise ValueError(
+ "DB_IDLE_IN_TRANSACTION_SESSION_TIMEOUT must be a Postgres "
+ "interval such as '15s', '500ms' or a bare count of "
+ f"milliseconds, got {value!r}."
+ )
+ return self
+
@model_validator(mode="after")
def _validate_db_ssl_mode(self) -> "SwitchConfig":
allowed = {
diff --git a/core/switch_core/db/engine.py b/core/switch_core/db/engine.py
index b8bc989ed..aeb425a9a 100644
--- a/core/switch_core/db/engine.py
+++ b/core/switch_core/db/engine.py
@@ -8,10 +8,29 @@ from sqlalchemy.ext.asyncio import (
from switch_core.config import SwitchConfig
+def app_connect_args(config: SwitchConfig) -> dict[str, object]:
+ """asyncpg connect args for the application engine.
+
+ A superset of `config.db_connect_args`, which is also what Alembic builds
+ its engine from (`migrations/env.py`). Anything added here therefore
+ governs the running server and never a migration — which is the point for
+ `idle_in_transaction_session_timeout`, since a migration can legitimately
+ sit between two statements and being killed there is far worse than a
+ request that hangs.
+ """
+ connect_args = dict(config.db_connect_args)
+ timeout = config.db_idle_in_transaction_session_timeout
+ if timeout is not None:
+ connect_args["server_settings"] = {
+ "idle_in_transaction_session_timeout": timeout
+ }
+ return connect_args
+
+
def create_engine_from_config(
config: SwitchConfig, **engine_kwargs: object
) -> AsyncEngine:
- connect_args = dict(config.db_connect_args)
+ connect_args = app_connect_args(config)
override_connect_args = engine_kwargs.pop("connect_args", {})
if isinstance(override_connect_args, dict):
connect_args.update(override_connect_args)
diff --git a/core/switch_core/db/stores/api_key_store.py b/core/switch_core/db/stores/api_key_store.py
index 28f46c761..c24357bac 100644
--- a/core/switch_core/db/stores/api_key_store.py
+++ b/core/switch_core/db/stores/api_key_store.py
@@ -1,7 +1,7 @@
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from switch_core.db.models import ApiKey
+from switch_core.db.models import Agent, ApiKey
class ApiKeyStore:
@@ -18,6 +18,26 @@ class ApiKeyStore:
)
return result.scalar_one_or_none()
+ async def get_with_agent_by_hash(
+ self, session: AsyncSession, key_hash: str
+ ) -> tuple[ApiKey, Agent | None] | None:
+ """The key and the agent it belongs to, in one round trip.
+
+ `None` when no key matches. The agent is `None` for a key nothing
+ claims — a registration token, or an agent key whose agent is gone.
+ This pair answers every authenticated request, so it is the one query
+ worth not splitting in two.
+ """
+ result = await session.execute(
+ select(ApiKey, Agent)
+ .outerjoin(Agent, Agent.api_key_id == ApiKey.id)
+ .where(ApiKey.key_hash == key_hash)
+ )
+ row = result.one_or_none()
+ if row is None:
+ return None
+ return row[0], row[1]
+
async def get_by_user(self, session: AsyncSession, user_id: str) -> list[ApiKey]:
result = await session.execute(select(ApiKey).where(ApiKey.user_id == user_id))
return list(result.scalars().all())
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index fb38aa274..789d84253 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -16,6 +16,30 @@ class RoomStore:
async def get(self, session: AsyncSession, room_id: str) -> Room | None:
return await session.get(Room, room_id)
+ async def get_with_membership(
+ self, session: AsyncSession, room_id: str, agent_id: str
+ ) -> tuple[Room, bool] | None:
+ """The room plus whether `agent_id` is one of its members.
+
+ `None` when no such room exists, which the caller must distinguish
+ from a room the agent simply cannot see. Outer-joined so both answers
+ come back in one statement — the pair is the single most frequent
+ authorization question in the bridge.
+ """
+ result = await session.execute(
+ select(Room, room_agents.c.agent_id)
+ .outerjoin(
+ room_agents,
+ (Room.id == room_agents.c.room_id)
+ & (room_agents.c.agent_id == agent_id),
+ )
+ .where(Room.id == room_id)
+ )
+ row = result.one_or_none()
+ if row is None:
+ return None
+ return row[0], row[1] is not None
+
async def get_by_matrix_room_id(
self, session: AsyncSession, matrix_room_id: str
) -> Room | None:
diff --git a/core/switch_core/gateway/api_keys.py b/core/switch_core/gateway/api_keys.py
index 677dc3531..abddc989e 100644
--- a/core/switch_core/gateway/api_keys.py
+++ b/core/switch_core/gateway/api_keys.py
@@ -16,6 +16,7 @@ from switch_core.gateway.auth import get_current_user
from switch_core.gateway.dependencies import (
get_api_key_store,
get_config,
+ get_protocol,
get_session,
)
from switch_core.gateway.schemas import (
@@ -109,8 +110,10 @@ async def delete_api_key(
raise HTTPException(status_code=404, detail="API key not found")
if key.user_id != user.id:
raise HTTPException(status_code=403, detail="Not authorized to delete this key")
+ key_hash = key.key_hash
await api_key_store.delete(session, key_id)
await session.commit()
+ get_protocol().api_key_cache.invalidate(key_hash)
logger.info("Deleted API key '%s' for user %s", key.label, user.email)
return {"ok": True}
diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.py
index 9b59c1d93..bfadde2ef 100644
--- a/core/switch_core/gateway/rooms.py
+++ b/core/switch_core/gateway/rooms.py
@@ -105,7 +105,9 @@ async def _build_room_detail(
) -> RoomDetail:
agent_ids = await room_store.get_agent_ids(session, room.id)
client_ids = await room_store.get_client_ids(session, room.id)
- statuses = await protocol.get_agent_statuses_by_ids(room.id, agent_ids)
+ statuses = await protocol.get_agent_statuses_by_ids_in_session(
+ session, room.id, agent_ids
+ )
bridge_display_name: str | None = None
bridge_type: str | None = None
diff --git a/core/switch_core/migrations/versions/c81f4a06d2b7_merge_index_and_display_name_heads.py b/core/switch_core/migrations/versions/c81f4a06d2b7_merge_index_and_display_name_heads.py
new file mode 100644
index 000000000..64694ff69
--- /dev/null
+++ b/core/switch_core/migrations/versions/c81f4a06d2b7_merge_index_and_display_name_heads.py
@@ -0,0 +1,27 @@
+"""merge the api_key_id index and display_name heads
+
+Two migrations were merged in parallel off the same parent, leaving the chain
+with two heads and `alembic upgrade head` ambiguous. Neither carries schema of
+its own; this only rejoins them.
+
+Revision ID: c81f4a06d2b7
+Revises: f3b81c47d9a2, d3f7b1c95e42
+Create Date: 2026-09-02
+
+"""
+
+from collections.abc import Sequence
+
+# revision identifiers, used by Alembic.
+revision: str = "c81f4a06d2b7"
+down_revision: str | Sequence[str] | None = ("f3b81c47d9a2", "d3f7b1c95e42")
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ pass
+
+
+def downgrade() -> None:
+ pass
diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.py
index 61e6b1c1e..cc0be4289 100644
--- a/core/tests/integration/conftest.py
+++ b/core/tests/integration/conftest.py
@@ -40,6 +40,7 @@ from testcontainers.postgres import PostgresContainer
# Importing models registers every table on Base.metadata for create_all.
import switch_core.db.models # noqa: F401
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
from switch_core.bridges.agent.protocol.event_buffer import EventBuffer
from switch_core.bridges.agent.protocol.service import ProtocolService
@@ -506,6 +507,10 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:
resource_request_tracker=resource_request_tracker,
resource_service=resource_service,
api_key_store=session_env.api_key_store,
+ api_key_cache=ApiKeyCache(
+ ttl_seconds=config.agent_auth_cache_ttl_seconds,
+ max_entries=config.agent_auth_cache_max_entries,
+ ),
external_user_store=session_env.external_user_store,
bridge_store=session_env.bridge_store,
session_factory=session_factory,
diff --git a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
index a9494e6f8..1d1c69bf7 100644
--- a/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
+++ b/core/tests/switch_core/bridges/agent/protocol/registration_harness.py
@@ -11,6 +11,7 @@ from types import SimpleNamespace
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.protocol.service import ProtocolService
from switch_core.bridges.agent.protocol.types import (
IntegrationProfile,
@@ -69,6 +70,7 @@ def make_service(
svc.session_factory = session_factory # type: ignore[attr-defined]
svc.agent_store = AgentStore() # type: ignore[attr-defined]
svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
+ svc.api_key_cache = ApiKeyCache(ttl_seconds=5.0, max_entries=8) # type: ignore[attr-defined]
svc.client_lifecycle = FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
svc.collab_lifecycle = NoBridges() # type: ignore[attr-defined]
svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py
new file mode 100644
index 000000000..9a9342413
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py
@@ -0,0 +1,362 @@
+"""How many pool checkouts the hot paths cost.
+
+These are performance assertions, and they are here because the failure they
+guard against is not a slow page — it is fleet-wide agent loss. A request that
+takes two slots where one would do halves the pool; a request that takes a
+second slot *while holding the first* can wait the full pool timeout for it,
+and every heartbeat queued behind that misses its TTL and reaps a live
+connection. The numbers below are therefore contracts, not observations.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.protocol.connections import ConnectionRegistry
+from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.bridges.agent.protocol.types import RoomDescriptor
+from switch_core.db.models import Agent, ApiKey, Client, Room, User
+from switch_core.db.stores.agent_session_store import AgentSessionStore
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.room_store import RoomStore
+
+
+class _CountingSessionFactory:
+ """The real factory, counting the sessions opened through it.
+
+ One session is one pool checkout, which is the quantity this whole change
+ is about.
+ """
+
+ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:
+ self._inner = inner
+ self.opened = 0
+
+ def __call__(self) -> Any:
+ self.opened += 1
+ return self._inner()
+
+
+class _NoBridges:
+ def get(self, _bridge_id: str) -> None:
+ return None
+
+
+class _OneBridge:
+ def __init__(self) -> None:
+ self.typing: list[tuple[str, str, bool]] = []
+
+ def get(self, _bridge_id: str) -> Any:
+ return SimpleNamespace(handle_outbound_typing=self._record)
+
+ async def _record(self, room_id: str, agent_name: str, is_typing: bool) -> None:
+ self.typing.append((room_id, agent_name, is_typing))
+
+
+def _service(counting: _CountingSessionFactory) -> ProtocolService:
+ svc = object.__new__(ProtocolService)
+ svc.session_factory = counting # type: ignore[attr-defined]
+ svc.agent_store = AgentStore() # type: ignore[attr-defined]
+ svc.room_store = RoomStore() # type: ignore[attr-defined]
+ svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
+ svc.connections = ConnectionRegistry()
+ return svc
+
+
+async def _seed(
+ session_factory: async_sessionmaker[AsyncSession],
+ *,
+ policy: dict[str, Any] | None = None,
+) -> tuple[str, str, str]:
+ """One room with one member and one outsider. Returns (room, member, other).
+
+ `policy` is applied to the member, which is the agent the addressing tests
+ treat as the target.
+ """
+ async with session_factory() as session:
+ user = User(name="o", email="o@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ ids = []
+ for name in ("member", "outsider"):
+ key = ApiKey(
+ user_id=user.id,
+ key_hash=f"hash-{name}",
+ encrypted_key="enc",
+ label=name,
+ type="agent",
+ )
+ client = Client(
+ matrix_user_id=f"@{name}:test",
+ display_name=name,
+ type="agent",
+ password="x",
+ )
+ session.add_all([key, client])
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description="d",
+ agent_type="session_addressable",
+ connector_type="claude_code",
+ integration_profile={},
+ client_id=client.id,
+ api_key_id=key.id,
+ owner_id=user.id,
+ addressing_policy=policy if name == "member" else None,
+ )
+ session.add(agent)
+ await session.flush()
+ ids.append(agent.id)
+ room = Room(matrix_room_id="!r:test", name="room", description="d")
+ session.add(room)
+ await session.flush()
+ await RoomStore().add_agents(session, room.id, [ids[0]])
+ await session.commit()
+ return room.id, ids[0], ids[1]
+
+
+class TestRequireRoomMember:
+ async def test_membership_costs_one_checkout(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ room_id, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+
+ room = await svc.require_room_member(member_id, room_id)
+
+ assert room.id == room_id
+ assert counting.opened == 1, "one question, one slot"
+
+ async def test_a_non_member_is_still_one_checkout(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ room_id, _, outsider_id = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+
+ with pytest.raises(PermissionError):
+ await svc.require_room_member(outsider_id, room_id)
+
+ assert counting.opened == 1
+
+ async def test_a_missing_room_still_raises_value_error(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # "No such room" and "not your room" must stay distinguishable now that
+ # the two reads have been folded into one statement.
+ _, member_id, _ = await _seed(session_factory)
+ svc = _service(_CountingSessionFactory(session_factory))
+
+ with pytest.raises(ValueError, match="Room not found"):
+ await svc.require_room_member(member_id, "no-such-room")
+
+ async def test_the_resolved_room_carries_its_bridge(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ room_id, member_id, _ = await _seed(session_factory)
+ svc = _service(_CountingSessionFactory(session_factory))
+
+ room = await svc.require_room_member(member_id, room_id)
+
+ assert room.bridge_id is None
+
+
+class TestCanAddress:
+ async def test_a_restricted_target_reads_through_the_callers_session(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The nesting this replaces held one slot while blocking on a second,
+ # which is how pool pressure turned into a pool timeout.
+ _, member_id, outsider_id = await _seed(session_factory)
+ async with session_factory() as session:
+ await AgentStore().update(
+ session,
+ member_id,
+ addressing_policy={"rules": [{"agents": [outsider_id], "users": []}]},
+ )
+ await session.commit()
+
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ async with session_factory() as session:
+ target = await svc.agent_store.get(session, member_id)
+ assert target is not None
+ counting.opened = 0
+
+ allowed = await svc._can_address(
+ session,
+ target,
+ room_id="room",
+ group_id=None,
+ sender_agent_id=outsider_id,
+ )
+
+ assert allowed is True
+ assert counting.opened == 0, "_can_address must not open a session of its own"
+
+ async def test_a_denied_sender_is_also_answered_in_the_callers_session(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ _, member_id, outsider_id = await _seed(session_factory)
+ async with session_factory() as session:
+ await AgentStore().update(
+ session,
+ member_id,
+ addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},
+ )
+ await session.commit()
+
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ async with session_factory() as session:
+ target = await svc.agent_store.get(session, member_id)
+ assert target is not None
+ counting.opened = 0
+
+ allowed = await svc._can_address(
+ session,
+ target,
+ room_id="room",
+ group_id=None,
+ sender_agent_id=outsider_id,
+ )
+
+ assert allowed is False
+ assert counting.opened == 0
+
+ async def test_an_open_policy_reads_nothing_at_all(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ _, member_id, outsider_id = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+
+ async with session_factory() as session:
+ target = await svc.agent_store.get(session, member_id)
+ assert target is not None
+ counting.opened = 0
+
+ allowed = await svc._can_address(
+ session,
+ target,
+ room_id="room",
+ group_id=None,
+ sender_agent_id=outsider_id,
+ )
+
+ assert allowed is True
+ assert counting.opened == 0
+
+
+class TestTyping:
+ async def test_an_internal_room_costs_nothing_beyond_membership(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Was three checkouts: membership took two of its own, then a third
+ # re-read the agent and the room the caller had already resolved.
+ room_id, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+
+ await svc.set_typing(member_id, room_id, True)
+
+ assert counting.opened == 1
+
+ async def test_a_bridged_room_costs_one_read_for_the_agent_name(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ _, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ bridge = _OneBridge()
+ svc.collab_lifecycle = bridge # type: ignore[assignment]
+ room = RoomDescriptor(
+ id="room-1",
+ name="room",
+ description="d",
+ matrix_room_id="!r:test",
+ bridge_id="bridge-1",
+ )
+
+ await svc._set_typing(member_id, room, True)
+
+ assert bridge.typing == [("room-1", "member", True)]
+ assert counting.opened == 1
+
+
+class TestSendMessage:
+ async def test_posting_to_an_internal_room_costs_one_checkout(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # One to authorize. A bridged room adds exactly one more, to name the
+ # agent for the typing indicator — and no more than that, because the
+ # room the caller already resolved is passed along instead of re-read.
+ room_id, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ sent: list[tuple[str, str]] = []
+
+ class _Client:
+ async def send_message(
+ self, matrix_room_id: str, content: str, **_kwargs: Any
+ ) -> str:
+ sent.append((matrix_room_id, content))
+ return "$event"
+
+ svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]
+ get_by_agent_id=lambda _agent_id: _Client()
+ )
+
+ event_id = await svc.send_message(member_id, room_id, "hello")
+
+ assert event_id == "$event"
+ assert sent == [("!r:test", "hello")]
+ assert counting.opened == 1
+
+ async def test_a_non_member_cannot_post(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ room_id, _, outsider_id = await _seed(session_factory)
+ svc = _service(_CountingSessionFactory(session_factory))
+
+ with pytest.raises(PermissionError):
+ await svc.send_message(outsider_id, room_id, "hello")
+
+
+class TestAgentStatuses:
+ async def test_a_request_handler_can_reuse_its_own_session(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The gateway builds a room's detail inside its request transaction.
+ # Resolving statuses used to open a second one from underneath it.
+ room_id, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]
+
+ async with session_factory() as session:
+ counting.opened = 0
+ statuses = await svc.get_agent_statuses_by_ids_in_session(
+ session, room_id, [member_id]
+ )
+
+ assert member_id in statuses
+ assert counting.opened == 0
+
+ async def test_the_session_less_form_still_takes_exactly_one(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ room_id, member_id, _ = await _seed(session_factory)
+ counting = _CountingSessionFactory(session_factory)
+ svc = _service(counting)
+ svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]
+
+ await svc.get_agent_statuses_by_ids(room_id, [member_id])
+
+ assert counting.opened == 1
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py
index a8a4a4660..77e0c8a18 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_change_notices.py
@@ -50,6 +50,14 @@ class _FakeRoomStore:
async def get_agent_ids(self, _session: Any, _room_id: str) -> list[str]:
return list(self._members)
+ async def get_with_membership(
+ self, session: Any, room_id: str, agent_id: str
+ ) -> Any:
+ room = await self.get(session, room_id)
+ if room is None:
+ return None
+ return room, agent_id in await self.get_agent_ids(session, room_id)
+
class _FakeRoomRoleStore:
def __init__(
@@ -93,6 +101,8 @@ _ROOM = SimpleNamespace(
name="This Room",
description="desc",
matrix_room_id="!mx:switch.local",
+ archived_at=None,
+ bridge_id=None,
)
_ROLE = SimpleNamespace(id="role-m", name="manager", instructions="coordinate")
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py
index 277570532..0291e94a4 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_role_detail.py
@@ -83,6 +83,14 @@ class _FakeRoomStore:
async def get_agent_ids(self, _session: Any, room_id: str) -> list[str]:
return list(self._members.get(room_id, []))
+ async def get_with_membership(
+ self, session: Any, room_id: str, agent_id: str
+ ) -> Any:
+ room = await self.get(session, room_id)
+ if room is None:
+ return None
+ return room, agent_id in await self.get_agent_ids(session, room_id)
+
def _role(name: str, exclusive: bool, instructions: str) -> SimpleNamespace:
return SimpleNamespace(
@@ -100,7 +108,12 @@ def _lease(
def _room(room_id: str, name: str) -> SimpleNamespace:
return SimpleNamespace(
- id=room_id, name=name, description="d", matrix_room_id="!m:x"
+ id=room_id,
+ name=name,
+ description="d",
+ matrix_room_id="!m:x",
+ archived_at=None,
+ bridge_id=None,
)
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py
index e3ca85efe..508f06313 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_aliases.py
@@ -43,6 +43,14 @@ class _FakeRoomStore:
async def get_agent_ids(self, session: Any, room_id: str) -> list[str]:
return list(self._agent_ids)
+ async def get_with_membership(
+ self, session: Any, room_id: str, agent_id: str
+ ) -> Any:
+ room = await self.get(session, room_id)
+ if room is None:
+ return None
+ return room, agent_id in await self.get_agent_ids(session, room_id)
+
async def get_client_ids(self, session: Any, room_id: str) -> list[str]:
return []
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py
index e12a086a4..ef476aff5 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_detail.py
@@ -43,6 +43,14 @@ class _FakeRoomStore:
async def get_agent_ids(self, session: Any, room_id: str) -> list[str]:
return list(self._agent_ids)
+ async def get_with_membership(
+ self, session: Any, room_id: str, agent_id: str
+ ) -> Any:
+ room = await self.get(session, room_id)
+ if room is None:
+ return None
+ return room, agent_id in await self.get_agent_ids(session, room_id)
+
async def get_client_ids(self, session: Any, room_id: str) -> list[str]:
return list(self._client_ids)
diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py
index bc4ee49f4..f522a9e73 100644
--- a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py
+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py
@@ -49,10 +49,7 @@ class _FakeClient:
def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolService:
async def _require(agent_id: str, room_id: str):
- return SimpleNamespace(matrix_room_id="!room")
-
- async def _set_typing(agent_id: str, room_id: str, is_typing: bool) -> None:
- pass
+ return SimpleNamespace(id=room_id, matrix_room_id="!room", bridge_id=None)
async def _resolve_thread_root(client_: Any, matrix_room_id: str, thread_id: str):
return f"root-of-{thread_id}"
@@ -66,7 +63,6 @@ def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolServ
get_by_agent_id=lambda agent_id: client
)
svc.config = SimpleNamespace(agent_media_max_bytes=max_bytes) # type: ignore[assignment]
- svc.set_typing = _set_typing # type: ignore[assignment]
svc._resolve_thread_root = _resolve_thread_root # type: ignore[assignment]
return svc
diff --git a/core/tests/switch_core/bridges/agent/test_api_key_cache.py b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
new file mode 100644
index 000000000..8290aef72
--- /dev/null
+++ b/core/tests/switch_core/bridges/agent/test_api_key_cache.py
@@ -0,0 +1,445 @@
+"""The bearer-token memo in front of the auth query (CHOO pool exhaustion).
+
+Resolving a token is the highest-frequency database read in the server, so it
+is memoised — but it is still authentication, and the properties that keep it
+honest are the ones worth pinning: a failure is never remembered, an entry dies
+on rotation rather than on expiry, and the memo cannot grow without bound.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
+from switch_core.bridges.agent.auth import BearerAuthMiddleware
+from switch_core.bridges.agent.protocol.connections import HEARTBEAT_TTL_SECONDS
+from switch_core.bridges.agent.protocol.service import ProtocolService
+from switch_core.bridges.agent.protocol.types import (
+ IntegrationProfile,
+ TaskProtocolConfig,
+)
+from switch_core.config import SwitchConfig
+from switch_core.db.models import Agent, ApiKey, Client, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+
+_PROFILE = IntegrationProfile(
+ connection_model="session_passive",
+ message_exchange=True,
+ pre_invocation_mediation=[],
+ post_invocation_mediation=[],
+ event_reporting=[],
+ task_protocol=TaskProtocolConfig(can_delegate=False, can_accept=False),
+)
+
+
+class _CountingSessionFactory:
+ """Wraps the real factory and counts how many sessions are opened.
+
+ A session is a pool checkout, so this is the number the incident is about.
+ """
+
+ def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:
+ self._inner = inner
+ self.opened = 0
+
+ def __call__(self) -> Any:
+ self.opened += 1
+ return self._inner()
+
+
+class _FakeClientLifecycle:
+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
+ self._session_factory = session_factory
+ self.started: list[str] = []
+
+ async def create_client(self, *, client_type: str, display_name: str) -> Client:
+ async with self._session_factory() as session:
+ client = Client(
+ matrix_user_id=f"@{display_name}:test",
+ display_name=display_name,
+ type=client_type,
+ password="x",
+ )
+ session.add(client)
+ await session.commit()
+ return client
+
+ def start_client(self, client: Client) -> None:
+ self.started.append(client.id)
+
+ async def stop(self, client_id: str) -> None:
+ return None
+
+ async def remove(self, client_id: str) -> None:
+ return None
+
+
+class _NoBridges:
+ def all_bridges(self) -> list[object]:
+ return []
+
+
+def _middleware(session_factory: Any, cache: ApiKeyCache) -> BearerAuthMiddleware:
+ async def _app(scope: Any, receive: Any, send: Any) -> None:
+ return None
+
+ return BearerAuthMiddleware(
+ _app,
+ agent_store=AgentStore(),
+ api_key_store=ApiKeyStore(),
+ api_key_cache=cache,
+ session_factory=session_factory,
+ )
+
+
+def _hash(token: str) -> str:
+ return hashlib.sha256(token.encode()).hexdigest()
+
+
+async def _seed_agent(
+ session_factory: async_sessionmaker[AsyncSession],
+ token: str,
+ *,
+ name: str = "bot",
+ key_type: str = "agent",
+ with_agent: bool = True,
+) -> str:
+ async with session_factory() as session:
+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ key = ApiKey(
+ user_id=user.id,
+ key_hash=_hash(token),
+ encrypted_key="enc",
+ label=name,
+ type=key_type,
+ )
+ session.add(key)
+ await session.flush()
+ agent_id = ""
+ if with_agent:
+ client = Client(
+ matrix_user_id=f"@{name}:test",
+ display_name=name,
+ type="agent",
+ password="x",
+ )
+ session.add(client)
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description="d",
+ agent_type="session_addressable",
+ connector_type="claude_code",
+ integration_profile={},
+ client_id=client.id,
+ api_key_id=key.id,
+ owner_id=user.id,
+ )
+ session.add(agent)
+ await session.flush()
+ agent_id = agent.id
+ await session.commit()
+ return agent_id
+
+
+class TestCacheUnit:
+ def test_a_ttl_at_or_above_the_heartbeat_ttl_is_refused(self) -> None:
+ # Past the heartbeat TTL a revoked credential could still authenticate
+ # a connection the server has already declared dead.
+ with pytest.raises(ValueError, match="heartbeat TTL"):
+ ApiKeyCache(ttl_seconds=HEARTBEAT_TTL_SECONDS, max_entries=8)
+
+ def test_a_negative_ttl_is_refused(self) -> None:
+ with pytest.raises(ValueError, match="must not be negative"):
+ ApiKeyCache(ttl_seconds=-1, max_entries=8)
+
+ def test_zero_entries_is_refused(self) -> None:
+ with pytest.raises(ValueError, match="at least 1"):
+ ApiKeyCache(ttl_seconds=1, max_entries=0)
+
+ def test_ttl_zero_stores_nothing(self) -> None:
+ cache = ApiKeyCache(ttl_seconds=0, max_entries=8)
+ cache.put("h", SimpleNamespace(), SimpleNamespace()) # type: ignore[arg-type]
+
+ assert cache.enabled is False
+ assert cache.get("h") is None
+
+ def test_the_oldest_entry_is_evicted_past_the_bound(self) -> None:
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=2)
+ for i in range(3):
+ cache.put(f"h{i}", SimpleNamespace(), SimpleNamespace(id=f"a{i}")) # type: ignore[arg-type]
+
+ assert cache.get("h0") is None
+ assert cache.get("h1") is not None
+ assert cache.get("h2") is not None
+
+ def test_an_entry_expires(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ now = [1000.0]
+ monkeypatch.setattr(
+ "switch_core.bridges.agent.api_key_cache.time.monotonic", lambda: now[0]
+ )
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ cache.put("h", SimpleNamespace(), SimpleNamespace(id="a")) # type: ignore[arg-type]
+
+ now[0] = 1004.9
+ assert cache.get("h") is not None
+ now[0] = 1005.0
+ assert cache.get("h") is None
+
+ def test_invalidate_agent_drops_every_token_for_that_agent(self) -> None:
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ cache.put("old", SimpleNamespace(), SimpleNamespace(id="a1")) # type: ignore[arg-type]
+ cache.put("new", SimpleNamespace(), SimpleNamespace(id="a1")) # type: ignore[arg-type]
+ cache.put("other", SimpleNamespace(), SimpleNamespace(id="a2")) # type: ignore[arg-type]
+
+ cache.invalidate_agent("a1")
+
+ assert cache.get("old") is None
+ assert cache.get("new") is None
+ assert cache.get("other") is not None
+
+
+class TestResolutionHitsAndMisses:
+ async def test_a_hit_does_not_touch_the_database(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "tok")
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ mw = _middleware(counting, ApiKeyCache(ttl_seconds=5, max_entries=8))
+
+ first_key, first_agent = await mw._resolve_api_key("tok")
+ after_miss = counting.opened
+ second_key, second_agent = await mw._resolve_api_key("tok")
+
+ assert first_agent is not None
+ assert after_miss == 1
+ assert counting.opened == 1, "the second resolution must be answered in memory"
+ assert second_agent is not None
+ assert second_agent.id == first_agent.id
+ assert second_key is not None and first_key is not None
+ assert second_key.id == first_key.id
+
+ async def test_one_checkout_resolves_key_and_agent_together(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "tok")
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ mw = _middleware(counting, ApiKeyCache(ttl_seconds=0, max_entries=8))
+
+ await mw._resolve_api_key("tok")
+
+ assert counting.opened == 1
+
+ async def test_an_unknown_token_is_never_cached(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # A token that does not resolve must reach Postgres every time, or a
+ # key that starts existing would keep failing — and, far worse, the
+ # memo would become a place to park an attacker-chosen string.
+ counting = _CountingSessionFactory(session_factory)
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw = _middleware(counting, cache)
+
+ assert await mw._resolve_api_key("nope") == (None, None)
+ assert await mw._resolve_api_key("nope") == (None, None)
+
+ assert counting.opened == 2
+ assert cache.get(_hash("nope")) is None
+
+ async def test_a_registration_token_is_not_cached(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(
+ session_factory,
+ "reg",
+ name="regkey",
+ key_type="registration",
+ with_agent=False,
+ )
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw = _middleware(counting, cache)
+
+ key, agent = await mw._resolve_api_key("reg")
+ await mw._resolve_api_key("reg")
+
+ assert key is not None and key.type == "registration"
+ assert agent is None
+ assert counting.opened == 2
+ assert cache.get(_hash("reg")) is None
+
+ async def test_an_agent_key_with_no_agent_is_not_cached(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "orphan", name="orphan", with_agent=False)
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw = _middleware(counting, cache)
+
+ key, agent = await mw._resolve_api_key("orphan")
+ await mw._resolve_api_key("orphan")
+
+ assert key is not None
+ assert agent is None
+ assert counting.opened == 2
+ assert cache.get(_hash("orphan")) is None
+
+ async def test_a_disabled_cache_reads_every_time(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ await _seed_agent(session_factory, "tok")
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ mw = _middleware(counting, ApiKeyCache(ttl_seconds=0, max_entries=8))
+
+ await mw._resolve_api_key("tok")
+ await mw._resolve_api_key("tok")
+
+ assert counting.opened == 2
+
+ async def test_an_expired_entry_reads_again(
+ self,
+ session_factory: async_sessionmaker[AsyncSession],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ await _seed_agent(session_factory, "tok")
+ now = [1000.0]
+ monkeypatch.setattr(
+ "switch_core.bridges.agent.api_key_cache.time.monotonic", lambda: now[0]
+ )
+ counting = _CountingSessionFactory(session_factory)
+ counting.opened = 0
+ mw = _middleware(counting, ApiKeyCache(ttl_seconds=5, max_entries=8))
+
+ await mw._resolve_api_key("tok")
+ now[0] = 1006.0
+ await mw._resolve_api_key("tok")
+
+ assert counting.opened == 2
+
+
+class TestInvalidation:
+ async def test_deleting_an_agent_drops_its_cached_token(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ agent_id = await _seed_agent(session_factory, "tok")
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ mw = _middleware(session_factory, cache)
+ await mw._resolve_api_key("tok")
+ assert cache.get(_hash("tok")) is not None
+
+ svc = _protocol_service(session_factory, cache)
+ await svc.delete_agent(agent_id=agent_id)
+
+ assert cache.get(_hash("tok")) is None
+ # Deleting the agent leaves its api_keys row behind, so the token still
+ # names a key — but it no longer names an agent, which is what the
+ # middleware turns into a 401.
+ _, agent = await mw._resolve_api_key("tok")
+ assert agent is None
+ assert cache.get(_hash("tok")) is None
+
+ async def test_rotating_a_key_drops_the_cached_one(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # Re-registration issues a new key and deletes the old row. Without
+ # invalidation the retired credential keeps authenticating for the
+ # whole TTL, which is the failure mode this cache must not introduce.
+ cache = ApiKeyCache(ttl_seconds=5, max_entries=8)
+ svc = _protocol_service(session_factory, cache)
+ async with session_factory() as session:
+ owner = User(name="o", email="o@test", role="user", password_hash="x")
+ session.add(owner)
+ await session.commit()
+ owner_id = owner.id
+
+ first = await svc.register_agent(
+ name="bot",
+ description="d",
+ connector_type="claude_code",
+ integration_profile=_PROFILE,
+ owner_id=owner_id,
+ )
+ mw = _middleware(session_factory, cache)
+ _, agent = await mw._resolve_api_key(first.api_key)
+ assert agent is not None
+ assert cache.get(_hash(first.api_key)) is not None
+
+ second = await svc.register_agent(
+ name="bot",
+ description="d",
+ connector_type="claude_code",
+ integration_profile=_PROFILE,
+ owner_id=owner_id,
+ overwrite=True,
+ )
+
+ assert cache.get(_hash(first.api_key)) is None
+ assert await mw._resolve_api_key(first.api_key) == (None, None)
+ _, rotated = await mw._resolve_api_key(second.api_key)
+ assert rotated is not None
+
+
+def _protocol_service(
+ session_factory: async_sessionmaker[AsyncSession], cache: ApiKeyCache
+) -> ProtocolService:
+ svc = object.__new__(ProtocolService)
+ svc.session_factory = session_factory # type: ignore[attr-defined]
+ svc.agent_store = AgentStore() # type: ignore[attr-defined]
+ svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]
+ svc.api_key_cache = cache # type: ignore[attr-defined]
+ svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]
+ svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]
+ svc.event_buffer = SimpleNamespace(remove=lambda _agent_id: None) # type: ignore[attr-defined]
+ svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]
+ return svc
+
+
+_CONFIG_KWARGS = dict(
+ db_host="db",
+ db_port="5432",
+ db_user="postgres",
+ db_password="pw",
+ db_name="switch",
+ matrix_server="http://tuwunel:8008",
+ matrix_server_name="switch.local",
+ matrix_admin_user="admin",
+ matrix_admin_password="pw",
+ matrix_registration_shared_secret="secret",
+ agent_registration_token="token",
+ jwt_secret_key="jwt",
+ gateway_admin_email="[email protected]",
+ gateway_admin_password="pw",
+)
+
+
+def _config(**overrides: object) -> SwitchConfig:
+ return SwitchConfig(**{**_CONFIG_KWARGS, **overrides}) # type: ignore[arg-type]
+
+
+class TestAuthCacheConfig:
+ def test_the_default_ttl_is_under_the_heartbeat_ttl(self) -> None:
+ assert _config().agent_auth_cache_ttl_seconds < HEARTBEAT_TTL_SECONDS
+
+ def test_zero_is_allowed_and_disables_the_cache(self) -> None:
+ assert _config(agent_auth_cache_ttl_seconds=0).agent_auth_cache_ttl_seconds == 0
+
+ def test_a_negative_ttl_fails_at_startup(self) -> None:
+ with pytest.raises(ValueError, match="AGENT_AUTH_CACHE_TTL_SECONDS"):
+ _config(agent_auth_cache_ttl_seconds=-1)
+
+ def test_an_unbounded_cache_fails_at_startup(self) -> None:
+ with pytest.raises(ValueError, match="AGENT_AUTH_CACHE_MAX_ENTRIES"):
+ _config(agent_auth_cache_max_entries=0)
diff --git a/core/tests/switch_core/bridges/agent/test_deeplink_route.py b/core/tests/switch_core/bridges/agent/test_deeplink_route.py
index 27a88b134..799e69030 100644
--- a/core/tests/switch_core/bridges/agent/test_deeplink_route.py
+++ b/core/tests/switch_core/bridges/agent/test_deeplink_route.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from switch_core.bridges.agent.api_key_cache import ApiKeyCache
from switch_core.bridges.agent.auth import BearerAuthMiddleware, _is_public_path
from switch_core.bridges.agent.deeplink import router
@@ -22,6 +23,7 @@ def _client_with_auth() -> TestClient:
BearerAuthMiddleware,
agent_store=None, # type: ignore[arg-type]
api_key_store=None, # type: ignore[arg-type]
+ api_key_cache=ApiKeyCache(ttl_seconds=0, max_entries=1),
session_factory=None, # type: ignore[arg-type]
)
return TestClient(app, follow_redirects=False)
diff --git a/core/tests/switch_core/db/stores/test_api_key_agent_join.py b/core/tests/switch_core/db/stores/test_api_key_agent_join.py
new file mode 100644
index 000000000..5c73d93e7
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_api_key_agent_join.py
@@ -0,0 +1,133 @@
+"""`ApiKeyStore.get_with_agent_by_hash` resolves a bearer token and its agent in
+one statement — the query that runs before every authenticated request."""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Agent, ApiKey, Client, User
+from switch_core.db.stores.agent_store import AgentStore
+from switch_core.db.stores.api_key_store import ApiKeyStore
+
+
+async def _make_user(session: AsyncSession, name: str) -> User:
+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ return user
+
+
+async def _make_key(
+ session: AsyncSession, user: User, name: str, key_type: str
+) -> ApiKey:
+ key = ApiKey(
+ user_id=user.id,
+ key_hash=f"hash-{name}",
+ encrypted_key="enc",
+ label=name,
+ type=key_type,
+ )
+ session.add(key)
+ await session.flush()
+ return key
+
+
+async def _make_agent(session: AsyncSession, name: str, api_key: ApiKey) -> Agent:
+ client = Client(
+ matrix_user_id=f"@{name}:test", display_name=name, type="agent", password="x"
+ )
+ session.add(client)
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description=f"{name} desc",
+ agent_type="session_addressable",
+ connector_type="claude_code",
+ integration_profile={},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
+
+
+class TestGetWithAgentByHash:
+ async def test_agent_key_returns_both_rows(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ApiKeyStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "owner")
+ key = await _make_key(session, user, "bot", "agent")
+ agent = await _make_agent(session, "bot", key)
+ await session.commit()
+
+ found = await store.get_with_agent_by_hash(session, "hash-bot")
+
+ assert found is not None
+ loaded_key, loaded_agent = found
+ assert loaded_key.id == key.id
+ assert loaded_agent is not None
+ assert loaded_agent.id == agent.id
+
+ async def test_registration_key_has_no_agent(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ApiKeyStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "owner")
+ key = await _make_key(session, user, "reg", "registration")
+ await session.commit()
+
+ found = await store.get_with_agent_by_hash(session, "hash-reg")
+
+ assert found is not None
+ loaded_key, loaded_agent = found
+ assert loaded_key.id == key.id
+ assert loaded_agent is None
+
+ async def test_agent_key_with_no_agent_still_returns_the_key(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # An outer join, not an inner one: the caller decides what a key with
+ # nothing behind it means, rather than seeing "no such token".
+ store = ApiKeyStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "owner")
+ await _make_key(session, user, "orphan", "agent")
+ await session.commit()
+
+ found = await store.get_with_agent_by_hash(session, "hash-orphan")
+
+ assert found is not None
+ assert found[1] is None
+
+ async def test_unknown_hash_is_none(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ApiKeyStore()
+ async with session_factory() as session:
+ assert await store.get_with_agent_by_hash(session, "nope") is None
+
+ async def test_matches_the_two_query_resolution_it_replaces(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = ApiKeyStore()
+ agents = AgentStore()
+ async with session_factory() as session:
+ user = await _make_user(session, "owner")
+ key = await _make_key(session, user, "bot", "agent")
+ await _make_agent(session, "bot", key)
+ await session.commit()
+
+ joined = await store.get_with_agent_by_hash(session, "hash-bot")
+ separate_key = await store.get_by_hash(session, "hash-bot")
+ assert separate_key is not None
+ separate_agent = await agents.get_by_api_key_id(session, separate_key.id)
+
+ assert joined is not None
+ assert joined[0].id == separate_key.id
+ assert separate_agent is not None
+ assert joined[1] is not None
+ assert joined[1].id == separate_agent.id
diff --git a/core/tests/switch_core/db/stores/test_room_membership_lookup.py b/core/tests/switch_core/db/stores/test_room_membership_lookup.py
new file mode 100644
index 000000000..0050f0c51
--- /dev/null
+++ b/core/tests/switch_core/db/stores/test_room_membership_lookup.py
@@ -0,0 +1,114 @@
+"""`RoomStore.get_with_membership` answers "does this room exist, and is this
+agent in it" in one statement, so authorization costs one checkout."""
+
+from __future__ import annotations
+
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
+
+from switch_core.db.models import Agent, ApiKey, Client, Room, User
+from switch_core.db.stores.room_store import RoomStore
+
+
+async def _make_agent(session: AsyncSession, name: str) -> Agent:
+ user = User(name=name, email=f"{name}@test", role="user", password_hash="x")
+ session.add(user)
+ await session.flush()
+ api_key = ApiKey(
+ user_id=user.id,
+ key_hash=f"hash-{name}",
+ encrypted_key="enc",
+ label=name,
+ type="agent",
+ )
+ client = Client(
+ matrix_user_id=f"@{name}:test", display_name=name, type="agent", password="x"
+ )
+ session.add_all([api_key, client])
+ await session.flush()
+ agent = Agent(
+ name=name,
+ description=f"{name} desc",
+ agent_type="session_addressable",
+ connector_type="claude_code",
+ integration_profile={},
+ client_id=client.id,
+ api_key_id=api_key.id,
+ )
+ session.add(agent)
+ await session.flush()
+ return agent
+
+
+class TestGetWithMembership:
+ async def test_member_gets_the_room_and_a_true_flag(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ room = await store.create(
+ session, Room(matrix_room_id="!a:test", name="alpha", description="d")
+ )
+ agent = await _make_agent(session, "member")
+ await store.add_agents(session, room.id, [agent.id])
+ await session.commit()
+
+ found = await store.get_with_membership(session, room.id, agent.id)
+
+ assert found is not None
+ loaded, is_member = found
+ assert loaded.id == room.id
+ assert loaded.name == "alpha"
+ assert is_member is True
+
+ async def test_non_member_still_gets_the_room_but_a_false_flag(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The caller has to tell "no such room" from "not yours" — they are a
+ # 404 and a 403, and collapsing them loses the distinction.
+ store = RoomStore()
+ async with session_factory() as session:
+ room = await store.create(
+ session, Room(matrix_room_id="!b:test", name="beta", description="d")
+ )
+ outsider = await _make_agent(session, "outsider")
+ await session.commit()
+
+ found = await store.get_with_membership(session, room.id, outsider.id)
+
+ assert found is not None
+ loaded, is_member = found
+ assert loaded.id == room.id
+ assert is_member is False
+
+ async def test_unknown_room_is_none(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ agent = await _make_agent(session, "lost")
+ await session.commit()
+
+ assert (
+ await store.get_with_membership(session, "no-such-room", agent.id)
+ is None
+ )
+
+ async def test_another_members_row_does_not_admit_this_agent(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ # The join is filtered on the agent, not merely on the room: a room
+ # with members must not read as "everyone is a member".
+ store = RoomStore()
+ async with session_factory() as session:
+ room = await store.create(
+ session, Room(matrix_room_id="!c:test", name="gamma", description="d")
+ )
+ insider = await _make_agent(session, "insider")
+ outsider = await _make_agent(session, "stranger")
+ await store.add_agents(session, room.id, [insider.id])
+ await session.commit()
+
+ found = await store.get_with_membership(session, room.id, outsider.id)
+
+ assert found is not None
+ assert found[1] is False
diff --git a/core/tests/switch_core/test_db_idle_in_transaction_timeout.py b/core/tests/switch_core/test_db_idle_in_transaction_timeout.py
new file mode 100644
index 000000000..bf7493f24
--- /dev/null
+++ b/core/tests/switch_core/test_db_idle_in_transaction_timeout.py
@@ -0,0 +1,83 @@
+"""The `idle_in_transaction_session_timeout` guardrail.
+
+Off by default, and it has to stay off until Matrix I/O moves out of the
+RoomService transactions — enabling it before that converts a latency problem
+into a membership-drift one. It must also never reach Alembic: a migration
+killed between two statements is a much worse afternoon than a slow request.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from switch_core.config import SwitchConfig
+from switch_core.db.engine import app_connect_args
+
+_BASE_KWARGS = dict(
+ db_host="db",
+ db_port="5432",
+ db_user="postgres",
+ db_password="pw",
+ db_name="switch",
+ matrix_server="http://tuwunel:8008",
+ matrix_server_name="switch.local",
+ matrix_admin_user="admin",
+ matrix_admin_password="pw",
+ matrix_registration_shared_secret="secret",
+ agent_registration_token="token",
+ jwt_secret_key="jwt",
+ gateway_admin_email="[email protected]",
+ gateway_admin_password="pw",
+)
+
+
+def _config(**overrides: object) -> SwitchConfig:
+ return SwitchConfig(**{**_BASE_KWARGS, **overrides}) # type: ignore[arg-type]
+
+
+class TestDefaultIsOff:
+ def test_no_timeout_is_configured_by_default(self) -> None:
+ assert _config().db_idle_in_transaction_session_timeout is None
+
+ def test_the_engine_sends_no_server_setting_by_default(self) -> None:
+ assert app_connect_args(_config()) == {}
+
+
+class TestWhenEnabled:
+ def test_it_reaches_asyncpg_as_a_server_setting(self) -> None:
+ config = _config(db_idle_in_transaction_session_timeout="15s")
+
+ assert app_connect_args(config) == {
+ "server_settings": {"idle_in_transaction_session_timeout": "15s"}
+ }
+
+ def test_it_composes_with_tls(self) -> None:
+ config = _config(
+ db_ssl_mode="require", db_idle_in_transaction_session_timeout="15s"
+ )
+
+ assert app_connect_args(config) == {
+ "ssl": "require",
+ "server_settings": {"idle_in_transaction_session_timeout": "15s"},
+ }
+
+ def test_it_does_not_leak_into_db_connect_args(self) -> None:
+ # `migrations/env.py` builds its engine straight from this property, so
+ # anything added here would silently apply to migrations too.
+ config = _config(db_idle_in_transaction_session_timeout="15s")
+
+ assert config.db_connect_args == {}
+
+ @pytest.mark.parametrize("value", ["15s", "500ms", "30000", "2min", "1h"])
+ def test_accepted_values(self, value: str) -> None:
+ assert (
+ _config(
+ db_idle_in_transaction_session_timeout=value
+ ).db_idle_in_transaction_session_timeout
+ == value
+ )
+
+ @pytest.mark.parametrize("value", ["", "soon", "15 seconds", "-5s", "15s;"])
+ def test_a_value_postgres_would_reject_fails_at_startup(self, value: str) -> None:
+ with pytest.raises(ValueError, match="DB_IDLE_IN_TRANSACTION_SESSION_TIMEOUT"):
+ _config(db_idle_in_transaction_session_timeout=value)
diff --git a/core/tests/switch_core/test_migration_chain.py b/core/tests/switch_core/test_migration_chain.py
index 10108b0c8..ab1359139 100644
--- a/core/tests/switch_core/test_migration_chain.py
+++ b/core/tests/switch_core/test_migration_chain.py
@@ -51,13 +51,19 @@ def test_single_head() -> None:
def test_every_down_revision_exists() -> None:
"""A migration pointing at a revision that was renamed or removed breaks
- the walk, and does so only when the chain is actually replayed."""
+ the walk, and does so only when the chain is actually replayed.
+
+ A merge revision names several parents, so compare against
+ `_all_down_revisions`, which is a tuple either way.
+ """
script = _script_directory()
known = {revision.revision for revision in script.walk_revisions()}
dangling = {
- revision.revision: revision.down_revision
+ revision.revision: tuple(
+ parent for parent in revision._all_down_revisions if parent not in known
+ )
for revision in script.walk_revisions()
- if revision.down_revision is not None and revision.down_revision not in known
+ if any(parent not in known for parent in revision._all_down_revisions)
}
assert not dangling, f"migrations pointing at unknown parents: {dangling}"
diff --git a/deploy/remote/helm/switch/templates/_helpers.tpl b/deploy/remote/helm/switch/templates/_helpers.tpl
index 87ebab2ad..fcc6a5dbf 100644
--- a/deploy/remote/helm/switch/templates/_helpers.tpl
+++ b/deploy/remote/helm/switch/templates/_helpers.tpl
@@ -233,6 +233,12 @@ Include with `nindent 12`.
value: {{ .Values.postgresql.pool.maxOverflow | quote }}
- name: DB_POOL_TIMEOUT
value: {{ .Values.postgresql.pool.timeout | quote }}
+{{- with .Values.postgresql.idleInTransactionSessionTimeout }}
+- name: DB_IDLE_IN_TRANSACTION_SESSION_TIMEOUT
+ value: {{ . | quote }}
+{{- end }}
+- name: AGENT_AUTH_CACHE_TTL_SECONDS
+ value: {{ .Values.switchCore.authCache.ttlSeconds | quote }}
- name: MATRIX_SERVER
value: "http://{{ include "switch.tuwunelHost" . }}:8008"
- name: MATRIX_SERVER_NAME
diff --git a/deploy/remote/helm/switch/values.yaml b/deploy/remote/helm/switch/values.yaml
index 2f7baa22a..7a813469a 100644
--- a/deploy/remote/helm/switch/values.yaml
+++ b/deploy/remote/helm/switch/values.yaml
@@ -120,6 +120,15 @@ switchCore:
redirectUrl: ""
# Set false to disable password login entirely (OIDC-only).
passwordLoginEnabled: true
+ # Bearer-token resolution runs before every authenticated request and agents
+ # beat continuously, so a successful resolution is memoised in process for
+ # this many seconds. Only successes are cached — an unknown or revoked token
+ # always reads the database — and a key rotation or agent deletion drops the
+ # entry at once rather than waiting for it to expire. This is therefore the
+ # window in which an already-issued credential can outlive its revocation;
+ # it must stay under the 6s agent heartbeat TTL, and 0 disables the cache.
+ authCache:
+ ttlSeconds: 5
service:
type: ClusterIP
port: 8000
@@ -318,6 +327,16 @@ postgresql:
# SQLAlchemy's 30s default hides starvation as latency.
timeout: 5
+ # Postgres kills a switch-core connection that sits inside an open
+ # transaction without executing anything for longer than this (e.g. "15s"),
+ # so a leaked checkout becomes a loud, attributable error instead of a slot
+ # that never comes back. Empty (the default) leaves it off, and it must stay
+ # off until switch-core stops holding transactions across Matrix round trips
+ # on the room-membership paths — until then this trades request latency for
+ # membership drift: agents invited on Matrix with no row recording it. Set it
+ # in staging first. Migrations are unaffected; Alembic does not read it.
+ idleInTransactionSessionTimeout: ""
+
# Password source. By default the password is read from the chart-managed
# Secret (secrets.postgresPassword). To source it from a pre-existing Secret
# instead (e.g. synced by external-secrets / sealed-secrets), set