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): boot on a fresh database, and scope what the policies exposed (CHOO-2623)
Wojciech Wojtyniak21534fae20d6
diff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex c8c57b5b0..222b5a34a 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -13,8 +13,9 @@ from switch_core.config import SwitchConfigfrom switch_core.db.models import Clientfrom switch_core.db.session_scope import unscoped_sessionfrom switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.tenant_store import TenantStorefrom switch_core.provisioning import Provisioning-from switch_core.tenant_context import no_tenant+from switch_core.tenant_context import no_tenant, tenant_scopelogger = logging.getLogger(__name__)@@ -25,12 +26,14 @@ class ClientLifecycleService:*,matrix_admin: Provisioning,client_store: ClientStore,+ tenant_store: TenantStore,client_factory: ClientFactory,session_factory: async_sessionmaker[AsyncSession],config: SwitchConfig,) -> None:self._matrix_admin = matrix_adminself._client_store = client_store+ self._tenant_store = tenant_storeself._client_factory = client_factoryself._session_factory = session_factoryself._config = config@@ -44,16 +47,38 @@ class ClientLifecycleService:COLLAB_CLIENT_TYPES = ("bridge", "user")async def ensure_system_client(self, client_type: str) -> None:- async with self._session_factory() as session:- existing = await self._client_store.get_by_type(session, client_type)- if existing:- return+ """One system client of `client_type` per tenant, created where missing.++ `clients` is a scoped table, so the admin client is one row per tenant+ rather than one per deployment — that is the whole reason+ `clients.matrix_user_id` became unique per tenant rather than globally+ (`docs/old/multi-tenancy-phase1-db.md`, "Which tables are scoped"). A+ tenant with no admin client has no client in its rooms to provision+ them or relay system messages, so "does one exist anywhere" is the+ wrong question to ask: it answers yes for a tenant that has none.++ The enumeration is unscoped by nature — which tenants exist is exactly+ what a bound session cannot see — and each row is then created with+ that tenant bound, so the `Client` picks it up from the same default+ every other scoped write uses instead of being handed a constant.+ """+ async with unscoped_session(self._session_factory) as session:+ tenant_ids = await self._tenant_store.get_all_ids(session)+ already_served = {+ client.tenant_id+ for client in await self._client_store.get_by_type(session, client_type)+ }+localpart = f"switch-{client_type.replace('_', '-')}"- await self.create_client(- client_type=client_type,- display_name=client_type.replace("_", "-"),- localpart=localpart,- )+ for tenant_id in tenant_ids:+ if tenant_id in already_served:+ continue+ with tenant_scope(tenant_id):+ await self.create_client(+ client_type=client_type,+ display_name=client_type.replace("_", "-"),+ localpart=localpart,+ )async def start_all(self) -> None:# Every tenant's clients in one pass at boot, so this read isdiff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex dfce0c420..4685137ea 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -101,13 +101,18 @@ class TenantNotBoundError(RuntimeError):"""-def _tenant_id_default() -> str:- """The tenant a new scoped row lands in when nothing tells it otherwise.-- Used to prefer the tenant bound to the current unit of work and fall back- to tenant zero when nothing was bound. That fallback is gone: with the- row-level-security policies in place (`db/rls_ddl.py`), a write into- tenant zero on behalf of a caller who forgot to bind is not a safe+def require_tenant_id() -> str:+ """The tenant bound to this unit of work, raising when nothing is bound.++ The Python-side default on every scoped column, and the answer for the one+ store whose primary key includes the tenant and so has to name it in a+ `session.get` (`ReferenceTypeStore`). Named after the SQL function of the+ same name in `db/rls_ddl.py` because it is the same rule on the other side+ of the wire, and it fails the same way.++ This used to prefer the bound tenant and fall back to tenant zero. That+ fallback is gone: with the row-level-security policies in place, a write+ into tenant zero on behalf of a caller who forgot to bind is not a safedefault any more — it is a write into a real tenant that happens to bewrong the day a second one exists, and `with check` cannot tell it apartfrom a write tenant zero actually intended. Every writer is expected to@@ -150,7 +155,7 @@ class TenantScoped:name=f"fk_{cls.__tablename__}_tenant", # type: ignore[attr-defined]),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,)@@ -426,7 +431,7 @@ agent_skills = Table(Text,ForeignKey("tenants.id", name="fk_agent_skills_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("agent_id", Text, primary_key=True),Column("skill_id", Text, primary_key=True),@@ -481,7 +486,7 @@ room_agents = Table(Text,ForeignKey("tenants.id", name="fk_room_agents_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("room_id", Text, primary_key=True),Column("agent_id", Text, primary_key=True),@@ -515,7 +520,7 @@ room_skills = Table(Text,ForeignKey("tenants.id", name="fk_room_skills_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("room_id", Text, primary_key=True),Column("skill_id", Text, primary_key=True),@@ -735,7 +740,7 @@ room_references = Table(Text,ForeignKey("tenants.id", name="fk_room_references_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("room_id", Text, primary_key=True),Column("reference_id", Text, primary_key=True),@@ -759,7 +764,7 @@ room_documents = Table(Text,ForeignKey("tenants.id", name="fk_room_documents_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("room_id", Text, primary_key=True),Column("document_id", Text, primary_key=True),@@ -812,12 +817,7 @@ class ReferenceType(TenantScoped, Base):Text,ForeignKey("tenants.id", name="fk_reference_types_tenant"),primary_key=True,- # Deliberately still the literal constant, not `_tenant_id_default`:- # every read in `ReferenceTypeStore` is hardcoded to `TENANT_ZERO_ID`- # too (each marked `TODO(next PR)`), so a context-aware write here- # would create rows a same-tenant read could no longer find. Fixing- # the pair is that follow-up's job, not this one's.- default=TENANT_ZERO_ID,+ default=require_tenant_id,)type: Mapped[str] = mapped_column(Text, primary_key=True)owner_id: Mapped[str] = mapped_column(Text, ForeignKey("users.id"), nullable=False)@@ -884,7 +884,7 @@ room_packages = Table(Text,ForeignKey("tenants.id", name="fk_room_packages_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("room_id", Text, primary_key=True),Column("package_id", Text, primary_key=True),@@ -908,7 +908,7 @@ package_references = Table(Text,ForeignKey("tenants.id", name="fk_package_references_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("package_id", Text, primary_key=True),Column("reference_id", Text, primary_key=True),@@ -932,7 +932,7 @@ package_documents = Table(Text,ForeignKey("tenants.id", name="fk_package_documents_tenant"),nullable=False,- default=_tenant_id_default,+ default=require_tenant_id,),Column("package_id", Text, primary_key=True),Column("document_id", Text, primary_key=True),diff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.pyindex 9b58e3f29..62bfd87ea 100644--- a/core/switch_core/db/rls_ddl.py+++ b/core/switch_core/db/rls_ddl.py@@ -20,6 +20,13 @@ this whole design exists to close: a session that finishes a tenant'stransaction and is then handed unset-but-not-NULL to the next borrower. Emptystring produced a real incident elsewhere in the company for that reason, soit gets the same treatment as NULL here rather than being assumed away.+Whitespace is the third spelling of the same thing and gets it too: no tenant+id is whitespace, `set_config('app.tenant_id', ' ')` would otherwise satisfy+the check, and what follows is a session whose every read is silently empty+and whose every write silently matches nothing. The raise trims to decide,+and returns the value untrimmed — a fail-closed function that quietly+repaired its input would be deciding, on a caller's behalf, that a malformed+tenant id meant a real tenant.The policy text is one shape, applied identically to every scoped table:@@ -29,12 +36,21 @@ The policy text is one shape, applied identically to every scoped table:using (<col> = (select require_tenant_id()))with check (<col> = (select require_tenant_id()));-- **`with check` is not optional.** `using` only gates which existing rows a- statement can see; it says nothing about what a statement may write. An- `INSERT` has no existing row for `using` to filter, so without `with check`- it is free to address any tenant at all — writing a row into another- tenant that the writer can never read back. Prior art elsewhere, not a- hypothetical.+- **`with check` is not optional, on inserts *and* on updates.** `using` only+ gates which existing rows a statement can see; it says nothing about the row+ a statement leaves behind. An `INSERT` has no existing row for `using` to+ filter, so without `with check` it is free to address any tenant at all —+ writing a row into another tenant that the writer can never read back.+ Prior art elsewhere, not a hypothetical.++ `UPDATE` is the same gap, and it is easy to talk yourself out of that.+ Postgres *does* re-check the updated row against `using` — but only when+ the statement needs `SELECT` rights on the table, which is to say when it+ carries a `WHERE` or a `RETURNING` clause. `UPDATE t SET tenant_id = 'B'`+ carries neither, so under a `with check (true)` it succeeds and moves every+ row the caller can see into another tenant. Verified on Postgres 16;+ `tests/switch_core/db/test_row_level_security.py` pins both shapes so the+ weaker claim cannot be restated.- **`(select require_tenant_id())`**, not a bare call: wrapping it in a`select` makes the planner evaluate it once per query, as an `InitPlan`,instead of once per row. Marking the function `stable` is necessary but not@@ -87,7 +103,7 @@ LANGUAGE plpgsql STABLE AS $$DECLAREv text := current_setting('app.tenant_id', true);BEGIN- IF v IS NULL OR v = '' THEN+ IF v IS NULL OR btrim(v) = '' THENRAISE EXCEPTION 'app.tenant_id is not set on this session'USING ERRCODE = '{_TENANT_NOT_SET_SQLSTATE}';END IF;diff --git a/core/switch_core/db/session_scope.py b/core/switch_core/db/session_scope.pyindex 68cbc47ab..36a048172 100644--- a/core/switch_core/db/session_scope.py+++ b/core/switch_core/db/session_scope.py@@ -6,7 +6,7 @@ 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 164 places that open a session from the factory+Nothing does that for the 157 places that open a session from the factorydirectly 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 adiff --git a/core/switch_core/db/stores/__init__.py b/core/switch_core/db/stores/__init__.pyindex ede68f314..11e7d5ce4 100644--- a/core/switch_core/db/stores/__init__.py+++ b/core/switch_core/db/stores/__init__.py@@ -13,6 +13,7 @@ from switch_core.db.stores.room_link_store import RoomLinkStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.skill_store import SkillStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStore__all__ = [@@ -31,5 +32,6 @@ __all__ = ["RoomStore","SkillStore","TaskStore",+ "TenantStore","UserStore",]diff --git a/core/switch_core/db/stores/reference_type_store.py b/core/switch_core/db/stores/reference_type_store.pyindex fa29a2a08..8bd4843af 100644--- a/core/switch_core/db/stores/reference_type_store.py+++ b/core/switch_core/db/stores/reference_type_store.py@@ -1,25 +1,46 @@+"""Customer-defined reference types, which are per tenant and read as such.++Every method here names the bound tenant rather than leaving the filter to+row-level security, and that is deliberate rather than belt-and-braces.+`reference_types` is the one scoped table whose primary key *is* `(tenant_id,+type)`, so a `session.get` has to supply the tenant to address a row at all;+having only some of the methods name it, and the rest inherit a policy that+is still inert against the owner connection every environment uses today (see+`docs/old/multi-tenancy-phase1-db.md`, "The runtime role"), is how a read and+a write end up disagreeing about which rows exist.+"""+from sqlalchemy import ColumnElement, func, or_, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import TENANT_ZERO_ID, Reference, ReferenceType+from switch_core.db.models import Reference, ReferenceType, require_tenant_idclass ReferenceTypeStore:async def create(self, session: AsyncSession, reference_type: ReferenceType) -> ReferenceType:+ if reference_type.tenant_id is None:+ # Named here rather than left to the column default, because the+ # savepoint below undoes the default too: rolling it back restores+ # the instance to its pre-flush state, and the clash lookup would+ # then have no tenant to look in and report a real duplicate as an+ # unexplained IntegrityError.+ reference_type.tenant_id = require_tenant_id()try:# Savepoint: a duplicate slug must not poison the caller's transaction.async with session.begin_nested():session.add(reference_type)await session.flush()except IntegrityError as exc:- # TODO(next PR): scope to the request's tenant instead of matching- # across all of them.+ # The row's own tenant, not the bound one: a caller may pass a+ # `ReferenceType` it addressed explicitly, and reporting a clash+ # against some other tenant's slug would be a lie either way.clash = await session.execute(select(ReferenceType.type).where(- ReferenceType.type == reference_type.type+ ReferenceType.tenant_id == reference_type.tenant_id,+ ReferenceType.type == reference_type.type,))if clash.scalar_one_or_none() is not None:@@ -30,18 +51,18 @@ class ReferenceTypeStore:return reference_typeasync def get(self, session: AsyncSession, type_: str) -> ReferenceType | None:- # TODO(next PR): use the request's tenant instead of TENANT_ZERO_ID.- return await session.get(ReferenceType, (TENANT_ZERO_ID, type_))+ return await session.get(ReferenceType, (require_tenant_id(), type_))async def get_many(self, session: AsyncSession, types: list[str]) -> list[ReferenceType]:- # TODO(next PR): scope to the request's tenant instead of matching- # across all of them.if not types:return []result = await session.execute(- select(ReferenceType).where(ReferenceType.type.in_(types))+ select(ReferenceType).where(+ ReferenceType.tenant_id == require_tenant_id(),+ ReferenceType.type.in_(types),+ ))return list(result.scalars().all())@@ -54,8 +75,6 @@ class ReferenceTypeStore:``owner_id = NULL`` comparison is never true in SQL, so it is left outrather than relied on."""- # TODO(next PR): scope to the request's tenant instead of matching- # across all of them.condition: ColumnElement[bool]if user_id is None:condition = ReferenceType.read_visibility == "public"@@ -64,13 +83,19 @@ class ReferenceTypeStore:ReferenceType.owner_id == user_id,ReferenceType.read_visibility == "public",)- result = await session.execute(select(ReferenceType).where(condition))+ result = await session.execute(+ select(ReferenceType).where(+ ReferenceType.tenant_id == require_tenant_id(), condition+ )+ )return list(result.scalars().all())async def list_all(self, session: AsyncSession) -> list[ReferenceType]:- # TODO(next PR): scope to the request's tenant instead of matching- # across all of them.- result = await session.execute(select(ReferenceType))+ """Every type in the bound tenant — "all" as an admin means it, not+ every customer's."""+ result = await session.execute(+ select(ReferenceType).where(ReferenceType.tenant_id == require_tenant_id())+ )return list(result.scalars().all())async def update_fields(@@ -84,8 +109,7 @@ class ReferenceTypeStore:read_visibility: str | None = None,write_visibility: str | None = None,) -> ReferenceType:- # TODO(next PR): use the request's tenant instead of TENANT_ZERO_ID.- rt = await session.get(ReferenceType, (TENANT_ZERO_ID, type_))+ rt = await session.get(ReferenceType, (require_tenant_id(), type_))if rt is None:raise ValueError(f"Reference type not found: {type_}")if display_name is not None:@@ -102,15 +126,22 @@ class ReferenceTypeStore:return rtasync def delete(self, session: AsyncSession, type_: str) -> None:- # TODO(next PR): use the request's tenant instead of TENANT_ZERO_ID.- rt = await session.get(ReferenceType, (TENANT_ZERO_ID, type_))+ rt = await session.get(ReferenceType, (require_tenant_id(), type_))if rt is None:raise ValueError(f"Reference type not found: {type_}")await session.delete(rt)await session.flush()async def count_references_of_type(self, session: AsyncSession, type_: str) -> int:+ """How many references of this slug the bound tenant holds.++ Scoped for the same reason the reads above are: this decides whether a+ type may be deleted, and counting another tenant's references would+ refuse a deletion that is perfectly safe here.+ """result = await session.execute(- select(func.count()).select_from(Reference).where(Reference.type == type_)+ select(func.count())+ .select_from(Reference)+ .where(Reference.tenant_id == require_tenant_id(), Reference.type == type_))return int(result.scalar_one())diff --git a/core/switch_core/db/stores/tenant_store.py b/core/switch_core/db/stores/tenant_store.pynew file mode 100644index 000000000..3f5f3b831--- /dev/null+++ b/core/switch_core/db/stores/tenant_store.py@@ -0,0 +1,25 @@+from __future__ import annotations++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.db.models import Tenant+++class TenantStore:+ async def get_all_ids(self, session: AsyncSession) -> list[str]:+ """Every tenant in the deployment, oldest first.++ The one question a tenant-scoped session cannot answer: `tenants`+ carries the same policy as everything else, comparing on `id`, so a+ bound session sees exactly its own row. Callers that need the whole+ list — the startup work that has to do something once per tenant —+ ask on an `unscoped_session`.++ Ordered by creation so a fan-out over the result is deterministic and+ tenant zero, which predates every other row, comes first.+ """+ result = await session.execute(+ select(Tenant.id).order_by(Tenant.created_at, Tenant.id)+ )+ return list(result.scalars().all())diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex a35a4a427..53e4c5b83 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -6,8 +6,12 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import TENANT_ZERO_ID, OidcIdentity, TenantMember, User-from switch_core.tenant_context import current_tenant_id+from switch_core.db.models import (+ OidcIdentity,+ TenantMember,+ User,+ require_tenant_id,+)logger = logging.getLogger(__name__)@@ -68,11 +72,18 @@ class UserStore:two.Joins the tenant bound to the caller's context, so an admin creating a- user joins them to their own tenant; falls back to tenant zero for the- callers with no tenant bound (startup and bootstrap seeding) — the- only tenant Phase 1 has anyway. The role mirrors the migration's own- mapping for pre-existing users: `owner` for the global admin role,- `member` otherwise.+ user joins them to their own tenant. There is no fallback: `tenant_id`+ is not nullable and nothing else in this schema fills it in, so an+ unbound caller would otherwise get whichever tenant this function+ happened to name — the same silent write into a real tenant that+ `require_tenant_id` exists to refuse, and this is the one scoped write+ the model default cannot cover because `TenantMember` is addressed by+ its whole primary key. The seeding paths that legitimately run with+ nothing bound name tenant zero themselves (`main.py`,+ `gateway/oidc_routes.py`).++ The role mirrors the migration's own mapping for pre-existing users:+ `owner` for the global admin role, `member` otherwise."""existing = await session.execute(select(TenantMember.tenant_id).where(TenantMember.user_id == user.id)@@ -81,7 +92,7 @@ class UserStore:returnsession.add(TenantMember(- tenant_id=current_tenant_id() or TENANT_ZERO_ID,+ tenant_id=require_tenant_id(),user_id=user.id,role="owner" if user.role == "admin" else "member",)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex fbce5f0b2..3bbd2459f 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -76,7 +76,7 @@ from switch_core.db.engine import (create_unpooled_engine,)from switch_core.db.models import TENANT_ZERO_ID, ApiKey, User-from switch_core.db.session_scope import unscoped_session+from switch_core.db.session_scope import tenant_session, 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@@ -97,6 +97,7 @@ from switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.tenant_member_store import TenantMemberStore+from switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.app import create_gateway_appfrom switch_core.gateway.auth import hash_password@@ -105,7 +106,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_tenant+from switch_core.tenant_context import no_tenant, tenant_scopefrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBusfrom switch_core.version import switch_core_version@@ -214,6 +215,7 @@ async def run(config: SwitchConfig) -> None:user_store = UserStore()api_key_store = ApiKeyStore()tenant_member_store = TenantMemberStore()+ tenant_store = TenantStore()reference_store = ReferenceStore()reference_type_store = ReferenceTypeStore()document_store = DocumentStore()@@ -243,8 +245,15 @@ async def run(config: SwitchConfig) -> None:room_link_store=room_link_store,session_factory=session_factory,)- async with session_factory() as session:- await resource_service.log_builtin_shadowing(session)+ # Once per tenant, not once for the deployment: `reference_types` is+ # scoped, so "every stored type a built-in shadows" is a question asked of+ # one tenant at a time. Which tenants there are is the one read that+ # cannot be scoped to any of them.+ async with unscoped_session(session_factory) as session:+ tenant_ids = await tenant_store.get_all_ids(session)+ for tenant_id in tenant_ids:+ async with tenant_session(session_factory, tenant_id) as session:+ await resource_service.log_builtin_shadowing(session)# ── Provisioning ─────────────────────────────────────────────────────────matrix_admin: Provisioning = PostgresProvisioning(@@ -295,6 +304,7 @@ async def run(config: SwitchConfig) -> None:client_lifecycle = ClientLifecycleService(matrix_admin=matrix_admin,client_store=client_store,+ tenant_store=tenant_store,client_factory=client_factory,session_factory=session_factory,config=config,@@ -487,11 +497,15 @@ async def _seed_admin_user(user_store: UserStore,config: SwitchConfig,) -> None:- # 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:+ # Tenant zero by name, not by fallback. The admin `User` row is global+ # (db/models.py) and the lookup below spans every tenant either way, but+ # `UserStore.create` also writes a `tenant_members` row, and which tenant+ # the deployment's own admin joins is a decision this line makes rather+ # than one a default makes for it. It is the same decision, and the same+ # reasoning, as `gateway/oidc_routes.py` binding tenant zero around a+ # just-in-time provisioned account: exactly one tenant exists, and signing+ # up into a tenant of one's own is a later phase, whose change is here.+ async with tenant_session(session_factory, TENANT_ZERO_ID) 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)@@ -534,10 +548,13 @@ 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."""- # 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.+ # Genuinely cross-tenant, unlike `_seed_admin_user`: the bootstrap key is+ # one per deployment, resolved by a globally unique hash, and the+ # admin-owned-agent warning below must see every tenant's agents or it+ # under-reports exactly the case it exists to flag. So the session stays+ # unscoped and the two scoped rows written under it — the bootstrap+ # owner's membership, and the `ApiKey` — name tenant zero themselves+ # rather than inheriting a binding there isn't one of.async with unscoped_session(session_factory) as session:admin = await user_store.get_by_email(session, config.gateway_admin_email)if admin is None:@@ -545,7 +562,8 @@ async def _seed_agent_registration_bootstrap_key("Cannot seed agent-registration bootstrap key: admin user "f"{config.gateway_admin_email} not found")- bootstrap_owner = await ensure_bootstrap_owner(session, user_store)+ with tenant_scope(TENANT_ZERO_ID):+ bootstrap_owner = await ensure_bootstrap_owner(session, user_store)admin_owned_agents = [a for a in await agent_store.get_all(session) if a.owner_id == admin.iddiff --git a/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py b/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.pyindex 7f983be2b..b21b1bead 100644--- a/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py+++ b/core/switch_core/migrations/versions/265ed188ad6f_row_level_security.py@@ -8,19 +8,24 @@ tables — the 36 the schema migration named plus `tenants` and`tenant_members`.`require_tenant_id()` reads `current_setting('app.tenant_id', true)` and-raises unless it is a non-empty string. Both empty cases matter: a session-that never bound a tenant reads NULL; a session whose transaction already-committed — releasing the `is_local` setting `db/tenant_session.py` issued —-reads the empty string, not NULL. A function that only checked for NULL would-miss the second, which is exactly the pooled-connection leak this design-exists to close.+raises unless it holds something other than whitespace. All three empty cases+matter: a session that never bound a tenant reads NULL; a session whose+transaction already committed — releasing the `is_local` setting+`db/tenant_session.py` issued — reads the empty string, not NULL; and a+whitespace-only value is neither of those while naming no tenant that can+exist. A function that only checked for NULL would miss the second, which is+exactly the pooled-connection leak this design exists to close, and one that+stopped at the empty string would let the third through into a session whose+every read comes back silently empty.Every policy is `for all`, comparing `tenant_id` (or, for `tenants` itself,`id`) against `(select require_tenant_id())` in both `using` and `withcheck`. The `select` wrapper makes the planner evaluate the function once perquery rather than once per row; `with check` is not optional — without it an-`insert` or `update` can write any tenant at all, which is two of the four-prior-art bugs this design cites. There is no `to <role>` clause: naming the+`insert` can address any tenant at all, and an `update` with neither a+`where` clause nor a `returning` clause can move rows out of the caller's own+tenant, which is two of the four prior-art bugs this design cites. There is+no `to <role>` clause: naming thefuture runtime role here would make this migration fail on every environmentthat role does not exist in yet, and Postgres already exempts a table's ownerfrom its own policies (this migration does not set `force row level@@ -64,7 +69,7 @@ LANGUAGE plpgsql STABLE AS $$DECLAREv text := current_setting('app.tenant_id', true);BEGIN- IF v IS NULL OR v = '' THEN+ IF v IS NULL OR btrim(v) = '' THENRAISE EXCEPTION 'app.tenant_id is not set on this session'USING ERRCODE = '42501';END IF;diff --git a/core/switch_core/tenant_context.py b/core/switch_core/tenant_context.pyindex a64e5a9c6..c347d26bc 100644--- a/core/switch_core/tenant_context.py+++ b/core/switch_core/tenant_context.py@@ -13,15 +13,16 @@ decide what happens when nothing is bound — callers do, deliberately:- `db/tenant_session.py`'s `after_begin` hook treats "nothing bound" as"do nothing" — a system session (auth resolution, startup seeding, Alembic)has no tenant and must not be given one it invented.-- `db/models.py`'s `TenantScoped` default treats "nothing bound" as tenant- zero, because the background call sites that still write through it have- not been converted to bind one yet — and because the long-lived tasks now- unbind deliberately (`no_tenant` below), "nothing bound" is the ordinary- state there rather than an accident.--Neither of those fallbacks lives here. A `current_tenant_id()` that quietly-substituted a default would make both of those call sites indistinguishable-from a real bind, which is exactly the ambiguity the fail-closed design (see+- `db/models.py`'s `require_tenant_id` treats "nothing bound" as an error and+ raises, because a scoped row has to land in *some* tenant and guessing+ which is how a write ends up in a real customer's data. It answered tenant+ zero until row-level security landed; that made the guess unsafe rather+ than merely approximate, since `with check` cannot tell a guess apart from+ a write tenant zero actually intended.++Neither of those answers lives here. A `current_tenant_id()` that quietly+substituted a default would make an unbound context indistinguishable from a+bound one, which is exactly the ambiguity the fail-closed design (see`docs/old/multi-tenancy-phase1-db.md`) depends on not existing."""diff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex d1bb41e6d..ed5e92126 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -74,6 +74,7 @@ from switch_core.db.stores.room_link_store import RoomLinkStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStore+from switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.main import _seed_agent_registration_bootstrap_keyfrom switch_core.messages.notify import MessageListener@@ -484,6 +485,7 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:client_lifecycle = ClientLifecycleService(matrix_admin=provisioning,client_store=session_env.client_store,+ tenant_store=TenantStore(),client_factory=client_factory,session_factory=session_factory,config=config,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.pyindex e473ca960..c41c3033e 100644--- a/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py+++ b/core/tests/switch_core/clients/test_client_lifecycle_tenant_binding.py@@ -25,6 +25,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.db.models import Client, Tenantfrom switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.tenant_store import TenantStorefrom switch_core.tenant_context import current_tenant_id, tenant_scope@@ -50,6 +51,7 @@ def _service(return ClientLifecycleService(matrix_admin=MagicMock(),client_store=ClientStore(),+ tenant_store=TenantStore(),client_factory=client_factory, # type: ignore[arg-type]session_factory=session_factory,config=MagicMock(),diff --git a/core/tests/switch_core/clients/test_ensure_system_client.py b/core/tests/switch_core/clients/test_ensure_system_client.pynew file mode 100644index 000000000..309e6bf13--- /dev/null+++ b/core/tests/switch_core/clients/test_ensure_system_client.py@@ -0,0 +1,122 @@+"""`ensure_system_client` is per tenant, and had no test at all (CHOO-2623).++`main.run` calls it on every boot with nothing bound. Before this, that was a+read of "does a client of this type exist anywhere" followed by a+`Client(...)` with no `tenant_id` — which, once the tenant column stopped+falling back to tenant zero, raised `TenantNotBoundError` and killed the+process before it ever served a request. Only on a *fresh* database: a+seeded one short-circuits on the read, which is why nothing noticed.++So there are two things to pin. The boot case — an empty database gets an+admin client rather than an exception — and the shape the design actually+asks for: `clients` is scoped, so this is one row per tenant, and a second+tenant with no admin client of its own is not served by the first tenant's.+"""++from __future__ import annotations++import uuid+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.clients.client_lifecycle_service import ClientLifecycleService+from switch_core.db.models import TENANT_ZERO_ID, Client, Tenant+from switch_core.db.stores.client_store import ClientStore+from switch_core.db.stores.tenant_store import TenantStore+from switch_core.tenant_context import current_tenant_id+++def _service(+ session_factory: async_sessionmaker[AsyncSession],+) -> ClientLifecycleService:+ return ClientLifecycleService(+ matrix_admin=MagicMock(),+ client_store=ClientStore(),+ tenant_store=TenantStore(),+ client_factory=MagicMock(),+ session_factory=session_factory,+ config=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]+ )+++async def _admin_clients(+ session_factory: async_sessionmaker[AsyncSession],+) -> list[Client]:+ async with session_factory() as session:+ result = await session.execute(+ select(Client).where(Client.type == "admin").order_by(Client.tenant_id)+ )+ return list(result.scalars().all())+++async def _make_tenant(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> None:+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()++[email protected]_ambient_tenant+async def test_a_fresh_database_gets_an_admin_client_rather_than_an_exception(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The boot case, verbatim: nothing bound, no client anywhere, one+ tenant. This is the call that took the process down."""+ await _service(session_factory).ensure_system_client("admin")++ clients = await _admin_clients(session_factory)+ assert [c.tenant_id for c in clients] == [TENANT_ZERO_ID]+ assert clients[0].matrix_user_id == "@switch-admin:test"++[email protected]_ambient_tenant+async def test_each_tenant_gets_its_own_row(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Not "one exists, so we are done": a tenant whose rooms have no admin+ client in them has nothing to provision or narrate them."""+ other = f"tenant-{uuid.uuid4().hex[:8]}"+ await _make_tenant(session_factory, other)++ await _service(session_factory).ensure_system_client("admin")++ clients = await _admin_clients(session_factory)+ assert sorted(c.tenant_id for c in clients) == sorted([TENANT_ZERO_ID, other])++[email protected]_ambient_tenant+async def test_it_is_idempotent_and_fills_only_the_gap(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Every boot runs this. A second pass adds nothing, and a tenant+ onboarded between two boots gets the row the first pass could not have+ made."""+ service = _service(session_factory)+ await service.ensure_system_client("admin")+ await service.ensure_system_client("admin")+ assert [c.tenant_id for c in await _admin_clients(session_factory)] == [+ TENANT_ZERO_ID+ ]++ latecomer = f"tenant-{uuid.uuid4().hex[:8]}"+ await _make_tenant(session_factory, latecomer)+ await service.ensure_system_client("admin")++ clients = await _admin_clients(session_factory)+ assert sorted(c.tenant_id for c in clients) == sorted([TENANT_ZERO_ID, latecomer])++[email protected]_ambient_tenant+async def test_nothing_stays_bound_afterwards(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """It binds a tenant per row it creates and releases it: startup carries+ on into work that must not inherit whichever tenant happened to be last."""+ await _make_tenant(session_factory, f"tenant-{uuid.uuid4().hex[:8]}")+ await _service(session_factory).ensure_system_client("admin")+ assert current_tenant_id() is Nonediff --git a/core/tests/switch_core/db/stores/test_reference_type_store.py b/core/tests/switch_core/db/stores/test_reference_type_store.pyindex 837f63379..f26bc7f9d 100644--- a/core/tests/switch_core/db/stores/test_reference_type_store.py+++ b/core/tests/switch_core/db/stores/test_reference_type_store.py@@ -1,12 +1,15 @@from __future__ import annotations+import uuid+import pytestfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import Reference, ReferenceType, User+from switch_core.db.models import Reference, ReferenceType, Tenant, Userfrom switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.reference_type_store import ReferenceTypeStore+from switch_core.tenant_context import tenant_scopeasync def _make_user(session: AsyncSession, name: str) -> User:@@ -250,3 +253,103 @@ class TestReferenceTypeStore:assert await store.count_references_of_type(session, "notion") == 2assert await store.count_references_of_type(session, "github") == 1assert await store.count_references_of_type(session, "unused") == 0+++class TestReferenceTypesAreScopedToTheBoundTenant:+ """Reads and writes both, because half of either is worse than neither.++ Every method here used to hardcode tenant zero or filter on nothing at+ all, each marked `TODO(next PR)`. Left half-done, a context-aware write+ puts a row where a tenant-zero read can never find it, and an unfiltered+ read serves one customer's type slugs — and their instructions — to+ another. These run on the owner connection, where no policy bites, so+ what they assert is the store's own filtering rather than the database's.+ """++ async def test_a_write_lands_in_the_bound_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ other = f"tenant-{uuid.uuid4().hex[:8]}"+ store = ReferenceTypeStore()+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name=other))+ ada = await _make_user(session, "ada")+ await session.flush()+ with tenant_scope(other):+ created = await store.create(session, _type("notion", ada.id))+ await session.commit()+ assert created.tenant_id == other++ async def test_a_read_does_not_see_another_tenants_type(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ other = f"tenant-{uuid.uuid4().hex[:8]}"+ store = ReferenceTypeStore()+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name=other))+ ada = await _make_user(session, "ada")+ await session.flush()+ with tenant_scope(other):+ await store.create(+ session, _type("notion", ada.id, read_visibility="public")+ )+ await session.commit()++ # Bound to tenant zero, which `session_factory` binds by default.+ assert await store.get(session, "notion") is None+ assert await store.get_many(session, ["notion"]) == []+ assert await store.list_all(session) == []+ assert await store.list_for_user(session, None) == []+ assert await store.list_for_user(session, ada.id) == []++ async def test_the_same_slug_is_two_independent_types(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The collision the per-tenant primary key exists for, through the+ store: two customers both call something `notion`, and editing or+ deleting one leaves the other alone."""+ other = f"tenant-{uuid.uuid4().hex[:8]}"+ store = ReferenceTypeStore()+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name=other))+ ada = await _make_user(session, "ada")+ await session.flush()+ await store.create(session, _type("notion", ada.id))+ with tenant_scope(other):+ await store.create(session, _type("notion", ada.id))+ await session.commit()++ with tenant_scope(other):+ await store.update_fields(session, "notion", display_name="Theirs")+ await session.commit()++ mine = await store.get(session, "notion")+ assert mine is not None and mine.display_name == "Notion"++ await store.delete(session, "notion")+ await session.commit()+ with tenant_scope(other):+ theirs = await store.get(session, "notion")+ assert theirs is not None and theirs.display_name == "Theirs"++ async def test_counting_references_ignores_another_tenants(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """This count decides whether a type may be deleted; another+ customer's references must not veto it."""+ other = f"tenant-{uuid.uuid4().hex[:8]}"+ store = ReferenceTypeStore()+ references = ReferenceStore()+ async with session_factory() as session:+ session.add(Tenant(id=other, slug=other, name=other))+ ada = await _make_user(session, "ada")+ await session.flush()+ await store.create(session, _type("notion", ada.id))+ with tenant_scope(other):+ await store.create(session, _type("notion", ada.id))+ await references.create(session, _reference("notion", ada.id))+ await session.commit()++ assert await store.count_references_of_type(session, "notion") == 0+ with tenant_scope(other):+ assert await store.count_references_of_type(session, "notion") == 1diff --git a/core/tests/switch_core/db/test_require_tenant_id.py b/core/tests/switch_core/db/test_require_tenant_id.pynew file mode 100644index 000000000..66a592665--- /dev/null+++ b/core/tests/switch_core/db/test_require_tenant_id.py@@ -0,0 +1,168 @@+"""The Python half of the fail-closed rule (CHOO-2623).++`require_tenant_id` (`db/models.py`) is the Python-side default on every+scoped column, and it replaced a fallback to tenant zero. Under row-level+security that fallback stopped being a safe default: a caller who forgot to+bind wrote into a *real* tenant, and `with check` cannot tell that apart from+a write tenant zero actually intended.++The raise is worth testing on its own rather than through the policies,+because it does something the policies cannot: it fails in Python, at the+write that forgot to bind, instead of at whatever error Postgres raises later+— and it fails on the owner connection every environment still uses today,+where no policy bites at all.++What is deliberately *not* tested here is the whole suite under+`no_ambient_tenant`. Applying that marker suite-wide turns 354 tests red,+which is the expected shape rather than a finding: most of them construct+scoped rows directly, with no request or unit of work behind them, and+binding tenant zero for them is what `session_factory` exists to do. What+must be pinned is the invariant itself, and the handful of paths that are+supposed to bind one.+"""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy import insert, select+from sqlalchemy.exc import StatementError+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ TENANT_ZERO_ID,+ RoomGroup,+ TenantMember,+ TenantNotBoundError,+ User,+ require_tenant_id,+ room_agents,+)+from switch_core.db.stores.user_store import UserStore+from switch_core.tenant_context import no_tenant, tenant_scope++pytestmark = pytest.mark.no_ambient_tenant+++class TestRequireTenantId:+ def test_it_raises_when_nothing_is_bound(self) -> None:+ with pytest.raises(TenantNotBoundError, match="no tenant is bound"):+ require_tenant_id()++ def test_it_returns_the_bound_tenant(self) -> None:+ with tenant_scope("tenant-x"):+ assert require_tenant_id() == "tenant-x"++ def test_it_raises_again_inside_a_deliberate_unbind(self) -> None:+ """`no_tenant` is what every long-lived background task enters first,+ so this is the state a unit of work that forgot to bind runs in."""+ with tenant_scope("tenant-x"), no_tenant():+ with pytest.raises(TenantNotBoundError):+ require_tenant_id()+++class TestTheOrmDefault:+ """Through SQLAlchemy the raise arrives wrapped.++ A column default is invoked while the statement is being compiled, so+ SQLAlchemy catches whatever it raises and re-raises it as a+ `StatementError` with the original as `__cause__`. That matters to a+ caller: a `except SQLAlchemyError` around a write — the store layer has+ several — swallows this, and the row simply never appears. The tests+ below assert the cause rather than the surface type, and say so, because+ the wrapping is easy to mistake for the invariant not firing.+ """++ async def test_a_scoped_row_with_nothing_bound_refuses_to_be_written(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Not a row in tenant zero, which is what this used to be."""+ async with session_factory() as session:+ session.add(RoomGroup(name="orphan"))+ with pytest.raises(StatementError) as excinfo:+ await session.flush()+ assert isinstance(excinfo.value.orig, TenantNotBoundError)++ async def test_a_bound_tenant_fills_the_column(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with tenant_scope(TENANT_ZERO_ID):+ group = RoomGroup(name="bound")+ session.add(group)+ await session.flush()+ assert group.tenant_id == TENANT_ZERO_ID++ async def test_an_explicit_tenant_still_bypasses_the_default(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The sanctioned hatch: system seeding names its tenant rather than+ binding one, and the default is not consulted at all."""+ async with session_factory() as session:+ group = RoomGroup(tenant_id=TENANT_ZERO_ID, name="named")+ session.add(group)+ await session.flush()+ assert group.tenant_id == TENANT_ZERO_ID++ async def test_a_plain_table_junction_insert_raises_the_same_way(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """`room_agents` and its siblings are `Table()`s, not declarative+ classes, so they carry the default inline rather than through the+ mixin. Same rule, and easy to leave behind when only the mixin is+ edited."""+ async with session_factory() as session:+ with pytest.raises(StatementError) as excinfo:+ await session.execute(+ insert(room_agents).values(+ room_id=str(uuid.uuid4()), agent_id=str(uuid.uuid4())+ )+ )+ assert isinstance(excinfo.value.orig, TenantNotBoundError)+++class TestMembershipNeedsOneToo:+ """`tenant_members` is the one scoped write the model default cannot+ cover — its whole primary key is supplied by the caller — so `UserStore`+ asks for the tenant itself. It used to fall back to tenant zero here,+ a hand-rolled copy of exactly the default this change removed.+ """++ async def test_creating_a_user_with_nothing_bound_raises(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with pytest.raises(TenantNotBoundError):+ await UserStore().create(+ session,+ User(name="nobody", email="[email protected]", role="user"),+ )++ async def test_a_bound_tenant_is_the_one_they_join(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with tenant_scope(TENANT_ZERO_ID):+ user = User(name="joiner", email="[email protected]", role="user")+ await UserStore().create(session, user)+ await session.commit()+ memberships = await session.execute(+ select(TenantMember.tenant_id).where(+ TenantMember.user_id == user.id+ )+ )+ assert list(memberships.scalars()) == [TENANT_ZERO_ID]++ async def test_an_admin_joins_as_owner(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ async with session_factory() as session:+ with tenant_scope(TENANT_ZERO_ID):+ user = User(name="boss", email="[email protected]", role="admin")+ await UserStore().create(session, user)+ await session.commit()+ roles = await session.execute(+ select(TenantMember.role).where(TenantMember.user_id == user.id)+ )+ assert list(roles.scalars()) == ["owner"]diff --git a/core/tests/switch_core/db/test_row_level_security.py b/core/tests/switch_core/db/test_row_level_security.pyindex cc2c2d2cc..d581a8ccd 100644--- a/core/tests/switch_core/db/test_row_level_security.py+++ b/core/tests/switch_core/db/test_row_level_security.py@@ -20,28 +20,39 @@ see `tests/conftest.py`'s `rls_harness` docstring and the design doc'sthis suite was written and worth repeating after touching `db/rls_ddl.py`):weaken `create_policy_ddl`'s `WITH CHECK` clause to something permissive like`WITH CHECK (true)` and rerun `TestWriteSideNeedsWithCheck` — the insert test-should fail. Omitting `WITH CHECK` entirely does *not* demonstrate this:-Postgres reuses `USING` as `WITH CHECK` when none is given, which happens to-still block that same insert and would falsely look like the test caught-nothing.+and the unqualified-update test should both fail. Omitting `WITH CHECK`+entirely does *not* demonstrate this: Postgres reuses `USING` as `WITH CHECK`+when none is given, which happens to still block both and would falsely look+like the tests caught nothing."""from __future__ import annotationsimport uuid+from pathlib import Path+from types import ModuleTypeimport pytest+from alembic.config import Config+from alembic.script import ScriptDirectoryfrom sqlalchemy import insert, select, text, updatefrom sqlalchemy.exc import DBAPIErrorfrom sqlalchemy.ext.asyncio import async_sessionmaker+import switch_corefrom switch_core.db.base import Basefrom switch_core.db.models import RoomGroup, Tenant-from switch_core.db.rls_ddl import POLICY_NAME, scoped_tables+from switch_core.db.rls_ddl import (+ POLICY_NAME,+ REQUIRE_TENANT_FUNCTION_NAME,+ scoped_tables,+)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_group_store import RoomGroupStorefrom tests.conftest import RLSHarness+_RLS_REVISION = "265ed188ad6f"+async def _make_tenant(owner: async_sessionmaker, tenant_id: str) -> None:async with owner() as session:@@ -136,15 +147,16 @@ class TestWriteSideNeedsWithCheck:verification note) actually bites: loosen `WITH CHECK` and this test isthe one that turns red.- The `UPDATE` case included below is *not* the same gap. Postgres re-checks- a row's new state against a table's visibility policy on `UPDATE`- regardless of what `WITH CHECK` says, so — because this design gives- `USING` and `WITH CHECK` the identical predicate — moving a row tenant A- can see into tenant B is already refused before `WITH CHECK` gets- involved. It is included anyway as the write-side counterpart the "Done- when" list asks for, and because a future edit that let the two- predicates diverge would only be caught by a test that actually exercises- `UPDATE`.+ `UPDATE` is the same gap, in two shapes that behave differently and are+ both pinned below. Postgres re-checks the updated row against `USING`+ only when the statement needs `SELECT` rights on the table — that is,+ when it carries a `WHERE` or a `RETURNING` clause. A qualified update is+ therefore refused even under `WITH CHECK (true)`; an **unqualified** one+ (`UPDATE t SET tenant_id = 'B'`, no `WHERE`, no `RETURNING`) is not, and+ under a weakened `WITH CHECK` it succeeds and moves every row the caller+ can see into another tenant. Measured on Postgres 16, twice restated the+ other way round before that: `WITH CHECK` is load-bearing for updates,+ not belt-and-braces over a re-check that covers them."""async def test_cannot_insert_a_row_explicitly_addressed_to_another_tenant(@@ -172,11 +184,12 @@ class TestWriteSideNeedsWithCheck:async def test_cannot_update_an_own_row_into_another_tenant(self, rls_harness: RLSHarness) -> None:- """Belt-and-suspenders, not a gap `WITH CHECK` alone closes here: see- the class docstring. `USING` and `WITH CHECK` share one predicate by- design, so this stays refused either way — pinned so a future change- that let them diverge would be caught by a test that exercises- `UPDATE`, not only the `INSERT` case above.+ """The *qualified* update: refused by the `USING` re-check, which+ applies because a `WHERE` clause makes the statement need `SELECT`+ rights. This one stays red even under `WITH CHECK (true)`, so it is+ the weaker of the pair — kept because it is the shape application+ code actually writes, and because it is the half whose defence would+ disappear if `USING` and `WITH CHECK` were ever allowed to diverge."""tenant_a, tenant_b = _tenant_pair()await _make_tenant(rls_harness.owner, tenant_a)@@ -202,6 +215,50 @@ class TestWriteSideNeedsWithCheck:.values(tenant_id=tenant_b))+ async def test_cannot_move_own_rows_out_with_an_unqualified_update(+ self, rls_harness: RLSHarness+ ) -> None:+ """The update that only `WITH CHECK` refuses.++ No `WHERE`, no `RETURNING`, so the statement needs no `SELECT` rights+ and Postgres does not re-check the new row against `USING`. Under a+ `WITH CHECK` weakened to `true` this succeeds and rewrites every row+ tenant A can see into tenant B — measured on Postgres 16, and the+ reason the class docstring no longer says the re-check covers+ updates. The row is read back through the owner afterwards rather+ than through tenant A, because a row that *did* move is by+ construction invisible to the session that moved it.+ """+ tenant_a, tenant_b = _tenant_pair()+ await _make_tenant(rls_harness.owner, tenant_a)+ await _make_tenant(rls_harness.owner, tenant_b)++ store = RoomGroupStore()+ async with tenant_session(rls_harness.restricted, tenant_a) as session:+ own = await store.create(+ session,+ name="mine",+ description=None,+ color=None,+ parent_group_id=None,+ )+ await session.commit()+ own_id = own.id++ async with tenant_session(rls_harness.restricted, tenant_a) as session:+ with pytest.raises(DBAPIError, match="row-level security"):+ await session.execute(+ update(RoomGroup.__table__).values(tenant_id=tenant_b)+ )++ async with rls_harness.owner() as session:+ landed = await session.get(RoomGroup, own_id)+ assert landed is not None+ assert landed.tenant_id == tenant_a, (+ "an unqualified UPDATE moved a row out of its tenant — "+ "WITH CHECK is what refuses this one, and USING does not"+ )+class TestNoTenantSetRaises:async def test_a_query_with_no_tenant_bound_raises(@@ -213,6 +270,25 @@ class TestNoTenantSetRaises:with pytest.raises(DBAPIError, match="app.tenant_id is not set"):await session.execute(select(RoomGroup))+ async def test_a_whitespace_tenant_raises_rather_than_matching_nothing(+ self, rls_harness: RLSHarness+ ) -> None:+ """The third spelling of "unset", and the one that looks set.++ `set_config('app.tenant_id', ' ')` passes a bare `v = ''` test, and+ what follows is a session whose reads all come back empty and whose+ writes all match nothing, with no error anywhere to say why. No+ tenant id is whitespace, so it gets the same raise the other two do.+ Issued as raw SQL rather than through `tenant_session`, because the+ value would have to be constructed by hand to get here at all.+ """+ async with rls_harness.restricted() as session:+ await session.execute(+ text("SELECT set_config('app.tenant_id', ' ', true)")+ )+ with pytest.raises(DBAPIError, match="app.tenant_id is not set"):+ await session.execute(select(RoomGroup))+async def _rowsecurity_by_table(session) -> dict[str, bool]: # type: ignore[no-untyped-def]result = await session.execute(@@ -234,6 +310,36 @@ async def _tenant_isolation_policies(return {row.tablename: (row.qual, row.with_check) for row in result}+def _expected_predicate(tenant_column: str) -> str:+ """`create_policy_ddl`'s predicate as `pg_policies` reads it back.++ Postgres stores a parsed expression and renders it from the tree, so the+ text is not the text that was submitted: the quoting is dropped and the+ scalar subquery comes back with its output column named. Written out+ literally rather than derived from `create_policy_ddl`, because a+ derivation that reused the same string-building would agree with a typo in+ it.+ """+ return (+ f"({tenant_column} = ( SELECT {REQUIRE_TENANT_FUNCTION_NAME}() "+ f"AS {REQUIRE_TENANT_FUNCTION_NAME}))"+ )+++def _migration_module() -> ModuleType:+ """The `265ed188ad6f` revision module, loaded through Alembic.++ Alembic's own loader, rather than an `importlib` call on a path, so this+ finds the file the same way a deployment would and fails the same way if+ the revision were renamed or removed.+ """+ core = Path(switch_core.__file__).resolve().parents[1]+ config = Config(str(core / "alembic.ini"))+ config.set_main_option("script_location", str(core / "switch_core" / "migrations"))+ revision = ScriptDirectory.from_config(config).get_revision(_RLS_REVISION)+ return revision.module++class TestCatalogueCoverage:"""Read the built schema back out of the database — `pg_tables` and`pg_policies` — rather than the model source, so a scoped table added@@ -255,9 +361,18 @@ class TestCatalogueCoverage:for global_table in ("users", "oidc_identities", "feature_flags"):assert global_table not in scoped- async def test_every_scoped_table_has_rls_enabled_and_a_well_formed_policy(+ async def test_every_scoped_table_has_rls_enabled_and_the_right_policy(self, session_factory: async_sessionmaker) -> None:+ """Both predicates, compared against the expected text.++ Asserting only that `qual` and `with_check` are non-null passes for+ `USING (true)` — a policy that is present, enabled, catalogued, and+ isolates nothing. So the comparison is on content: each table's+ expected predicate is built from the column `rls_ddl` says that table+ is scoped by, in the shape Postgres renders a `(SELECT f())` back as,+ and a table whose policy says anything else is named in the failure.+ """scoped = scoped_tables(Base.metadata)async with session_factory() as session:rowsecurity = await _rowsecurity_by_table(session)@@ -265,16 +380,39 @@ class TestCatalogueCoverage:missing_rls = sorted(t for t in scoped if not rowsecurity.get(t))missing_policy = sorted(t for t in scoped if t not in policies)- missing_using_or_check = sorted(- t- for t, (qual, with_check) in policies.items()- if t in scoped and (qual is None or with_check is None)- )+ wrong_predicate = {+ table: policies[table]+ for table, column in sorted(scoped.items())+ if table in policies+ and policies[table] != (_expected_predicate(column),) * 2+ }assert missing_rls == [], f"row-level security not enabled: {missing_rls}"assert missing_policy == [], f"no {POLICY_NAME!r} policy: {missing_policy}"- assert missing_using_or_check == [], (- f"policy missing USING or WITH CHECK: {missing_using_or_check}"+ assert wrong_predicate == {}, (+ "policy does not isolate on the tenant column (USING, WITH CHECK): "+ f"{wrong_predicate}"+ )++ async def test_the_migrations_frozen_table_list_matches_the_models(self) -> None:+ """`265ed188ad6f` carries its own copy of the scoped-table list, on+ purpose — a migration must not change meaning because a model did. The+ cost of a frozen copy is that it can silently fall behind: a table+ added to the models gets a policy from `create_all`, so every test in+ this file still passes, while a real deployment built by Alembic has+ none. Nothing compared the two before this; they agree at 38 today.++ A deliberate divergence is still expressible — it just has to be a+ new migration, which is the point.+ """+ from_models = scoped_tables(Base.metadata)+ from_migration = dict(_migration_module().SCOPED_TABLES)++ assert from_migration == from_models, (+ "the frozen SCOPED_TABLES in migration 265ed188ad6f no longer "+ "matches the models: only in the migration "+ f"{sorted(set(from_migration) - set(from_models))}, only in the "+ f"models {sorted(set(from_models) - set(from_migration))}")async def test_global_tables_carry_no_policy(diff --git a/core/tests/switch_core/db/test_unscoped_session_allowlist.py b/core/tests/switch_core/db/test_unscoped_session_allowlist.pyindex 6dc4187c5..b04f9718e 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 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.+that announces itself. There are 174 of them across the nineteen 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@@ -79,6 +79,8 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.bridges.agent.operations.context","switch_core.bridges.agent.operations.definitions","switch_core.bridges.agent.mediation",+ # Reached only from the gateway's rooms endpoints, so the same holds.+ "switch_core.rooms_yaml",# ── Reached only from inside a unit of work that has already bound the# tenant of the row it is acting on — an inbound bridge event, a delivery,# a sweep row, an authenticated agent operation.@@ -93,11 +95,11 @@ _RAW_SESSION_FACTORY_MODULES = {"switch_core.provisioning.postgres","switch_core.room_service","switch_core.transport.postgres",- # ── Deployment-level startup, with no tenant to inherit and none bound.- # Rows these write land in tenant zero via the model default. Correct- # while one tenant exists; both need revisiting before a second.- "switch_core.main",- "switch_core.rooms_yaml",+ # `switch_core.main` came off this list when the tenant-zero fallback+ # went. Every session startup opens now says which it is: a tenant+ # session for the admin-user seeding and for the per-tenant work at boot,+ # `unscoped_session` for the deployment-wide bootstrap key, which is+ # resolved by a globally unique hash and has no tenant to be scoped to.}# Calls that end in `session_factory` but hand one back rather than open adiff --git a/docs/old/multi-tenancy-phase1-db.md b/docs/old/multi-tenancy-phase1-db.mdindex 5f7df515f..3411bbc9f 100644--- a/docs/old/multi-tenancy-phase1-db.md+++ b/docs/old/multi-tenancy-phase1-db.md@@ -13,7 +13,7 @@ foreign keys** landed first, in the migration `8b276792ee30`.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-164 session sites outside the request path now bind a tenant at each unit of+157 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@@ -112,8 +112,12 @@ Three entries are worth justifying:holds attachment bytes reached by an opaque URI, and unguessable identifiersare not an isolation boundary.- **`clients` is scoped**, so the admin/system client becomes one row per- tenant rather than one per deployment. Today that is a no-op — the single- existing row backfills to tenant zero — and it is the right shape later.+ tenant rather than one per deployment. The single existing row backfills to+ tenant zero, and `ClientLifecycleService.ensure_system_client` — the+ startup call that guarantees the admin client exists — enumerates tenants+ and creates the missing row in each, rather than asking whether one exists+ anywhere. The distinction has teeth: "one exists" is true for a deployment+ whose second tenant has no admin client in any of its rooms.**Global — no `tenant_id`, no policy:** `users`, `oidc_identities`,`feature_flags`, `alembic_version`.@@ -143,7 +147,14 @@ second tenant appears, so the whole list was walked.- `reference_types` primary key → `(tenant_id, type)`. Customer-defined typeslugs collide. This table has no `id` column at all, so it is the one scopedtable that cannot carry a `unique (id, tenant_id)` — harmless, because- nothing references it by foreign key.+ nothing references it by foreign key. It is also the one store that has to+ name the tenant in every method rather than leaving the filter to the+ policy: `session.get` on a composite primary key cannot address a row+ without it. That is why `ReferenceTypeStore` reads and writes both say+ `require_tenant_id()` explicitly. They said `TENANT_ZERO_ID` until the+ policies landed, which under enforcement gave a second tenant a bare 500 on+ create and silence on read, and as owner leaked every tenant's type slugs+ and instructions to every other.- `collaboration_bridges` default-bridge index → `unique (tenant_id) whereis_default`. "One default bridge for the deployment" is exactly the globalsingleton that breaks on the second tenant.@@ -219,7 +230,7 @@ create or replace function require_tenant_id() returns textlanguage plpgsql stable as $$declare v text := current_setting('app.tenant_id', true);begin- if v is null or v = '' then+ if v is null or btrim(v) = '' thenraise exception 'app.tenant_id is not set on this session'using errcode = '42501';end if;@@ -227,11 +238,19 @@ beginend $$;```-Three cases, one behaviour. Never set in this session returns NULL because of+Four cases, one behaviour. Never set in this session returns NULL because ofthe `true`; set and then released at commit returns the empty string, not NULL-— the trap that produced a P1 elsewhere in the company; set returns the value.-Both empty cases raise. **The function fails closed, and every other safety-property here rests on that.**+— the trap that produced a P1 elsewhere in the company; whitespace is neither+of those and names no tenant that can exist; set returns the value. The first+three raise. **The function fails closed, and every other safety property here+rests on that.**++The `btrim` decides but does not repair: the value is returned as it was+given. Trimming it on the way out would be the function deciding, on a+caller's behalf, that a malformed tenant id meant a real tenant. Without the+`btrim` at all, `set_config('app.tenant_id', ' ')` passes and what follows+is a session whose every read comes back empty and whose every write matches+nothing, with no error anywhere to say why.```sqlalter table <t> enable row level security;@@ -242,10 +261,19 @@ create policy tenant_isolation on <t>with check (tenant_id = (select require_tenant_id()));```-- **`with check` is not optional.** `using` filters what you can read; without- `with check` a write is unconstrained and you can insert a row into another- tenant that you cannot then read back. Two of the four prior-art bugs are- this.+- **`with check` is not optional, and it is load-bearing for updates too.**+ `using` filters what you can read; without `with check` a write is+ unconstrained and you can insert a row into another tenant that you cannot+ then read back. Two of the four prior-art bugs are this. It is tempting to+ think `update` is covered anyway, because Postgres re-checks the updated+ row against `using` — but it only does that when the statement needs+ `select` rights, which is to say when it carries a `where` or a+ `returning` clause. `update t set tenant_id = 'B'` carries neither, and+ under a `with check (true)` it succeeds and moves every row the caller can+ see into another tenant. Verified on 16, after this document twice claimed+ otherwise; both shapes are pinned in+ `tests/switch_core/db/test_row_level_security.py` so the weaker claim+ cannot come back a third time.- **`(select require_tenant_id())`** rather than a bare call, so the plannerevaluates it once per query as an InitPlan rather than once per row. Markingthe function `stable` is not sufficient on its own.@@ -359,9 +387,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 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:+are 157 places that open a session from the factory directly, with no request+behind them (174 in all, across nineteen modules, once the request path's own+seventeen 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@@ -457,7 +485,7 @@ back rather than open a session named as exceptions.) The second is the one thatmay 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 176 call sites across twenty modules are the+announces itself. Those 174 call sites across nineteen modules are theinventory this design has to work down; pinning the module list makes a newone a decision rather than a default.@@ -476,9 +504,39 @@ fewer times, and skipping it is how the prior-art bugs happened.**Writes fill the column automatically.** `tenant_id` gets a Python-sidedefault reading the request's tenant, so ordinary ORM inserts need no changeacross roughly 250 store methods, and `with check` catches anything that-disagrees. Two caveats, both real: the default yields nothing in a system-session, so the startup seeding paths must pass tenant zero explicitly; and one-Core `executemany` in the room store needs checking rather than assuming.+disagrees. One Core `executemany` in the room store needed checking rather+than assuming.++**What the default does when nothing is bound changed with the policies.** It+used to answer tenant zero. `db/models.py`'s `require_tenant_id` now raises+`TenantNotBoundError` instead, in Python, before the row reaches the+database — so the failure names the write that forgot to bind rather than+whatever error Postgres would have raised later, and it fails on the owner+connection every environment still uses, where no policy bites at all. The+fallback was defensible while a missing tenant merely meant "the only tenant+we have"; under `with check` it is a write into a real customer's data that+the database cannot tell apart from one tenant zero intended.++Three consequences worth naming, because they are the whole cost of removing+it:++- **Startup names its tenant.** Seeding the admin user, and provisioning the+ admin client, run before any request has bound anything. They say tenant+ zero, or the tenant of the row they are creating, rather than letting a+ default say it for them — the same shape `gateway/oidc_routes.py` already+ used for a just-in-time provisioned account.+- **`tenant_members` is the one scoped write the default cannot cover**,+ because the caller supplies its whole primary key. `UserStore` therefore+ called `current_tenant_id() or TENANT_ZERO_ID` by hand: a private copy of+ exactly the fallback being removed, and the thing keeping admin seeding+ alive. It now calls `require_tenant_id` like everything else, and the+ seeding paths bind.+- **The test fixtures bind tenant zero by default.** Most of the suite+ constructs scoped rows directly rather than through a request, so without+ it they would be exercising a path the design does not have. A test that+ is *about* what is bound opts out with the `no_ambient_tenant` marker.+ Applying that marker suite-wide turns 354 tests red, which is the expected+ shape rather than a finding.The same context value feeds the logging filter, which has had a `tenant_id`field since before tenants existed and which nothing has ever bound@@ -529,7 +587,7 @@ that; it is pinned by a test in`tests/switch_core/transport/test_postgres_transport.py` because the shape ofthe room list rests on it.)-Two exceptions to the uniform rule, in full:+Three exceptions to the uniform rule, in full:1. **`api_keys.key_hash` stays globally unique**, because authenticationresolves it before a tenant exists.@@ -537,8 +595,21 @@ Two exceptions to the uniform rule, in full:inside a fail-closed design and is named as such: nothing stops a pinnedmodule reading across tenants once a second one exists. Phase 1 acceptsthat; the pinned list is what keeps it reviewable.--An earlier draft had a third — a membership-based policy on `users` — and it+3. **The agent-registration bootstrap key is seeded on an unbound+ transaction, and writes two scoped rows there.** Everything else that+ writes with nothing bound was converted to name its tenant; this one+ cannot be, because the same block genuinely spans tenants — the key is+ one per deployment, resolved by that globally unique hash, and the+ admin-owned-agent warning beside it must see every tenant's agents or it+ under-reports the case it exists to flag. So the block stays unscoped and+ the two scoped rows in it, the bootstrap owner's membership and the+ `ApiKey`, name tenant zero themselves. That works today only because+ startup connects as the table owner. When the runtime role lands+ (CHOO-2685) this path needs a system connection of its own; it is the one+ place in the tree where "unscoped session" and "scoped write" meet, and it+ is listed here rather than left for that work to discover.++An earlier draft had one more — a membership-based policy on `users` — and itwas wrong. Its `with check` made creating a user impossible: the membership rowcannot exist before the user, and the user cannot be inserted before themembership. It also would not have held, because `tenant_members` has no@@ -650,19 +721,41 @@ to them — that is the role work, and until it lands the same test against areal environment would pass for the wrong reason.Alongside it, the cheap tests that catch the regressions this design exists-to prevent, also in that file:--- Every scoped table has row-level security enabled and a policy, asserted by- querying `pg_policies` and `pg_tables` rather than by reading the code, with- the table list itself derived from `rls_ddl.scoped_tables` rather than- copied.-- A write-side pair — an `INSERT` addressed to another tenant, and an- `UPDATE` moving an own row into one — for what `with check` catches that- `using` alone would not. (The `UPDATE` case turns out to be defended either- way, because Postgres re-checks a row's new state against `using` on- `UPDATE` regardless of `with check`; it stays as the write-side test the- design calls for, and as a pin against the day the two predicates diverge.)-- A query issued with no tenant set raises rather than returning nothing.+to prevent — in that file unless another is named:++- Every scoped table has row-level security enabled and a policy whose+ `using` and `with check` both isolate on that table's tenant column,+ asserted by querying `pg_policies` and `pg_tables` rather than by reading+ the code, with the table list itself derived from `rls_ddl.scoped_tables`+ rather than copied. The predicates are compared by content, not merely for+ being present: `using (true)` is a policy that is enabled, catalogued and+ isolates nothing.+- The migration's frozen `SCOPED_TABLES` matches that same derivation. A+ frozen copy is the right shape (a migration must not change meaning+ because a model did) and its failure mode is falling behind in silence —+ a table added to the models gets a policy from `create_all`, so every test+ above still passes, while a deployment built by Alembic has none. They+ agree at 38; a deliberate divergence is still expressible, as a new+ migration.+- A write-side trio for what `with check` catches that `using` alone would+ not: an `INSERT` addressed to another tenant, an `UPDATE` moving an own row+ into one, and an **unqualified** `UPDATE` that names no rows. The last is+ the one that matters — see the `with check` bullet above — and the middle+ one is refused by the `using` re-check either way, kept because it is the+ shape application code writes.+- A query issued with no tenant set raises rather than returning nothing, and+ so does one issued with a whitespace tenant.+- `TenantNotBoundError` — the Python-side half of the same rule — raises for+ a scoped ORM row, a plain `Table()` junction insert and a membership write+ with nothing bound, in+ `tests/switch_core/db/test_require_tenant_id.py`. It arrives wrapped in a+ `StatementError` when a column default raises it, which that file pins+ too, because a caller catching `SQLAlchemyError` would otherwise swallow+ it.+- `ensure_system_client` creates one admin client per tenant, on a fresh+ database and on a deployment that gained a tenant between two boots+ (`tests/switch_core/clients/test_ensure_system_client.py`). It had no test+ at all until it stopped booting.The foreign-key-carries-`tenant_id` catalogue check this section originallyasked for shipped earlier, with the schema migration — see@@ -692,6 +785,18 @@ Named so they are decisions rather than omissions.exists in another tenant fails on the index rather than being handled — anexistence oracle and a bad error. Phase 2.- **System sessions can read across tenants** by design, as above.+- **`RoomService._resolve_system_clients` is tenant-blind**, and now that+ `ensure_system_client` makes one admin client per tenant there is more than+ one for it to be blind about. It returns every running system client, and+ both callers — creating a room, and `reconcile_room_clients` at startup —+ put all of them in the room. With two tenants that means offering tenant+ B's admin client to tenant A's room, which `client_rooms`' composite+ foreign key refuses, so the failure is loud rather than a leak. It was+ equally broken before, in the other direction: one admin client in tenant+ zero, offered to every tenant's rooms, refused the same way. The fix is a+ filter on the room's tenant at both call sites, and it belongs with+ whatever onboards the second tenant rather than in the change that made+ the row exist.- **No indexes on `tenant_id`.** With one tenant the column has no selectivityand an index is pure write cost. Add them when the second tenant lands, inone migration, `concurrently`, with data to measure against.@@ -710,8 +815,23 @@ Named so they are decisions rather than omissions.matches — `agent_store.get_by_name`, `collaboration_bridge_store.get_default`,`client_store.get_by_matrix_user_id`, and `room_store.get_by_matrix_room_id`are four of them. They are correct today, with one tenant, and wrong the- day a second one exists; making the session tenant-scoped, in the next PR,- is what makes them correct rather than each needing its own fix.+ day a second one exists; the session being tenant-scoped is what makes them+ correct, and until the runtime role lands that is true of the policies+ rather than of the connection. `client_store.get_by_matrix_user_id` is now+ reachably ambiguous rather than theoretically so, because the admin client+ is one row per tenant and every one of them carries the same+ `@switch-admin:<server>` id.+- **`INSERT … ON CONFLICT` against a row the policy hides behaves two+ different unhelpful ways.** `DO NOTHING` reports zero rows inserted, which+ the caller reads as "already there" when in fact it is another tenant's+ row and the caller's own is now missing. `DO UPDATE` raises *"new row+ violates row-level security policy (USING expression)"*, which is an+ existence oracle for a row the caller may not see. Both measured on 16.+ Not reachable today: every conflict target in this tree is a UUID or a+ hash, so a conflict across tenants would need a guessed identifier. It is+ reachable the moment a natural key gains an upsert, so it is recorded+ rather than fixed — the fix is to include `tenant_id` in the conflict+ target, which the composite unique constraints already permit.- No plan, status or soft-delete on `tenants`; no tenant deletion; noper-tenant feature flags; no tenant switching.- No per-tenant agent registration credential — Phase 2 owns it as a security