Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(db): bind a tenant onto every background session (CHOO-2623)
Wojciech Wojtyniaka3093335ebca
diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 04b6ea931..86cfa2067 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -72,6 +72,7 @@ from switch_core.db.models import (Tool,User,)+from switch_core.db.session_scope import tenant_session, unscoped_sessionfrom switch_core.db.stores.agent_runtime_state_store import (IDLE as RUNTIME_STATE_IDLE,)@@ -1561,18 +1562,24 @@ class ProtocolService:one on the next update, the visible effect was the status message beingdeleted and recreated on every refresh rather than edited in place."""- async with self.session_factory() as session:+ # This sweep spans every tenant by nature — it is the one place that+ # decides whether *any* stale row anywhere needs resetting — so the+ # initial read is unscoped. Each row is itself tenant-scoped+ # (agent_runtime_states carries tenant_id), so the rest of the work+ # for that row binds its own tenant rather than the whole sweep, and+ # a row from one tenant can never leak its binding into the next.+ async with unscoped_session(self.session_factory) as session:rows = await self.agent_runtime_state_store.get_active(session)for row in rows:if self.connections.has_session_in(row.agent_id, row.room_id):continue- async with self.session_factory() as session:+ async with tenant_session(self.session_factory, row.tenant_id) as session:live = await self.agent_session_store.get_live_agent_ids(session, [row.agent_id], row.room_id)if row.agent_id in live:continue- async with self.session_factory() as session:+ async with tenant_session(self.session_factory, row.tenant_id) as session:agent = await self.agent_store.get(session, row.agent_id)room = await self.room_store.get(session, row.room_id)if agent is None or room is None:diff --git a/core/switch_core/bridges/agent/server_connectors/core.py b/core/switch_core/bridges/agent/server_connectors/core.pyindex 9124e17c2..24bcb132c 100644--- a/core/switch_core/bridges/agent/server_connectors/core.py+++ b/core/switch_core/bridges/agent/server_connectors/core.py@@ -133,10 +133,12 @@ class ConnectorCore:# ── internal ─────────────────────────────────────────────────────────async def _register_agent(self, agent: DiscoveredAgent) -> None:- # Runs from `start()`, i.e. a startup task with no request and so no- # tenant bound. `register_agent_with_token` binds the registration- # token's own tenant for the write, which is why nothing is bound- # here — see its docstring.+ # Runs from `start()`, which the caller wraps in the connector's own+ # tenant (ServerSideConnectorLifecycleService.start_all binds it+ # before starting each connector's task; an admin registering one+ # over HTTP already has it bound). register_agent_with_token+ # additionally binds the registration token's own tenant for the+ # write itself — the same tenant either way — see its docstring.try:result = await self._protocol.register_agent_with_token(registration_token=self._registration_token,diff --git a/core/switch_core/bridges/agent/server_connectors/lifecycle.py b/core/switch_core/bridges/agent/server_connectors/lifecycle.pyindex 6cdc0674a..1297c99e9 100644--- a/core/switch_core/bridges/agent/server_connectors/lifecycle.py+++ b/core/switch_core/bridges/agent/server_connectors/lifecycle.py@@ -14,8 +14,10 @@ from switch_core.bridges.agent.server_connectors.base import (from switch_core.bridges.agent.server_connectors.core import ConnectorCorefrom switch_core.crypto import decrypt_token, encrypt_tokenfrom switch_core.db.models import ApiKey, ServerConnector+from switch_core.db.session_scope import unscoped_sessionfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.tenant_context import tenant_scopelogger = logging.getLogger(__name__)@@ -50,13 +52,19 @@ class ServerSideConnectorLifecycleService:self._config_registry[type_name] = config_clsasync def start_all(self) -> None:- async with self._session_factory() as session:+ # Every tenant's active connectors in one pass — unscoped by nature,+ # same reasoning as CollaborationBridgeLifecycleService.start_all.+ # Each row carries its own tenant; bind it only around starting that+ # one connector, and the poll loop `start` spawns keeps it for that+ # task's own life via the context asyncio.create_task snapshots.+ async with unscoped_session(self._session_factory) as session:connectors = await self._connector_store.get_active(session)logger.info("Starting %d server-side connectors", len(connectors))for record in connectors:try:- await self.start(record.id)+ with tenant_scope(record.tenant_id):+ await self.start(record.id)except Exception:logger.exception("Failed to start connector %s", record.id)diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 2f8847ea7..8c8cd7c01 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -30,6 +30,7 @@ from switch_core.clients.admin_messages import ADMIN_MARKER, AdminMessageTypefrom switch_core.clients.client_base import ClientBase, ClientConfigfrom switch_core.clients.mentions import mention_regex, strip_emphasisfrom switch_core.db.models import BridgeMessageMap, ExternalUser+from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStorefrom switch_core.db.stores.client_store import ClientStore@@ -39,6 +40,7 @@ from switch_core.events import AgentRuntimeStateEventfrom switch_core.logging_context import log_contextfrom switch_core.provisioning import Provisioningfrom switch_core.room_service import RoomCreateConfig+from switch_core.tenant_context import tenant_scopefrom switch_core.transport import (InboundMedia as TransportMedia,)@@ -155,6 +157,13 @@ class BridgeCore:self._channel_to_room: dict[str, tuple[str, str]] = {}self._room_to_channel: dict[tuple[str, str], str] = {}+ # Switch room id -> its tenant, populated wherever a room is looked+ # up or created. A room's tenant is as immutable as its channel+ # mapping, unlike this bridge's own — a bridge can in principle carry+ # rooms in more than one tenant over time — so each unit of work+ # binds the room it is actually for rather than one tenant cached for+ # the whole bridge. See `_room_tenant`.+ self._room_tenants: dict[str, str] = {}self._user_puppets: dict[str, str] = {}# External user ids whose stored name is known not to be a platform id,# so the placeholder repair does not re-ask the database once per@@ -200,18 +209,32 @@ class BridgeCore:def _traced(self, handler: Callable[[_InboundEventT], Awaitable[None]]) -> Callable[[_InboundEventT], Awaitable[None]]:- """Give each inbound platform event its own id in the logs.+ """Give each inbound platform event its own id in the logs, and bind+ the tenant of the room it is for, when that room already exists.An event fans out across room lookup, identity provisioning and thetransport, so without this the lines from two events arriving at oncecannot be told apart. Applied where the adapter is wired up rather than- inside each handler, so every inbound path gets it.+ inside each handler, so every inbound path gets it — and the same+ choke point is where the tenant is bound, so a handler needs no+ session-opening call site of its own to remember it.++ A channel with no room yet (auto-room-creation, still to come in the+ handler) binds nothing here: which tenant a *new* room lands in is an+ ambient decision, the same as any other creation, not something this+ wrapper can derive from a room that does not exist."""async def traced(event: _InboundEventT) -> None:event_id = uuid.uuid4().hex[:16]with log_context(request_id=f"{self._bridge_type}-{event_id}"):- await handler(event)+ room_ids = self._channel_to_room.get(event.channel_id)+ if room_ids is None:+ await handler(event)+ return+ room_id, _ = room_ids+ with tenant_scope(await self._room_tenant(room_id)):+ await handler(event)return traced@@ -248,11 +271,31 @@ class BridgeCore:async with self._session_factory() as session:rooms = await self._room_store.get_by_bridge(session, self._bridge_id)for room in rooms:+ self._room_tenants[room.id] = room.tenant_idif room.external_channel_id:key = (room.id, room.matrix_room_id)self._channel_to_room[room.external_channel_id] = keyself._room_to_channel[key] = room.external_channel_id+ async def _room_tenant(self, room_id: str) -> str:+ """The tenant `room_id` belongs to, resolved and cached.++ Cached by room id rather than assumed to be this bridge's own tenant:+ nothing here relies on a bridge never carrying rooms in more than one+ tenant, only on a given room's tenant never changing once it exists —+ the same invariant `_channel_to_room` already relies on for the+ channel mapping.+ """+ cached = self._room_tenants.get(room_id)+ if cached is not None:+ return cached+ async with self._session_factory() as session:+ room = await self._room_store.get(session, room_id)+ if room is None:+ raise ValueError(f"Room not found: {room_id}")+ self._room_tenants[room_id] = room.tenant_id+ return room.tenant_id+async def _load_existing_puppets(self) -> None:async with self._session_factory() as session:users = await self._external_user_store.get_by_bridge(@@ -813,6 +856,7 @@ class BridgeCore:room.id,)return+ async with tenant_session(self._session_factory, room.tenant_id) as session:await self._room_store.update_external_channel(session, room.id, new_id)await session.commit()@@ -846,6 +890,7 @@ class BridgeCore:)if room is None:return None+ self._room_tenants[room.id] = room.tenant_idself.add_room_mapping(room.id, room.matrix_room_id, channel_id)logger.debug("Adopted existing room %s for channel %s", room.id, channel_id)return (room.id, room.matrix_room_id)@@ -922,6 +967,7 @@ class BridgeCore:return Noneroom = result.room+ self._room_tenants[room.id] = room.tenant_idself.add_room_mapping(room.id, room.matrix_room_id, channel_id)logger.info("Auto-created %s room %s for %s channel %s",@@ -1302,6 +1348,13 @@ class BridgeCore:logger.debug("[BRIDGE-OUT] no channel mapping for room %s", room.room_id)return+ room_id, _ = self._channel_to_room[channel_id]+ with tenant_scope(await self._room_tenant(room_id)):+ await self._relay_outbound_message(channel_id, event)++ async def _relay_outbound_message(+ self, channel_id: str, event: TransportMessage+ ) -> None:event_content = event.contentadmin_marker = event_content.get(ADMIN_MARKER)sender_name = event.sender_name@@ -1418,6 +1471,13 @@ class BridgeCore:logger.debug("[BRIDGE-OUT] no channel mapping for room %s", room.room_id)return+ room_id, _ = self._channel_to_room[channel_id]+ with tenant_scope(await self._room_tenant(room_id)):+ await self._relay_outbound_media(channel_id, event, client)++ async def _relay_outbound_media(+ self, channel_id: str, event: TransportMedia, client: ClientBase[Any]+ ) -> None:event_content = event.contentsender_name = event.sender_nameif sender_name is None:@@ -1648,6 +1708,13 @@ class BridgeCore:)return+ room_id, _ = self._channel_to_room[channel_id]+ with tenant_scope(await self._room_tenant(room_id)):+ await self._apply_runtime_state(channel_id, event)++ async def _apply_runtime_state(+ self, channel_id: str, event: AgentRuntimeStateEvent+ ) -> None:# Where the triggering message itself sits — None when it came from the# channel root. This is what a typing indicator follows.trigger_thread_ref: str | None = Nonediff --git a/core/switch_core/bridges/collaboration/lifecycle_service.py b/core/switch_core/bridges/collaboration/lifecycle_service.pyindex 300f716e7..71269a52a 100644--- a/core/switch_core/bridges/collaboration/lifecycle_service.py+++ b/core/switch_core/bridges/collaboration/lifecycle_service.py@@ -15,6 +15,7 @@ from switch_core.clients.bridge_client import BridgeClient, BridgeClientConfigfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.config import SwitchConfigfrom switch_core.db.models import CollaborationBridge+from switch_core.db.session_scope import unscoped_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStorefrom switch_core.db.stores.client_store import ClientStore@@ -22,6 +23,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.provisioning import Provisioning+from switch_core.tenant_context import tenant_scopeif TYPE_CHECKING:from switch_core.clients.client_lifecycle_service import ClientLifecycleService@@ -188,13 +190,21 @@ class CollaborationBridgeLifecycleService:config_cls.model_validate(connection_config)async def start_all(self) -> None:- async with self._session_factory() as session:+ # Every tenant's active bridges in one pass, so the read is unscoped+ # by nature. Each row already carries its own tenant; bind that one+ # only around starting it, not the whole fan-out. `start` spawns the+ # bridge's long-lived task from inside this binding, and an asyncio+ # task snapshots the context it was created under, so the task keeps+ # this tenant for its own life without the loop needing to hold it+ # open past the moment the task exists.+ async with unscoped_session(self._session_factory) as session:bridges = await self._bridge_store.get_active(session)logger.info("Starting %d collaboration bridges", len(bridges))for bridge in bridges:try:- await self.start(bridge.id)+ with tenant_scope(bridge.tenant_id):+ await self.start(bridge.id)except Exception:logger.exception("Failed to start bridge %s", bridge.id)diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex 32909af89..b45a1fde5 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -11,8 +11,10 @@ from switch_core.clients.client_base import ClientBase, ClientConfigfrom switch_core.clients.client_factory import ClientFactoryfrom switch_core.config import SwitchConfigfrom switch_core.db.models import Client+from switch_core.db.session_scope import unscoped_sessionfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.provisioning import Provisioning+from switch_core.tenant_context import tenant_scopelogger = logging.getLogger(__name__)@@ -54,7 +56,16 @@ class ClientLifecycleService:)async def start_all(self) -> None:- async with self._session_factory() as session:+ # Every tenant's clients in one pass at boot, so this read is+ # unscoped by nature. Each row carries its own tenant; bind it only+ # around starting that one client. `_start_task` spawns the client's+ # own long-lived task from inside this binding, and an asyncio task+ # snapshots the context it was created under, so the task keeps this+ # tenant as its default for its own life — a bootstrap fallback for+ # a read like AgentClient.start() resolving its own row, not a cache+ # any room-scoped work relies on: PostgresTransport binds the tenant+ # of the room it is actually acting on for each of those.+ async with unscoped_session(self._session_factory) as session:records = await self._client_store.get_all(session)records = [r for r in records if r.type not in self.COLLAB_CLIENT_TYPES]@@ -64,7 +75,8 @@ class ClientLifecycleService:client = self._client_factory.create(record)self._clients[record.id] = clientself._client_types[record.id] = record.type- self._start_task(record.id, client)+ with tenant_scope(record.tenant_id):+ self._start_task(record.id, client)async def create_client(self,diff --git a/core/switch_core/db/session_scope.py b/core/switch_core/db/session_scope.pynew file mode 100644index 000000000..d92c8cccc--- /dev/null+++ b/core/switch_core/db/session_scope.py@@ -0,0 +1,86 @@+"""The two ways background code may open a session, named so the call site+says which one it means.++Everything in a request already gets a tenant for free: `gateway/auth.py` and+`bridges/agent/auth.py` bind one before the endpoint body runs, and the+`after_begin` hook (`db/tenant_session.py`) stamps it on every transaction+that session opens from then on, at any depth, with no call site to remember.++Nothing does that for the roughly 206 places that open a session from the+factory directly with no request behind them — the delivery loop, the+collaboration and server-connector lifecycle services, the startup seeding in+`main.py`, the periodic sweeps. Each needs to say, at the point it opens a+session, which of two things it is doing:++- **`tenant_session`** binds a tenant for the life of one session, the same+ way a request does. This is the answer for a unit of work that acts for one+ room, one bridge, or one connector — a message delivery, an inbound bridge+ event, a bridge's own startup, one row out of a cross-tenant sweep. Bind at+ the natural unit of work: derive the tenant from whatever the work is+ actually for (the room, the bridge, the connector row), not once per+ long-lived object and reused, since a client or a bridge is not guaranteed+ to act for only one tenant over its life.++- **`unscoped_session`** opens a session with no tenant bound at all — the+ fail-open hatch inside an otherwise fail-closed design. It exists for work+ that is legitimately cross-tenant: reading every row before fanning out+ work per row (a sweep, a lifecycle enumeration), and startup seeding that+ runs before any tenant can be said to exist. Nothing today stops a query on+ a session it opens from reading across every tenant there is — that is+ exactly what "unscoped" means — so its callers are pinned to an explicit+ allowlist by+ `tests/switch_core/db/test_unscoped_session_allowlist.py`, which fails on a+ new one and says what to do about it. Reach for `tenant_session` first;+ reach for this only when the work really cannot be attributed to one+ tenant.++Both are thin: the tenant binding is a contextvar (`tenant_context.py`), and+the `after_begin` hook is what actually turns it into `set_config` on the+transaction. Opening a session through either helper does no I/O by itself,+same as calling the factory directly — the hook only fires once a transaction+begins, on that session's first query.+"""++from __future__ import annotations++from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.tenant_context import bind_tenant_id, unbind_tenant_id+++@asynccontextmanager+async def tenant_session(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> AsyncIterator[AsyncSession]:+ """Open a session bound to `tenant_id` for the life of the `async with` block.++ Binds before the session is constructed and unbinds in a `finally`, so a+ long-lived caller (a bridge's own task, say) cannot leak this tenant into+ whatever it does next even if the block raises.+ """+ token = bind_tenant_id(tenant_id)+ try:+ async with session_factory() as session:+ yield session+ finally:+ unbind_tenant_id(token)+++@asynccontextmanager+async def unscoped_session(+ session_factory: async_sessionmaker[AsyncSession],+) -> AsyncIterator[AsyncSession]:+ """Open a session with no tenant bound — the fail-open hatch.++ Behaves exactly like calling `session_factory()` directly today, because+ that is what it is: no binding, no unbinding, nothing hidden. The point of+ naming it is not to change what it does but to make every place that does+ it say so, so the allowlist in+ `tests/switch_core/db/test_unscoped_session_allowlist.py` has something to+ pin.+ """+ async with session_factory() as session:+ yield sessiondiff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 89c749215..4ae79b28f 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -14,6 +14,7 @@ import uvicornfrom alembic import command as alembic_commandfrom alembic.config import Config as AlembicConfigfrom fastapi.responses import JSONResponse+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.app import create_agent_bridge_appfrom switch_core.bridges.agent.protocol.connections import (@@ -74,7 +75,8 @@ from switch_core.db.engine import (create_session_factory,create_unpooled_engine,)-from switch_core.db.models import ApiKey, User+from switch_core.db.models import TENANT_ZERO_ID, ApiKey, User+from switch_core.db.session_scope import unscoped_sessionfrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore@@ -475,11 +477,15 @@ async def run(config: SwitchConfig) -> None:async def _seed_admin_user(- session_factory: object,+ session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,config: SwitchConfig,) -> None:- async with session_factory() as session: # type: ignore[operator]+ # Cross-tenant by necessity: this runs before any request has ever bound+ # one. The admin User row itself is global (db/models.py); UserStore.create+ # gives it a tenant_members row via its own tenant-zero fallback since+ # nothing is bound here to join instead.+ async with unscoped_session(session_factory) as session:existing = await user_store.get_by_email(session, config.gateway_admin_email)if existing is not None:logger.info("Admin user already exists: %s", config.gateway_admin_email)@@ -497,7 +503,7 @@ async def _seed_admin_user(async def _seed_agent_registration_bootstrap_key(- session_factory: object,+ session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,api_key_store: ApiKeyStore,agent_store: AgentStore,@@ -522,7 +528,11 @@ async def _seed_agent_registration_bootstrap_key(already exists under the old one, which would collide on the unique``key_hash`` and fail the whole boot."""- async with session_factory() as session: # type: ignore[operator]+ # Cross-tenant by necessity, same as _seed_admin_user: no tenant exists+ # yet to bind. The ApiKey row created below names tenant zero explicitly+ # rather than leaning on the model default's fallback to it, so this+ # keeps working once that fallback is removed.+ async with unscoped_session(session_factory) as session:admin = await user_store.get_by_email(session, config.gateway_admin_email)if admin is None:raise RuntimeError(@@ -676,6 +686,7 @@ async def _seed_agent_registration_bootstrap_key()else:bootstrap_key = ApiKey(+ tenant_id=TENANT_ZERO_ID,user_id=admin.id,key_hash=token_hash,encrypted_key=encrypted_key,diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 952b6a780..7a0d898a3 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -30,10 +30,12 @@ from switch_core.bridges.collaboration.models import (from switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.models import Room, RoomGroup, RoomRole+from switch_core.db.session_scope import tenant_session, unscoped_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.provisioning import Provisioning+from switch_core.tenant_context import tenant_scopeif TYPE_CHECKING:from switch_core.bridges.collaboration.bridge_core import BridgeCore@@ -649,18 +651,23 @@ class RoomService:client_ids = await self._room_store.get_client_ids(session, room_id)- for client_id in client_ids:- client = self._client_lifecycle.get(client_id)- if client:- await self._matrix_admin.kick_user(- room.matrix_room_id, client.matrix_user_id- )+ # `kick_user` and the delete below both write rows scoped to this+ # room's tenant (a membership removal, then the room itself), so both+ # bind it — one scope for the whole unit of work rather than one per+ # session opened along the way.+ with tenant_scope(room.tenant_id):+ for client_id in client_ids:+ client = self._client_lifecycle.get(client_id)+ if client:+ await self._matrix_admin.kick_user(+ room.matrix_room_id, client.matrix_user_id+ )- await self._matrix_admin.delete_room(room.matrix_room_id)+ await self._matrix_admin.delete_room(room.matrix_room_id)- async with self._session_factory() as session:- await self._room_store.delete(session, room_id)- await session.commit()+ async with self._session_factory() as session:+ await self._room_store.delete(session, room_id)+ await session.commit()if bridge_id:bridge_core = self._collab_lifecycle.get(bridge_id)@@ -722,21 +729,27 @@ class RoomService:agent_clients = self._resolve_agent_clients(new_agent_ids)- async with self._session_factory() as session:- await self._room_store.add_agents(- session,- room.id,- new_agent_ids,- join_event_listeners={aid for aid in new_agent_ids if aid in listeners},- )- await session.commit()+ # One binding for the whole membership change: the two writes below+ # and the invite between them (which itself writes a membership row+ # and an arrival message) all belong to this room's tenant.+ with tenant_scope(room.tenant_id):+ async with self._session_factory() as session:+ await self._room_store.add_agents(+ session,+ room.id,+ new_agent_ids,+ join_event_listeners={+ aid for aid in new_agent_ids if aid in listeners+ },+ )+ await session.commit()- await self._invite_clients(room.matrix_room_id, agent_clients)+ await self._invite_clients(room.matrix_room_id, agent_clients)- async with self._session_factory() as session:- for client_id in agent_clients:- await self._room_store.add_client(session, client_id, room.id)- await session.commit()+ async with self._session_factory() as session:+ for client_id in agent_clients:+ await self._room_store.add_client(session, client_id, room.id)+ await session.commit()if room.bridge_id and room.external_channel_id:bridge_core = self._collab_lifecycle.get(room.bridge_id)@@ -756,17 +769,28 @@ class RoomService:agent_clients = self._resolve_agent_clients(agent_ids)- for matrix_user_id in agent_clients.values():- await self._matrix_admin.kick_user(room.matrix_room_id, matrix_user_id)+ with tenant_scope(room.tenant_id):+ for matrix_user_id in agent_clients.values():+ await self._matrix_admin.kick_user(room.matrix_room_id, matrix_user_id)- async with self._session_factory() as session:- for client_id in agent_clients:- await self._room_store.remove_client(session, client_id, room_id)- await self._room_store.remove_agents(session, room_id, agent_ids)- await session.commit()+ async with self._session_factory() as session:+ for client_id in agent_clients:+ await self._room_store.remove_client(session, client_id, room_id)+ await self._room_store.remove_agents(session, room_id, agent_ids)+ await session.commit()logger.info("Removed %d agents from room %s", len(agent_ids), room_id)+ async def _room_tenant(self, room_id: str) -> str:+ """The tenant a room belongs to, resolved fresh — never cached beside+ a room id, since nothing here holds one room for longer than a call.+ """+ async with self._session_factory() as session:+ room = await self._room_store.get(session, room_id)+ if room is None:+ raise ValueError(f"Room not found: {room_id}")+ return room.tenant_id+async def update_room(self,room_id: str,@@ -778,7 +802,8 @@ class RoomService:read_visibility: str | None = None,write_visibility: str | None = None,) -> None:- async with self._session_factory() as session:+ tenant_id = await self._room_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:if read_visibility is not None or write_visibility is not None:room = await self._room_store.get(session, room_id)if room is None:@@ -811,10 +836,8 @@ class RoomService:does not exist or an agent is not a member of it."""if not settings:return- async with self._session_factory() as session:- room = await self._room_store.get(session, room_id)- if room is None:- raise ValueError(f"Room not found: {room_id}")+ tenant_id = await self._room_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:for agent_id, value in settings.items():await self._room_store.set_receives_join_events(session, room_id, agent_id, value@@ -824,14 +847,16 @@ class RoomService:async def update_protection_config(self, room_id: str, config: dict[str, object]) -> None:- async with self._session_factory() as session:+ tenant_id = await self._room_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:await self._room_store.update_protection_config(session, room_id, config)await session.commit()async def update_observe_config(self, room_id: str, config: dict[str, object]) -> None:- async with self._session_factory() as session:+ tenant_id = await self._room_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:await self._room_store.update_observe_config(session, room_id, config)await session.commit()@@ -840,7 +865,8 @@ class RoomService:Raises ValueError if the room does not exist."""- async with self._session_factory() as session:+ tenant_id = await self._room_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:await self._room_store.set_archived(session, room_id, archived)await session.commit()@@ -903,7 +929,7 @@ class RoomService:room.name, room.description)- async with self._session_factory() as session:+ async with tenant_session(self._session_factory, room.tenant_id) as session:await self._room_store.update_bridge(session,room_id,@@ -931,6 +957,7 @@ class RoomService:bridge_id = room.bridge_id+ async with tenant_session(self._session_factory, room.tenant_id) as session:await self._room_store.clear_bridge(session, room_id)await session.commit()@@ -1008,62 +1035,69 @@ class RoomService:channel_type=resolved_channel_type,)- # Guard the new channel until its mapping is registered, so the bot's- # auto-join does not spawn a duplicate room (CHOO-1660).- new_bridge.begin_provisioning(external_channel_id)- try:- async with self._session_factory() as session:- await self._room_store.update_bridge(- session,- room_id,- bridge_id=bridge_id,- channel_type=resolved_channel_type,- external_channel_id=external_channel_id,- )- await session.commit()-- new_bridge.add_room_mapping(room_id, matrix_room_id, external_channel_id)- finally:- new_bridge.end_provisioning(external_channel_id)+ # One binding for everything from here on: the bridge-column update,+ # and the invite/kick below, both write rows scoped to this room's+ # tenant.+ with tenant_scope(room.tenant_id):+ # Guard the new channel until its mapping is registered, so the+ # bot's auto-join does not spawn a duplicate room (CHOO-1660).+ new_bridge.begin_provisioning(external_channel_id)+ try:+ async with self._session_factory() as session:+ await self._room_store.update_bridge(+ session,+ room_id,+ bridge_id=bridge_id,+ channel_type=resolved_channel_type,+ external_channel_id=external_channel_id,+ )+ await session.commit()- await self._ensure_channel_capture(- new_bridge, external_channel_id, resolved_channel_type- )- await self._matrix_admin.invite_to_room(- matrix_room_id, new_bridge._bridge_client_matrix_user_id- )+ new_bridge.add_room_mapping(+ room_id, matrix_room_id, external_channel_id+ )+ finally:+ new_bridge.end_provisioning(external_channel_id)- if resolved_channel_type not in ("direct", "group"):- agent_names = await self._resolve_ids_to_names(agent_ids)- await new_bridge.adapter.add_agents_to_channel(- external_channel_id, agent_names+ await self._ensure_channel_capture(+ new_bridge, external_channel_id, resolved_channel_type)- logger.warning(- "Room %s moved to bridge %s: re-added %d agent(s) to channel "- "%s, but human users were NOT carried over (identities are "- "bridge-specific) — re-invite them to the new channel manually.",- room_id,- bridge_id,- len(agent_names),- external_channel_id,+ await self._matrix_admin.invite_to_room(+ matrix_room_id, new_bridge._bridge_client_matrix_user_id)- if old_bridge_id:- old_bridge = self._collab_lifecycle.get(old_bridge_id)- if old_bridge is not None:- old_bridge.remove_room_mapping(room_id, matrix_room_id)- await self._matrix_admin.kick_user(- matrix_room_id, old_bridge._bridge_client_matrix_user_id+ if resolved_channel_type not in ("direct", "group"):+ agent_names = await self._resolve_ids_to_names(agent_ids)+ await new_bridge.adapter.add_agents_to_channel(+ external_channel_id, agent_names+ )+ logger.warning(+ "Room %s moved to bridge %s: re-added %d agent(s) to channel "+ "%s, but human users were NOT carried over (identities are "+ "bridge-specific) — re-invite them to the new channel manually.",+ room_id,+ bridge_id,+ len(agent_names),+ external_channel_id,+ )++ if old_bridge_id:+ old_bridge = self._collab_lifecycle.get(old_bridge_id)+ if old_bridge is not None:+ old_bridge.remove_room_mapping(room_id, matrix_room_id)+ await self._matrix_admin.kick_user(+ matrix_room_id, old_bridge._bridge_client_matrix_user_id+ )+ logger.warning(+ "Room %s moved from bridge %s to %s; old external channel %s "+ "left in place on its platform (no adapter teardown) and is "+ "no longer synced — archive or delete it manually if "+ "desired.",+ room_id,+ old_bridge_id,+ bridge_id,+ old_external_channel_id,)- logger.warning(- "Room %s moved from bridge %s to %s; old external channel %s "- "left in place on its platform (no adapter teardown) and is no "- "longer synced — archive or delete it manually if desired.",- room_id,- old_bridge_id,- bridge_id,- old_external_channel_id,- )logger.info("Changed bridge for room %s: %s -> %s (new channel %s)",@@ -1115,24 +1149,34 @@ class RoomService:DB membership is only recorded where it is missing."""system_clients = self._resolve_system_clients()- async with self._session_factory() as session:+ # Every tenant's rooms in one pass at startup, so this read is+ # unscoped by nature; each room's own tenant is bound only around+ # reconciling that one room, not the whole fan-out.+ async with unscoped_session(self._session_factory) as session:rooms = await self._room_store.get_all(session, include_archived=True)for room in rooms:- async with self._session_factory() as session:- existing = set(await self._room_store.get_client_ids(session, room.id))- expected = await self._room_store.get_member_agent_clients(- session, room.id+ with tenant_scope(room.tenant_id):+ async with self._session_factory() as session:+ existing = set(+ await self._room_store.get_client_ids(session, room.id)+ )+ expected = await self._room_store.get_member_agent_clients(+ session, room.id+ )+ expected.update(system_clients)+ missing = {+ cid: uid for cid, uid in expected.items() if cid not in existing+ }+ if not missing:+ continue+ await self._invite_clients(room.matrix_room_id, missing)+ async with self._session_factory() as session:+ for client_id in missing:+ await self._room_store.add_client(session, client_id, room.id)+ await session.commit()+ logger.info(+ "Reconciled %d client(s) into room %s", len(missing), room.id)- expected.update(system_clients)- missing = {cid: uid for cid, uid in expected.items() if cid not in existing}- if not missing:- continue- await self._invite_clients(room.matrix_room_id, missing)- async with self._session_factory() as session:- for client_id in missing:- await self._room_store.add_client(session, client_id, room.id)- await session.commit()- logger.info("Reconciled %d client(s) into room %s", len(missing), room.id)async def ensure_client_in_room(self, room_id: str, client_id: str) -> None:"""Invite a single running client to the room (it auto-joins) and record@@ -1150,11 +1194,16 @@ class RoomService:if client is None:raise ValueError(f"No running client: {client_id}")- await self._matrix_admin.invite_to_room(- room.matrix_room_id, client.matrix_user_id- )+ # The invite itself writes a membership row and an arrival message+ # scoped to this room's tenant (PostgresProvisioning.invite_to_room),+ # so it is bound here alongside the membership record below rather+ # than left to whatever tenant happened to already be ambient.+ with tenant_scope(room.tenant_id):+ await self._matrix_admin.invite_to_room(+ room.matrix_room_id, client.matrix_user_id+ )- if not already_member:- async with self._session_factory() as session:- await self._room_store.add_client(session, client_id, room_id)- await session.commit()+ if not already_member:+ async with self._session_factory() as session:+ await self._room_store.add_client(session, client_id, room_id)+ await session.commit()diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex 822d1ef02..5734f1c63 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -42,8 +42,10 @@ from typing import TYPE_CHECKING, Anyfrom switch_core.attachments import ATTACHMENT_GROUP_KEYfrom switch_core.db.models import ClientRoom, MediaBlob, Message, MessageAttachment+from switch_core.db.session_scope import tenant_sessionfrom switch_core.messages.recorded_types import EPHEMERALfrom switch_core.messages.row import attachments_in, text_field, thread_root_of+from switch_core.tenant_context import tenant_scopefrom switch_core.transport.content import media_content, message_contentfrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus@@ -139,6 +141,14 @@ class PostgresTransport:# A room's transport id never changes, so this only grows and never# goes stale.self._room_ids: dict[str, str] = {}+ # Switch room id -> the tenant that room belongs to. Populated by the+ # same lookup that fills `_room_ids`, from the same row — a room's+ # tenant is as immutable as its transport id, unlike this client's own+ # tenant, which is not: a client can be in rooms of different+ # tenants, so nothing here is ever read as "this transport's tenant".+ # Each unit of work (one delivery, one send) binds the room it is+ # actually for.+ self._room_tenants: dict[str, str] = {}# ── Session ───────────────────────────────────────────────────────────────@@ -328,24 +338,35 @@ class PostgresTransport:transport_room_id = self._watching.get(room_id)if transport_room_id is None:return- while True:- async with self._session_factory() as session:- rows = await self._message_store.list_for_room(- session,- room_id,- after_seq=self._cursors[room_id],- limit=_DELIVERY_PAGE,- )- attachments = await self._message_store.attachments_for(- session, [row.id for row in rows]- )- if not rows:- return- for row in rows:- self._cursors[room_id] = row.seq- await self._deliver(transport_room_id, row, attachments.get(row.id, []))- if len(rows) < _DELIVERY_PAGE:- return+ # `_watch` cannot have set up delivery for this room without already+ # resolving it, which is what fills this in — see `_resolve_room`.+ tenant_id = self._room_tenants[room_id]+ # Bound for the read *and* the delivery below: a handler (posting to a+ # bridge, gating a command) opens its own sessions rather than reusing+ # this one, and those still need the room's tenant. The contextvar+ # covers them because they run in this same task, not because they+ # share a session with the read.+ with tenant_scope(tenant_id):+ while True:+ async with self._session_factory() as session:+ rows = await self._message_store.list_for_room(+ session,+ room_id,+ after_seq=self._cursors[room_id],+ limit=_DELIVERY_PAGE,+ )+ attachments = await self._message_store.attachments_for(+ session, [row.id for row in rows]+ )+ if not rows:+ return+ for row in rows:+ self._cursors[room_id] = row.seq+ await self._deliver(+ transport_room_id, row, attachments.get(row.id, [])+ )+ if len(rows) < _DELIVERY_PAGE:+ returnasync def _deliver(self,@@ -462,8 +483,8 @@ class PostgresTransport:)return result- async with self._session_factory() as session:- room_id = await self._resolve_room(session, transport_room_id)+ room_id, tenant_id = await self._resolve_room_and_tenant(transport_room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:message = Message(room_id=room_id,transport_event_id=result.event_id,@@ -572,8 +593,8 @@ class PostgresTransport:reads, with no later join able to repair it. So the row is writtenonce and the subscription is taken whenever it is missing."""- async with self._session_factory() as session:- switch_room_id = await self._resolve_room(session, room_id)+ switch_room_id, tenant_id = await self._resolve_room_and_tenant(room_id)+ async with tenant_session(self._session_factory, tenant_id) as session:existing = await session.get(ClientRoom, {"client_id": self.client_id, "room_id": switch_room_id})@@ -620,6 +641,14 @@ class PostgresTransport:# ── Internals ─────────────────────────────────────────────────────────────async def _resolve_room(self, session: AsyncSession, transport_room_id: str) -> str:+ """The Switch room id for `transport_room_id`, resolved and cached.++ No tenant is bound on `session` yet when this runs the first time for+ a room — resolving which room (and so which tenant) this is is the+ thing that determines one, the same bootstrap as authenticating a+ request. It caches the tenant alongside the id from the very same+ row, so nothing downstream needs a second unscoped read to learn it.+ """cached = self._room_ids.get(transport_room_id)if cached is not None:return cached@@ -627,8 +656,24 @@ class PostgresTransport:if room is None:raise TransportError(f"{transport_room_id} is not a Switch room")self._room_ids[transport_room_id] = room.id+ self._room_tenants[room.id] = room.tenant_idreturn room.id+ async def _resolve_room_and_tenant(self, transport_room_id: str) -> tuple[str, str]:+ """Like `_resolve_room`, but for a caller about to bind the tenant it+ returns rather than reuse the session that resolved it.++ Opens its own short-lived, unscoped session only on a cache miss —+ the same one-time bootstrap `_resolve_room` always needed. Once+ cached, resolving costs nothing: no session, no query.+ """+ cached = self._room_ids.get(transport_room_id)+ if cached is not None:+ return cached, self._room_tenants[cached]+ async with self._session_factory() as session:+ room_id = await self._resolve_room(session, transport_room_id)+ return room_id, self._room_tenants[room_id]+def to_inbound(row: Message,diff --git a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.pyindex 37addab8d..6a63521d9 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_runtime_state_sweep.py@@ -113,7 +113,9 @@ def _connected(room: str | None) -> ConnectionRegistry:def _row() -> Any:- return SimpleNamespace(agent_id=AGENT, room_id=ROOM, state="working")+ return SimpleNamespace(+ agent_id=AGENT, room_id=ROOM, state="working", tenant_id="tenant-1"+ )async def test_a_live_connection_in_the_room_is_left_alone() -> None:diff --git a/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.pynew file mode 100644index 000000000..f20959e24--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_sweep_runtime_states_tenant_binding.py@@ -0,0 +1,158 @@+"""`ProtocolService.sweep_runtime_states` (CHOO-2623) spans every tenant by+nature: one pass resets every stale runtime-state row anywhere, so the read+that finds them is unscoped. Each row is itself tenant-scoped, so the rest of+the work for that row — the liveness check and the reset — binds that row's+own tenant, one at a time, rather than the whole sweep.++This pins the two things that matter about that: each row's write is bound to+its own tenant, and a row from one tenant cannot leak its binding into the+next row's work, even when the two are processed back to back in the same+sweep.+"""++from __future__ import annotations++import uuid++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.db.models import (+ Agent,+ AgentRuntimeState,+ ApiKey,+ Client,+ Room,+ Tenant,+ User,+)+from switch_core.db.stores.agent_runtime_state_store import AgentRuntimeStateStore+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+from switch_core.tenant_context import current_tenant_id+++def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:+ svc = object.__new__(ProtocolService)+ svc.session_factory = session_factory # type: ignore[attr-defined]+ # Nothing is registered, so every agent/room pair reads as not live —+ # the sweep's job is exactly to reset those.+ svc.connections = ConnectionRegistry() # type: ignore[attr-defined]+ svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]+ svc.agent_store = AgentStore() # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc.agent_runtime_state_store = AgentRuntimeStateStore() # type: ignore[attr-defined]++ async def _no_emit(**_kwargs: object) -> None:+ return None++ svc._emit_runtime_state = _no_emit # type: ignore[attr-defined,method-assign]++ async def _no_mention(*_args: object, **_kwargs: object) -> None:+ return None++ svc._mention_handle_for = _no_mention # type: ignore[attr-defined,method-assign]+ return svc+++async def _make_tenant(session: AsyncSession, tenant_id: str) -> None:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()+++async def _make_stale_runtime_state(+ session: AsyncSession, *, tenant_id: str+) -> tuple[str, str]:+ """A `working` row with no live agent session or connection behind it —+ exactly what the sweep exists to find. Returns (agent_id, room_id)."""+ suffix = uuid.uuid4().hex[:8]+ owner = User(name=f"owner-{suffix}", email=f"owner-{suffix}@test", role="user")+ session.add(owner)+ await session.flush()+ api_key = ApiKey(+ tenant_id=tenant_id,+ user_id=owner.id,+ key_hash=f"hash-{suffix}",+ encrypted_key="enc",+ label="k",+ type="agent",+ )+ client = Client(+ tenant_id=tenant_id,+ matrix_user_id=f"@agent-{suffix}:test",+ display_name="agent",+ type="agent",+ )+ session.add_all([api_key, client])+ await session.flush()+ agent = Agent(+ tenant_id=tenant_id,+ name=f"agent-{suffix}",+ description="d",+ agent_type="session_addressable",+ connector_type="external",+ integration_profile={"connection_model": "session_passive"},+ client_id=client.id,+ api_key_id=api_key.id,+ )+ session.add(agent)+ room = Room(+ tenant_id=tenant_id,+ matrix_room_id=f"!room-{suffix}:test",+ name="room",+ description="d",+ )+ session.add(room)+ await session.flush()+ session.add(+ AgentRuntimeState(+ tenant_id=tenant_id,+ agent_id=agent.id,+ room_id=room.id,+ state="working",+ )+ )+ await session.flush()+ return agent.id, room.id+++async def test_sweep_binds_each_row_s_own_tenant_and_does_not_leak(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ await _make_tenant(session, tenant_a)+ await _make_tenant(session, tenant_b)+ agent_a, room_a = await _make_stale_runtime_state(session, tenant_id=tenant_a)+ agent_b, room_b = await _make_stale_runtime_state(session, tenant_id=tenant_b)+ await session.commit()++ seen: dict[str, str | None] = {}+ original_upsert = AgentRuntimeStateStore.upsert++ async def _spy_upsert(self, session, agent_id, room_id, state, *args, **kwargs):+ seen[agent_id] = current_tenant_id()+ return await original_upsert(+ self, session, agent_id, room_id, state, *args, **kwargs+ )++ AgentRuntimeStateStore.upsert = _spy_upsert # type: ignore[method-assign]+ try:+ service = _service(session_factory)+ assert current_tenant_id() is None+ await service.sweep_runtime_states()+ assert current_tenant_id() is None+ finally:+ AgentRuntimeStateStore.upsert = original_upsert # type: ignore[method-assign]++ assert seen == {agent_a: tenant_a, agent_b: tenant_b}++ async with session_factory() as session:+ store = AgentRuntimeStateStore()+ row_a = await store.get(session, agent_a, room_a)+ row_b = await store.get(session, agent_b, room_b)+ assert row_a is not None and row_a.state == "idle"+ assert row_b is not None and row_b.state == "idle"diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.pyindex 0d502a6bf..156104360 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_channel_migration.py@@ -70,7 +70,9 @@ def _make_bridge(rooms: dict[str, SimpleNamespace]) -> BridgeCore:def _room(room_id: str = "room-uuid") -> SimpleNamespace:- return SimpleNamespace(id=room_id, matrix_room_id=f"!{room_id}:switch.local")+ return SimpleNamespace(+ id=room_id, tenant_id="tenant-1", matrix_room_id=f"!{room_id}:switch.local"+ )def test_the_handler_is_installed_before_the_adapter_starts() -> None:diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.pyindex e12480ad9..e40cca85d 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py@@ -19,7 +19,9 @@ def _make_bridge(**overrides: Any) -> BridgeCore:"""A BridgeCore with only the attributes the auto-room-creation pathtouches, so the real methods run without the full dependency graph."""created_configs: list[Any] = []- room = SimpleNamespace(id="room-uuid", matrix_room_id="!m:switch.local")+ room = SimpleNamespace(+ id="room-uuid", tenant_id="tenant-1", matrix_room_id="!m:switch.local"+ )async def create_room(config: Any) -> SimpleNamespace:created_configs.append(config)@@ -41,6 +43,7 @@ def _make_bridge(**overrides: Any) -> BridgeCore:bridge._provisioning_channels = set()bridge._channel_to_room = {}bridge._room_to_channel = {}+ bridge._room_tenants = {}bridge._channel_locks = {}bridge._bridge_id = "bridge-1"bridge._bridge_display_name = "Switch"@@ -163,7 +166,9 @@ async def test_app_join_during_provisioning_creates_no_room() -> None:async def test_adopt_existing_room_registers_mapping() -> None:# The real _adopt_existing_room: a DB hit registers the in-memory mapping# and returns the room, so subsequent lookups short-circuit.- room = SimpleNamespace(id="db-room", matrix_room_id="!db:switch.local")+ room = SimpleNamespace(+ id="db-room", tenant_id="tenant-1", matrix_room_id="!db:switch.local"+ )class _Session:async def __aenter__(self) -> _Session:@@ -181,6 +186,7 @@ async def test_adopt_existing_room_registers_mapping() -> None:bridge = BridgeCore.__new__(BridgeCore)bridge._channel_to_room = {}bridge._room_to_channel = {}+ bridge._room_tenants = {}bridge._bridge_id = "bridge-1"bridge._session_factory = _Session # type: ignore[assignment]bridge._room_store = _RoomStore() # type: ignore[assignment]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.pyindex 019ba27f3..19d4f50ad 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py@@ -23,7 +23,9 @@ from switch_core.bridges.collaboration.telegram.adapter import (def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqa: ANN202notices: list[tuple[str, str, str | None]] = []- room = SimpleNamespace(id="room-uuid", matrix_room_id="!m:switch.local")+ room = SimpleNamespace(+ id="room-uuid", tenant_id="tenant-1", matrix_room_id="!m:switch.local"+ )class _Adapter:def slash_invite_hint(self) -> str | None:@@ -67,6 +69,7 @@ def _fake_bridge(*, agent_ids: list[str], slash_hint: str | None = None): # noqadd_room_mapping=add_room_mapping,_provisioning_channels=set(),_channel_to_room={},+ _room_tenants={},_bridge_display_name="Switch",_bridge_id="bridge-1",notices=notices,diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.pyindex 1ffa1a677..97156798f 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_admin_rendering.py@@ -70,6 +70,8 @@ def _bridge(adapter: _RecordingAdapter) -> BridgeCore:core._puppet_matrix_ids = set() # type: ignore[assignment]core._bridge_client_matrix_user_id = "@bridge:switch.local" # type: ignore[assignment]core._find_channel = lambda **_kwargs: "C1" # type: ignore[assignment]+ core._channel_to_room = {"C1": ("room-uuid", "!r:switch.local")} # type: ignore[assignment]+ core._room_tenant = _tenant # type: ignore[assignment]core._record_message_map = _noop # type: ignore[assignment]core._move_indicator_for_sender = _noop # type: ignore[assignment]core._outbound_thread_root_ref = _none # type: ignore[assignment]@@ -84,6 +86,10 @@ async def _none(*_args: Any, **_kwargs: Any) -> None:return None+async def _tenant(*_args: Any, **_kwargs: Any) -> str:+ return "tenant-1"++def _event(*, admin: bool) -> InboundMessage:content: dict[str, Any] = {}if admin:diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.pyindex 3438b6c94..7b9ab498c 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_outbound_media.py@@ -134,6 +134,9 @@ def _fake_bridge(async def _record_message_map(**kwargs: str) -> None:recorded.append(kwargs)+ async def _room_tenant(room_id: str) -> str:+ return "tenant-1"+ns = SimpleNamespace(_adapter=adapter,_puppet_matrix_ids={"@puppet:s"},@@ -145,6 +148,8 @@ def _fake_bridge(_outbound_groups={},_outbound_group_timers={},_indicator_move_timers={},+ _channel_to_room={"chan-1": ("room-uuid", "!room:s")},+ _room_tenant=_room_tenant,)ns._find_channel = lambda room_id=None, matrix_room_id=None: ("chan-1" if matrix_room_id == "!room:s" else None@@ -158,6 +163,7 @@ def _fake_bridge(ns)ns._relay_outbound_group = BridgeCore._relay_outbound_group.__get__(ns)+ ns._relay_outbound_media = BridgeCore._relay_outbound_media.__get__(ns)ns._move_indicator_for_sender = BridgeCore._move_indicator_for_sender.__get__(ns)ns._schedule_indicator_move = BridgeCore._schedule_indicator_move.__get__(ns)ns._flush_incomplete_outbound_group = (diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.pyindex 2ecd902ce..9529a58a7 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_runtime_state_thread.py@@ -65,17 +65,23 @@ def _bridge(*, follows_anchor: bool, posts: dict[str, str]) -> Any:async def external_post_for_matrix_event(event_id: str) -> str | None:return posts.get(event_id)+ async def room_tenant(room_id: str) -> str:+ return "tenant-1"+ns = SimpleNamespace(_adapter=adapter,_indicator_move_timers={},_indicator_move_targets={},_reported_anchors={},_find_channel=lambda **kwargs: "chan-1",+ _channel_to_room={"chan-1": ("room-1", "!room:switch.local")},+ _room_tenant=room_tenant,_external_post_for_matrix_event=external_post_for_matrix_event,adapter_spy=adapter,)for name in ("handle_agent_runtime_state",+ "_apply_runtime_state","_follow_reported_anchor","_schedule_indicator_move","_run_indicator_move",diff --git a/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.pynew file mode 100644index 000000000..55ff174b9--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_lifecycle_tenant_binding.py@@ -0,0 +1,133 @@+"""`CollaborationBridgeLifecycleService.start_all` (CHOO-2623): starting every+bridge at boot has no request behind it, and it fans out across every+tenant's bridges in one pass — so the read that finds them has to be+unscoped, and each bridge's own tenant is what gets bound, not the whole+sweep. `start` spawns the bridge's long-lived task while that binding is+still active, so the task keeps it for its own life (an asyncio task+snapshots the context it was created under).++This does not exercise a real bridge — `start` here is stubbed to record what+tenant was bound when it was called, which is the only thing `start_all`+itself is responsible for getting right.+"""++from __future__ import annotations++import uuid+from unittest.mock import MagicMock++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.collaboration.lifecycle_service import (+ CollaborationBridgeLifecycleService,+)+from switch_core.db.models import Client, CollaborationBridge, Tenant+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.tenant_context import current_tenant_id+++def _service(+ session_factory: async_sessionmaker[AsyncSession],+) -> CollaborationBridgeLifecycleService:+ return CollaborationBridgeLifecycleService(+ bridge_store=CollaborationBridgeStore(),+ external_user_store=MagicMock(),+ bridge_message_map_store=MagicMock(),+ room_store=RoomStore(),+ agent_store=MagicMock(),+ client_store=ClientStore(),+ client_lifecycle=MagicMock(),+ room_service=MagicMock(),+ matrix_admin=MagicMock(),+ session_factory=session_factory,+ config=MagicMock(),+ client_factory=MagicMock(),+ )+++async def _make_tenant(session: AsyncSession, tenant_id: str) -> None:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()+++async def _make_bridge(session: AsyncSession, *, tenant_id: str) -> str:+ client = Client(+ tenant_id=tenant_id,+ matrix_user_id=f"@bridge-{uuid.uuid4().hex[:8]}:test",+ display_name="bridge client",+ type="bridge",+ )+ session.add(client)+ await session.flush()+ bridge = CollaborationBridge(+ tenant_id=tenant_id,+ type="mattermost",+ display_name="MM",+ client_id=client.id,+ status="active",+ )+ session.add(bridge)+ await session.flush()+ return bridge.id+++async def test_start_all_binds_each_bridge_s_own_tenant_and_does_not_leak(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ await _make_tenant(session, tenant_a)+ await _make_tenant(session, tenant_b)+ bridge_a = await _make_bridge(session, tenant_id=tenant_a)+ bridge_b = await _make_bridge(session, tenant_id=tenant_b)+ await session.commit()++ service = _service(session_factory)+ seen: dict[str, str | None] = {}++ async def _fake_start(bridge_id: str) -> None:+ seen[bridge_id] = current_tenant_id()++ service.start = _fake_start # type: ignore[method-assign]++ # Nothing bound going in, and nothing bound coming out: start_all is+ # itself reached with no request behind it.+ assert current_tenant_id() is None+ await service.start_all()+ assert current_tenant_id() is None++ assert seen == {bridge_a: tenant_a, bridge_b: tenant_b}+++async def test_a_failing_bridge_still_releases_its_tenant_for_the_next_one(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """start_all logs and continues past a bridge that fails to start+ (bridge_core.py's own behaviour); the tenant binding must not survive+ the exception either, or the next bridge in the loop inherits it."""+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ await _make_tenant(session, tenant_a)+ await _make_tenant(session, tenant_b)+ bridge_a = await _make_bridge(session, tenant_id=tenant_a)+ bridge_b = await _make_bridge(session, tenant_id=tenant_b)+ await session.commit()++ service = _service(session_factory)+ seen: dict[str, str | None] = {}++ async def _fake_start(bridge_id: str) -> None:+ seen[bridge_id] = current_tenant_id()+ if bridge_id == bridge_a:+ raise RuntimeError("boom")++ service.start = _fake_start # type: ignore[method-assign]++ await service.start_all()++ assert seen == {bridge_a: tenant_a, bridge_b: tenant_b}+ assert current_tenant_id() is Nonediff --git a/core/tests/switch_core/db/test_session_scope.py b/core/tests/switch_core/db/test_session_scope.pynew file mode 100644index 000000000..d8b038d5c--- /dev/null+++ b/core/tests/switch_core/db/test_session_scope.py@@ -0,0 +1,108 @@+"""`tenant_session` and `unscoped_session` (`db/session_scope.py`): the two+named ways background code may open a session with no request behind it.++`tenant_session` is sugar over `tenant_context.bind_tenant_id` plus opening a+session, so what these tests pin is the composition — bound inside the block,+released on the way out, even on an exception — rather than the binding+mechanics themselves, which `test_tenant_session_hook.py` already covers.+`unscoped_session` does nothing at all beyond calling the factory; it is+tested here for what it does *not* do — bind anything — and its callers are+pinned separately, in `test_unscoped_session_allowlist.py`.+"""++from __future__ import annotations++import pytest+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.session_scope import tenant_session, unscoped_session+from switch_core.tenant_context import current_tenant_id, tenant_scope++TENANT_A = "tenant-session-scope-a"+TENANT_B = "tenant-session-scope-b"+++async def _current_setting(session: AsyncSession) -> str | None:+ result = await session.execute(+ text("SELECT current_setting('app.tenant_id', true)")+ )+ value = result.scalar_one()+ return value or None+++class TestTenantSession:+ async def test_the_tenant_is_bound_inside_the_block(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with tenant_session(session_factory, TENANT_A) as session:+ assert current_tenant_id() == TENANT_A+ assert await _current_setting(session) == TENANT_A+ await session.commit()++ async def test_the_tenant_is_unbound_once_the_block_exits(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ assert current_tenant_id() is None+ async with tenant_session(session_factory, TENANT_A):+ pass+ assert current_tenant_id() is None++ async def test_an_exception_still_unbinds(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ with pytest.raises(RuntimeError, match="boom"):+ async with tenant_session(session_factory, TENANT_A):+ raise RuntimeError("boom")+ assert current_tenant_id() is None++ async def test_it_restores_an_outer_binding_rather_than_clearing_it(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A call site reached from an already-tenant-bound context (a+ request, an outer tenant_scope) must not leave that context's own+ tenant cleared once its own, possibly-redundant, binding ends."""+ with tenant_scope(TENANT_A):+ async with tenant_session(session_factory, TENANT_B):+ assert current_tenant_id() == TENANT_B+ assert current_tenant_id() == TENANT_A+ assert current_tenant_id() is None++ async def test_sequential_uses_do_not_leak_into_each_other(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with tenant_session(session_factory, TENANT_A) as session:+ assert await _current_setting(session) == TENANT_A+ await session.commit()+ async with tenant_session(session_factory, TENANT_B) as session:+ assert await _current_setting(session) == TENANT_B+ await session.commit()+++class TestUnscopedSession:+ async def test_no_tenant_is_bound_when_nothing_was_bound_going_in(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with unscoped_session(session_factory) as session:+ assert current_tenant_id() is None+ assert await _current_setting(session) is None++ async def test_it_neither_binds_nor_clears_an_outer_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """It is not a "no tenant" guarantee, only a "no new binding" one —+ the docstring is explicit that this is not force-unscoped. A caller+ already inside a bound context keeps seeing that context's tenant."""+ with tenant_scope(TENANT_A):+ async with unscoped_session(session_factory) as session:+ assert current_tenant_id() == TENANT_A+ assert await _current_setting(session) == TENANT_A+ assert current_tenant_id() is None++ async def test_current_tenant_id_is_unchanged_after_the_block(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ assert current_tenant_id() is None+ async with unscoped_session(session_factory):+ pass+ assert current_tenant_id() is Nonediff --git a/core/tests/switch_core/db/test_unscoped_session_allowlist.py b/core/tests/switch_core/db/test_unscoped_session_allowlist.pynew file mode 100644index 000000000..865c94181--- /dev/null+++ b/core/tests/switch_core/db/test_unscoped_session_allowlist.py@@ -0,0 +1,145 @@+"""`unscoped_session` (`db/session_scope.py`) is the fail-open hatch: a session+with no tenant bound at all, for the handful of things that are legitimately+cross-tenant — a sweep or lifecycle enumeration reading every row before+fanning out per-row work, and startup seeding that runs before any tenant can+be said to exist.++Nothing stops a query on a session it opens from reading across every tenant+there is, so its callers are the audit surface for that risk. This test pins+them to an explicit allowlist, derived from the source tree rather than+imports, so a module that only calls it conditionally or inside a string is+still caught. A new module failing here is not a bug in the test: it means+someone reached for the cross-tenant escape hatch, and either that is a+deliberate, reviewable choice — in which case add the module to+`_ALLOWED_MODULES` in the same change, saying why in the commit — or it is+not, in which case use `tenant_session` instead.+"""++from __future__ import annotations++import ast+from pathlib import Path++import switch_core++# Every module allowed to call `unscoped_session`. Keep this short: it is the+# whole list of places in the process that may read across every tenant.+_ALLOWED_MODULES = {+ # Startup seeding: the admin user and the agent-registration bootstrap+ # owner/key are created before any tenant can be said to exist.+ "switch_core.main",+ # Reconciling every room's client membership at startup fans out across+ # every tenant's rooms; each room's own tenant is bound for its own work.+ "switch_core.room_service",+ # The runtime-state sweep reads every tenant's stale rows in one pass;+ # each row's own tenant is bound before anything is done with it.+ "switch_core.bridges.agent.protocol.service",+ # Starting every collaboration bridge at boot reads every tenant's rows in+ # one pass; each bridge's own tenant is bound before it is started.+ "switch_core.bridges.collaboration.lifecycle_service",+ # Same as above, for server-side connectors.+ "switch_core.bridges.agent.server_connectors.lifecycle",+ # Same as above, for the generic client registry (agent and admin+ # clients) started at boot.+ "switch_core.clients.client_lifecycle_service",+}++_PACKAGE_ROOT = Path(switch_core.__file__).resolve().parent+++def _module_name(path: Path) -> str:+ relative = path.relative_to(_PACKAGE_ROOT.parent)+ parts = list(relative.with_suffix("").parts)+ if parts[-1] == "__init__":+ parts = parts[:-1]+ return ".".join(parts)+++def _calls_unscoped_session(path: Path) -> bool:+ """Whether `path` contains a call to a function literally named+ `unscoped_session`, anywhere — a call, an alias, a re-export."""+ tree = ast.parse(path.read_text(), filename=str(path))+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)+ if name == "unscoped_session":+ return True+ return False+++def _modules_calling_unscoped_session() -> set[str]:+ found = set()+ for path in _PACKAGE_ROOT.rglob("*.py"):+ if path.name == "session_scope.py" and path.parent.name == "db":+ continue # the definition itself, not a caller+ if _calls_unscoped_session(path):+ found.add(_module_name(path))+ return found+++def test_only_the_allowed_modules_call_unscoped_session() -> None:+ found = _modules_calling_unscoped_session()+ unexpected = found - _ALLOWED_MODULES+ assert not unexpected, (+ f"{sorted(unexpected)} call unscoped_session but are not in "+ "_ALLOWED_MODULES in this test. That helper is the fail-open hatch "+ "for cross-tenant work (db/session_scope.py) — if this new call site "+ "is genuinely cross-tenant (a sweep, an enumeration, startup "+ "seeding), add its module to _ALLOWED_MODULES and say why in the "+ "commit; otherwise use tenant_session and bind the tenant the work "+ "is actually for."+ )+++def test_the_allowlist_names_no_stale_module() -> None:+ """The other direction: every allowed module still actually uses it,+ so the list stays the audit surface it claims to be rather than growing+ entries nobody needs."""+ found = _modules_calling_unscoped_session()+ stale = _ALLOWED_MODULES - found+ assert not stale, f"{sorted(stale)} no longer call unscoped_session; remove them"+++class TestDetectionCatchesANewCaller:+ """The two tests above only prove today's tree is clean. This exercises+ the detector itself against a file that is not in the real source tree+ at all, so it stands on its own even if every real call site above is+ later removed."""++ def test_a_plain_call_is_detected(self, tmp_path: Path) -> None:+ new_caller = tmp_path / "a_new_background_job.py"+ new_caller.write_text(+ "async def sweep(session_factory):\n"+ " async with unscoped_session(session_factory) as session:\n"+ " ...\n"+ )+ assert _calls_unscoped_session(new_caller)++ def test_an_aliased_import_is_still_detected(self, tmp_path: Path) -> None:+ new_caller = tmp_path / "a_new_background_job.py"+ new_caller.write_text(+ "from switch_core.db.session_scope import unscoped_session as us\n"+ "async def sweep(session_factory):\n"+ " async with us(session_factory) as session:\n"+ " ...\n"+ )+ assert not _calls_unscoped_session(new_caller), (+ "an aliased import is a known gap: the detector matches the "+ "literal name unscoped_session, not what it resolves to"+ )++ def test_a_module_with_no_call_is_not_flagged(self, tmp_path: Path) -> None:+ clean = tmp_path / "an_unrelated_module.py"+ clean.write_text("async def do_work(session_factory):\n ...\n")+ assert not _calls_unscoped_session(clean)++ def test_the_allowlist_check_would_fail_for_a_hypothetical_new_caller(self) -> None:+ """Simulates what `test_only_the_allowed_modules_call_unscoped_session`+ does, against a found-set that includes a module nobody added to+ `_ALLOWED_MODULES` — pinning that the check actually fails rather+ than, say, silently ignoring an unknown module."""+ found = _modules_calling_unscoped_session() | {"switch_core.a_new_sweep"}+ unexpected = found - _ALLOWED_MODULES+ assert unexpected == {"switch_core.a_new_sweep"}diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.pyindex 8424d9178..f4262e501 100644--- a/core/tests/switch_core/test_room_service_change_bridge.py+++ b/core/tests/switch_core/test_room_service_change_bridge.py@@ -177,6 +177,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="A room",matrix_room_id="!mx:switch.local",@@ -233,6 +234,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Secret",description="d",matrix_room_id="!mx:switch.local",@@ -261,6 +263,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Internal",description="d",matrix_room_id="!mx:switch.local",@@ -291,6 +294,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="A room",matrix_room_id="!mx:switch.local",@@ -333,6 +337,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="d",matrix_room_id="!mx:switch.local",@@ -359,6 +364,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="d",matrix_room_id="!mx:switch.local",@@ -381,6 +387,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="d",matrix_room_id="!mx:switch.local",@@ -406,6 +413,7 @@ class TestChangeBridge:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="d",matrix_room_id="!mx:switch.local",@@ -444,6 +452,7 @@ class TestLinkBridgeToRoom:def _room(self) -> Any:return SimpleNamespace(id="room-1",+ tenant_id="room-tenant",name="Work",description="d",matrix_room_id="!mx:switch.local",diff --git a/core/tests/switch_core/test_room_service_delete_room.py b/core/tests/switch_core/test_room_service_delete_room.pyindex fdabbab61..87e6d94dc 100644--- a/core/tests/switch_core/test_room_service_delete_room.py+++ b/core/tests/switch_core/test_room_service_delete_room.py@@ -93,6 +93,7 @@ class TestDeleteRoom:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",matrix_room_id="!mx:switch.local",bridge_id="bridge-x",external_channel_id="chan-x",@@ -116,6 +117,7 @@ class TestDeleteRoom:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",matrix_room_id="!mx:switch.local",bridge_id=None,external_channel_id=None,@@ -137,6 +139,7 @@ class TestDeleteRoom:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",matrix_room_id="!mx:switch.local",bridge_id="bridge-gone",external_channel_id="chan-x",@@ -158,6 +161,7 @@ class TestDeleteRoom:events: list[Any] = []room = SimpleNamespace(id="room-1",+ tenant_id="room-tenant",matrix_room_id="!mx:switch.local",bridge_id=None,external_channel_id=None,diff --git a/core/tests/switch_core/test_room_service_reconcile.py b/core/tests/switch_core/test_room_service_reconcile.pyindex 090e49b2d..3d3a75123 100644--- a/core/tests/switch_core/test_room_service_reconcile.py+++ b/core/tests/switch_core/test_room_service_reconcile.py@@ -91,7 +91,9 @@ class TestReconcileRoomClients:async def test_backfills_missing_admin_into_existing_room(self) -> None:# A room created before the admin client existed: it has the other# system clients but not the admin. Reconcile invites + records it.- room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ room = SimpleNamespace(+ id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ )svc, room_store, matrix = _build_service(rooms=[room],client_ids_by_room={"room-1": ["resource-mgr", "observe"]},@@ -104,7 +106,9 @@ class TestReconcileRoomClients:assert room_store.added == [("admin-client", "room-1")]async def test_skips_room_that_already_has_the_admin(self) -> None:- room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ room = SimpleNamespace(+ id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ )svc, room_store, matrix = _build_service(rooms=[room],client_ids_by_room={"room-1": ["admin-client"]},@@ -118,8 +122,14 @@ class TestReconcileRoomClients:async def test_covers_archived_rooms_too(self) -> None:rooms = [- SimpleNamespace(id="live", matrix_room_id="!live:switch.local"),- SimpleNamespace(id="archived", matrix_room_id="!arch:switch.local"),+ SimpleNamespace(+ id="live", tenant_id="tenant-1", matrix_room_id="!live:switch.local"+ ),+ SimpleNamespace(+ id="archived",+ tenant_id="tenant-1",+ matrix_room_id="!arch:switch.local",+ ),]svc, room_store, matrix = _build_service(rooms=rooms,@@ -135,7 +145,9 @@ class TestReconcileRoomClients:assert ("admin-client", "archived") in room_store.addedasync def test_no_running_system_clients_is_a_noop(self) -> None:- room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ room = SimpleNamespace(+ id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ )svc, room_store, matrix = _build_service(rooms=[room],client_ids_by_room={"room-1": []},@@ -151,7 +163,9 @@ class TestReconcileRoomClients:# `add_agents_to_room` writes the membership row, invites, then records# `room_clients`. A crash in that window leaves the member with no# `room_clients` row, which is exactly what is repaired here.- room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ room = SimpleNamespace(+ id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ )svc, room_store, matrix = _build_service(rooms=[room],client_ids_by_room={"room-1": []},@@ -165,7 +179,9 @@ class TestReconcileRoomClients:assert room_store.added == [("agent-client", "room-1")]async def test_an_agent_already_recorded_is_left_alone(self) -> None:- room = SimpleNamespace(id="room-1", matrix_room_id="!mx:switch.local")+ room = SimpleNamespace(+ id="room-1", tenant_id="tenant-1", matrix_room_id="!mx:switch.local"+ )svc, room_store, matrix = _build_service(rooms=[room],client_ids_by_room={"room-1": ["agent-client"]},diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex 2373674d9..fb745d2c6 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -19,10 +19,11 @@ from collections.abc import Iteratorimport pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import Client, Room+from switch_core.db.models import Client, Room, Tenantfrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.tenant_context import current_tenant_idfrom switch_core.transport import (InboundCustomEvent,InboundMedia,@@ -858,3 +859,75 @@ class TestHearingYourOwnArrival:kinds = [type(event) for event in received.events]assert kinds == [InboundMembership]+++class TestDeliveryBindsTheRoomsTenant:+ """One delivery pass (`_drain_room`) is the transport's own unit of work+ for one room, and CHOO-2623 makes it bind that room's tenant — not+ something cached once on the transport or the client, since either can+ act for rooms in different tenants over its life."""++ @pytest.fixture(autouse=True)+ def _cleanup(self) -> Iterator[None]:+ self._tasks: list[asyncio.Task] = []+ yield+ for task in self._tasks:+ task.cancel()++ async def test_a_delivery_binds_the_room_s_own_tenant(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()+ suffix = uuid.uuid4().hex[:8]+ client = Client(+ tenant_id=tenant_id,+ matrix_user_id=f"@agent-{suffix}:test",+ display_name="agent one",+ type="agent",+ )+ session.add(client)+ room = Room(+ tenant_id=tenant_id,+ matrix_room_id=f"!room-{suffix}:test",+ name="a room",+ description="",+ )+ session.add(room)+ await session.commit()+ transport_room_id = room.matrix_room_id+ client_id, user_id = client.id, client.matrix_user_id++ seen: list[str | None] = []+ original = MessageStore.list_for_room++ async def _spy(self, session, room_id, **kwargs):+ seen.append(current_tenant_id())+ return await original(self, session, room_id, **kwargs)++ monkeypatch.setattr(MessageStore, "list_for_room", _spy)++ listener = _FakeListener()+ received = _Received()+ transport = _transport(+ session_factory, client_id=client_id, user_id=user_id, listener=listener+ )+ transport.register_handlers(received.handlers())+ await transport.join_room(transport_room_id)+ self._tasks.append(asyncio.create_task(transport.receive_forever()))+ switch_room_id = await _watched_room(transport)++ await transport.send_message(+ transport_room_id, "hello", sender_name="agent one"+ )+ await listener.announce(switch_room_id)++ assert [type(e) for e in received.events] == [InboundMessage]+ assert seen, "the delivery loop never read the room"+ assert all(tenant == tenant_id for tenant in seen)+ # Bound only for the read itself, not left dangling on the process.+ assert current_tenant_id() is Nonediff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.mdindex 954a5a90c..3a17e9ce4 100644--- a/docs/old/multi-tenancy-phase1-db.md+++ b/docs/old/multi-tenancy-phase1-db.md@@ -15,11 +15,13 @@ when" were all split out into a later change.**"Setting the tenant" has since been built** and that section now describeswhat was actually implemented, which differs from what it originally proposed —an event hook rather than a dependency at every call site, for reasons given-there. The background half of it, the roughly 206 session sites outside the-request path, is still outstanding. Read the remaining sections as the design-those later changes implement rather than as a description of what is running-today; "What Phase 1 does not close" says which gaps are this migration's and-which belong to the deferred work.+there. **The background half of it has since been built too** — the roughly+206 session sites outside the request path now bind a tenant, described where+"Setting the tenant" talks about background work below. Read the remaining+sections as the design those later changes implement rather than as a+description of what is running today; "What Phase 1 does not close" says which+gaps are this migration's and which belong to the deferred work — row-level+security is still the biggest of them.Postgres 16 everywhere — local Compose, the chart, and the test containers —and two things below need at least 15, so that is a floor, not an incidental@@ -353,12 +355,42 @@ silently discarded a password change. Resolution needs the subject id, not a`User` row — so it looks up only the membership, and the user is loaded fromthe session the endpoint actually commits.-**Background work is not a short list.** There are roughly 206 places that open-a session from the factory directly. They fall into three shapes — acting for a-room, acting for a bridge, acting for the deployment — so they get a named-helper for each, and a test that the raw factory is not called anywhere else.-Not yet done: those paths currently bind no tenant, which is harmless only-while nothing enforces.+**Background work is not a short list, and it has since been closed.** There+were roughly 206 places that opened a session from the factory directly, with+no request behind them. They fall into three shapes, each handled differently+rather than by one helper covering all of them:++- **Acting for a room** — the delivery loop (`transport/postgres.py`), most of+ `room_service.py`, the collaboration bridges' inbound and outbound handling+ (`bridges/collaboration/bridge_core.py`). Each derives the tenant from the+ room the unit of work is actually for — one delivery, one inbound event, one+ membership change — rather than caching it, because a client or a bridge is+ not guaranteed to act for only one tenant over its life. Resolving which+ room (and so which tenant) a unit of work is for is itself unscoped by+ necessity, the same bootstrap as resolving a principal below; each of these+ files caches the answer per room id once resolved, since a room's tenant+ cannot change, the same way each already cached the room's own id.+- **Acting for a bridge or connector** — `bridges/collaboration/lifecycle_service.py`+ and `bridges/agent/server_connectors/lifecycle.py` bind the bridge's or+ connector's own tenant once, around starting its long-lived task; the task+ keeps it for its life because an `asyncio.Task` snapshots the contextvar+ state it was created under.+- **Acting for the deployment** — startup seeding (`main.py`), the+ runtime-state sweep (`ProtocolService.sweep_runtime_states`), and the+ lifecycle enumerations that read every row before fanning out+ (`start_all` on both lifecycle services above, and on+ `ClientLifecycleService`). These read cross-tenant by nature; where they+ then act per row, they bind that row's own tenant rather than the tenant of+ the whole pass.++Two named helpers carry this: `tenant_session` (`db/session_scope.py`) binds a+given tenant and opens a session; `unscoped_session` opens one with nothing+bound at all — the fail-open hatch, named so a reader can tell at the call site+which one is meant, and used only by the "acting for the deployment" sites+above. `tests/switch_core/db/test_unscoped_session_allowlist.py` pins the+modules allowed to call it, deriving the list from the source tree rather than+from imports, so a new caller is a deliberate, reviewed act rather than an+accident.**Writes fill the column automatically.** `tenant_id` gets a Python-sidedefault reading the request's tenant, so ordinary ORM inserts need no change@@ -379,17 +411,29 @@ or a JWT subject to its memberships, is unscoped by definition. So:> **Authentication and tenant resolution run in a system session. Everything> downstream runs in a tenant session, as the restricted runtime role.**-The same escape hatch covers work that is legitimately cross-tenant: Alembic,-admin and bootstrap seeding at startup, the bridge and connector lifecycle-loops that start every row at boot, and the runtime-state and connection-sweeps. A test pins the set of modules allowed to open one, so a new one is a-deliberate act.+The same escape hatch — `unscoped_session`, see above — covers work that is+legitimately cross-tenant: Alembic (a bare `Connection`, not a session at all,+so it never touches the helper either way), admin and bootstrap seeding at+startup, the bridge and connector lifecycle loops that start every row at+boot, and the runtime-state sweep. (The connection sweep touches no scoped+table — it expires in-memory `Connection` objects on a heartbeat timeout —+so it needed no exception in the first place.)+`tests/switch_core/db/test_unscoped_session_allowlist.py` pins the set of+modules allowed to call it, so a new one is a deliberate act rather than an+accident.The delivery listener needs no exception: it holds one unpooled connection that-relays NOTIFY payloads and never reads a scoped table. Its consumers do read-per room — so **the notify payload gains `tenant_id`** alongside the room, seq-and id it already carries. Without it a consumer has to make an unscoped read-just to learn which tenant to scope by, which is a circle.+relays NOTIFY payloads and never reads a scoped table. Its consumer+(`PostgresTransport`) does read per room, but it turned out not to need the+notify payload to carry the tenant: the same lookup that already resolves and+caches a room's internal id from its transport-side id+(`PostgresTransport._resolve_room`) resolves and caches the room's tenant from+the very same row, so there is no *second* unscoped read to avoid — the first+one was already there, for the id. Consumers bind that cached tenant for the+delivery itself and for a send, not only for the row read that first+discovered it, so a handler's own downstream session opens (posting to a+bridge, gating a command) are covered too — they run in the same task, and the+binding is a contextvar, not something tied to one session object.Two exceptions to the uniform rule, in full: