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
fix(db): close the gaps a review of the tenant rework found (CHOO-2623)
Wojciech Wojtyniak6fb0f070dc0f
diff --git a/core/switch_core/db/session_scope.py b/core/switch_core/db/session_scope.pyindex c00e679ae..68cbc47ab 100644--- a/core/switch_core/db/session_scope.py+++ b/core/switch_core/db/session_scope.py@@ -6,8 +6,8 @@ Everything in a request already gets a tenant for free: `gateway/auth.py` and`after_begin` hook (`db/tenant_session.py`) stamps it on every transactionthat session opens from then on, at any depth, with no call site to remember.-Nothing does that for the roughly 197 places that open a session from the-factory directly with no request behind them — the delivery loop, the+Nothing does that for the 164 places that open a session from the factory+directly with no request behind them — the delivery loop, thecollaboration and server-connector lifecycle services, the startup seeding in`main.py`, the periodic sweeps. Each needs to say, at the point it opens asession, which of two things it is doing:diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex 4ae79b28f..fbce5f0b2 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -105,6 +105,7 @@ from switch_core.messages.notify import MessageListenerfrom switch_core.provisioning import Provisioningfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.room_service import RoomService+from switch_core.tenant_context import no_tenantfrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBusfrom switch_core.version import switch_core_version@@ -123,12 +124,17 @@ _CONNECTION_SWEEP_INTERVAL = 2.0async def _runtime_state_sweep_loop(protocol: ProtocolService) -> None:- while True:- await asyncio.sleep(_RUNTIME_STATE_SWEEP_INTERVAL)- try:- await protocol.sweep_runtime_states()- except Exception:- logger.exception("Runtime-state sweep failed")+ # `no_tenant` for the reason every other long-lived task does it: a task+ # keeps the context of whoever created it, and nothing in here may depend+ # on that. Boot binds nothing today, so this changes no behaviour — it+ # removes the dependency on boot continuing not to.+ with no_tenant():+ while True:+ await asyncio.sleep(_RUNTIME_STATE_SWEEP_INTERVAL)+ try:+ await protocol.sweep_runtime_states()+ except Exception:+ logger.exception("Runtime-state sweep failed")async def _connection_sweep_loop(protocol: ProtocolService) -> None:diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 45265d3dc..95d9b43b9 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -782,15 +782,21 @@ class RoomService:logger.info("Removed %d agents from room %s", len(agent_ids), room_id)async def _load_room(self, room_id: str) -> Room:- """A room row, read with no tenant bound.-- The bootstrap read: every caller below is about to bind the tenant- this returns, so scoping the read to a tenant would be circular — and- worse than circular under policies, where the wrong guess turns into- `Room not found` for a room that exists. Nothing is cached: no caller- here holds a room for longer than the call.+ """A room row, read on the caller's session.++ Deliberately *not* unscoped, even though its callers go on to bind the+ tenant it returns. Every entry point here is a request or an inbound+ event that already has a tenant bound and has already authorised the+ caller against this room, so an unscoped read followed by+ `tenant_session(room.tenant_id)` would be a confused deputy: read a+ row from any tenant, then act as that tenant. Reading it scoped keeps+ the elevation impossible rather than merely unreachable — under+ policies a room the caller may not see is `Room not found`, which is+ the correct answer.++ Nothing is cached: no caller here holds a room for longer than a call."""- async with unscoped_session(self._session_factory) as session:+ 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}")diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex bd00bfa6a..d98da420b 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -45,7 +45,7 @@ from switch_core.db.models import ClientRoom, MediaBlob, Message, MessageAttachmfrom switch_core.db.session_scope import tenant_session, unscoped_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_scope+from switch_core.tenant_context import no_tenant, tenant_scopefrom switch_core.transport.content import media_content, message_contentfrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus@@ -207,7 +207,16 @@ class PostgresTransport:and a redelivered message is indistinguishable to a reader from a newone. Overlapping wake-ups collapse into one more pass instead, whichalso bounds this client to one outstanding read.++ `no_tenant` because this is a task and a task keeps its creator's+ context. `receive_forever` is itself reached from a task that unbound+ already, so this changes nothing today — it means the loop stays+ ambient-free if it is ever created from somewhere else."""+ with no_tenant():+ await self._deliver_forever_unbound()++ async def _deliver_forever_unbound(self) -> None:while True:await self._wake.wait()self._wake.clear()diff --git a/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.pynew file mode 100644index 000000000..605a47610--- /dev/null+++ b/core/tests/switch_core/bridges/agent/server_connectors/test_connector_tenant_binding.py@@ -0,0 +1,156 @@+"""A server-side connector acts as its own row's tenant (CHOO-2623).++A connector runs in-process and calls `ProtocolService` directly, so unlike an+external agent there is no bearer token in front of it to resolve a tenant+from. Its own row is the answer, and `ServerSideConnectorLifecycleService.start`+reads it unscoped — from boot with nothing bound, and from an HTTP request+with the caller's tenant bound, which is not necessarily the connector's.++What the runtime then does with it is the point of these tests: the poll loop+is a long-lived task, so it unbinds for its lifetime and binds per pass,+rather than binding once and holding it for days.+"""++from __future__ import annotations++import asyncio+from typing import Any+from unittest.mock import MagicMock++import pytest++from switch_core.bridges.agent.protocol.types import (+ IntegrationProfile,+ TaskProtocolConfig,+)+from switch_core.bridges.agent.server_connectors.base import DiscoveredAgent+from switch_core.bridges.agent.server_connectors.core import ConnectorCore+from switch_core.tenant_context import current_tenant_id, tenant_scope++CONNECTOR_TENANT = "tenant-connector"+CALLER_TENANT = "tenant-caller"+++def _core(protocol: Any, connector: Any) -> ConnectorCore:+ return ConnectorCore(+ connector_id="connector-1",+ connector_tenant_id=CONNECTOR_TENANT,+ connector_type="opencode",+ connector=connector,+ registration_token="tok",+ protocol=protocol,+ )+++class TestThePollLoop:+ async def test_it_binds_per_pass_and_holds_nothing_between_them(self) -> None:+ seen: list[str | None] = []+ between: list[str | None] = []++ class _Protocol:+ async def poll_events(self, agent_id: str, timeout: int) -> list[Any]:+ seen.append(current_tenant_id())+ if len(seen) >= 3:+ raise asyncio.CancelledError+ return []++ core = _core(_Protocol(), MagicMock())+ handle = MagicMock()+ handle.agent_id = "agent-1"+ handle.agent_name = "agent"++ # Created from a context that has no business deciding how the+ # connector acts, exactly as `restart` from a gateway request would.+ with tenant_scope(CALLER_TENANT):+ task = asyncio.create_task(core._poll_loop(handle))+ await task+ between.append(current_tenant_id())++ assert seen == [CONNECTOR_TENANT] * 3, (+ "a poll ran under something other than the connector's own tenant"+ )+ assert between == [CALLER_TENANT], (+ "the loop's unbinding escaped it and cleared its creator's context"+ )++ async def test_a_failing_pass_leaves_nothing_bound_for_the_next(self) -> None:+ """The loop logs and sleeps past an error. The tenant must not survive+ the exception into the retry, or a pass that raised would decide what+ the next one reads."""+ seen: list[str | None] = []+ inside_sleep: list[str | None] = []+ real_sleep = asyncio.sleep++ async def _sleep(delay: float) -> None:+ inside_sleep.append(current_tenant_id())+ await real_sleep(0)++ class _Protocol:+ async def poll_events(self, agent_id: str, timeout: int) -> list[Any]:+ seen.append(current_tenant_id())+ if len(seen) >= 2:+ raise asyncio.CancelledError+ raise RuntimeError("boom")++ core = _core(_Protocol(), MagicMock())+ handle = MagicMock()+ handle.agent_id = "agent-1"+ handle.agent_name = "agent"++ with pytest.MonkeyPatch.context() as patch:+ patch.setattr(+ "switch_core.bridges.agent.server_connectors.core.asyncio.sleep",+ _sleep,+ )+ await core._poll_loop(handle)++ assert seen == [CONNECTOR_TENANT, CONNECTOR_TENANT]+ assert inside_sleep == [None], (+ "the failed pass's tenant was still bound over the backoff"+ )+++async def test_registering_an_agent_binds_the_connectors_tenant() -> None:+ """`register_agent_with_token` re-derives the tenant from the token for+ the write itself, but everything else `register_agent` touches — the+ client, the identity fan-out — runs under whatever is bound here, and+ `start` is reached from boot with nothing bound."""+ seen: list[str | None] = []++ class _Protocol:+ async def register_agent_with_token(self, **kwargs: Any) -> Any:+ seen.append(current_tenant_id())+ return MagicMock(agent_id="agent-1")++ class _Connector:+ async def start(self) -> None:+ return None++ async def stop(self) -> None:+ return None++ async def discover_agents(self) -> list[DiscoveredAgent]:+ return [+ DiscoveredAgent(+ name="worker",+ description="d",+ integration_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+ ),+ ),+ tools=[],+ models=[],+ )+ ]++ core = _core(_Protocol(), _Connector())+ await core.start()+ await core.stop()++ assert seen == [CONNECTOR_TENANT]diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.pyindex 099bf75a4..9920a25ef 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_tenant_binding.py@@ -23,6 +23,8 @@ message arrived on can no longer decide where its room goes.from __future__ import annotationsimport asyncio+import concurrent.futures+import threadingimport uuidfrom types import SimpleNamespacefrom typing import Any@@ -127,14 +129,23 @@ async def test_removing_a_mapping_forgets_the_tenant_with_it() -> None:assert bridge._room_tenants == {}-async def test_a_thread_dispatched_event_lands_in_the_same_tenant() -> None:- """Mattermost, in miniature.+async def test_the_dispatch_style_cannot_change_the_tenant() -> None:+ """Mattermost, in miniature, and the reason platform stopped mattering.- `asyncio.run_coroutine_threadsafe` starts the coroutine in an empty- context — nothing the bridge's task had bound reaches it. Under the model- this replaces, that made auto-created rooms land in tenant zero on- Mattermost and in the bridge's tenant everywhere else: a per-platform- lottery. Both dispatch styles now agree.+ The two arms differ in the context the handler is reached under, which is+ the whole variable:++ - the *threaded* arm is what Mattermost does — its websocket runs on an OS+ thread and hands the coroutine over with `run_coroutine_threadsafe`,+ which copies the calling thread's context. That thread has never bound+ anything, so the handler starts empty;+ - the *inline* arm is what every other adapter does, from a task that+ inherited whatever created it — here, a third tenant that is neither the+ room's nor the bridge's, standing in for the operator who restarted the+ bridge.++ Under the model this replaces, the first landed in tenant zero and the+ second in whatever it inherited. Both now land on the room's."""bridge = _bridge()bridge.add_room_mapping("room-1", "!one:test", "C1", ROOM_TENANT)@@ -145,13 +156,22 @@ async def test_a_thread_dispatched_event_lands_in_the_same_tenant() -> None:traced = bridge._traced(_handler)loop = asyncio.get_running_loop()+ from_thread: list[concurrent.futures.Future[None]] = []++ def _dispatch_from_a_thread() -> None:+ # A real OS thread, so the context it copies is genuinely empty rather+ # than this test's own.+ from_thread.append(asyncio.run_coroutine_threadsafe(traced(_event("C1")), loop))++ thread = threading.Thread(target=_dispatch_from_a_thread)+ thread.start()+ while not from_thread:+ await asyncio.sleep(0)+ await asyncio.wrap_future(from_thread[0])+ thread.join()- # Dispatched the way the Mattermost adapter does it, from a thread with no- # context of its own, and the way every other adapter does it, inline.- await asyncio.wrap_future(- asyncio.run_coroutine_threadsafe(traced(_event("C1")), loop)- )- await traced(_event("C1"))+ with tenant_scope("tenant-whoever-restarted-the-bridge"):+ await traced(_event("C1"))assert seen == [ROOM_TENANT, ROOM_TENANT]@@ -210,3 +230,74 @@ async def test_the_mapping_records_whatever_tenant_it_is_given(tenant: str) -> Nbridge.add_room_mapping(room_id, f"!{room_id}:test", "C1", tenant)assert await bridge._room_tenant(room_id) == tenant+++class TestBridgeLevelWorkBindsTheBridgesTenant:+ """Everything a bridge does that is not for one room in particular. All of+ it is reached with nothing bound — from `BridgeCore.start`, which the+ bridge's task calls after unbinding, or from a callback the adapter holds+ and invokes on its own task."""++ def _bridge_with_store(self, seen: list[str | None]) -> BridgeCore:+ class _Session:+ async def __aenter__(self) -> Any:+ seen.append(current_tenant_id())+ return self++ async def __aexit__(self, *exc: object) -> None:+ return None++ class _AgentStore:+ async def get_by_name(self, session: Any, name: str) -> Any:+ return None++ async def get_all(self, session: Any) -> list[Any]:+ return []++ bridge = BridgeCore.__new__(BridgeCore)+ bridge._bridge_id = "bridge-1"+ bridge._bridge_tenant_id = BRIDGE_TENANT+ bridge._bridge_type = "mattermost"+ bridge._agent_store = _AgentStore() # type: ignore[assignment]+ bridge._session_factory = _Session # type: ignore[assignment]+ return bridge++ async def test_the_presentation_resolver_binds_it(self) -> None:+ """Installed on the adapter, so it is called from the adapter's own+ task with nothing bound. Agent names are unique *per tenant*, so an+ unscoped read here raises `MultipleResultsFound` the day two tenants+ both have a `reviewer`."""+ seen: list[str | None] = []+ bridge = self._bridge_with_store(seen)++ assert await bridge._agent_presentation("worker") is None++ assert seen == [BRIDGE_TENANT]++ async def test_the_identity_task_unbinds_and_then_binds_it(self) -> None:+ """The provisioning task is spawned from `BridgeCore.start`; it must+ not keep whatever created it, and the read it does must still be the+ bridge's."""+ seen: list[str | None] = []+ bridge = self._bridge_with_store(seen)+ inside: list[str | None] = []++ class _Adapter:+ async def create_agent_identity(self, *_: object) -> None:+ return None++ bridge._adapter = _Adapter() # type: ignore[assignment]++ original = bridge._create_agent_identities++ async def _watched() -> None:+ inside.append(current_tenant_id())+ await original()++ bridge._create_agent_identities = _watched # type: ignore[method-assign]++ with tenant_scope("tenant-whoever-started-the-bridge"):+ await bridge._run_agent_identities()++ assert inside == [None], "the identity task kept its creator's tenant"+ assert seen == [BRIDGE_TENANT]diff --git a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.pynew file mode 100644index 000000000..b5c1d6781--- /dev/null+++ b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py@@ -0,0 +1,111 @@+"""A client's task owns no tenant (CHOO-2623).++`start_all` reads every tenant's clients in one pass and binds nothing around+starting any of them, because a client is not a single-tenant actor for the+purposes of its own task: it reads which rooms it is in — a lookup keyed by a+globally unique client id — and then works one room at a time, binding that+room's tenant per delivery.++`_run_client` unbinds first, and the creator matters here more than anywhere+else. A puppet client is minted mid-conversation, from inside an inbound+bridge event bound to *that* room's tenant, and then reused for every room the+person it stands for ever speaks in. Whatever the first room was must not+become the client's identity for the rest of its life.+"""++from __future__ import annotations++import asyncio+import uuid+from unittest.mock import MagicMock++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.clients.client_lifecycle_service import ClientLifecycleService+from switch_core.db.models import Client, Tenant+from switch_core.db.stores.client_store import ClientStore+from switch_core.tenant_context import current_tenant_id, tenant_scope+++class _RecordingClient:+ """Stands in for a running client, noting the tenant it was started under."""++ def __init__(self, seen: list[str | None]) -> None:+ self.display_name = "recorded"+ self.matrix_user_id = "@recorded:test"+ self._seen = seen++ async def start(self) -> None:+ self._seen.append(current_tenant_id())++ async def stop(self) -> None:+ return None+++def _service(+ session_factory: async_sessionmaker[AsyncSession],+ client_factory: object,+) -> ClientLifecycleService:+ return ClientLifecycleService(+ matrix_admin=MagicMock(),+ client_store=ClientStore(),+ client_factory=client_factory, # type: ignore[arg-type]+ session_factory=session_factory,+ config=MagicMock(),+ )+++async def test_a_client_task_runs_with_no_tenant_bound(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The puppet case, in miniature: created from inside a room's tenant,+ and it must not keep it."""+ room_tenant = f"tenant-{uuid.uuid4().hex[:8]}"+ seen: list[str | None] = []+ service = _service(session_factory, MagicMock())++ with tenant_scope(room_tenant):+ service._start_task("client-1", _RecordingClient(seen)) # type: ignore[arg-type]+ await asyncio.sleep(0)++ assert seen == [None], (+ "the client's task kept the tenant of whatever created it; a puppet "+ "reused in a second room would act as the first room's tenant"+ )+++async def test_start_all_binds_nothing_around_starting_each_client(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Reading every tenant's clients is unscoped, and nothing is bound+ afterwards: whatever the enumeration bound would only decide what each+ task snapshots, which is exactly what must not matter."""+ tenant_a = f"tenant-{uuid.uuid4().hex[:8]}"+ tenant_b = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ for tenant_id in (tenant_a, tenant_b):+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.flush()+ for tenant_id in (tenant_a, tenant_b):+ session.add(+ Client(+ tenant_id=tenant_id,+ matrix_user_id=f"@agent-{tenant_id}:test",+ display_name="agent",+ type="agent",+ )+ )+ await session.commit()++ seen: list[str | None] = []+ client_factory = MagicMock()+ client_factory.create.side_effect = lambda record: _RecordingClient(seen)++ service = _service(session_factory, client_factory)+ await service.start_all()+ await asyncio.sleep(0)+ await service.stop_all()++ assert len(seen) >= 2, "the clients were never started"+ assert set(seen) == {None}+ 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.pyindex 8f4329d0a..6dc4187c5 100644--- a/core/tests/switch_core/db/test_unscoped_session_allowlist.py+++ b/core/tests/switch_core/db/test_unscoped_session_allowlist.py@@ -11,9 +11,9 @@ is ambient — the request's tenant on the request path, and *nothing at all* inbackground code, since the long-lived tasks deliberately unbind (see`tenant_context.no_tenant`). So a raw call in background code is unscoped infact while saying nothing about it, which is strictly worse than the hatch-that announces itself. There are ~197 of them across the modules below; that-is the number this design has to work down, and pinning the module list is how-a new one becomes a decision rather than a default.+that announces itself. There are 176 of them across the twenty modules below;+that is the number this design has to work down, and pinning the module list+is how a new one becomes a decision rather than a default.A module failing either check is not a bug in the test. It means someoneopened a session without saying which tenant it is for, and either that is@@ -36,8 +36,8 @@ _ALLOWED_MODULES = {# 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; and `_load_room` is the bootstrap read that says- # which tenant a room is in before that tenant is bound.+ # every tenant's rooms, before binding each room's own tenant for its own+ # work."switch_core.room_service",# The runtime-state sweep reads every tenant's stale rows in one pass, and# `register_agent_with_token` resolves a credential by its globally unique@@ -100,6 +100,10 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.rooms_yaml",}+# Calls that end in `session_factory` but hand one back rather than open a+# session with it.+_FACTORY_ACCESSORS = {"create_session_factory", "get_session_factory"}+_PACKAGE_ROOT = Path(switch_core.__file__).resolve().parent# The module that defines the helpers, not a caller of them.@@ -166,12 +170,17 @@ def _calls_session_factory(path: Path) -> bool:Matches any call whose name ends in `session_factory`, which is how everysuch call in this tree is spelled — `session_factory()`,- `self._session_factory()`, `self.session_factory()`. `create_session_- factory` is excluded: it builds a factory rather than opening a session.+ `self._session_factory()`, `self.session_factory()`.++ A name match, not a resolved reference, unlike `_calls_unscoped_session`:+ there is no single definition to alias, since every service is handed its+ own factory. That makes it over-eager rather than under-eager, which is+ the safe direction for an audit — except for the two accessors that hand a+ factory back instead of opening a session with it, which are named."""tree = ast.parse(path.read_text(), filename=str(path))return any(- name.endswith("session_factory") and name != "create_session_factory"+ name.endswith("session_factory") and name not in _FACTORY_ACCESSORSfor name in _called_names(tree))@@ -302,10 +311,15 @@ class TestTheDetectorsCatchANewCaller:)assert _calls_session_factory(new_caller)- def test_building_a_factory_is_not_opening_a_session(self, tmp_path: Path) -> None:+ def test_handing_a_factory_back_is_not_opening_a_session(+ self, tmp_path: Path+ ) -> None:clean = tmp_path / "wiring.py"clean.write_text(- "def wire(engine):\n return create_session_factory(engine)\n"+ "def wire(engine):\n"+ " return create_session_factory(engine)\n"+ "def fetch():\n"+ " return get_session_factory()\n")assert not _calls_session_factory(clean)diff --git a/core/tests/switch_core/test_tenant_context.py b/core/tests/switch_core/test_tenant_context.pyindex f4f3bd67a..4394d2569 100644--- a/core/tests/switch_core/test_tenant_context.py+++ b/core/tests/switch_core/test_tenant_context.py@@ -3,9 +3,13 @@ that reads or writes it for a real request."""from __future__ import annotations+import asyncio+from switch_core.tenant_context import (bind_tenant_id,+ clear_tenant_id,current_tenant_id,+ no_tenant,tenant_scope,unbind_tenant_id,)@@ -49,3 +53,63 @@ class TestTenantScope:except ValueError:passassert current_tenant_id() is None+++class TestNoTenant:+ """The unbind side. It is what makes "nothing is ambient" enforceable+ rather than aspirational: a long-lived task enters it before doing+ anything, so a unit of work inside that forgets to bind reads nothing+ instead of reading whoever created the task."""++ def test_it_unbinds_for_the_block_and_restores_after(self) -> None:+ with tenant_scope("tenant-a"):+ with no_tenant():+ assert current_tenant_id() is None+ assert current_tenant_id() == "tenant-a"++ def test_it_is_a_no_op_when_nothing_was_bound(self) -> None:+ with no_tenant():+ assert current_tenant_id() is None+ assert current_tenant_id() is None++ def test_it_restores_even_if_the_block_raises(self) -> None:+ with tenant_scope("tenant-a"):+ try:+ with no_tenant():+ raise ValueError("boom")+ except ValueError:+ pass+ assert current_tenant_id() == "tenant-a"++ def test_a_binding_inside_it_still_works_and_still_releases(self) -> None:+ """The shape every converted task takes: unbind for the lifetime,+ bind per unit of work, and be back to nothing between them."""+ with tenant_scope("creator"):+ with no_tenant():+ with tenant_scope("the-row-s-tenant"):+ assert current_tenant_id() == "the-row-s-tenant"+ assert current_tenant_id() is None+ assert current_tenant_id() == "creator"++ async def test_a_task_created_inside_it_inherits_nothing(self) -> None:+ """Why it is entered at the top of a task body rather than around the+ `create_task` call: what a task snapshots is its creator's context, so+ the unbinding has to be inside the task to cover anything the task+ itself spawns."""+ seen: list[str | None] = []++ async def _child() -> None:+ seen.append(current_tenant_id())++ with tenant_scope("creator"):+ with no_tenant():+ await asyncio.create_task(_child())++ assert seen == [None]++ def test_clear_tenant_id_returns_a_token_that_restores(self) -> None:+ with tenant_scope("tenant-a"):+ token = clear_tenant_id()+ assert current_tenant_id() is None+ unbind_tenant_id(token)+ assert current_tenant_id() == "tenant-a"diff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.mdindex 7ddd1d223..8674d4fa3 100644--- a/docs/old/multi-tenancy-phase1-db.md+++ b/docs/old/multi-tenancy-phase1-db.md@@ -16,7 +16,7 @@ when" were all split out into a later change.what was actually implemented, which differs from what it originally proposed —an event hook rather than a dependency at every call site, for reasons giventhere. **The background half of it has since been built too** — the roughly-197 session sites outside the request path now bind a tenant at each unit of+164 session sites outside the request path now bind a tenant at each unit ofwork, described where "Setting the tenant" talks about background work below.That section also records the model that was tried first, of binding once perlong-lived task, and the four ways it leaked; it is written up rather than@@ -360,8 +360,9 @@ silently discarded a password change. Resolution needs the subject id, not athe session the endpoint actually commits.**Background work is not a short list, and it has since been closed.** There-are roughly 197 places that open a session from the factory directly, with no-request behind them. One rule covers all of them:+are 164 places that open a session from the factory directly, with no request+behind them (176 in all, across twenty modules, once the request path's own+twelve are counted). One rule covers all of them:> **Nothing is ambient. Every unit of background work binds the tenant of the> row it is acting on, at the point it acts. Long-lived tasks bind nothing for@@ -399,12 +400,20 @@ of whoever created it. Four things went wrong, and they are one thing:So what is built now is:-- **Long-lived tasks unbind first.** `CollaborationBridgeLifecycleService._run_bridge`,- `ClientLifecycleService._run_client`, `BridgeCore._run_agent_identities` and- the connectors' per-agent poll loop each enter `tenant_context.no_tenant()`- as their first act. Nothing inside them can read a tenant it did not derive,- and once the policies land, a unit of work that forgot to bind reads nothing- rather than reading someone else's rows.+- **Long-lived tasks unbind first.** Every task in the process that outlives+ the call that created it enters `tenant_context.no_tenant()` as its first+ act: `CollaborationBridgeLifecycleService._run_bridge`,+ `ClientLifecycleService._run_client`, `BridgeCore._run_agent_identities`,+ `ConnectorCore._poll_loop`, `PostgresTransport._deliver_forever` and+ `main._runtime_state_sweep_loop`. Nothing inside them can read a tenant it+ did not derive, and once the policies land, a unit of work that forgot to+ bind reads nothing rather than reading someone else's rows. Three of those+ six are created from a context that binds nothing anyway, so entering it+ changes no behaviour there — that is the point. Being correct because of+ where you were created is the dependency this rule exists to remove, so it+ is not left standing where it happens to be harmless. (`main.+ _connection_sweep_loop` is the one long-lived task that does not, because it+ expires in-memory `Connection` objects and opens no session at all.)- **Each unit of work binds the row it is acting on.** A delivery binds theroom's tenant (`transport/postgres.py`); an inbound platform event binds theroom's, or — when the handler is about to auto-create the room — the@@ -438,13 +447,18 @@ the transaction, so the cross-tenant read the call site asked for is silentlya single-tenant one — and the allowlist pinning it certifies a lie.`tests/switch_core/db/test_unscoped_session_allowlist.py` pins two lists,-derived from the source tree rather than from imports and resolving aliased-imports rather than matching a spelling. The first is who may call-`unscoped_session`. The second is the one that matters more: **which modules+both derived from the source tree rather than from imports. The first is who+may call `unscoped_session`, and it resolves the local name the helper was+bound to rather than matching the spelling, so `import … as` does not walk+past it. (The second cannot do the same: every service is handed its own+factory, so there is no single definition to resolve. It matches on the name+ending in `session_factory`, which is over-eager rather than under-eager —+the safe direction for an audit — with the two accessors that hand a factory+back rather than open a session named as exceptions.) The second is the one that matters more: **which modulesmay open a session straight from the factory at all.** A raw call inheritswhatever is ambient, which in background code is now nothing — so it isunscoped in fact while declaring nothing, strictly worse than the hatch that-announces itself. Those ~197 call sites across nineteen modules are the+announces itself. Those 176 call sites across twenty modules are theinventory this design has to work down; pinning the module list makes a newone a decision rather than a default.