Skip to content

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

Resolve a request's workspaces with one lookup, and index what it reads

Petr Bauch4496ad3420ea
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index bb60eff03..0275a4728 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -131,6 +131,9 @@ class OrganizationMember(Base):
CheckConstraint(
"role IN ('org_admin', 'member')", name="ck_organization_members_role"
),
+ # Which workspaces a person may enter is read by user on every
+ # authenticated request (`tenants_bindable_by_user`).
+ Index("ix_organization_members_user_id", "user_id"),
)
organization_id: Mapped[str] = mapped_column(
@@ -159,6 +162,7 @@ class Tenant(Base):
"""
__tablename__ = "tenants"
+ __table_args__ = (Index("ix_tenants_organization_id", "organization_id"),)
id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)
slug: Mapped[str] = mapped_column(Text, unique=True, nullable=False)
diff --git a/core/switch_core/db/tenant_lookup.py b/core/switch_core/db/tenant_lookup.py
index bad3a7f5c..f6994d7e5 100644
--- a/core/switch_core/db/tenant_lookup.py
+++ b/core/switch_core/db/tenant_lookup.py
@@ -159,13 +159,15 @@ those are, so each row is read with its own tenant bound. It discloses which
workspaces a machine, and so its owner, belongs to: what `tenants_of_user`
already discloses about the same person.
-**`tenants_administered_through_organization` is the fourteenth**, and the
-same question as `tenants_of_user` asked of the organization above the
-workspace. An organization's `org_admin` administers every workspace in it,
-and may bind one without holding a membership row there, so resolving a
-request's workspace has to read which workspaces those are before any is
-bound. It discloses which workspaces a person administers through an
-organization; the gateway asks it only about the signed-in caller.
+**`tenants_bindable_by_user` is the fourteenth**, and `tenants_of_user`
+widened to the organization above the workspace. An organization's
+`org_admin` administers every workspace in it, and may bind one without
+holding a membership row there, so resolving a request's workspace has to
+read which workspaces those are before any is bound. One function answers
+both halves, so every authenticated request costs one lookup rather than
+two. It discloses which workspaces a person belongs to or administers
+through an organization; the gateway asks it only about the signed-in
+caller.
Why not the obvious alternatives is argued in
`docs/old/multi-tenancy-phase1-db.md`, "The bootstrap problem"; the short
@@ -286,19 +288,21 @@ TENANT_LOOKUPS: tuple[TenantLookup, ...] = (
),
),
TenantLookup(
- name="tenants_administered_through_organization",
+ name="tenants_bindable_by_user",
arguments=("user_id",),
query=(
- "SELECT tenants.id FROM tenants "
+ "SELECT tenant_id FROM tenant_members WHERE user_id = p_user_id "
+ "UNION SELECT tenants.id FROM tenants "
"JOIN organization_members "
"ON organization_members.organization_id = tenants.organization_id "
"WHERE organization_members.user_id = p_user_id "
- "AND organization_members.role = 'org_admin' ORDER BY tenants.id"
+ "AND organization_members.role = 'org_admin' ORDER BY 1"
),
purpose=(
- "Which tenants a gateway login administers as its organization's "
- "`org_admin`, holding a membership row there or not. Read before "
- "a tenant is bound, for the same reason as `tenants_of_user`."
+ "Which tenants a gateway login may bind: those it holds a "
+ "membership row in, and those it administers as its "
+ "organization's `org_admin`. Read before a tenant is bound, for "
+ "the same reason as `tenants_of_user`, and once per request."
),
),
TenantLookup(
@@ -508,9 +512,8 @@ _LOOKUP_STATEMENTS: dict[str, TextClause] = {
"tenants_of_user": text(
"SELECT tenant_id FROM tenants_of_user(:user_id) AS tenant_id"
),
- "tenants_administered_through_organization": text(
- "SELECT tenant_id FROM "
- "tenants_administered_through_organization(:user_id) AS tenant_id"
+ "tenants_bindable_by_user": text(
+ "SELECT tenant_id FROM tenants_bindable_by_user(:user_id) AS tenant_id"
),
"tenant_of_api_key": text(
"SELECT tenant_id FROM tenant_of_api_key(:key_hash) AS tenant_id"
@@ -606,13 +609,11 @@ async def tenants_of_user(
)
-async def tenants_administered_through_organization(
+async def tenants_bindable_by_user(
session_factory: async_sessionmaker[AsyncSession], user_id: str
) -> list[str]:
return await _call(
- session_factory,
- TENANT_LOOKUPS_BY_NAME["tenants_administered_through_organization"],
- user_id,
+ session_factory, TENANT_LOOKUPS_BY_NAME["tenants_bindable_by_user"], user_id
)
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 45edceec2..c806cb3ad 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -30,7 +30,7 @@ from switch_core.db.stores.user_store import UserStore
from switch_core.db.tenant_lookup import (
all_tenant_ids,
tenant_of_invitation,
- tenants_administered_through_organization,
+ tenants_bindable_by_user,
tenants_inviting_email,
tenants_of_user,
tenants_open_to_domain,
@@ -365,11 +365,9 @@ async def tenants_bindable_by(
session_factory: async_sessionmaker[AsyncSession], user_id: str
) -> list[str]:
"""Every tenant `user_id` may bind: those they are a member of, and those
- they administer as their organization's `org_admin`. Sorted, each once."""
- return sorted(
- set(await tenants_of_user(session_factory, user_id))
- | set(await tenants_administered_through_organization(session_factory, user_id))
- )
+ they administer as their organization's `org_admin`. Sorted, each once.
+ One lookup, read on every authenticated request."""
+ return await tenants_bindable_by_user(session_factory, user_id)
async def workspaces_in_organization(
@@ -400,9 +398,7 @@ async def workspaces_reached_through_organization(
`workspaces_in_organization` does."""
members_of = set(await tenants_of_user(session_factory, user_id))
found: list[Tenant] = []
- for tenant_id in await tenants_administered_through_organization(
- session_factory, user_id
- ):
+ for tenant_id in await tenants_bindable_by_user(session_factory, user_id):
if tenant_id in members_of:
continue
async with tenant_session(session_factory, tenant_id) as session:
diff --git a/core/switch_core/migrations/versions/238c68b7306e_organizations.py b/core/switch_core/migrations/versions/238c68b7306e_organizations.py
index f29b60922..9e6a73648 100644
--- a/core/switch_core/migrations/versions/238c68b7306e_organizations.py
+++ b/core/switch_core/migrations/versions/238c68b7306e_organizations.py
@@ -138,6 +138,12 @@ def upgrade() -> None:
["organization_id"],
["id"],
)
+ # Read by user, and joined on the organization, on every authenticated
+ # request (`tenants_bindable_by_user`).
+ op.create_index(
+ "ix_organization_members_user_id", "organization_members", ["user_id"]
+ )
+ op.create_index("ix_tenants_organization_id", "tenants", ["organization_id"])
# One organization per workspace. Workspace slugs are unique, so the slug
# carries each organization back to the workspace it was made for.
@@ -159,6 +165,8 @@ def upgrade() -> None:
def downgrade() -> None:
+ op.drop_index("ix_tenants_organization_id", table_name="tenants")
+ op.drop_index("ix_organization_members_user_id", table_name="organization_members")
op.drop_constraint("fk_tenants_organization", "tenants", type_="foreignkey")
op.drop_column("tenants", "organization_id")
op.execute(
diff --git a/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py b/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py
deleted file mode 100644
index d7d0d4dd2..000000000
--- a/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_administered_through_organization.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""the lookup that finds the workspaces a person administers through an organization
-
-An organization's `org_admin` administers every workspace in it and may bind
-one without a membership row there. Resolving which workspaces those are
-happens before any is bound, so this adds the fourteenth lookup to the
-exemption from row-level security. See `db/tenant_lookup.py` for what it
-discloses.
-
-The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it
-stood when this migration was written, copied rather than imported so a later
-edit cannot change what this revision means.
-
-Revision ID: 5c2e8f17a9d4
-Revises: 238c68b7306e
-Create Date: 2026-10-29 00:00:00.000000
-
-"""
-
-from collections.abc import Sequence
-
-from alembic import op
-
-revision: str = "5c2e8f17a9d4"
-down_revision: str | Sequence[str] | None = "238c68b7306e"
-branch_labels: str | Sequence[str] | None = None
-depends_on: str | Sequence[str] | None = None
-expand_only: bool = True
-
-SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
-
-CREATE_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION = f"""CREATE OR REPLACE FUNCTION tenants_administered_through_organization(p_user_id text)
- RETURNS SETOF text
- LANGUAGE sql STABLE SECURITY DEFINER
- SET search_path = {SECURE_SEARCH_PATH}
-AS $$SELECT tenants.id FROM tenants JOIN organization_members ON organization_members.organization_id = tenants.organization_id WHERE organization_members.user_id = p_user_id AND organization_members.role = 'org_admin' ORDER BY tenants.id$$"""
-
-DROP_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION = (
- "DROP FUNCTION IF EXISTS tenants_administered_through_organization(text)"
-)
-
-
-def upgrade() -> None:
- op.execute(CREATE_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION)
-
-
-def downgrade() -> None:
- op.execute(DROP_TENANTS_ADMINISTERED_THROUGH_ORGANIZATION)
diff --git a/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_bindable_by_user.py b/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_bindable_by_user.py
new file mode 100644
index 000000000..cc8c4a552
--- /dev/null
+++ b/core/switch_core/migrations/versions/5c2e8f17a9d4_tenants_bindable_by_user.py
@@ -0,0 +1,47 @@
+"""the lookup that finds the workspaces a person may enter, through an organization too
+
+An organization's `org_admin` administers every workspace in it and may bind
+one without a membership row there. Resolving which workspaces a person may
+bind happens before any is bound, on every authenticated request, so this
+adds the fourteenth lookup to the exemption from row-level security: one
+function answering both halves, membership rows and `org_admin`, so a request
+pays one lookup rather than two. See `db/tenant_lookup.py` for what it
+discloses.
+
+The DDL below is a verbatim copy of `switch_core/db/tenant_lookup.py` as it
+stood when this migration was written, copied rather than imported so a later
+edit cannot change what this revision means.
+
+Revision ID: 5c2e8f17a9d4
+Revises: 238c68b7306e
+Create Date: 2026-10-29 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+from alembic import op
+
+revision: str = "5c2e8f17a9d4"
+down_revision: str | Sequence[str] | None = "238c68b7306e"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+expand_only: bool = True
+
+SECURE_SEARCH_PATH = "pg_catalog, public, pg_temp"
+
+CREATE_TENANTS_BINDABLE_BY_USER = f"""CREATE OR REPLACE FUNCTION tenants_bindable_by_user(p_user_id text)
+ RETURNS SETOF text
+ LANGUAGE sql STABLE SECURITY DEFINER
+ SET search_path = {SECURE_SEARCH_PATH}
+AS $$SELECT tenant_id FROM tenant_members WHERE user_id = p_user_id UNION SELECT tenants.id FROM tenants JOIN organization_members ON organization_members.organization_id = tenants.organization_id WHERE organization_members.user_id = p_user_id AND organization_members.role = 'org_admin' ORDER BY 1$$"""
+
+DROP_TENANTS_BINDABLE_BY_USER = "DROP FUNCTION IF EXISTS tenants_bindable_by_user(text)"
+
+
+def upgrade() -> None:
+ op.execute(CREATE_TENANTS_BINDABLE_BY_USER)
+
+
+def downgrade() -> None:
+ op.execute(DROP_TENANTS_BINDABLE_BY_USER)
diff --git a/core/tests/switch_core/db/test_tenant_lookup.py b/core/tests/switch_core/db/test_tenant_lookup.py
index 3452b37ea..abd58e380 100644
--- a/core/tests/switch_core/db/test_tenant_lookup.py
+++ b/core/tests/switch_core/db/test_tenant_lookup.py
@@ -107,7 +107,7 @@ _ADDED_SINCE = {
"tenants_inviting_email": "4b8e2d61c9f7",
"tenants_open_to_domain": "7d3f5a19e2c8",
"tenant_of_sign_in_flow": "e5956cbd3bdc",
- "tenants_administered_through_organization": "5c2e8f17a9d4",
+ "tenants_bindable_by_user": "5c2e8f17a9d4",
}
# A third kind of change, and the quietest: a lookup whose body a later
diff --git a/core/tests/switch_core/gateway/test_tenant_resolution.py b/core/tests/switch_core/gateway/test_tenant_resolution.py
index cb07244ed..de9655512 100644
--- a/core/tests/switch_core/gateway/test_tenant_resolution.py
+++ b/core/tests/switch_core/gateway/test_tenant_resolution.py
@@ -788,14 +788,15 @@ class TestNoClaimWithSeveralMemberships:
goes through, and the case that builds a body is the one where a
second `SECURITY DEFINER` round trip would be easiest not to notice."""
calls = 0
- real = gw_auth.tenants_of_user
+ real = gw_auth.tenants_bindable_by_user
async def counting(*args: object, **kwargs: object) -> list[str]:
nonlocal calls
calls += 1
return await real(*args, **kwargs) # type: ignore[arg-type]
- monkeypatch.setattr(gw_auth, "tenants_of_user", counting)
+ monkeypatch.setattr(gw_auth, "tenants_bindable_by_user", counting)
+ monkeypatch.setattr(gw_auth, "tenants_of_user", _never)
user_id = await _make_user_with_memberships(
session_factory, name="counted", tenant_ids=[TENANT_ZERO_ID, TENANT_B]
@@ -809,6 +810,10 @@ class TestNoClaimWithSeveralMemberships:
assert calls == 1
+async def _never(*args: object, **kwargs: object) -> list[str]:
+ raise AssertionError("tenant resolution asked a second lookup")
+
+
class TestAUserWithNoMembership:
"""The failure has no current cause — every creation path leaves a
membership — but it must be legible if one ever appears, rather than the