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
revert: remove per-tenant usage metering and usage budgets (#561)
Louis Amaudruz05428df20f4f
diff --git a/core/switch_core/bridges/agent/api/activity_routes.py b/core/switch_core/bridges/agent/api/activity_routes.pyindex 0be7a3567..5407dba77 100644--- a/core/switch_core/bridges/agent/api/activity_routes.py+++ b/core/switch_core/bridges/agent/api/activity_routes.py@@ -18,20 +18,16 @@ from switch_core.bridges.agent.dependencies import get_session_factoryfrom switch_core.db.models import Agent, ApprovalRequestfrom switch_core.session_activity.service import (MAX_DETAIL_CHARS,- MAX_MODEL_CHARS,- MAX_MODELS_PER_TURN,MAX_OPTIONS,MAX_QUESTION_OPTIONS,MAX_QUESTIONS,MAX_TEXT_CHARS,MAX_TITLE_CHARS,- MAX_TOKENS,ApprovalOption,Decision,Question,QuestionOption,SessionActivityService,- TokenSpend,)router = APIRouter(prefix="/agent-sessions")@@ -40,14 +36,22 @@ AuthenticatedAgent = Annotated[Agent, Depends(get_agent_from_scope)]_Id = Annotated[str, Field(min_length=1, max_length=200)]+# Per-tenant usage metering was removed, but shipped Switch Console 0.37 still+# posts a `usage` array on every activity report and `ActivityReport` forbids+# extra fields, so the schema is kept only to accept those reports; the value+# is validated and then discarded.+_MAX_MODEL_CHARS = 200+_MAX_MODELS_PER_TURN = 50+_MAX_TOKENS = 2**53 - 1+class TokenUsageIn(BaseModel):model_config = ConfigDict(extra="forbid")- model: str = Field(max_length=MAX_MODEL_CHARS)- input_tokens: int = Field(ge=0, le=MAX_TOKENS)- output_tokens: int = Field(ge=0, le=MAX_TOKENS)- cache_read_tokens: int = Field(ge=0, le=MAX_TOKENS)- cache_write_tokens: int = Field(ge=0, le=MAX_TOKENS)+ model: str = Field(max_length=_MAX_MODEL_CHARS)+ input_tokens: int = Field(ge=0, le=_MAX_TOKENS)+ output_tokens: int = Field(ge=0, le=_MAX_TOKENS)+ cache_read_tokens: int = Field(ge=0, le=_MAX_TOKENS)+ cache_write_tokens: int = Field(ge=0, le=_MAX_TOKENS)class ActivityReport(BaseModel):@@ -66,9 +70,9 @@ class ActivityReport(BaseModel):thread_id: _Id | Nonemessage_id: _Id | Noneoccurred_at: datetime- # Hosts that predate usage reporting do not send it.+ # Accepted from Switch Console 0.37 and ignored; see the note above.usage: list[TokenUsageIn] = Field(- default_factory=list, max_length=MAX_MODELS_PER_TURN+ default_factory=list, max_length=_MAX_MODELS_PER_TURN)@@ -169,16 +173,6 @@ async def report_activity(thread_id=body.thread_id,message_id=body.message_id,occurred_at=body.occurred_at,- usage=[- TokenSpend(- model=u.model,- input_tokens=u.input_tokens,- output_tokens=u.output_tokens,- cache_read_tokens=u.cache_read_tokens,- cache_write_tokens=u.cache_write_tokens,- )- for u in body.usage- ],)return ActivityReceipt(recorded=recorded)diff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 1b05075ce..8c16ba2ec 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -105,7 +105,6 @@ from switch_core.bridges.agent.registration_bootstrap import (REGISTRATION_KEY_TYPES,resolve_registration_owner_id,)-from switch_core.budgets import BudgetExceededfrom switch_core.db.models import Agent, Taskfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.feature_flag_store import FeatureFlagStore@@ -464,8 +463,6 @@ async def send_message(logger.debug("Recieved message from agent %s: %s", agent.name, req.content)try:event_id = await protocol.send_message(agent.id, req.room_id, req.content)- except BudgetExceeded as e:- raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:@@ -552,8 +549,6 @@ async def upload_media(caption=caption,thread_id=thread_id,)- except BudgetExceeded as e:- raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from eexcept PermissionError as e:@@ -1302,8 +1297,6 @@ async def delegate_task(description=req.description,)task = await protocol.get_task(agent.id, result.task_id)- except BudgetExceeded as e:- raise HTTPException(status_code=429, detail=str(e)) from eexcept ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from eexcept PermissionError as e:diff --git a/core/switch_core/bridges/agent/api/operations.py b/core/switch_core/bridges/agent/api/operations.pyindex 53fc928c9..af547f55f 100644--- a/core/switch_core/bridges/agent/api/operations.py+++ b/core/switch_core/bridges/agent/api/operations.py@@ -34,7 +34,6 @@ from switch_core.bridges.agent.operations.callctx import ()from switch_core.bridges.agent.protocol.connections import UnknownConnectionErrorfrom switch_core.bridges.agent.protocol.service import ProtocolService-from switch_core.budgets import BudgetExceededfrom switch_core.db.models import Agentlogger = logging.getLogger(__name__)@@ -239,8 +238,6 @@ async def post_operation(raise HTTPException(status_code=404, detail=str(exc)) from excexcept BadArgumentsError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc- except BudgetExceeded as exc:- raise HTTPException(status_code=429, detail=str(exc)) from excexcept PermissionError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excexcept ValueError as exc:diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex 17804816d..ad551d5bf 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -58,7 +58,6 @@ from switch_core.bridges.agent.registration_bootstrap import (resolve_registration_owner_id,)from switch_core.bridges.resource.service import ResourceService-from switch_core.budgets import BudgetGuardfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.admin_messages import (platform_on_behalf_of,@@ -80,7 +79,6 @@ from switch_core.db.models import (Task,Tool,User,- require_tenant_id,)from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_runtime_state_store import (@@ -89,7 +87,6 @@ from switch_core.db.stores.agent_runtime_state_store import (from switch_core.db.stores.agent_runtime_state_store import (AgentRuntimeStateStore,)-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_role_store import RoomRoleStore@@ -291,7 +288,6 @@ class ProtocolService:self.room_role_store = RoomRoleStore()self.room_group_store = RoomGroupStore()self.message_store = MessageStore()- self.budget_guard = BudgetGuard(BudgetStore())self.user_store = UserStore()self.room_store = room_storeself.room_service = room_service@@ -996,23 +992,9 @@ class ProtocolService:async def require_room_member(self, agent_id: str, room_id: str) -> RoomDescriptor:"""Get room and verify agent is a member. Raises PermissionError if not."""async with self.session_factory() as session:- return await self._room_member_in(session, agent_id, room_id)-- async def require_room_poster(self, agent_id: str, room_id: str) -> RoomDescriptor:- """`require_room_member`, and raise `BudgetExceeded` if the agent has- reached a budget covering it. One session for both, so a post still- costs one pool checkout."""- async with self.session_factory() as session:- room = await self._room_member_in(session, agent_id, room_id)- await self.budget_guard.require_within(- session, tenant_id=require_tenant_id(), agent_id=agent_id+ found = await self.room_store.get_with_membership(+ session, room_id, agent_id)- return room-- async def _room_member_in(- self, session: AsyncSession, agent_id: str, room_id: str- ) -> RoomDescriptor:- found = await self.room_store.get_with_membership(session, room_id, agent_id)if found is None:raise ValueError(f"Room not found: {room_id}")room, is_member = found@@ -1160,7 +1142,7 @@ class ProtocolService:bridges — the resource manager isn't a bridge participant, so its ownnotices wouldn't reach Slack/Mattermost."""try:- await client.send_message(matrix_room_id, body, metered=False)+ await client.send_message(matrix_room_id, body)except Exception:logger.exception("Failed to post agent activity notice to %s", matrix_room_id@@ -1213,7 +1195,7 @@ class ProtocolService:logger.debug("[AGENT-MSG] agent=%s room=%s content=%s", agent_id, room_id, content[:80])- room = await self.require_room_poster(agent_id, room_id)+ room = await self.require_room_member(agent_id, room_id)client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")@@ -1223,10 +1205,7 @@ class ProtocolService:client, room.matrix_room_id, thread_id)event_id = await client.send_message(- room.matrix_room_id,- content,- thread_root_id=thread_root_id,- metered=True,+ room.matrix_room_id, content, thread_root_id=thread_root_id)if event_id is None:raise ValueError("Failed to send message")@@ -1288,7 +1267,7 @@ class ProtocolService:f"attachment '{filename}' is {len(data)} bytes, over the "f"{max_bytes}-byte limit (AGENT_MEDIA_MAX_BYTES)")- room = await self.require_room_poster(agent_id, room_id)+ room = await self.require_room_member(agent_id, room_id)client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")@@ -1320,7 +1299,6 @@ class ProtocolService:if group_id is not Noneelse None),- metered=True,)if event_id is None:raise ValueError(f"Failed to send media message for '{filename}'")@@ -1588,9 +1566,7 @@ class ProtocolService:client = self.client_lifecycle.get_by_agent_id(agent_id)if client is None:raise ValueError("Agent client not running")- await client.send_message(- room.matrix_room_id, f"*{detail}*", format="markdown", metered=True- )+ await client.send_message(room.matrix_room_id, f"*{detail}*", format="markdown")async def set_runtime_state(self,@@ -2169,10 +2145,9 @@ class ProtocolService:"""Delegate a task from one agent to another.Returns task_id and the performer's reachability status at delegation time.- Raises ValueError if agents or room not found, or agents not in room,- and `BudgetExceeded` if either agent has reached a budget covering it.+ Raises ValueError if agents or room not found, or agents not in room."""- room = await self.require_room_poster(requester_id, room_id)+ room = await self.require_room_member(requester_id, room_id)async with self.session_factory() as session:performer = await self.agent_store.get(session, performer_id)@@ -2194,9 +2169,6 @@ class ProtocolService:group_id=room_row.group_id if room_row is not None else None,sender_agent_id=requester_id,)- await self.budget_guard.require_within(- session, tenant_id=require_tenant_id(), agent_id=performer_id- )async with self.session_factory() as session:task = Task(@@ -2326,9 +2298,7 @@ class ProtocolService:"outcome": outcome,},)- await client.send_message(- room.matrix_room_id, outcome, format="markdown", metered=True- )+ await client.send_message(room.matrix_room_id, outcome, format="markdown")async def cancel_task(self, agent_id: str, task_id: str, reason: str) -> None:"""Cancel a task (requester only)."""diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 07296362f..2e64cfba9 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -810,7 +810,6 @@ class BridgeCore:content,format="markdown",thread_root_id=thread_root_id,- metered=True,)if event_id is None:logger.error(@@ -860,7 +859,6 @@ class BridgeCore:if group_id is not Noneelse None),- metered=True,)if event_id is None:logger.error(diff --git a/core/switch_core/budgets.py b/core/switch_core/budgets.pydeleted file mode 100644index 58bc94938..000000000--- a/core/switch_core/budgets.py+++ /dev/null@@ -1,63 +0,0 @@-"""The one check every path an agent spends through makes before it spends.--An agent that has reached a budget covering it is stopped until the period-turns over: addressed room messages are answered with a refusal instead of-delivered (so no session is started or prompted for them), and its own posts-are refused. People are never stopped — a budget caps what agents spend.--What a person types into a session from Switch Console goes straight to the-session's host and never passes through Switch, so it is not stopped here.--Usage is counted after the fact (a turn's tokens arrive when it ends), so the-check stops the next piece of work, not the one in flight, and a budget can be-overshot by whatever was already running when it was reached.-"""--from sqlalchemy.ext.asyncio import AsyncSession--from switch_core.db.stores.budget_store import BudgetStanding, BudgetStore---def _describe(standing: BudgetStanding) -> str:- whose = (- f"Agent {standing.agent_name}"- if standing.agent_name is not None- else "This workspace"- )- metric = standing.metric.replace("_", " ")- model = f" on {standing.model}" if standing.model else ""- resets = standing.resets_at.strftime("%Y-%m-%d %H:%M UTC")- return (- f"{whose} has reached its budget of {standing.amount_limit:,} {metric}"- f"{model} per {standing.period_hours}h. It resets at {resets}."- )---class BudgetExceeded(Exception):- """An agent has reached a budget covering it. The message is written for- the people in the room, since they are who see it."""-- def __init__(self, standing: BudgetStanding) -> None:- super().__init__(_describe(standing))- self.standing = standing---class BudgetGuard:- def __init__(self, store: BudgetStore) -> None:- self._store = store-- async def require_within(- self, session: AsyncSession, *, tenant_id: str, agent_id: str- ) -> None:- """Raise `BudgetExceeded` if the agent has reached any budget covering- it. When several have, the one that resets last is reported, because- that is how long the agent is actually stopped for."""- exhausted = [- standing- for standing in await self._store.standings(- session, tenant_id=tenant_id, agent_id=agent_id- )- if standing.exhausted- ]- if exhausted:- raise BudgetExceeded(max(exhausted, key=lambda s: s.resets_at))diff --git a/core/switch_core/clients/admin_client.py b/core/switch_core/clients/admin_client.pyindex 02942d58c..8eefd8547 100644--- a/core/switch_core/clients/admin_client.py+++ b/core/switch_core/clients/admin_client.py@@ -125,7 +125,6 @@ class AdminClient(ClientBase[ClientConfig]):format=format,thread_root_id=thread_root_id,extra_content=admin_extra_content(AdminMessageType.COMMAND_RESULT),- metered=False,)# ── Platform messages ───────────────────────────────────────────────────@@ -164,7 +163,6 @@ class AdminClient(ClientBase[ClientConfig]):format="markdown",thread_root_id=thread_root_id,extra_content={PLATFORM_MARKER: marker_value},- metered=False,)# ── Admin notices ─────────────────────────────────────────────────────────@@ -285,7 +283,6 @@ class AdminClient(ClientBase[ClientConfig]):mentions=mentions,thread_root_id=thread_root_id,extra_content=admin_extra_content(message_type),- metered=False,)def _sender_handle(self, event: InboundMessage) -> str:diff --git a/core/switch_core/clients/agent_client.py b/core/switch_core/clients/agent_client.pyindex f1968c74a..c311dc9ca 100644--- a/core/switch_core/clients/agent_client.py+++ b/core/switch_core/clients/agent_client.py@@ -33,7 +33,6 @@ from switch_core.bridges.agent.protocol.types import (TaskFinalisePayload,TaskUpdatePayload,)-from switch_core.budgets import BudgetExceeded, BudgetGuardfrom switch_core.clients.admin_messages import (PLATFORM_MARKER,platform_on_behalf_of,@@ -58,7 +57,6 @@ from switch_core.db.models import Agentfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_session_store import AgentSessionStorefrom switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStorefrom switch_core.db.stores.external_user_store import ExternalUserStore@@ -278,7 +276,6 @@ class AgentClient(ClientBase[ClientConfig]):external_user_store=external_user_store,live_connection_ids=connections.live_connection_ids,)- self._budget_guard = BudgetGuard(BudgetStore())self._room_meta: dict[str, RoomMeta | None] = {}# In-flight multi-attachment groups, by group id, with their safety-net# timers. Both are cleared when a group completes or times out, so a@@ -348,9 +345,7 @@ class AgentClient(ClientBase[ClientConfig]):greeting = f"Hi! I'm {name} — how can I help?"else:greeting = random.choice(AGENT_GREETINGS).format(name=name)- await self.send_message(- room.room_id, greeting, format="markdown", metered=False- )+ await self.send_message(room.room_id, greeting, format="markdown")async def on_removed(self, room: RoomRef, event: InboundMembership) -> None:"""Forget the room's events, everywhere this agent could still read them.@@ -862,11 +857,7 @@ class AgentClient(ClientBase[ClientConfig]):"""Post a command result as this agent (an agent-owned command like`!run-cmd` answers in the agent's own voice, not as a system message)."""await self.send_message(- room_id,- body,- format=format,- thread_root_id=thread_root_id,- metered=False,+ room_id, body, format=format, thread_root_id=thread_root_id)async def _resolve_room_meta(self, matrix_room_id: str) -> RoomMeta | None:@@ -1135,9 +1126,7 @@ class AgentClient(ClientBase[ClientConfig]):async def on_task_delegate(self, room: RoomRef, event: TaskDelegate) -> None:if event.performer_agent_id != self.agent.id:return- await self.send_message(- room.room_id, "Working on it.", format="markdown", metered=False- )+ await self.send_message(room.room_id, "Working on it.", format="markdown")meta = await self._resolve_room_meta(room.room_id)if meta is None:return@@ -1333,8 +1322,8 @@ class AgentClient(ClientBase[ClientConfig]):) -> _GateOutcome:"""Apply the scoped addressing policy to a message that tags this agent.- When the sender is not permitted by the agent's policy, or the agent- has reached a budget covering it, the message is demoted to unaddressed room chatter and the caller is handed a refusal+ When the sender is not permitted by the agent's policy, the message is+ demoted to unaddressed room chatter and the caller is handed a refusalto post (once, guarded by AUTO_REPLY_FLAG so two agents can'tping-pong). Zero cost for the common case: only messages that alreadytag this agent are ever checked, and open policies short-circuit.@@ -1343,19 +1332,10 @@ class AgentClient(ClientBase[ClientConfig]):session, agent, event.sender, meta.room_id, event.content)if decision.allowed:- try:- await self._budget_guard.require_within(- session, tenant_id=self.tenant_id, agent_id=agent.id- )- except BudgetExceeded as exc:- refusal = str(exc)- else:- return _GateOutcome(addressed=True, refusal=None)- else:- refusal = decision.refusal+ return _GateOutcome(addressed=True, refusal=None)if self._triggered_by_auto_reply(event):return _GateOutcome(addressed=False, refusal=None)- return _GateOutcome(addressed=False, refusal=refusal)+ return _GateOutcome(addressed=False, refusal=decision.refusal)@staticmethoddef _triggered_by_auto_reply(event: InboundMessage) -> bool:@@ -1379,7 +1359,6 @@ class AgentClient(ClientBase[ClientConfig]):mentions=[event.sender],thread_root_id=thread_root_id,extra_content={AUTO_REPLY_FLAG: True},- metered=False,)def _args_tag_my_name(self, text: str) -> bool:diff --git a/core/switch_core/clients/client_base.py b/core/switch_core/clients/client_base.pyindex b9cc288b6..c21634e87 100644--- a/core/switch_core/clients/client_base.py+++ b/core/switch_core/clients/client_base.py@@ -476,7 +476,6 @@ class ClientBase[ConfigT: ClientConfig]:room_id: str,body: str,*,- metered: bool,format: Literal["text", "markdown"] = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -487,7 +486,6 @@ class ClientBase[ConfigT: ClientConfig]:room_id,body,sender_name=self.display_name,- metered=metered,format=format,mentions=mentions,thread_root_id=thread_root_id,@@ -527,7 +525,6 @@ class ClientBase[ConfigT: ClientConfig]:mimetype: str,size: int,*,- metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -555,7 +552,6 @@ class ClientBase[ConfigT: ClientConfig]:mimetype,size,sender_name=self.display_name,- metered=metered,msgtype=msgtype,caption=caption,thread_root_id=thread_root_id,diff --git a/core/switch_core/clients/client_factory.py b/core/switch_core/clients/client_factory.pyindex a68fb64ee..50b75b1e8 100644--- a/core/switch_core/clients/client_factory.py+++ b/core/switch_core/clients/client_factory.py@@ -12,7 +12,6 @@ from switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.messages.notify import MessageListenerfrom switch_core.transport import MessageTransportfrom switch_core.transport.ephemeral import EphemeralBus@@ -31,7 +30,6 @@ class ClientFactory:config: SwitchConfig,room_store: RoomStore,message_store: MessageStore,- usage_store: UsageStore,media_store: MediaStore,listener: MessageListener,invites: InviteBus,@@ -42,7 +40,6 @@ class ClientFactory:self._config = configself._room_store = room_storeself._message_store = message_store- self._usage_store = usage_storeself._media_store = media_storeself._listener = listenerself._invites = invites@@ -98,7 +95,6 @@ class ClientFactory:session_factory=self._session_factory,room_store=self._room_store,message_store=self._message_store,- usage_store=self._usage_store,media_store=self._media_store,listener=self._listener,invites=self._invites,diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 28be83933..c31d70019 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -1,6 +1,5 @@import uuidfrom datetime import datetime-from enum import StrEnumfrom sqlalchemy import (DDL,@@ -2306,131 +2305,6 @@ for _table, _triggers in (event.listen(_table, "after_create", DDL(_ddl).execute_if(dialect="postgresql"))-# ── Usage metering ───────────────────────────────────────────────────────────---class UsageMetric(StrEnum):- """What is counted. Cache reads and writes are kept apart from input- tokens because providers price them apart."""-- MESSAGES = "messages"- TURNS = "turns"- INPUT_TOKENS = "input_tokens"- OUTPUT_TOKENS = "output_tokens"- CACHE_READ_TOKENS = "cache_read_tokens"- CACHE_WRITE_TOKENS = "cache_write_tokens"---class TenantUsage(TenantScoped, Base):- """What a tenant has consumed, counted as it happens, one row per hour.-- The record that quotas are enforced against and that billing will read,- so it is kept apart from the rows it counts: deleting a room cascades to- its messages, and a count derived from `messages` would forget usage the- tenant has already spent. Written in the same transaction as the thing it- counts, so the two cannot disagree.-- Hourly buckets because a budget period is configurable: any period of a- whole number of hours is a sum over these rows, while a coarser bucket- would fix the shortest period a budget can have.-- `client_id` is who consumed it: the sender of a message, or the client of- the agent a turn ran for. No foreign key, so a count outlives the client it- names. `model` is empty where a metric has none.- """-- __tablename__ = "tenant_usage"- __table_args__ = (- # Leads on the metric so "this tenant's turns since a moment" — the- # shape every budget check asks — is a range scan on the key itself.- PrimaryKeyConstraint(- "tenant_id", "metric", "bucket_start", "client_id", "model"- ),- CheckConstraint(- "metric IN ({})".format(", ".join(f"'{m}'" for m in UsageMetric)),- name="ck_tenant_usage_metric",- ),- CheckConstraint("amount > 0", name="ck_tenant_usage_amount"),- )-- metric: Mapped[str] = mapped_column(Text, nullable=False)- bucket_start: Mapped[datetime] = mapped_column(- DateTime(timezone=True), nullable=False- )- client_id: Mapped[str] = mapped_column(Text, nullable=False)- model: Mapped[str] = mapped_column(Text, nullable=False)- amount: Mapped[int] = mapped_column(BigInteger, nullable=False)---# A budget's period is at most a leap year, and its limit at most the largest-# integer a JavaScript client reads exactly. Both keep the period arithmetic-# and the gateway's numbers from overflowing.-MAX_BUDGET_PERIOD_HOURS = 8784-MAX_BUDGET_AMOUNT = 2**53 - 1---class UsageBudget(TenantScoped, Base):- """A ceiling on one metric over a repeating period.-- `agent_id` null covers every agent in the tenant; otherwise the one agent.- `model` empty covers every model. An agent that has reached any budget- covering it is stopped until the period turns over; people are never- stopped. A tenant with no budgets is unlimited.-- Periods are whole hours counted from the Unix epoch in UTC, so a daily- budget turns over at midnight UTC and every writer agrees when.- """-- __tablename__ = "usage_budgets"- __table_args__ = (- ForeignKeyConstraint(- ["tenant_id", "agent_id"],- ["agents.tenant_id", "agents.id"],- name="fk_usage_budgets_agent",- ondelete="CASCADE",- ),- CheckConstraint(- "metric IN ({})".format(", ".join(f"'{m}'" for m in UsageMetric)),- name="ck_usage_budgets_metric",- ),- CheckConstraint(- f"amount_limit > 0 AND amount_limit <= {MAX_BUDGET_AMOUNT}",- name="ck_usage_budgets_amount_limit",- ),- CheckConstraint(- f"period_hours > 0 AND period_hours <= {MAX_BUDGET_PERIOD_HOURS}",- name="ck_usage_budgets_period_hours",- ),- Index(- "uq_usage_budgets_tenant_wide",- "tenant_id",- "metric",- "model",- unique=True,- postgresql_where=text("agent_id IS NULL"),- ),- Index(- "uq_usage_budgets_agent",- "tenant_id",- "agent_id",- "metric",- "model",- unique=True,- postgresql_where=text("agent_id IS NOT NULL"),- ),- )-- id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)- agent_id: Mapped[str | None] = mapped_column(Text, nullable=True)- metric: Mapped[str] = mapped_column(Text, nullable=False)- model: Mapped[str] = mapped_column(Text, nullable=False)- amount_limit: Mapped[int] = mapped_column(BigInteger, nullable=False)- period_hours: Mapped[int] = mapped_column(Integer, nullable=False)- created_at: Mapped[datetime] = mapped_column(- DateTime(timezone=True), server_default=func.now(), nullable=False- )--# Same reasoning as the notify trigger above: `create_all` has to build the# row-level-security policies too, or the isolation test would pass against a# schema that has none. See `db/rls_ddl.py` for the DDL and why it takes thisdiff --git a/core/switch_core/db/stores/budget_store.py b/core/switch_core/db/stores/budget_store.pydeleted file mode 100644index 12cb9aaba..000000000--- a/core/switch_core/db/stores/budget_store.py+++ /dev/null@@ -1,186 +0,0 @@-from dataclasses import dataclass-from datetime import datetime--from sqlalchemy import BigInteger, ColumnElement, and_, cast, delete, func, or_, select-from sqlalchemy.ext.asyncio import AsyncSession-from sqlalchemy.orm import aliased--from switch_core.db.models import Agent, TenantUsage, UsageBudget, UsageMetric---@dataclass(frozen=True)-class BudgetStanding:- """A budget and what has been spent against it in the current period.-- `agent_id` and `agent_name` are null for a budget covering every agent.- """-- id: str- agent_id: str | None- agent_name: str | None- metric: str- model: str- amount_limit: int- period_hours: int- spent: int- resets_at: datetime-- @property- def exhausted(self) -> bool:- return self.spent >= self.amount_limit---class BudgetNotFound(LookupError):- pass---def _period_start() -> ColumnElement[datetime]:- """The start of the budget's current period, on the database's clock.-- Periods are counted from the Unix epoch in whole hours, which puts a daily- boundary at midnight UTC and lines every period up with the hourly usage- buckets it sums.- """- seconds = cast(UsageBudget.period_hours, BigInteger) * 3600- return func.to_timestamp(- func.floor(func.extract("epoch", func.now()) / seconds) * seconds- )---class BudgetStore:- async def standings(- self, session: AsyncSession, *, tenant_id: str, agent_id: str | None- ) -> list[BudgetStanding]:- """The tenant's budgets with their current spend.-- With `agent_id`, only the budgets covering that agent: its own and the- tenant-wide ones. Without, every budget the tenant has.-- A tenant-wide budget sums what the tenant's agents spent, not what its- people and bridges did, since it is agents that a budget stops.-- Names the tenant explicitly as well as relying on the bound session,- for the reason `UsageStore.totals` gives.- """- period_start = _period_start()- agent_clients = aliased(Agent)- spent = (- select(func.coalesce(func.sum(TenantUsage.amount), 0))- .where(- TenantUsage.tenant_id == UsageBudget.tenant_id,- TenantUsage.metric == UsageBudget.metric,- TenantUsage.bucket_start >= period_start,- or_(UsageBudget.model == "", TenantUsage.model == UsageBudget.model),- or_(- and_(- UsageBudget.agent_id.is_(None),- TenantUsage.client_id.in_(- select(agent_clients.client_id).where(- agent_clients.tenant_id == UsageBudget.tenant_id- )- ),- ),- TenantUsage.client_id == Agent.client_id,- ),- )- .correlate(UsageBudget, Agent)- .scalar_subquery()- )- statement = (- select(- UsageBudget,- Agent.name,- spent,- period_start + func.make_interval(0, 0, 0, 0, UsageBudget.period_hours),- )- .outerjoin(- Agent,- and_(- Agent.tenant_id == UsageBudget.tenant_id,- Agent.id == UsageBudget.agent_id,- ),- )- .where(UsageBudget.tenant_id == tenant_id)- .order_by(- UsageBudget.agent_id.nulls_first(),- UsageBudget.metric,- UsageBudget.model,- )- )- if agent_id is not None:- statement = statement.where(- or_(UsageBudget.agent_id.is_(None), UsageBudget.agent_id == agent_id)- )- rows = await session.execute(statement)- return [- BudgetStanding(- id=budget.id,- agent_id=budget.agent_id,- agent_name=agent_name,- metric=budget.metric,- model=budget.model,- amount_limit=budget.amount_limit,- period_hours=budget.period_hours,- spent=int(amount),- resets_at=resets_at,- )- for budget, agent_name, amount, resets_at in rows- ]-- async def create(- self,- session: AsyncSession,- *,- tenant_id: str,- agent_id: str | None,- metric: UsageMetric,- model: str,- amount_limit: int,- period_hours: int,- ) -> UsageBudget:- """Add a budget. A second budget on the same agent (or tenant-wide),- metric and model fails on the unique index; the caller decides what- that means to its user."""- budget = UsageBudget(- tenant_id=tenant_id,- agent_id=agent_id,- metric=metric.value,- model=model,- amount_limit=amount_limit,- period_hours=period_hours,- )- session.add(budget)- await session.flush()- return budget-- async def update(- self,- session: AsyncSession,- *,- tenant_id: str,- budget_id: str,- amount_limit: int,- period_hours: int,- ) -> UsageBudget:- budget = await session.scalar(- select(UsageBudget).where(- UsageBudget.tenant_id == tenant_id, UsageBudget.id == budget_id- )- )- if budget is None:- raise BudgetNotFound(budget_id)- budget.amount_limit = amount_limit- budget.period_hours = period_hours- await session.flush()- return budget-- async def delete(- self, session: AsyncSession, *, tenant_id: str, budget_id: str- ) -> None:- result = await session.execute(- delete(UsageBudget).where(- UsageBudget.tenant_id == tenant_id, UsageBudget.id == budget_id- )- )- if result.rowcount == 0: # type: ignore[attr-defined]- raise BudgetNotFound(budget_id)diff --git a/core/switch_core/db/stores/session_activity_store.py b/core/switch_core/db/stores/session_activity_store.pyindex c271fbc25..44cce1404 100644--- a/core/switch_core/db/stores/session_activity_store.py+++ b/core/switch_core/db/stores/session_activity_store.py@@ -101,27 +101,6 @@ class ApprovalRequestStore:class SessionActivityStore:- async def status_for_update(- self,- session: AsyncSession,- agent_id: str,- session_id: str,- turn_id: str,- item_id: str,- ) -> str | None:- """The row's stored status, locked until the transaction ends, or None."""- status: str | None = await session.scalar(- select(SessionActivityItem.status)- .where(- SessionActivityItem.agent_id == agent_id,- SessionActivityItem.session_id == session_id,- SessionActivityItem.turn_id == turn_id,- SessionActivityItem.item_id == item_id,- )- .with_for_update()- )- return status-async def upsert(self, session: AsyncSession, item: SessionActivityItem) -> bool:"""Record `item` unless a revision at least as new is stored.diff --git a/core/switch_core/db/stores/usage_store.py b/core/switch_core/db/stores/usage_store.pydeleted file mode 100644index 0ea4b13f6..000000000--- a/core/switch_core/db/stores/usage_store.py+++ /dev/null@@ -1,124 +0,0 @@-from dataclasses import dataclass-from datetime import datetime--from sqlalchemy import and_, func, literal, select-from sqlalchemy.dialects.postgresql import insert-from sqlalchemy.ext.asyncio import AsyncSession--from switch_core.db.models import Client, TenantUsage, UsageMetric---@dataclass(frozen=True)-class UsageTotal:- """One consumer's total of one metric over a window.-- `client_name` and `client_type` are null for a client that no longer- exists; the usage it spent is still the tenant's.- """-- metric: str- client_id: str- client_name: str | None- client_type: str | None- model: str- amount: int---class UsageStore:- async def record(- self,- session: AsyncSession,- *,- tenant_id: str,- metric: UsageMetric,- client_id: str,- model: str,- amount: int,- ) -> None:- """Add `amount` to the current hour's count, in the caller's transaction.-- The bucket is the database's clock, not this process's, so every writer- agrees on which hour it is. Hours are taken in UTC so a deployment's- `TimeZone` setting cannot move a bucket boundary.- """- if amount <= 0:- raise ValueError(f"usage amount must be positive, got {amount}")- bucket = func.date_trunc("hour", func.now(), literal("UTC"))- statement = insert(TenantUsage).values(- tenant_id=tenant_id,- metric=metric.value,- bucket_start=bucket,- client_id=client_id,- model=model,- amount=amount,- )- statement = statement.on_conflict_do_update(- index_elements=[- "tenant_id",- "metric",- "bucket_start",- "client_id",- "model",- ],- set_={"amount": TenantUsage.amount + statement.excluded.amount},- )- await session.execute(statement)-- async def totals(- self,- session: AsyncSession,- *,- tenant_id: str,- since: datetime,- until: datetime,- ) -> list[UsageTotal]:- """Totals per metric, consumer and model for buckets in `[since, until)`.-- Buckets are whole hours, so `since` is rounded down to the hour it- falls in and a bucket counts if it starts before `until`.-- Names the tenant explicitly as well as relying on the bound session:- the policy does not apply on an owner connection, and a fan-out that- leaned on it alone would count every tenant's rows as this one's.- """- rows = await session.execute(- select(- TenantUsage.metric,- TenantUsage.client_id,- Client.display_name,- Client.type,- TenantUsage.model,- func.sum(TenantUsage.amount),- )- .outerjoin(- Client,- and_(- Client.id == TenantUsage.client_id,- Client.tenant_id == TenantUsage.tenant_id,- ),- )- .where(- TenantUsage.tenant_id == tenant_id,- TenantUsage.bucket_start >= func.date_trunc("hour", since, "UTC"),- TenantUsage.bucket_start < until,- )- .group_by(- TenantUsage.metric,- TenantUsage.client_id,- Client.display_name,- Client.type,- TenantUsage.model,- )- .order_by(TenantUsage.metric, TenantUsage.client_id, TenantUsage.model)- )- return [- UsageTotal(- metric=metric,- client_id=client_id,- client_name=client_name,- client_type=client_type,- model=model,- amount=int(amount),- )- for metric, client_id, client_name, client_type, model, amount in rows- ]diff --git a/core/switch_core/gateway/app.py b/core/switch_core/gateway/app.pyindex 74de0ddba..038baf073 100644--- a/core/switch_core/gateway/app.py+++ b/core/switch_core/gateway/app.py@@ -19,7 +19,6 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.invitation_store import InvitationStore@@ -27,7 +26,6 @@ from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.agent_sessions import router as agent_sessions_routerfrom switch_core.gateway.agents import router as agents_router@@ -73,8 +71,6 @@ def create_gateway_app(api_key_store: ApiKeyStore,invitation_store: InvitationStore,template_store: TemplateStore,- usage_store: UsageStore,- budget_store: BudgetStore,resource_service: ResourceService,protocol: ProtocolService,install_service: MessagingInstallService | None,@@ -97,8 +93,6 @@ def create_gateway_app(api_key_store=api_key_store,invitation_store=invitation_store,template_store=template_store,- usage_store=usage_store,- budget_store=budget_store,resource_service=resource_service,protocol=protocol,install_service=install_service,diff --git a/core/switch_core/gateway/dependencies.py b/core/switch_core/gateway/dependencies.pyindex d75ad0444..4e5aecbd4 100644--- a/core/switch_core/gateway/dependencies.py+++ b/core/switch_core/gateway/dependencies.py@@ -21,7 +21,6 @@ from switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfigfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.invitation_store import InvitationStore@@ -30,7 +29,6 @@ from switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.template_store import TemplateStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.room_service import RoomServicefrom switch_core.rooms_yaml import RoomYamlService@@ -57,8 +55,6 @@ def init_dependencies(api_key_store: ApiKeyStore,invitation_store: InvitationStore,template_store: TemplateStore,- usage_store: UsageStore,- budget_store: BudgetStore,resource_service: ResourceService,protocol: ProtocolService,install_service: MessagingInstallService | None,@@ -80,8 +76,6 @@ def init_dependencies(_state["api_key_store"] = api_key_store_state["invitation_store"] = invitation_store_state["template_store"] = template_store- _state["usage_store"] = usage_store- _state["budget_store"] = budget_store_state["resource_service"] = resource_service_state["protocol"] = protocol_state["install_service"] = install_service@@ -200,14 +194,6 @@ def get_invitation_store() -> InvitationStore:return _state["invitation_store"] # type: ignore[no-any-return]-def get_usage_store() -> UsageStore:- return _state["usage_store"] # type: ignore[no-any-return]---def get_budget_store() -> BudgetStore:- return _state["budget_store"] # type: ignore[no-any-return]--def get_connector_lifecycle() -> ServerSideConnectorLifecycleService:return _state["connector_lifecycle"] # type: ignore[no-any-return]diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 26901d9f2..d8178781c 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -1,17 +1,11 @@from __future__ import annotations-from datetime import datetimefrom typing import Any, Literal-from pydantic import BaseModel, Field, model_validator+from pydantic import BaseModel, Fieldfrom switch_core.addressing import AddressingPolicyfrom switch_core.bridges.collaboration.models import BridgeInstallLink-from switch_core.db.models import (- MAX_BUDGET_AMOUNT,- MAX_BUDGET_PERIOD_HOURS,- UsageMetric,-)# ── Rooms ─────────────────────────────────────────────────────────────────────@@ -727,21 +721,6 @@ class MemberDetail(BaseModel):created_at: str-class UsageTotalResponse(BaseModel):- """One consumer's total of one metric over the requested window.-- `client_name` and `client_type` are null when the client has since been- deleted; what it spent still counts against the workspace.- """-- metric: str- client_id: str- client_name: str | None- client_type: str | None- model: str- amount: int--class MemberUpdateRequest(BaseModel):role: str@@ -1196,44 +1175,3 @@ class TemplateValidateResponse(BaseModel):blocked: boolerrors: list[TemplateFinding]warnings: list[TemplateFinding]---class BudgetCreateRequest(BaseModel):- """A new budget. `agent_id` null covers every agent in the workspace;- `model` empty covers every model."""-- agent_id: str | None- metric: UsageMetric- model: str- amount_limit: int = Field(gt=0, le=MAX_BUDGET_AMOUNT)- period_hours: int = Field(gt=0, le=MAX_BUDGET_PERIOD_HOURS)-- @model_validator(mode="after")- def _model_only_on_token_metrics(self) -> BudgetCreateRequest:- if self.model and self.metric in (UsageMetric.MESSAGES, UsageMetric.TURNS):- raise ValueError(- f"A {self.metric.value} budget cannot name a model: "- f"{self.metric.value} are not counted per model"- )- return self---class BudgetUpdateRequest(BaseModel):- amount_limit: int = Field(gt=0, le=MAX_BUDGET_AMOUNT)- period_hours: int = Field(gt=0, le=MAX_BUDGET_PERIOD_HOURS)---class BudgetResponse(BaseModel):- """A budget and what has been spent against it in the current period,- which ends at `resets_at`."""-- id: str- agent_id: str | None- agent_name: str | None- metric: str- model: str- amount_limit: int- period_hours: int- spent: int- resets_at: datetime- exhausted: booldiff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex a42bcf9c3..4b2065dac 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -6,7 +6,7 @@ import refrom datetime import UTC, datetime, timedeltafrom typing import Annotated-from fastapi import APIRouter, Depends, HTTPException, Query, Response+from fastapi import APIRouter, Depends, HTTPException, Responsefrom sqlalchemy import selectfrom sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker@@ -18,16 +18,10 @@ from switch_core.db.models import Invitation, Tenant, TenantMember, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.budget_store import (- BudgetNotFound,- BudgetStanding,- BudgetStore,-)from switch_core.db.stores.invitation_store import (InvitationNotUsableError,InvitationStore,)-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (AuthenticatedCaller,@@ -46,7 +40,6 @@ from switch_core.gateway.dependencies import (current_telemetry,get_agent_store,get_api_key_store,- get_budget_store,get_client_lifecycle,get_config,get_invitation_store,@@ -54,13 +47,9 @@ from switch_core.gateway.dependencies import (get_session,get_session_factory,get_system_session,- get_usage_store,get_user_store,)from switch_core.gateway.schemas import (- BudgetCreateRequest,- BudgetResponse,- BudgetUpdateRequest,InvitationAcceptRequest,InvitationCreateRequest,InvitationCreateResponse,@@ -70,7 +59,6 @@ from switch_core.gateway.schemas import (SessionUserResponse,TenantCreateRequest,TenantMembershipResponse,- UsageTotalResponse,)from switch_core.telemetry import emit_safelyfrom switch_core.telemetry.ages import age_hours@@ -441,169 +429,6 @@ async def create_invitation(return InvitationCreateResponse(token=token, **_invitation_fields(invitation))[email protected]("/tenants/{tenant_id}/usage")-async def get_usage(- tenant_id: str,- since: Annotated[datetime, Query()],- until: Annotated[datetime, Query()],- session: Annotated[AsyncSession, Depends(get_session)],- usage_store: Annotated[UsageStore, Depends(get_usage_store)],- _user: Annotated[User, Depends(require_tenant_admin)],-) -> list[UsageTotalResponse]:- """The bound tenant's usage per metric, consumer and model over `[since, until)`.-- `owner`/`admin` only. Usage is counted in whole UTC hours, so `since` is- widened to the start of its hour. Both bounds must carry a timezone: a- naive time would be read in the server's zone and quietly shift the window.- """- _require_bound_tenant(tenant_id)- if since.tzinfo is None or until.tzinfo is None:- raise HTTPException(- status_code=400, detail="since and until must include a timezone offset"- )- if since >= until:- raise HTTPException(status_code=400, detail="since must be before until")- totals = await usage_store.totals(- session, tenant_id=tenant_id, since=since, until=until- )- return [- UsageTotalResponse(- metric=t.metric,- client_id=t.client_id,- client_name=t.client_name,- client_type=t.client_type,- model=t.model,- amount=t.amount,- )- for t in totals- ]---def _budget_response(standing: BudgetStanding) -> BudgetResponse:- return BudgetResponse(- id=standing.id,- agent_id=standing.agent_id,- agent_name=standing.agent_name,- metric=standing.metric,- model=standing.model,- amount_limit=standing.amount_limit,- period_hours=standing.period_hours,- spent=standing.spent,- resets_at=standing.resets_at,- exhausted=standing.exhausted,- )---async def _budget_standing(- session: AsyncSession, budget_store: BudgetStore, tenant_id: str, budget_id: str-) -> BudgetResponse:- for standing in await budget_store.standings(- session, tenant_id=tenant_id, agent_id=None- ):- if standing.id == budget_id:- return _budget_response(standing)- raise HTTPException(status_code=404, detail="Budget not found")--[email protected]("/tenants/{tenant_id}/budgets")-async def list_budgets(- tenant_id: str,- session: Annotated[AsyncSession, Depends(get_session)],- budget_store: Annotated[BudgetStore, Depends(get_budget_store)],- _user: Annotated[User, Depends(require_tenant_admin)],-) -> list[BudgetResponse]:- """Every budget of the bound tenant with its spend in the current period.- `owner`/`admin` only."""- _require_bound_tenant(tenant_id)- standings = await budget_store.standings(- session, tenant_id=tenant_id, agent_id=None- )- return [_budget_response(s) for s in standings]--[email protected]("/tenants/{tenant_id}/budgets", status_code=201)-async def create_budget(- tenant_id: str,- body: BudgetCreateRequest,- session: Annotated[AsyncSession, Depends(get_session)],- budget_store: Annotated[BudgetStore, Depends(get_budget_store)],- agent_store: Annotated[AgentStore, Depends(get_agent_store)],- _user: Annotated[User, Depends(require_tenant_admin)],-) -> BudgetResponse:- """Add a budget to the bound tenant. `owner`/`admin` only.-- 404 when `agent_id` names no agent in this workspace; 409 when the same- agent (or the whole workspace), metric and model already has one — edit- that one instead.- """- _require_bound_tenant(tenant_id)- if body.agent_id is not None:- agent = await agent_store.get(session, body.agent_id)- if agent is None or agent.tenant_id != tenant_id:- raise HTTPException(status_code=404, detail="Agent not found")- try:- budget = await budget_store.create(- session,- tenant_id=tenant_id,- agent_id=body.agent_id,- metric=body.metric,- model=body.model,- amount_limit=body.amount_limit,- period_hours=body.period_hours,- )- except IntegrityError as exc:- raise HTTPException(- status_code=409,- detail="A budget for this agent, metric and model already exists",- ) from exc- await session.commit()- return await _budget_standing(session, budget_store, tenant_id, budget.id)--[email protected]("/tenants/{tenant_id}/budgets/{budget_id}")-async def update_budget(- tenant_id: str,- budget_id: str,- body: BudgetUpdateRequest,- session: Annotated[AsyncSession, Depends(get_session)],- budget_store: Annotated[BudgetStore, Depends(get_budget_store)],- _user: Annotated[User, Depends(require_tenant_admin)],-) -> BudgetResponse:- """Change a budget's limit and period. `owner`/`admin` only. What it- covers is fixed; to cover something else, add another budget."""- _require_bound_tenant(tenant_id)- try:- await budget_store.update(- session,- tenant_id=tenant_id,- budget_id=budget_id,- amount_limit=body.amount_limit,- period_hours=body.period_hours,- )- except BudgetNotFound as exc:- raise HTTPException(status_code=404, detail="Budget not found") from exc- await session.commit()- return await _budget_standing(session, budget_store, tenant_id, budget_id)--[email protected]("/tenants/{tenant_id}/budgets/{budget_id}", status_code=204)-async def delete_budget(- tenant_id: str,- budget_id: str,- session: Annotated[AsyncSession, Depends(get_session)],- budget_store: Annotated[BudgetStore, Depends(get_budget_store)],- _user: Annotated[User, Depends(require_tenant_admin)],-) -> Response:- """Remove a budget. `owner`/`admin` only."""- _require_bound_tenant(tenant_id)- try:- await budget_store.delete(session, tenant_id=tenant_id, budget_id=budget_id)- except BudgetNotFound as exc:- raise HTTPException(status_code=404, detail="Budget not found") from exc- await session.commit()- return Response(status_code=204)--@router.get("/tenants/{tenant_id}/invitations")async def list_invitations(tenant_id: str,diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex f9a7785f3..9f3119d6e 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -100,7 +100,6 @@ from 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 ApiKeyStorefrom switch_core.db.stores.bridge_message_map_store import BridgeMessageMapStore-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.document_store import DocumentStore@@ -121,7 +120,6 @@ from switch_core.db.stores.server_connector_store import ServerConnectorStorefrom switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.tenant_store import TenantStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import all_tenant_idsfrom switch_core.gateway.app import create_gateway_app@@ -391,8 +389,6 @@ async def run(config: SwitchConfig) -> None:room_group_store = RoomGroupStore()room_role_store = RoomRoleStore()message_store = MessageStore()- usage_store = UsageStore()- budget_store = BudgetStore()media_store = MediaStore()template_store = TemplateStore()@@ -474,7 +470,6 @@ async def run(config: SwitchConfig) -> None:config=config,room_store=room_store,message_store=message_store,- usage_store=usage_store,media_store=media_store,listener=message_listener,invites=invites,@@ -647,8 +642,6 @@ async def run(config: SwitchConfig) -> None:api_key_store=api_key_store,invitation_store=invitation_store,template_store=template_store,- usage_store=usage_store,- budget_store=budget_store,resource_service=resource_service,protocol=protocol,install_service=install_service,diff --git a/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.py b/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.pydeleted file mode 100644index 44573b964..000000000--- a/core/switch_core/migrations/versions/c7e4a91d3b20_tenant_usage.py+++ /dev/null@@ -1,75 +0,0 @@-"""per-tenant usage, counted as it happens--Revision ID: c7e4a91d3b20-Revises: c4e9a1f7b203--The metering record quotas are enforced against and billing will read: one row-per tenant, metric, hour, consumer and model, incremented in the same-transaction as the message or turn it counts (CHOO-2625).--It is a table of its own rather than a count over ``messages`` because usage-must outlive what it counts: deleting a room cascades to its messages, and a-tenant's spend cannot shrink when it tidies up. Nothing here can be backfilled-— counting starts when this migration runs.--Buckets are an hour wide so that a budget period can be any whole number of-hours; the key leads on the metric so the question a budget asks, "this-tenant's turns since a moment", is a range scan on the key itself.--``client_id`` carries no foreign key, so a count outlives the client it names.--The row-level-security DDL is a verbatim copy of ``switch_core/db/rls_ddl.py``-as it stood when this migration was written, copied rather than imported for-the reason ``265ed188ad6f`` gives.-"""--from collections.abc import Sequence--import sqlalchemy as sa-from alembic import op--revision: str = "c7e4a91d3b20"-down_revision: str | Sequence[str] | None = "c4e9a1f7b203"-branch_labels: str | Sequence[str] | None = None-depends_on: str | Sequence[str] | None = None--REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"-POLICY_NAME = "tenant_isolation"--_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'-_CREATE_POLICY = (- f'CREATE POLICY {POLICY_NAME} ON "tenant_usage"\n'- f" FOR ALL\n"- f" USING ({_PREDICATE})\n"- f" WITH CHECK ({_PREDICATE})"-)---def upgrade() -> None:- op.create_table(- "tenant_usage",- sa.Column("tenant_id", sa.Text(), nullable=False),- sa.Column("metric", sa.Text(), nullable=False),- sa.Column("bucket_start", sa.DateTime(timezone=True), nullable=False),- sa.Column("client_id", sa.Text(), nullable=False),- sa.Column("model", sa.Text(), nullable=False),- sa.Column("amount", sa.BigInteger(), nullable=False),- sa.ForeignKeyConstraint(- ["tenant_id"], ["tenants.id"], name="fk_tenant_usage_tenant"- ),- sa.PrimaryKeyConstraint(- "tenant_id", "metric", "bucket_start", "client_id", "model"- ),- sa.CheckConstraint(- "metric IN ('messages', 'turns', 'input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens')",- name="ck_tenant_usage_metric",- ),- sa.CheckConstraint("amount > 0", name="ck_tenant_usage_amount"),- )- op.execute('ALTER TABLE "tenant_usage" ENABLE ROW LEVEL SECURITY')- op.execute(_CREATE_POLICY)---def downgrade() -> None:- op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "tenant_usage"')- op.drop_table("tenant_usage")diff --git a/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.py b/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.pydeleted file mode 100644index 2f56507eb..000000000--- a/core/switch_core/migrations/versions/e3b7c9d2a415_usage_budgets.py+++ /dev/null@@ -1,112 +0,0 @@-"""usage budgets: a ceiling on a metric over a repeating period--Revision ID: e3b7c9d2a415-Revises: c7e4a91d3b20--A budget caps one metric of ``tenant_usage`` for a whole tenant or for one-agent, optionally for one model, over a period of whole hours. An agent that-has reached a budget covering it is stopped until the period turns over. A-tenant with no budgets is unlimited, so nothing changes for existing tenants-when this runs.--Two partial unique indexes stand in for one unique constraint: ``agent_id`` is-null for a tenant-wide budget, and nulls never collide in a plain constraint.--The row-level-security DDL is a verbatim copy of ``switch_core/db/rls_ddl.py``-as it stood when this migration was written, copied rather than imported for-the reason ``265ed188ad6f`` gives.-"""--from collections.abc import Sequence--import sqlalchemy as sa-from alembic import op--revision: str = "e3b7c9d2a415"-down_revision: str | Sequence[str] | None = "c7e4a91d3b20"-branch_labels: str | Sequence[str] | None = None-depends_on: str | Sequence[str] | None = None--REQUIRE_TENANT_FUNCTION_NAME = "require_tenant_id"-POLICY_NAME = "tenant_isolation"--_PREDICATE = f'"tenant_id" = (SELECT {REQUIRE_TENANT_FUNCTION_NAME}())'-_CREATE_POLICY = (- f'CREATE POLICY {POLICY_NAME} ON "usage_budgets"\n'- f" FOR ALL\n"- f" USING ({_PREDICATE})\n"- f" WITH CHECK ({_PREDICATE})"-)--_METRICS = (- "messages",- "turns",- "input_tokens",- "output_tokens",- "cache_read_tokens",- "cache_write_tokens",-)---def upgrade() -> None:- op.create_table(- "usage_budgets",- sa.Column("tenant_id", sa.Text(), nullable=False),- sa.Column("id", sa.Text(), nullable=False),- sa.Column("agent_id", sa.Text(), nullable=True),- sa.Column("metric", sa.Text(), nullable=False),- sa.Column("model", sa.Text(), nullable=False),- sa.Column("amount_limit", sa.BigInteger(), nullable=False),- sa.Column("period_hours", sa.Integer(), nullable=False),- sa.Column(- "created_at",- sa.DateTime(timezone=True),- server_default=sa.text("now()"),- nullable=False,- ),- sa.ForeignKeyConstraint(- ["tenant_id"], ["tenants.id"], name="fk_usage_budgets_tenant"- ),- sa.ForeignKeyConstraint(- ["tenant_id", "agent_id"],- ["agents.tenant_id", "agents.id"],- name="fk_usage_budgets_agent",- ondelete="CASCADE",- ),- sa.CheckConstraint(- "metric IN ({})".format(", ".join(f"'{m}'" for m in _METRICS)),- name="ck_usage_budgets_metric",- ),- sa.CheckConstraint(- "amount_limit > 0 AND amount_limit <= 9007199254740991",- name="ck_usage_budgets_amount_limit",- ),- sa.CheckConstraint(- "period_hours > 0 AND period_hours <= 8784",- name="ck_usage_budgets_period_hours",- ),- sa.PrimaryKeyConstraint("id"),- )- op.create_index(- "uq_usage_budgets_tenant_wide",- "usage_budgets",- ["tenant_id", "metric", "model"],- unique=True,- postgresql_where=sa.text("agent_id IS NULL"),- )- op.create_index(- "uq_usage_budgets_agent",- "usage_budgets",- ["tenant_id", "agent_id", "metric", "model"],- unique=True,- postgresql_where=sa.text("agent_id IS NOT NULL"),- )- op.execute('ALTER TABLE "usage_budgets" ENABLE ROW LEVEL SECURITY')- op.execute(_CREATE_POLICY)---def downgrade() -> None:- op.execute(f'DROP POLICY IF EXISTS {POLICY_NAME} ON "usage_budgets"')- op.drop_index("uq_usage_budgets_agent", table_name="usage_budgets")- op.drop_index("uq_usage_budgets_tenant_wide", table_name="usage_budgets")- op.drop_table("usage_budgets")diff --git a/core/switch_core/session_activity/service.py b/core/switch_core/session_activity/service.pyindex 6d5362891..9c9793090 100644--- a/core/switch_core/session_activity/service.py+++ b/core/switch_core/session_activity/service.py@@ -16,7 +16,6 @@ from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Literal-from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import allows_on_behalf_of, parse_policy@@ -26,7 +25,6 @@ from switch_core.db.models import (Agent,ApprovalRequest,SessionActivityItem,- UsageMetric,require_tenant_id,)from switch_core.db.session_scope import tenant_session@@ -40,10 +38,8 @@ from switch_core.db.stores.session_activity_store import (ApprovalRequestStore,SessionActivityStore,)-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.sessions.contract import (- TURN_ENDED,ApprovalResult,QuestionsResult,RequestResult,@@ -57,10 +53,6 @@ MAX_OPTIONS = 10MAX_QUESTIONS = 50MAX_QUESTION_OPTIONS = 50MAX_CUSTOM_ANSWER_CHARS = 4000-MAX_MODEL_CHARS = 200-MAX_MODELS_PER_TURN = 50-# A host counts in JavaScript numbers, exact only up to 2**53 - 1.-MAX_TOKENS = 2**53 - 1# What the host sends inside a question is not truncated by the host, so it is# cut here to what any platform can show rather than refused._QUESTION_TITLE_CHARS = 500@@ -85,18 +77,6 @@ DECISIONS: tuple[Decision, ...] = ("accept", "acceptForSession", "decline", "canRequestKind = Literal["approval", "questions"]-@dataclass(frozen=True)-class TokenSpend:- """Tokens one model spent in a turn. `model` is empty when the provider- ran its default without naming it."""-- model: str- input_tokens: int- output_tokens: int- cache_read_tokens: int- cache_write_tokens: int--@dataclass(frozen=True)class ApprovalOption:id: str@@ -153,7 +133,6 @@ class SessionActivityService:self._sessions = session_factoryself._approvals = ApprovalRequestStore()self._activity = SessionActivityStore()- self._usage = UsageStore()self._rooms = RoomStore()self._external_users = ExternalUserStore()self._addressing = AddressingResolver(@@ -185,13 +164,8 @@ class SessionActivityService:thread_id: str | None,message_id: str | None,occurred_at: datetime,- usage: list[TokenSpend],) -> bool:- """Record one step of a turn. False when a revision at least as new is stored.-- `usage` is what the turn spent, and only a turn's own row, reported as- ended, carries it.- """+ """Record one step of a turn. False when a revision at least as new is stored."""if kind not in SESSION_ACTIVITY_KINDS:raise SessionError("INVALID_EVENT", f"Unknown activity kind: {kind}")if status not in ITEM_STATUSES[kind]:@@ -213,10 +187,6 @@ class SessionActivityService:)if revision < 0:raise SessionError("INVALID_EVENT", "A revision is never negative.")- if usage and not (kind == "turn" and status in TURN_ENDED):- raise SessionError(- "INVALID_EVENT", "Only an ended turn's own row carries its usage."- )if len(title) > MAX_TITLE_CHARS or len(text) > MAX_TEXT_CHARS:raise SessionError("INVALID_EVENT",@@ -227,14 +197,7 @@ class SessionActivityService:async with tenant_session(self._sessions, tenant_id) as db, db.begin():if room_id is not None:await self._require_member(db, agent_id, room_id)- prior_status = (- await self._activity.status_for_update(- db, agent_id, session_id, turn_id, item_id- )- if kind == "turn"- else None- )- moved = await self._activity.upsert(+ return await self._activity.upsert(db,SessionActivityItem(tenant_id=tenant_id,@@ -254,78 +217,6 @@ class SessionActivityService:occurred_at=occurred_at,),)- if moved and kind == "turn":- if prior_status is None:- await self._meter_turn(db, tenant_id, agent_id)- if status in TURN_ENDED and prior_status not in TURN_ENDED:- await self._meter_tokens(db, tenant_id, agent_id, usage)- return moved-- async def _meter_turn(- self, db: AsyncSession, tenant_id: str, agent_id: str- ) -> None:- """Count a turn the first time its host reports it, whatever its status.-- A turn has been paid for once it exists: one that errors or is- interrupted still spent the model's time, so counting only the ones- that complete would under-report exactly the runaway loops a budget is- for.- """- await self._usage.record(- db,- tenant_id=tenant_id,- metric=UsageMetric.TURNS,- client_id=await self._agent_client_id(db, tenant_id, agent_id),- model="",- amount=1,- )-- async def _meter_tokens(- self,- db: AsyncSession,- tenant_id: str,- agent_id: str,- usage: list[TokenSpend],- ) -> None:- """Count what a turn spent, once: when its row first reports it ended.-- The counts are what the host says: a customer's own agent reports on- itself, which is enough for a budget the customer sets for itself.- """- if not usage:- return- client_id = await self._agent_client_id(db, tenant_id, agent_id)- # One agent's turns can end concurrently; upserting the counters in the- # same order in each keeps two of them from deadlocking.- for spend in sorted(usage, key=lambda s: s.model):- for metric, amount in (- (UsageMetric.INPUT_TOKENS, spend.input_tokens),- (UsageMetric.OUTPUT_TOKENS, spend.output_tokens),- (UsageMetric.CACHE_READ_TOKENS, spend.cache_read_tokens),- (UsageMetric.CACHE_WRITE_TOKENS, spend.cache_write_tokens),- ):- if amount > 0:- await self._usage.record(- db,- tenant_id=tenant_id,- metric=metric,- client_id=client_id,- model=spend.model,- amount=amount,- )-- @staticmethod- async def _agent_client_id(db: AsyncSession, tenant_id: str, agent_id: str) -> str:- """The client an agent's usage is charged to, the identity every other- metric is counted against."""- client_id = await db.scalar(- select(Agent.client_id).where(- Agent.tenant_id == tenant_id, Agent.id == agent_id- )- )- if client_id is None:- raise SessionError("NOT_FOUND", f"Agent {agent_id} does not exist.")- return client_idasync def turn_items(self, agent_id: str, session_id: str, turn_id: strdiff --git a/core/switch_core/transport/port.py b/core/switch_core/transport/port.pyindex a1e5be81c..d2f5cb825 100644--- a/core/switch_core/transport/port.py+++ b/core/switch_core/transport/port.py@@ -77,20 +77,12 @@ class MessageTransport(Protocol):body: str,*,sender_name: str,- metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,extra_content: dict[str, object] | None = None,) -> SendResult:- """Post a text message. Raises `TransportError` if it is not accepted.-- `metered` says whether the message counts toward the tenant's usage. It- is false for what Switch posts on a participant's behalf — greetings,- command replies, automatic refusals — which the participant never chose- to say. It is an argument rather than something read from the content,- because a sender controls the content.- """+ """Post a text message. Raises `TransportError` if it is not accepted."""...async def send_event(@@ -111,7 +103,6 @@ class MessageTransport(Protocol):size: int,*,sender_name: str,- metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -121,7 +112,7 @@ class MessageTransport(Protocol):`group` marks this as one part of a multi-attachment message —`{"id": ..., "index": i, "total": n}` — for transports that cannot- carry several files on one event. `metered` is as for `send_message`.+ carry several files on one event."""...diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex dbef6b843..281134861 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -41,13 +41,7 @@ from datetime import UTC, datetimefrom typing import TYPE_CHECKING, Anyfrom switch_core.attachments import ATTACHMENT_GROUP_KEY-from switch_core.db.models import (- ClientRoom,- MediaBlob,- Message,- MessageAttachment,- UsageMetric,-)+from switch_core.db.models import ClientRoom, MediaBlob, Message, MessageAttachmentfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.logging_context import log_contextfrom switch_core.messages.recorded_types import EPHEMERAL@@ -86,7 +80,6 @@ if TYPE_CHECKING:from switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore- from switch_core.db.stores.usage_store import UsageStorefrom switch_core.messages.notify import MessageListenerlogger = logging.getLogger(__name__)@@ -100,12 +93,6 @@ _DELIVERY_PAGE = 200_MEDIA_MSGTYPES = frozenset({"m.image", "m.file", "m.video", "m.audio"})-# What a tenant is metered for: something a participant said. Custom events-# are the platform's own bookkeeping — reports, state, receipts — and charging-# a tenant for them would bill it for how Switch works.-_METERED_KINDS = frozenset({"message", "media"})--def _sent_kind(event_type: str, content: dict[str, object]) -> str:"""A bounded label for what was sent.@@ -174,7 +161,6 @@ class PostgresTransport:session_factory: async_sessionmaker[AsyncSession],room_store: RoomStore,message_store: MessageStore,- usage_store: UsageStore,media_store: MediaStore,listener: MessageListener,invites: InviteBus,@@ -200,7 +186,6 @@ class PostgresTransport:self._session_factory = session_factoryself._room_store = room_storeself._message_store = message_store- self._usage_store = usage_storeself._media_store = media_storeself._listener = listenerself._invites = invites@@ -594,7 +579,6 @@ class PostgresTransport:body: str,*,sender_name: str,- metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -608,9 +592,7 @@ class PostgresTransport:thread_root_id=thread_root_id,extra_content=extra_content,)- return await self._send(- room_id, "m.room.message", content, sender_name, metered=metered- )+ return await self._send(room_id, "m.room.message", content, sender_name)async def send_event(self,@@ -618,9 +600,7 @@ class PostgresTransport:event_type: str,content: dict[str, object],) -> SendResult:- return await self._send(- room_id, event_type, content, self.display_name, metered=False- )+ return await self._send(room_id, event_type, content, self.display_name)async def send_media(self,@@ -631,7 +611,6 @@ class PostgresTransport:size: int,*,sender_name: str,- metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -648,9 +627,7 @@ class PostgresTransport:thread_root_id=thread_root_id,group=group,)- return await self._send(- room_id, "m.room.message", content, sender_name, metered=metered- )+ return await self._send(room_id, "m.room.message", content, sender_name)async def _send(self,@@ -658,8 +635,6 @@ class PostgresTransport:event_type: str,content: dict[str, object],sender_name: str,- *,- metered: bool,) -> SendResult:"""Write the event, which is what sending it means here.@@ -710,15 +685,6 @@ class PostgresTransport:await self._message_store.create(session, message, attachments_in(content))- if metered and kind in _METERED_KINDS:- await self._usage_store.record(- session,- tenant_id=tenant_id,- metric=UsageMetric.MESSAGES,- client_id=self.client_id,- model="",- amount=1,- )await session.commit()except Exception:# `MESSAGES_SENT` is recorded only after the commit, so withoutdiff --git a/core/tests/integration/conftest.py b/core/tests/integration/conftest.pyindex cc95737b2..001c21e81 100644--- a/core/tests/integration/conftest.py+++ b/core/tests/integration/conftest.py@@ -76,7 +76,6 @@ from switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStorefrom switch_core.db.stores.tenant_store import TenantStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.main import _seed_agent_registration_bootstrap_keyfrom switch_core.messages.notify import MessageListener@@ -558,7 +557,6 @@ async def harness(session_env: SessionEnv) -> AsyncIterator[Harness]:config=config,room_store=session_env.room_store,message_store=session_env.message_store,- usage_store=UsageStore(),media_store=session_env.media_store,listener=message_listener,invites=invites,diff --git a/core/tests/integration/test_removal_stops_delivery_e2e.py b/core/tests/integration/test_removal_stops_delivery_e2e.pyindex 14180b706..08915c1ce 100644--- a/core/tests/integration/test_removal_stops_delivery_e2e.py+++ b/core/tests/integration/test_removal_stops_delivery_e2e.py@@ -93,9 +93,7 @@ async def test_removal_stops_every_reader_serving_the_room(harness: Harness) ->bodies = {}for label, room in rooms.items():bodies[label] = f"@e2e-removed-watcher please look at the {label} room"- await talker_client.send_message(- room.matrix_room_id, bodies[label], metered=True- )+ await talker_client.send_message(room.matrix_room_id, bodies[label])await _wait_buffered(harness, watcher.agent_id, room.id, bodies[label])# Both rooms are in the buffer and addressed, so every assertion after the@@ -165,9 +163,7 @@ async def test_a_room_the_agent_is_still_in_is_untouched(harness: Harness) -> Nobody = "@e2e-still-in-watcher this one still applies"await harness.client_for(talker.agent_id).send_message(- kept.room.matrix_room_id,- body,- metered=True,+ kept.room.matrix_room_id, body)await _wait_buffered(harness, watcher.agent_id, kept.room.id, body)diff --git a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.pyindex 422b4c44b..a85147746 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_delegate_addressing.py@@ -6,22 +6,10 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.connections import ConnectionRegistryfrom switch_core.bridges.agent.protocol.service import ProtocolServicefrom switch_core.bridges.agent.protocol.types import AgentStatus-from switch_core.budgets import BudgetExceeded, BudgetGuard-from switch_core.db.models import (- Agent,- ApiKey,- Client,- Room,- UsageBudget,- UsageMetric,- User,- require_tenant_id,-)+from switch_core.db.models import Agent, ApiKey, Client, Room, Userfrom switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.budget_store import BudgetStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.task_store import TaskStore-from switch_core.db.stores.usage_store import UsageStoredef _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:@@ -33,7 +21,6 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolServisvc.agent_store = AgentStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]svc.task_store = TaskStore() # type: ignore[attr-defined]- svc.budget_guard = BudgetGuard(BudgetStore()) # type: ignore[attr-defined]# No live matrix client → delegate_task skips the custom-event send.svc.client_lifecycle = _NoClients() # type: ignore[attr-defined]@@ -231,57 +218,3 @@ class TestDelegateAddressingGate:result = await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")assert result.task_id---async def _spend_budget(session: AsyncSession, agent: Agent) -> None:- session.add(- UsageBudget(- agent_id=agent.id,- metric="turns",- model="",- amount_limit=1,- period_hours=24,- )- )- await UsageStore().record(- session,- tenant_id=require_tenant_id(),- metric=UsageMetric.TURNS,- client_id=agent.client_id,- model="",- amount=1,- )---class TestDelegateBudgetGate:- @pytest.mark.parametrize("over_budget", ["requester", "performer"])- async def test_an_agent_over_its_budget_takes_no_part_in_a_delegation(- self, session_factory: async_sessionmaker[AsyncSession], over_budget: str- ) -> None:- svc = _service(session_factory)- async with session_factory() as session:- owner = await _make_user(session, "owner")- requester = await _make_agent(session, "req", owner_id=owner.id)- performer = await _make_agent(- session,- "perf",- owner_id=owner.id,- addressing_policy={- "rules": [{"users": [], "agents": [], "owner_agents": True}]- },- )- room = await _make_room(- session, svc.room_store, [requester.id, performer.id]- )- await _spend_budget(- session, requester if over_budget == "requester" else performer- )- await session.commit()- req_id, perf_id, room_id = requester.id, performer.id, room.id-- with pytest.raises(BudgetExceeded, match="has reached its budget of 1 turns"):- await svc.delegate_task(req_id, room_id, perf_id, "do it", "details")-- async with session_factory() as session:- tasks = await svc.task_store.get_by_room(session, room_id)- assert tasks == []diff --git a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py b/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.pydeleted file mode 100644index 891d8e0cb..000000000--- a/core/tests/switch_core/bridges/agent/protocol/test_pool_checkouts.py+++ /dev/null@@ -1,407 +0,0 @@-"""How many pool checkouts the hot paths cost.--These are performance assertions, and they are here because the failure they-guard against is not a slow page — it is fleet-wide agent loss. A request that-takes two slots where one would do halves the pool; a request that takes a-second slot *while holding the first* can wait the full pool timeout for it,-and every heartbeat queued behind that misses its TTL and reaps a live-connection. The numbers below are therefore contracts, not observations.-"""--from __future__ import annotations--from types import SimpleNamespace-from typing import Any--import pytest-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.bridges.agent.protocol.service import ProtocolService-from switch_core.bridges.agent.protocol.types import RoomDescriptor-from switch_core.budgets import BudgetExceeded, BudgetGuard-from switch_core.db.models import (- Agent,- ApiKey,- Client,- Room,- UsageBudget,- UsageMetric,- User,-)-from switch_core.db.stores.agent_session_store import AgentSessionStore-from switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.budget_store import BudgetStore-from switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.usage_store import UsageStore---class _CountingSessionFactory:- """The real factory, counting the sessions opened through it.-- One session is one pool checkout, which is the quantity this whole change- is about.- """-- def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:- self._inner = inner- self.opened = 0-- def __call__(self) -> Any:- self.opened += 1- return self._inner()---class _NoBridges:- def get(self, _bridge_id: str) -> None:- return None---class _OneBridge:- def __init__(self) -> None:- self.typing: list[tuple[str, str, bool]] = []-- def get(self, _bridge_id: str) -> Any:- return SimpleNamespace(handle_outbound_typing=self._record)-- async def _record(self, room_id: str, agent_name: str, is_typing: bool) -> None:- self.typing.append((room_id, agent_name, is_typing))---def _service(counting: _CountingSessionFactory) -> ProtocolService:- svc = object.__new__(ProtocolService)- svc.session_factory = counting # type: ignore[attr-defined]- svc.agent_store = AgentStore() # type: ignore[attr-defined]- svc.room_store = RoomStore() # type: ignore[attr-defined]- svc.budget_guard = BudgetGuard(BudgetStore()) # type: ignore[attr-defined]- svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]- svc.connections = ConnectionRegistry()- return svc---async def _seed(- session_factory: async_sessionmaker[AsyncSession],- *,- policy: dict[str, Any] | None = None,-) -> tuple[str, str, str]:- """One room with one member and one outsider. Returns (room, member, other).-- `policy` is applied to the member, which is the agent the addressing tests- treat as the target.- """- async with session_factory() as session:- user = User(name="o", email="o@test", role="user", password_hash="x")- session.add(user)- await session.flush()- ids = []- for name in ("member", "outsider"):- key = ApiKey(- user_id=user.id,- key_hash=f"hash-{name}",- encrypted_key="enc",- label=name,- type="agent",- )- client = Client(- matrix_user_id=f"@{name}:test",- display_name=name,- type="agent",- )- session.add_all([key, client])- await session.flush()- agent = Agent(- name=name,- description="d",- agent_type="session_addressable",- connector_type="claude_code",- integration_profile={},- client_id=client.id,- api_key_id=key.id,- owner_id=user.id,- addressing_policy=policy if name == "member" else None,- )- session.add(agent)- await session.flush()- ids.append(agent.id)- room = Room(matrix_room_id="!r:test", name="room", description="d")- session.add(room)- await session.flush()- await RoomStore().add_agents(session, room.id, [ids[0]])- await session.commit()- return room.id, ids[0], ids[1]---class TestRequireRoomMember:- async def test_membership_costs_one_checkout(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)-- room = await svc.require_room_member(member_id, room_id)-- assert room.id == room_id- assert counting.opened == 1, "one question, one slot"-- async def test_a_non_member_is_still_one_checkout(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, _, outsider_id = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)-- with pytest.raises(PermissionError):- await svc.require_room_member(outsider_id, room_id)-- assert counting.opened == 1-- async def test_a_missing_room_still_raises_value_error(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # "No such room" and "not your room" must stay distinguishable now that- # the two reads have been folded into one statement.- _, member_id, _ = await _seed(session_factory)- svc = _service(_CountingSessionFactory(session_factory))-- with pytest.raises(ValueError, match="Room not found"):- await svc.require_room_member(member_id, "no-such-room")-- async def test_the_resolved_room_carries_its_bridge(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, member_id, _ = await _seed(session_factory)- svc = _service(_CountingSessionFactory(session_factory))-- room = await svc.require_room_member(member_id, room_id)-- assert room.bridge_id is None---class TestCanAddress:- async def test_a_restricted_target_reads_through_the_callers_session(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The nesting this replaces held one slot while blocking on a second,- # which is how pool pressure turned into a pool timeout.- _, member_id, outsider_id = await _seed(session_factory)- async with session_factory() as session:- await AgentStore().update(- session,- member_id,- addressing_policy={"rules": [{"agents": [outsider_id], "users": []}]},- )- await session.commit()-- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- async with session_factory() as session:- target = await svc.agent_store.get(session, member_id)- assert target is not None- counting.opened = 0-- allowed = await svc._can_address(- session,- target,- room_id="room",- group_id=None,- sender_agent_id=outsider_id,- )-- assert allowed is True- assert counting.opened == 0, "_can_address must not open a session of its own"-- async def test_a_denied_sender_is_also_answered_in_the_callers_session(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, member_id, outsider_id = await _seed(session_factory)- async with session_factory() as session:- await AgentStore().update(- session,- member_id,- addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},- )- await session.commit()-- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- async with session_factory() as session:- target = await svc.agent_store.get(session, member_id)- assert target is not None- counting.opened = 0-- allowed = await svc._can_address(- session,- target,- room_id="room",- group_id=None,- sender_agent_id=outsider_id,- )-- assert allowed is False- assert counting.opened == 0-- async def test_an_open_policy_reads_nothing_at_all(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, member_id, outsider_id = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)-- async with session_factory() as session:- target = await svc.agent_store.get(session, member_id)- assert target is not None- counting.opened = 0-- allowed = await svc._can_address(- session,- target,- room_id="room",- group_id=None,- sender_agent_id=outsider_id,- )-- assert allowed is True- assert counting.opened == 0---class TestTyping:- async def test_an_internal_room_costs_nothing_beyond_membership(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Was three checkouts: membership took two of its own, then a third- # re-read the agent and the room the caller had already resolved.- room_id, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)-- await svc.set_typing(member_id, room_id, True)-- assert counting.opened == 1-- async def test_a_bridged_room_costs_one_read_for_the_agent_name(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- bridge = _OneBridge()- svc.collab_lifecycle = bridge # type: ignore[assignment]- room = RoomDescriptor(- id="room-1",- name="room",- description="d",- transport_room_id="!r:test",- matrix_room_id="!r:test",- bridge_id="bridge-1",- )-- await svc._set_typing(member_id, room, True)-- assert bridge.typing == [("room-1", "member", True)]- assert counting.opened == 1---class TestSendMessage:- async def test_posting_to_an_internal_room_costs_one_checkout(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # One to authorize. A bridged room adds exactly one more, to name the- # agent for the typing indicator — and no more than that, because the- # room the caller already resolved is passed along instead of re-read.- room_id, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- sent: list[tuple[str, str]] = []-- class _Client:- async def send_message(- self, matrix_room_id: str, content: str, **_kwargs: Any- ) -> str:- sent.append((matrix_room_id, content))- return "$event"-- svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]- get_by_agent_id=lambda _agent_id: _Client()- )-- event_id = await svc.send_message(member_id, room_id, "hello")-- assert event_id == "$event"- assert sent == [("!r:test", "hello")]- assert counting.opened == 1-- async def test_a_non_member_cannot_post(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, _, outsider_id = await _seed(session_factory)- svc = _service(_CountingSessionFactory(session_factory))-- with pytest.raises(PermissionError):- await svc.send_message(outsider_id, room_id, "hello")-- async def test_an_agent_over_its_budget_cannot_post_and_it_costs_one_checkout(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, member_id, _ = await _seed(session_factory)- async with session_factory() as session:- agent = await AgentStore().get(session, member_id)- assert agent is not None- session.add(- UsageBudget(- agent_id=member_id,- metric="messages",- model="",- amount_limit=2,- period_hours=24,- )- )- await UsageStore().record(- session,- tenant_id=agent.tenant_id,- metric=UsageMetric.MESSAGES,- client_id=agent.client_id,- model="",- amount=2,- )- await session.commit()- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)-- with pytest.raises(BudgetExceeded, match="member has reached its budget"):- await svc.send_message(member_id, room_id, "hello")-- assert counting.opened == 1---class TestAgentStatuses:- async def test_a_request_handler_can_reuse_its_own_session(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The gateway builds a room's detail inside its request transaction.- # Resolving statuses used to open a second one from underneath it.- room_id, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]-- async with session_factory() as session:- counting.opened = 0- statuses = await svc.get_agent_statuses_by_ids_in_session(- session, room_id, [member_id]- )-- assert member_id in statuses- assert counting.opened == 0-- async def test_the_session_less_form_still_takes_exactly_one(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, member_id, _ = await _seed(session_factory)- counting = _CountingSessionFactory(session_factory)- svc = _service(counting)- svc.agent_session_store = AgentSessionStore() # type: ignore[attr-defined]-- await svc.get_agent_statuses_by_ids(room_id, [member_id])-- assert counting.opened == 1diff --git a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py b/core/tests/switch_core/bridges/agent/protocol/test_send_media.pyindex 1eff08346..f522a9e73 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_send_media.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_send_media.py@@ -26,7 +26,6 @@ class _FakeClient:mimetype: str,size: int,*,- metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -39,7 +38,6 @@ class _FakeClient:"filename": filename,"mimetype": mimetype,"size": size,- "metered": metered,"msgtype": msgtype,"caption": caption,"thread_root_id": thread_root_id,@@ -60,7 +58,7 @@ def _build_service(client: _FakeClient, *, max_bytes: int = 100) -> ProtocolServ# Presence unions the heartbeat rows with the live connections# (CHOO-1857); an empty registry means "rows only".svc.connections = ConnectionRegistry()- svc.require_room_poster = _require # type: ignore[assignment]+ svc.require_room_member = _require # type: ignore[assignment]svc.client_lifecycle = SimpleNamespace( # type: ignore[assignment]get_by_agent_id=lambda agent_id: client)@@ -90,7 +88,6 @@ async def test_send_media_uploads_and_posts_image() -> None:sent = client.sends[0]assert sent["room_id"] == "!room"assert sent["msgtype"] == "m.image"- assert sent["metered"] is Trueassert sent["caption"] is Noneassert sent["thread_root_id"] is None# A lone attachment carries no group marker.diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.pyindex 4b49d8d47..65fed94ca 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_inbound_media.py@@ -30,8 +30,6 @@ class _FakePuppet:filename,mimetype,size,- *,- metered,msgtype,caption=None,thread_root_id=None,@@ -53,7 +51,7 @@ class _FakePuppet:return f"$evt-{len(self.media) - 1}"async def send_message(- self, matrix_room_id, content, *, metered, format=None, thread_root_id=None+ self, matrix_room_id, content, format=None, thread_root_id=None): # noqa: ANN001, ANN201, A002self.messages.append({"content": content, "thread_root_id": thread_root_id})return "$evt-text"diff --git a/core/tests/switch_core/clients/test_addressing_enforcement.py b/core/tests/switch_core/clients/test_addressing_enforcement.pyindex 0fd68f3aa..1bc1a6900 100644--- a/core/tests/switch_core/clients/test_addressing_enforcement.py+++ b/core/tests/switch_core/clients/test_addressing_enforcement.py@@ -1,13 +1,10 @@from __future__ import annotationsfrom contextlib import asynccontextmanager-from datetime import UTC, datetimefrom types import SimpleNamespace-from switch_core.budgets import BudgetGuardfrom switch_core.clients.admin_messages import PLATFORM_MARKER as _PLATFORM_MARKERfrom switch_core.clients.agent_client import AUTO_REPLY_FLAG, AgentClient-from switch_core.db.stores.budget_store import BudgetStandingfrom switch_core.delivery.addressing import (ADDRESSING_DENIED_MESSAGE as _ADDRESSING_DENIED_MESSAGE,)@@ -511,34 +508,7 @@ class TestOwnerAgentsAddressing:assert (await _decide(client)).refusal == _ADDRESSING_DENIED_MESSAGE-def _standing(*, spent: int) -> BudgetStanding:- return BudgetStanding(- id="budget-1",- agent_id="agent-1",- agent_name="fixer",- metric="turns",- model="",- amount_limit=10,- period_hours=24,- spent=spent,- resets_at=datetime(2026, 1, 2, tzinfo=UTC),- )---class _FakeBudgetStore:- def __init__(self, standings: list[BudgetStanding]) -> None:- self._standings = standings-- async def standings(self, _session, *, tenant_id, agent_id): # type: ignore[no-untyped-def]- return self._standings---def _gate_client( # type: ignore[no-untyped-def]- *,- allowed: bool,- refusal: str = _ADDRESSING_DENIED_MESSAGE,- budgets: list[BudgetStanding] | None = None,-):+def _gate_client(*, allowed: bool, refusal: str = _ADDRESSING_DENIED_MESSAGE): # type: ignore[no-untyped-def]"""Fake client for _gate_addressed and the auto-reply it hands back."""sent: list[dict] = []@@ -554,9 +524,7 @@ def _gate_client( # type: ignore[no-untyped-def]return "human"client = SimpleNamespace(- agent=SimpleNamespace(id="agent-1", name="fixer"),- tenant_id="tenant-1",- _budget_guard=BudgetGuard(_FakeBudgetStore(budgets or [])), # type: ignore[arg-type]+ agent=SimpleNamespace(name="fixer"),_addressing_allowed=_addressing_allowed,send_message=_send_message,_sender_handle=_sender_handle,@@ -631,32 +599,6 @@ class TestGateAddressed:assert outcome.refusal == _ADDRESSING_DENIED_MESSAGEassert client.sent == []- async def test_an_agent_within_its_budget_stays_addressed(self) -> None:- client = _gate_client(allowed=True, budgets=[_standing(spent=9)])- outcome = await _gate(client, _event())- assert outcome.addressed is True- assert client.sent == []-- async def test_an_agent_over_budget_is_demoted_and_says_so(self) -> None:- client = _gate_client(allowed=True, budgets=[_standing(spent=10)])- outcome = await _gate(client, _event())- assert outcome.addressed is False- reply = client.sent[0]- assert "Agent fixer has reached its budget of 10 turns per 24h" in reply["body"]- assert "2026-01-02 00:00 UTC" in reply["body"]- assert reply["extra_content"] == {AUTO_REPLY_FLAG: True}-- async def test_an_over_budget_agent_does_not_answer_an_auto_reply(self) -> None:- client = _gate_client(allowed=True, budgets=[_standing(spent=10)])- outcome = await _gate(client, _event(auto_reply=True))- assert outcome.addressed is False- assert client.sent == []-- async def test_a_denied_sender_hears_the_policy_not_the_budget(self) -> None:- client = _gate_client(allowed=False, budgets=[_standing(spent=10)])- await _gate(client, _event())- assert _ADDRESSING_DENIED_MESSAGE in client.sent[0]["body"]-def _command(args: str = "", user_id: str = "@u:switch.local", command: str = "reset"diff --git a/core/tests/switch_core/clients/test_admin_client.py b/core/tests/switch_core/clients/test_admin_client.pyindex a345d12f9..6127ceb09 100644--- a/core/tests/switch_core/clients/test_admin_client.py+++ b/core/tests/switch_core/clients/test_admin_client.py@@ -89,7 +89,6 @@ def _admin_client(room_id,body,*,- metered,format="markdown",mentions=None,thread_root_id=None,@@ -98,7 +97,6 @@ def _admin_client(sent.append({"body": body,- "metered": metered,"thread_root_id": thread_root_id,"mentions": mentions,"extra_content": extra_content,@@ -368,7 +366,6 @@ class TestAdminCommandDispatch:await client.reply_command("!m", "the result")assert sent[0]["body"] == "the result"assert _marker_type(sent[0]) == AdminMessageType.COMMAND_RESULT.value- assert sent[0]["metered"] is Falseasync def test_admin_owned_command_is_handled(self) -> None:host, sent = _command_host()diff --git a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py b/core/tests/switch_core/clients/test_agent_client_pool_checkouts.pydeleted file mode 100644index f300d3e66..000000000--- a/core/tests/switch_core/clients/test_agent_client_pool_checkouts.py+++ /dev/null@@ -1,287 +0,0 @@-"""How many pool checkouts one inbound room message costs an agent client.--A room fans every Matrix message out to *all* of its agent clients at once, in-a single event-loop tick. So this number is multiplied by the size of the room-before it ever reaches the pool: at two checkouts per client, a ten-agent room-turned one Slack message into twenty concurrent checkouts out of forty, and the-addressed client alone took up to nine more. That is the burst that pushed the-pool to its ceiling and started failing heartbeats.--The contract is one checkout per client per message, and none at all for a-message that needs no lookup — plus, as with the room service, no session held-open while the client posts to Matrix.-"""--from __future__ import annotations--from types import SimpleNamespace-from typing import Any--from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.bridges.agent.protocol.connections import ConnectionRegistry-from switch_core.budgets import BudgetGuard-from switch_core.clients.agent_client import AgentClient-from switch_core.clients.room_meta import RoomMeta-from switch_core.db.models import Agent, ApiKey, Client, Room, User-from switch_core.db.stores.agent_session_store import AgentSessionStore-from switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.budget_store import BudgetStore-from switch_core.db.stores.client_store import ClientStore-from switch_core.db.stores.external_user_store import ExternalUserStore-from switch_core.db.stores.room_role_store import RoomRoleStore-from switch_core.db.stores.room_store import RoomStore-from switch_core.delivery.addressing import AddressingResolver-from switch_core.transport import InboundMessage, RoomRef--MATRIX_ROOM_ID = "!r:test"---class _CountingSessionFactory:- """The real factory, counting sessions opened and tracking how many are- open right now. One session is one pool checkout."""-- def __init__(self, inner: async_sessionmaker[AsyncSession]) -> None:- self._inner = inner- self.opened = 0- self.live = 0-- def __call__(self) -> Any:- self.opened += 1- return _Tracked(self, self._inner())---class _Tracked:- def __init__(self, tracker: _CountingSessionFactory, inner: Any) -> None:- self._tracker = tracker- self._inner = inner-- async def __aenter__(self) -> AsyncSession:- self._tracker.live += 1- return await self._inner.__aenter__() # type: ignore[no-any-return]-- async def __aexit__(self, *exc: object) -> bool:- self._tracker.live -= 1- return await self._inner.__aexit__(*exc) # type: ignore[no-any-return]---async def _seed(- session_factory: async_sessionmaker[AsyncSession], *, names: list[str]-) -> tuple[str, dict[str, Agent]]:- async with session_factory() as session:- user = User(name="o", email="o@test", role="user", password_hash="x")- session.add(user)- await session.flush()- agents: dict[str, Agent] = {}- for name in names:- key = ApiKey(- user_id=user.id,- key_hash=f"hash-{name}",- encrypted_key="enc",- label=name,- type="agent",- )- client = Client(- matrix_user_id=f"@{name}:test",- display_name=name,- type="agent",- )- session.add_all([key, client])- await session.flush()- agent = Agent(- name=name,- description="d",- agent_type="session_addressable",- connector_type="claude_code",- integration_profile={"connection_model": "session_addressable"},- client_id=client.id,- api_key_id=key.id,- owner_id=user.id,- )- session.add(agent)- await session.flush()- agents[name] = agent- room = Room(matrix_room_id=MATRIX_ROOM_ID, name="room", description="d")- session.add(room)- await session.flush()- await RoomStore().add_agents(session, room.id, [a.id for a in agents.values()])- await session.commit()- return room.id, agents---def _client(- counting: _CountingSessionFactory, agent: Agent, room_id: str-) -> AgentClient:- """An AgentClient wired to the real stores, with its room-meta cache warm.-- The cache is warm because that is the steady state: a client resolves a- room once and then answers every later message in it from memory.- """- client = object.__new__(AgentClient)- client.session_factory = counting # type: ignore[assignment]- client.client_store = ClientStore()- client.matrix_user_id = f"@{agent.name}:test"- client.client_id = agent.client_id- client.tenant_id = agent.tenant_id- client._agent = agent- client._agent_store = AgentStore()- client._room_store = RoomStore()- client._room_role_store = RoomRoleStore()- client._agent_session_store = AgentSessionStore()- client._external_user_store = ExternalUserStore()- client._connections = ConnectionRegistry()- client._addressing = AddressingResolver(- room_store=client._room_store,- room_role_store=client._room_role_store,- client_store=client.client_store,- agent_store=client._agent_store,- external_user_store=client._external_user_store,- live_connection_ids=client._connections.live_connection_ids,- )- client._budget_guard = BudgetGuard(BudgetStore())- client._frontend_base_url = None- client._room_meta = {- MATRIX_ROOM_ID: RoomMeta(- room_id=room_id,- name="room",- bridge_id=None,- channel_type="channel_public",- )- }- client._attachment_groups = {}- client._attachment_group_timers = {}- client.sent = [] # type: ignore[attr-defined]-- async def _send_message(matrix_room_id: str, body: str, **kwargs: Any) -> str:- client.sent.append((body, counting.live)) # type: ignore[attr-defined]- return "$sent"-- client.send_message = _send_message # type: ignore[assignment, method-assign]- client._event_buffer = SimpleNamespace( # type: ignore[assignment]- enqueue=lambda *_a, **_k: None- )- return client---def _message(body: str, sender: str = "@switch-slack-louisa:test") -> InboundMessage:- return InboundMessage(- room_id=MATRIX_ROOM_ID,- event_id="$trigger",- sender=sender,- timestamp=0,- content={"body": body, "sender_name": "louisa"},- body=body,- sender_name="louisa",- )---def _room() -> RoomRef:- return RoomRef(room_id=MATRIX_ROOM_ID)---class TestInboundMessageCheckouts:- async def test_chatter_with_no_at_costs_nothing(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The common case in a busy room, and the one multiplied by every agent- # in it: no `@`, so there is nothing an alias or a role lease could- # match and no reason to touch the database at all.- room_id, agents = await _seed(session_factory, names=["member"])- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("just talking amongst ourselves"))-- assert counting.opened == 0-- async def test_an_at_message_for_somebody_else_costs_one(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Was two: the room alias and the role lease each took a session.- room_id, agents = await _seed(session_factory, names=["member", "other"])- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("@other can you look at this"))-- assert counting.opened == 1-- async def test_being_addressed_and_offline_still_costs_one(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The expensive path: addressing policy, liveness, and the whole- # offline-reply derivation. Was up to nine checkouts.- room_id, agents = await _seed(session_factory, names=["member"])- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("@member can you look at this"))-- assert counting.opened == 1- assert len(client.sent) == 1 # type: ignore[attr-defined]-- async def test_no_session_is_open_while_the_auto_reply_is_posted(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Posting to Matrix is an unbounded wait as far as the pool is- # concerned; doing it inside the transaction is how a slot ends up- # idle-in-transaction for seconds.- room_id, agents = await _seed(session_factory, names=["member"])- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("@member you there?"))-- assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]-- async def test_a_restricted_agent_refusing_a_sender_costs_one(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- room_id, agents = await _seed(session_factory, names=["member"])- async with session_factory() as session:- await AgentStore().update(- session,- agents["member"].id,- addressing_policy={"rules": [{"agents": ["nobody"], "users": []}]},- )- await session.commit()- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("@member you there?"))-- assert counting.opened == 1- assert [live for _body, live in client.sent] == [0] # type: ignore[attr-defined]-- async def test_an_alias_tag_costs_one(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Reached only after the alias lookup misses on name, so this is the- # path where alias and role used to be two separate checkouts.- room_id, agents = await _seed(session_factory, names=["member"])- async with session_factory() as session:- await RoomStore().set_alias(session, room_id, agents["member"].id, "fixer")- await session.commit()- counting = _CountingSessionFactory(session_factory)- client = _client(counting, agents["member"], room_id)-- await client.on_message(_room(), _message("@fixer please look"))-- assert counting.opened == 1- assert len(client.sent) == 1 # type: ignore[attr-defined]-- async def test_a_ten_agent_room_costs_ten(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The burst, end to end. One message, every client in the room handling- # it at once: ten slots out of forty, where it used to be twenty plus- # the addressed client's own handful.- names = [f"a{i}" for i in range(10)]- room_id, agents = await _seed(session_factory, names=names)- counting = _CountingSessionFactory(session_factory)- clients = [_client(counting, agents[name], room_id) for name in names]-- for client in clients:- await client.on_message(_room(), _message("@a3 can you take this"))-- assert counting.opened == 10diff --git a/core/tests/switch_core/clients/test_client_tenant_plumbing.py b/core/tests/switch_core/clients/test_client_tenant_plumbing.pyindex f14b7969a..09d217977 100644--- a/core/tests/switch_core/clients/test_client_tenant_plumbing.py+++ b/core/tests/switch_core/clients/test_client_tenant_plumbing.py@@ -47,7 +47,6 @@ from switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.tenant_store import TenantStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.tenant_context import tenant_scopefrom switch_core.transport.ephemeral import EphemeralBusfrom switch_core.transport.invites import InviteBus@@ -60,7 +59,6 @@ def _factory(session_factory: async_sessionmaker[AsyncSession]) -> ClientFactoryconfig=SimpleNamespace(matrix_server_name="test"), # type: ignore[arg-type]room_store=RoomStore(),message_store=MessageStore(),- usage_store=UsageStore(),media_store=MediaStore(),listener=MagicMock(),invites=InviteBus(),diff --git a/core/tests/switch_core/clients/test_no_session_reply_threading.py b/core/tests/switch_core/clients/test_no_session_reply_threading.pyindex 1f67a9c74..99467989b 100644--- a/core/tests/switch_core/clients/test_no_session_reply_threading.py+++ b/core/tests/switch_core/clients/test_no_session_reply_threading.py@@ -127,20 +127,6 @@ async def test_no_session_reply_threads_under_triggering_mention() -> None:]# The reply is stamped as an auto-reply so it can't re-trigger another one.assert send_message.calls[0]["extra_content"] == {AUTO_REPLY_FLAG: True}- # Switch said it, not the agent, so the tenant is not charged for it.- assert send_message.calls[0]["metered"] is False---async def test_a_command_reply_is_not_metered() -> None:- send_message = _Recorder()- await AgentClient.reply_command(- SimpleNamespace(send_message=send_message), # type: ignore[arg-type]- "!matrix:server",- "the result",- )-- assert send_message.calls[0]["metered"] is False@pytest.mark.asynciodiff --git a/core/tests/switch_core/clients/test_send_media.py b/core/tests/switch_core/clients/test_send_media.pyindex 2dc94eed8..c5d72a44d 100644--- a/core/tests/switch_core/clients/test_send_media.py+++ b/core/tests/switch_core/clients/test_send_media.py@@ -54,7 +54,6 @@ async def test_send_media_with_caption_passes_caption_and_filename_through() ->1234,msgtype="m.image",caption="look at this",- metered=True,)assert event_id == "$fake1"@@ -76,13 +75,7 @@ async def test_send_media_without_caption_sends_no_caption() -> None:client = _client(transport)await client.send_media(- "!room",- "mxc://s/abc",- "cat.png",- "image/png",- 1234,- msgtype="m.image",- metered=True,+ "!room", "mxc://s/abc", "cat.png", "image/png", 1234, msgtype="m.image")sent = transport.sent_media[0]@@ -94,13 +87,7 @@ async def test_send_media_returns_none_when_the_transport_rejects_it() -> None:client = _client(FakeTransport(fail_send="nope"))result = await client.send_media(- "!room",- "mxc://s/abc",- "cat.png",- "image/png",- 1234,- msgtype="m.image",- metered=True,+ "!room", "mxc://s/abc", "cat.png", "image/png", 1234, msgtype="m.image")assert result is Nonediff --git a/core/tests/switch_core/db/stores/test_budget_store.py b/core/tests/switch_core/db/stores/test_budget_store.pydeleted file mode 100644index d29460674..000000000--- a/core/tests/switch_core/db/stores/test_budget_store.py+++ /dev/null@@ -1,333 +0,0 @@-"""Budgets and what has been spent against them, against a real database.--The period arithmetic and the spend sum are SQL, so none of this is mocked.-"""--from __future__ import annotations--from datetime import UTC, datetime, timedelta--import pytest-from sqlalchemy.exc import IntegrityError-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.budgets import BudgetExceeded, BudgetGuard-from switch_core.db.models import (- MAX_BUDGET_AMOUNT,- MAX_BUDGET_PERIOD_HOURS,- TENANT_ZERO_ID,- Agent,- ApiKey,- Client,- TenantUsage,- UsageMetric,- User,-)-from switch_core.db.stores.budget_store import BudgetNotFound, BudgetStore---async def _agent(session: AsyncSession, name: str) -> Agent:- owner = User(- id=f"owner-{name}", name=name, email=f"{name}@example.test", role="user"- )- session.add(owner)- await session.flush()- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")- key = ApiKey(- user_id=owner.id,- key_hash=f"hash-{name}",- encrypted_key="",- label="unused fixture",- type="agent",- )- session.add_all([client, key])- await session.flush()- agent = Agent(- name=name,- description="test agent",- agent_type="session_addressable",- connector_type="codex",- integration_profile={},- client_id=client.id,- api_key_id=key.id,- )- session.add(agent)- await session.flush()- return agent---def _hour(offset: int) -> datetime:- now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)- return now + timedelta(hours=offset)---def _spent(client_id: str, amount: int, *, metric="turns", model="", hour=0):- return TenantUsage(- metric=metric,- bucket_start=_hour(hour),- client_id=client_id,- model=model,- amount=amount,- )---async def _budget(- session: AsyncSession,- *,- agent_id: str | None,- metric: UsageMetric = UsageMetric.TURNS,- model: str = "",- amount_limit: int = 10,- period_hours: int = 1,-):- return await BudgetStore().create(- session,- tenant_id=TENANT_ZERO_ID,- agent_id=agent_id,- metric=metric,- model=model,- amount_limit=amount_limit,- period_hours=period_hours,- )---async def _standings(session: AsyncSession, agent_id: str | None):- return await BudgetStore().standings(- session, tenant_id=TENANT_ZERO_ID, agent_id=agent_id- )---class TestSpend:- async def test_an_agent_budget_counts_only_that_agent_this_period(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- mine = await _agent(session, "mine")- other = await _agent(session, "other")- await _budget(session, agent_id=mine.id)- session.add_all(- [- _spent(mine.client_id, 3),- _spent(mine.client_id, 100, hour=-1),- _spent(other.client_id, 50),- ]- )- await session.commit()-- async with session_factory() as session:- [standing] = await _standings(session, None)-- assert standing.agent_name == "mine"- assert standing.spent == 3- assert standing.resets_at == _hour(1)- assert not standing.exhausted-- async def test_a_daily_budget_turns_over_at_midnight_utc(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- await _budget(session, agent_id=None, period_hours=24)- await session.commit()-- async with session_factory() as session:- [standing] = await _standings(session, None)-- midnight = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)- assert standing.resets_at == midnight + timedelta(days=1)-- async def test_a_tenant_wide_budget_counts_every_agent_and_no_one_else(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- one = await _agent(session, "one")- two = await _agent(session, "two")- await _budget(session, agent_id=None, metric=UsageMetric.MESSAGES)- session.add_all(- [- _spent("a-person", 40, metric="messages"),- _spent("a-bridge", 40, metric="messages"),- _spent(one.client_id, 4, metric="messages"),- _spent(two.client_id, 6, metric="messages"),- ]- )- await session.commit()-- async with session_factory() as session:- [standing] = await _standings(session, None)-- assert standing.agent_id is None- assert standing.spent == 10- assert standing.exhausted-- async def test_a_model_budget_counts_only_that_model(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- agent = await _agent(session, "modelled")- await _budget(- session,- agent_id=agent.id,- metric=UsageMetric.OUTPUT_TOKENS,- model="big",- amount_limit=1000,- )- session.add_all(- [- _spent(agent.client_id, 300, metric="output_tokens", model="big"),- _spent(agent.client_id, 900, metric="output_tokens", model="small"),- ]- )- await session.commit()-- async with session_factory() as session:- [standing] = await _standings(session, None)-- assert standing.spent == 300-- async def test_an_agent_is_covered_by_its_own_and_tenant_wide_budgets(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- mine = await _agent(session, "covered")- other = await _agent(session, "elsewhere")- await _budget(session, agent_id=None)- await _budget(session, agent_id=mine.id)- await _budget(session, agent_id=other.id)- await session.commit()-- async with session_factory() as session:- covering = await _standings(session, mine.id)-- assert [s.agent_id for s in covering] == [None, mine.id]---class TestChanges:- async def test_a_second_budget_on_the_same_thing_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- await _budget(session, agent_id=None)- with pytest.raises(IntegrityError, match="uq_usage_budgets_tenant_wide"):- await _budget(session, agent_id=None, amount_limit=99)-- @pytest.mark.parametrize(- ("amount_limit", "period_hours", "constraint"),- [- (MAX_BUDGET_AMOUNT + 1, 24, "ck_usage_budgets_amount_limit"),- (10, MAX_BUDGET_PERIOD_HOURS + 1, "ck_usage_budgets_period_hours"),- ],- )- async def test_a_budget_past_the_bounds_is_refused(- self,- session_factory: async_sessionmaker[AsyncSession],- amount_limit: int,- period_hours: int,- constraint: str,- ) -> None:- async with session_factory() as session:- with pytest.raises(IntegrityError, match=constraint):- await _budget(- session,- agent_id=None,- amount_limit=amount_limit,- period_hours=period_hours,- )-- async def test_the_longest_budget_reads_its_standing(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- agent = await _agent(session, "yearly")- session.add(_spent(agent.client_id, 4))- await _budget(- session,- agent_id=agent.id,- amount_limit=MAX_BUDGET_AMOUNT,- period_hours=MAX_BUDGET_PERIOD_HOURS,- )- [standing] = await _standings(session, agent.id)-- assert standing.spent == 4- assert standing.resets_at > datetime.now(UTC)-- async def test_update_and_delete_name_a_budget_that_exists(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- store = BudgetStore()- async with session_factory() as session:- budget = await _budget(session, agent_id=None)- await store.update(- session,- tenant_id=TENANT_ZERO_ID,- budget_id=budget.id,- amount_limit=5,- period_hours=48,- )- [standing] = await _standings(session, None)- assert (standing.amount_limit, standing.period_hours) == (5, 48)-- await store.delete(session, tenant_id=TENANT_ZERO_ID, budget_id=budget.id)- assert await _standings(session, None) == []- with pytest.raises(BudgetNotFound):- await store.delete(- session, tenant_id=TENANT_ZERO_ID, budget_id=budget.id- )-- async def test_deleting_an_agent_deletes_its_budgets(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- agent = await _agent(session, "deleted")- await _budget(session, agent_id=agent.id)- await session.commit()- await session.delete(agent)- await session.commit()-- async with session_factory() as session:- assert await _standings(session, None) == []---class TestGuard:- async def test_an_agent_within_its_budgets_passes(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- agent = await _agent(session, "within")- await _budget(session, agent_id=agent.id)- session.add(_spent(agent.client_id, 9))- await session.flush()-- await BudgetGuard(BudgetStore()).require_within(- session, tenant_id=TENANT_ZERO_ID, agent_id=agent.id- )-- async def test_the_budget_that_stops_the_agent_longest_is_reported(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- agent = await _agent(session, "stopped")- await _budget(session, agent_id=agent.id, period_hours=1)- await _budget(- session,- agent_id=None,- metric=UsageMetric.MESSAGES,- amount_limit=2,- period_hours=24,- )- session.add_all(- [- _spent(agent.client_id, 10),- _spent(agent.client_id, 2, metric="messages"),- ]- )- await session.flush()-- with pytest.raises(BudgetExceeded) as stopped:- await BudgetGuard(BudgetStore()).require_within(- session, tenant_id=TENANT_ZERO_ID, agent_id=agent.id- )-- assert stopped.value.standing.metric == "messages"- assert str(stopped.value).startswith(- "This workspace has reached its budget of 2 messages per 24h."- )diff --git a/core/tests/switch_core/db/stores/test_usage_store.py b/core/tests/switch_core/db/stores/test_usage_store.pydeleted file mode 100644index ecdf9c8f5..000000000--- a/core/tests/switch_core/db/stores/test_usage_store.py+++ /dev/null@@ -1,194 +0,0 @@-"""Per-tenant usage counters, against a real database.--The upsert, the hour bucket and the check constraints are the behaviour, so-none of this is mocked.-"""--from __future__ import annotations--from datetime import UTC, datetime, timedelta--import pytest-from sqlalchemy import func, select-from sqlalchemy.exc import IntegrityError-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.db.models import (- TENANT_ZERO_ID,- Client,- Tenant,- TenantUsage,- UsageMetric,-)-from switch_core.db.session_scope import tenant_session-from switch_core.db.stores.usage_store import UsageStore--OTHER_TENANT = "11111111-1111-1111-1111-111111111111"---async def _client(session: AsyncSession, name: str) -> str:- client = Client(matrix_user_id=f"@{name}:test", display_name=name, type="agent")- session.add(client)- await session.flush()- return client.id---async def _record(- session: AsyncSession,- client_id: str,- *,- metric: UsageMetric = UsageMetric.MESSAGES,- model: str = "",- amount: int = 1,- tenant_id: str = TENANT_ZERO_ID,-) -> None:- await UsageStore().record(- session,- tenant_id=tenant_id,- metric=metric,- client_id=client_id,- model=model,- amount=amount,- )---def _hour(offset: int) -> datetime:- now = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)- return now + timedelta(hours=offset)---class TestRecording:- async def test_counts_in_the_same_hour_add_up(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- client_id = await _client(session, "counted")- await _record(session, client_id)- await _record(session, client_id, amount=4)- await session.commit()-- async with session_factory() as session:- rows = (await session.scalars(select(TenantUsage))).all()-- assert len(rows) == 1- assert rows[0].amount == 5- assert rows[0].bucket_start == _hour(0)-- async def test_metrics_and_models_are_counted_apart(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- client_id = await _client(session, "several")- await _record(session, client_id)- await _record(session, client_id, metric=UsageMetric.TURNS)- await _record(- session, client_id, metric=UsageMetric.INPUT_TOKENS, model="a"- )- await _record(- session, client_id, metric=UsageMetric.INPUT_TOKENS, model="b"- )- await session.commit()-- async with session_factory() as session:- count = await session.scalar(select(func.count()).select_from(TenantUsage))-- assert count == 4-- async def test_a_count_that_is_not_positive_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # A zero or negative amount would let a caller spend usage back, so it- # is an error at the door rather than an adjustment.- async with session_factory() as session:- client_id = await _client(session, "refused")- with pytest.raises(ValueError, match="positive"):- await _record(session, client_id, amount=0)-- async def test_the_database_refuses_an_unknown_metric(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- session.add(- TenantUsage(- metric="vibes",- bucket_start=_hour(0),- client_id="c",- model="",- amount=1,- )- )- with pytest.raises(IntegrityError, match="ck_tenant_usage_metric"):- await session.flush()---class TestTotals:- async def test_totals_cover_the_hours_in_the_window(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- client_id = await _client(session, "windowed")- for offset, amount in ((-3, 100), (-2, 10), (-1, 1), (0, 1000)):- session.add(- TenantUsage(- metric="messages",- bucket_start=_hour(offset),- client_id=client_id,- model="",- amount=amount,- )- )- await session.commit()-- async with session_factory() as session:- # `since` mid-hour still takes that whole hour; `until` excludes- # the bucket that starts on it.- totals = await UsageStore().totals(- session,- tenant_id=TENANT_ZERO_ID,- since=_hour(-2) + timedelta(minutes=30),- until=_hour(0),- )-- assert [(t.metric, t.client_name, t.amount) for t in totals] == [- ("messages", "windowed", 11)- ]-- async def test_usage_outlives_the_client_it_names(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # What a deleted client spent is still the tenant's spend.- async with session_factory() as session:- await _record(session, "gone-client")- await session.commit()-- async with session_factory() as session:- totals = await UsageStore().totals(- session, tenant_id=TENANT_ZERO_ID, since=_hour(-1), until=_hour(1)- )-- assert len(totals) == 1- assert totals[0].client_id == "gone-client"- assert totals[0].client_name is None- assert totals[0].amount == 1-- async def test_another_tenants_usage_is_not_counted(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The owner connection ignores the policy, so this is the explicit- # tenant filter doing the work — the one a fan-out relies on.- async with session_factory() as session:- session.add(Tenant(id=OTHER_TENANT, slug="other", name="Other"))- await session.commit()- async with tenant_session(session_factory, OTHER_TENANT) as session:- await _record(session, "theirs", amount=50, tenant_id=OTHER_TENANT)- await session.commit()- async with session_factory() as session:- await _record(session, "ours", amount=2)- await session.commit()-- async with session_factory() as session:- totals = await UsageStore().totals(- session, tenant_id=TENANT_ZERO_ID, since=_hour(-1), until=_hour(1)- )-- assert [(t.client_id, t.amount) for t in totals] == [("ours", 2)]diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pydeleted file mode 100644index 2d4c048b0..000000000--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ /dev/null@@ -1,1477 +0,0 @@-"""The route half of CHOO-2722: `gateway/tenants.py`'s workspace, invitation-and member routes.--Builds route-scoped apps the same way `test_tenant_resolution.py` does —-`switch_core.gateway.dependencies`' functions overridden individually rather-than through `init_dependencies` — so nothing here leaks into another test and-nothing but `switch_core.gateway.tenants` itself is exercised for real.--`_FakeClientLifecycle.create_tenant` mirrors-`ClientLifecycleService.create_tenant`'s DB half (insert the tenant row inside-a `tenant_session` bound to its own id) without the Matrix admin-client-provisioning, which needs a running homeserver these tests have no business-depending on. The unique-slug behaviour under test comes from the same-`tenants.slug` column either way.-"""--from __future__ import annotations--import asyncio-import uuid-from datetime import UTC, datetime, timedelta-from types import SimpleNamespace--import httpx-import pytest-from fastapi import FastAPI-from sqlalchemy import select-from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker--from switch_core.db.models import (- Agent,- ApiKey,- Client,- Invitation,- Tenant,- TenantMember,- UsageMetric,- User,-)-from switch_core.db.session_scope import tenant_session-from switch_core.db.stores.agent_store import AgentStore-from switch_core.db.stores.api_key_store import ApiKeyStore-from switch_core.db.stores.budget_store import BudgetStore-from switch_core.db.stores.invitation_store import InvitationStore-from switch_core.db.stores.usage_store import UsageStore-from switch_core.db.stores.user_store import UserStore-from switch_core.gateway import dependencies as gw_deps-from switch_core.gateway.auth import create_jwt-from switch_core.gateway.tenants import router as tenants_router--_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow-TENANT_A = "tenant-api-routes-a"-TENANT_B = "tenant-api-routes-b"---class _FakeClientLifecycle:- def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:- self._session_factory = session_factory-- async def create_tenant(self, name: str, slug: str) -> Tenant:- tenant = Tenant(id=str(uuid.uuid4()), name=name, slug=slug)- async with tenant_session(self._session_factory, tenant.id) as session:- session.add(tenant)- await session.commit()- return tenant---def _fake_protocol() -> SimpleNamespace:- return SimpleNamespace(- api_key_cache=SimpleNamespace(- invalidate=lambda key_hash: None,- invalidate_agent=lambda agent_id: None,- )- )---def _app(- session_factory: async_sessionmaker[AsyncSession],- *,- client_lifecycle: object | None = None,- max_workspaces_per_user: int = 3,-) -> FastAPI:- async def _session_dep():- async with session_factory() as session:- yield session-- app = FastAPI()- app.include_router(tenants_router)- app.dependency_overrides[gw_deps.get_session] = _session_dep- app.dependency_overrides[gw_deps.get_system_session] = _session_dep- app.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factory- app.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()- app.dependency_overrides[gw_deps.get_agent_store] = lambda: AgentStore()- app.dependency_overrides[gw_deps.get_api_key_store] = lambda: ApiKeyStore()- app.dependency_overrides[gw_deps.get_invitation_store] = lambda: InvitationStore()- app.dependency_overrides[gw_deps.get_usage_store] = lambda: UsageStore()- app.dependency_overrides[gw_deps.get_budget_store] = lambda: BudgetStore()- app.dependency_overrides[gw_deps.get_protocol] = lambda: _fake_protocol()- app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (- client_lifecycle or _FakeClientLifecycle(session_factory)- )- app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(- jwt_secret_key=_SECRET,- gateway_cookie_secure=False,- gateway_tenant_choice_enabled=False,- gateway_max_workspaces_per_user=max_workspaces_per_user,- )- return app---def _client(app: FastAPI, token: str) -> httpx.AsyncClient:- return httpx.AsyncClient(- transport=httpx.ASGITransport(app=app),- base_url="http://test",- cookies={"switch_auth": token},- )---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()---async def _make_member(- session_factory: async_sessionmaker[AsyncSession],- *,- name: str,- tenant_id: str,- role: str,- email: str | None = None,- user_role: str = "user",-) -> str:- """A user with a membership in `tenant_id`.-- `role` is the per-tenant membership role; `user_role` is the global- `users.role`, which is a different axis entirely — `"admin"` there is the- deployment operator bit, granted by nothing self-service.- """- async with session_factory() as session:- user = User(name=name, email=email or f"{name}@example.invalid", role=user_role)- session.add(user)- await session.flush()- session.add(TenantMember(tenant_id=tenant_id, user_id=user.id, role=role))- await session.commit()- return user.id---def _token(user_id: str, email: str, tenant_id: str) -> str:- return create_jwt(user_id, email, "user", _SECRET, tenant_id)---async def _make_api_key(- session_factory: async_sessionmaker[AsyncSession],- *,- tenant_id: str,- user_id: str,- key_type: str = "registration",-) -> str:- """A personal (non-agent) API key for `user_id` in `tenant_id`. Returns- its `key_hash`."""- key_hash = uuid.uuid4().hex- async with session_factory() as session:- session.add(- ApiKey(- tenant_id=tenant_id,- user_id=user_id,- key_hash=key_hash,- encrypted_key="unused-in-tests",- label="test-key",- type=key_type,- )- )- await session.commit()- return key_hash---async def _make_agent_with_key(- session_factory: async_sessionmaker[AsyncSession],- *,- tenant_id: str,- owner_id: str,-) -> tuple[str, str, str]:- """An agent owned by `owner_id`, plus the `agents`-type key backing it.-- Returns `(agent_id, agent_name, key_hash)`. The agent's own client and- api_key rows are constructed first — `agents.client_id` and- `agents.api_key_id` are both foreign keys, not free-form strings.- """- key_hash = uuid.uuid4().hex- name = f"agent-{uuid.uuid4().hex[:8]}"- async with session_factory() as session:- client = Client(- tenant_id=tenant_id,- matrix_user_id=f"@bot-{uuid.uuid4().hex[:8]}:test",- display_name="test-agent-bot",- type="agent",- )- session.add(client)- await session.flush()-- api_key = ApiKey(- tenant_id=tenant_id,- user_id=owner_id,- key_hash=key_hash,- encrypted_key="unused-in-tests",- label="agent-key",- type="agent",- )- session.add(api_key)- await session.flush()-- agent = Agent(- tenant_id=tenant_id,- name=name,- description="test agent",- agent_type="other",- connector_type="claude-code",- integration_profile={},- client_id=client.id,- api_key_id=api_key.id,- owner_id=owner_id,- )- session.add(agent)- await session.commit()- return agent.id, name, key_hash---class TestCreateTenant:- async def test_creating_a_tenant_makes_the_caller_its_owner(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="founder", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post("/tenants", json={"name": "Acme Corp"})-- assert response.status_code == 201, response.text- body = response.json()- assert body["slug"] == "acme-corp"- assert body["role"] == "owner"-- async with session_factory() as session:- membership = await session.get(TenantMember, (body["id"], user_id))- assert membership is not None- assert membership.role == "owner"-- async def test_a_taken_slug_is_409_not_a_silent_suffix(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="second-founder", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- first = await client.post("/tenants", json={"name": "Widgets Inc"})- assert first.status_code == 201, first.text- second = await client.post("/tenants", json={"name": "Widgets Inc"})-- assert second.status_code == 409-- async def test_a_name_with_no_slug_characters_is_400(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="emoji-fan", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post("/tenants", json={"name": "!!!"})-- assert response.status_code == 400---class TestWorkspaceCreationLimit:- """`POST /tenants` is the one route here with no tenant to authorize- against, so what stands in for its neighbours' role check is a bound on how- many workspaces one person may own. It exists because a workspace is not- just a row: `all_tenant_ids()` drives a fan-out per tenant at boot and a- sweep every few seconds (`docs/old/multi-tenancy-phase2-tenants.md`, §5).- """-- async def test_a_caller_at_the_limit_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="serial-founder", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=2)- async with _client(app, token) as client:- assert (- await client.post("/tenants", json={"name": "First"})- ).status_code == 201- assert (- await client.post("/tenants", json={"name": "Second"})- ).status_code == 201- third = await client.post("/tenants", json={"name": "Third"})-- assert third.status_code == 403- assert "created 2 workspaces" in third.json()["detail"]-- async def test_nothing_is_provisioned_for_a_refused_caller(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The bound is checked before `create_tenant`, so a refusal must not- # leave the orphan workspace the handler's own docstring warns about.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="blocked-founder", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=0)- async with _client(app, token) as client:- response = await client.post("/tenants", json={"name": "Never Made"})-- assert response.status_code == 403- async with session_factory() as session:- found = await session.scalars(- select(Tenant).where(Tenant.slug == "never-made")- )- assert found.first() is None-- async def test_handing_a_workspace_over_does_not_free_the_allowance(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # What is bounded is creation. Were it ownership, creating, promoting a- # second account and stepping down would reset the count every time.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="hand-off", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=1)- async with _client(app, token) as client:- first = await client.post("/tenants", json={"name": "Handed Over"})- async with session_factory() as session:- member = await session.get(TenantMember, (first.json()["id"], user_id))- assert member is not None- member.role = "member"- await session.commit()- second = await client.post("/tenants", json={"name": "One Too Many"})-- assert first.status_code == 201- assert second.status_code == 403-- async def test_concurrent_requests_cannot_all_pass_the_check(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="burst", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=1)- async with _client(app, token) as client:- responses = await asyncio.gather(- *(- client.post("/tenants", json={"name": f"Burst {i}"})- for i in range(5)- )- )-- codes = sorted(r.status_code for r in responses)- assert codes.count(201) == 1- assert set(codes) - {201} <= {403, 409}- async with session_factory() as session:- owned = await session.scalars(- select(TenantMember).where(- TenantMember.user_id == user_id, TenantMember.role == "owner"- )- )- assert len(owned.all()) == 1-- async def test_a_request_during_another_creation_is_refused_not_queued(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Waiting would hold a pool connection for as long as the other- # creation takes; refusing at once holds none.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="in-flight", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=3)- async with session_factory() as holder:- await holder.scalar(- select(User).where(User.id == user_id).with_for_update(key_share=True)- )- async with _client(app, token) as client:- response = await client.post("/tenants", json={"name": "Queued"})-- assert response.status_code == 409- assert "being created" in response.json()["detail"]-- async def test_a_limit_of_zero_says_creation_is_disabled(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Zero is how a deployment closes the route, and it must not be- # reported as though the caller had used up an allowance.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="early-bird", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=0)- async with _client(app, token) as client:- response = await client.post("/tenants", json={"name": "Too Early"})-- assert response.status_code == 403- assert response.json()["detail"] == (- "Workspace creation is disabled on this deployment"- )-- async def test_memberships_the_caller_does_not_own_are_free(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Being invited into someone else's workspace must not spend an- # allowance: the invitee cannot get it back without being removed.- await _make_tenant(session_factory, TENANT_A)- await _make_tenant(session_factory, TENANT_B)- user_id = await _make_member(- session_factory, name="joiner", tenant_id=TENANT_A, role="admin"- )- async with session_factory() as session:- session.add(- TenantMember(tenant_id=TENANT_B, user_id=user_id, role="member")- )- await session.commit()- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=1)- async with _client(app, token) as client:- response = await client.post("/tenants", json={"name": "Mine At Last"})-- assert response.status_code == 201, response.text-- async def test_an_operator_is_exempt(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # `users.role == "admin"` is the deployment operator bit, and this- # bound is about self-service. An operator provisioning workspaces for- # other people is exactly who it must not stop — the same bypass- # `authz.administers_tenant` and `authz.owns_tenant` already give them.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory,- name="the-operator",- tenant_id=TENANT_A,- role="member",- user_role="admin",- )- token = _token(user_id, "[email protected]", TENANT_A)-- app = _app(session_factory, max_workspaces_per_user=0)- async with _client(app, token) as client:- first = await client.post("/tenants", json={"name": "Customer One"})- second = await client.post("/tenants", json={"name": "Customer Two"})-- assert first.status_code == 201, first.text- assert second.status_code == 201, second.text-- async def test_the_operator_bit_is_read_fresh_not_from_the_token(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # The JWT carries a role claim from login. Trusting it would keep a- # revoked operator exempt for the life of their cookie, so the bit- # comes from the `users` row on every request.- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="demoted", tenant_id=TENANT_A, role="member"- )- stale_operator_token = create_jwt(- user_id, "[email protected]", "admin", _SECRET, TENANT_A- )-- async with _client(- _app(session_factory, max_workspaces_per_user=0), stale_operator_token- ) as client:- response = await client.post("/tenants", json={"name": "Not Allowed"})-- assert response.status_code == 403---class TestInvitationAuthorisation:- """A member of workspace A cannot mint an invitation to workspace B —- each request is bound to exactly one tenant, and the path segment cannot- override that."""-- async def test_a_plain_member_cannot_mint_an_invitation(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="rank-and-file", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/invitations", json={"role": "member"}- )-- assert response.status_code == 403-- async def test_an_admin_of_a_cannot_mint_an_invitation_naming_b(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- await _make_tenant(session_factory, TENANT_B)- user_id = await _make_member(- session_factory, name="a-admin", tenant_id=TENANT_A, role="admin"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_B}/invitations", json={"role": "member"}- )-- assert response.status_code == 403-- async with tenant_session(session_factory, TENANT_B) as scoped:- assert await InvitationStore().list_for_tenant(scoped) == []-- async def test_an_owner_can_mint_an_invitation_to_their_own_tenant(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="a-owner", tenant_id=TENANT_A, role="owner"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/invitations",- json={"role": "member", "uses_remaining": 3},- )-- assert response.status_code == 201, response.text- body = response.json()- assert body["role"] == "member"- assert body["uses_remaining"] == 3- assert "token" in body and body["token"]-- async def test_an_absurd_expiry_is_refused_rather_than_crashing(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """`timedelta` raises `OverflowError` well before `int` runs out, so an- expiry bounded only from below turns a bad request into a 500. The- bound belongs on the schema, where it is a 422 with a field name."""- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="time-lord", tenant_id=TENANT_A, role="owner"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/invitations",- json={"role": "member", "expires_in_hours": 1000000000},- )-- assert response.status_code == 422, response.text---class TestOwnershipIsOwnerOnly:- """Who owns a workspace is decided by its owners, not by its admins.-- An `admin` runs the workspace; only an `owner` moves the ownership set.- The distinction exists because a last-owner guard cannot see a sequence:- each request below is individually safe — two owners stand at every- step — and together they hand the workspace to someone the founder never- promoted.- """-- async def test_an_admin_cannot_take_the_workspace_from_its_owner(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- founder_id = await _make_member(- session_factory, name="founder-owner", tenant_id=TENANT_A, role="owner"- )- admin_id = await _make_member(- session_factory, name="ambitious-admin", tenant_id=TENANT_A, role="admin"- )- token = _token(admin_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- promote_self = await client.patch(- f"/tenants/{TENANT_A}/members/{admin_id}", json={"role": "owner"}- )- demote_founder = await client.patch(- f"/tenants/{TENANT_A}/members/{founder_id}", json={"role": "member"}- )- remove_founder = await client.delete(- f"/tenants/{TENANT_A}/members/{founder_id}"- )-- assert promote_self.status_code == 403, promote_self.text- assert demote_founder.status_code == 403, demote_founder.text- assert remove_founder.status_code == 403, remove_founder.text-- async with session_factory() as session:- founder = await session.get(TenantMember, (TENANT_A, founder_id))- admin = await session.get(TenantMember, (TENANT_A, admin_id))- assert founder is not None and founder.role == "owner"- assert admin is not None and admin.role == "admin"-- async def test_an_admin_cannot_mint_an_owner_invitation(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """Otherwise the escalation above is the same three steps with a link- in the middle: invite an accomplice as owner, then let them do it."""- await _make_tenant(session_factory, TENANT_A)- await _make_member(- session_factory, name="quiet-owner", tenant_id=TENANT_A, role="owner"- )- admin_id = await _make_member(- session_factory, name="inviting-admin", tenant_id=TENANT_A, role="admin"- )- token = _token(admin_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- refused = await client.post(- f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}- )- allowed = await client.post(- f"/tenants/{TENANT_A}/invitations", json={"role": "admin"}- )-- assert refused.status_code == 403, refused.text- assert allowed.status_code == 201, allowed.text-- async with tenant_session(session_factory, TENANT_A) as scoped:- roles = [i.role for i in await InvitationStore().list_for_tenant(scoped)]- assert roles == ["admin"]-- async def test_an_owner_can_do_all_of_it(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """The guard is narrower authority, not a locked door: everything the- admin was refused above succeeds for an owner."""- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="real-owner", tenant_id=TENANT_A, role="owner"- )- member_id = await _make_member(- session_factory, name="promoted", tenant_id=TENANT_A, role="member"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- promote = await client.patch(- f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "owner"}- )- demote = await client.patch(- f"/tenants/{TENANT_A}/members/{member_id}", json={"role": "member"}- )- invite = await client.post(- f"/tenants/{TENANT_A}/invitations", json={"role": "owner"}- )- remove = await client.delete(f"/tenants/{TENANT_A}/members/{member_id}")-- assert promote.status_code == 200, promote.text- assert promote.json()["role"] == "owner"- assert demote.status_code == 200, demote.text- assert invite.status_code == 201, invite.text- assert remove.status_code == 200, remove.text---class TestInvitationLifecycle:- async def _mint(- self,- session_factory: async_sessionmaker[AsyncSession],- *,- tenant_id: str,- admin_id: str,- role: str = "member",- email: str | None = None,- uses_remaining: int = 1,- expires_in_hours: int = 168,- ) -> tuple[str, str]:- """Mint directly through the store (not the route) so a lifecycle- test does not depend on `TestInvitationAuthorisation` passing first.- Returns `(invitation_id, token)`."""- async with tenant_session(session_factory, tenant_id) as session:- invitation, token = await InvitationStore().create(- session,- role=role,- email=email,- expires_at=datetime.now(UTC) + timedelta(hours=expires_in_hours),- uses_remaining=uses_remaining,- created_by=admin_id,- )- await session.commit()- return invitation.id, token-- async def test_accepting_grants_membership_in_the_invited_role(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="inviter", tenant_id=TENANT_A, role="owner"- )- _id, token = await self._mint(- session_factory, tenant_id=TENANT_A, admin_id=admin_id, role="admin"- )- await _make_tenant(session_factory, TENANT_B)- invitee_id = await _make_member(- session_factory, name="invitee", tenant_id=TENANT_B, role="member"- )- caller_token = _token(invitee_id, "[email protected]", TENANT_B)-- async with _client(_app(session_factory), caller_token) as client:- response = await client.post("/invitations/accept", json={"token": token})-- assert response.status_code == 200, response.text- body = response.json()- assert body["id"] == TENANT_A- assert body["role"] == "admin"-- async with session_factory() as session:- membership = await session.get(TenantMember, (TENANT_A, invitee_id))- assert membership is not None- assert membership.role == "admin"-- async def test_re_accepting_an_invitation_you_already_hold_costs_nothing(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """A shared link is double-clicked, or reloaded, or opened on a phone- as well. The second acceptance grants nothing new, so it must spend- nothing either — otherwise one careless refresh burns a seat that was- meant for somebody else, and the invitation dies with nobody's- membership to show for it.- """- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="link-sharer", tenant_id=TENANT_A, role="owner"- )- invitation_id, token = await self._mint(- session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=2- )- await _make_tenant(session_factory, TENANT_B)- invitee_id = await _make_member(- session_factory, name="double-clicker", tenant_id=TENANT_B, role="member"- )-- app = _app(session_factory)- async with _client(- app, _token(invitee_id, "[email protected]", TENANT_B)- ) as client:- first = await client.post("/invitations/accept", json={"token": token})- second = await client.post("/invitations/accept", json={"token": token})-- assert first.status_code == 200, first.text- assert second.status_code == 200, second.text- assert second.json()["role"] == first.json()["role"]-- async with tenant_session(session_factory, TENANT_A) as session:- invitation = await session.get(Invitation, invitation_id)- assert invitation is not None- assert invitation.uses_remaining == 1-- async def test_accepting_twice_fails_the_second_time(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="inviter2", tenant_id=TENANT_A, role="owner"- )- _id, token = await self._mint(- session_factory, tenant_id=TENANT_A, admin_id=admin_id, uses_remaining=1- )- await _make_tenant(session_factory, TENANT_B)- first_invitee = await _make_member(- session_factory, name="first-invitee", tenant_id=TENANT_B, role="member"- )- second_invitee = await _make_member(- session_factory, name="second-invitee", tenant_id=TENANT_B, role="member"- )-- app = _app(session_factory)- async with _client(- app, _token(first_invitee, "[email protected]", TENANT_B)- ) as client:- first = await client.post("/invitations/accept", json={"token": token})- assert first.status_code == 200, first.text-- async with _client(- app, _token(second_invitee, "[email protected]", TENANT_B)- ) as client:- second = await client.post("/invitations/accept", json={"token": token})-- assert second.status_code == 403- assert "used" in second.json()["detail"].lower()-- async with session_factory() as session:- assert await session.get(TenantMember, (TENANT_A, second_invitee)) is None-- async def test_a_revoked_invitation_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="revoker", tenant_id=TENANT_A, role="owner"- )- invitation_id, token = await self._mint(- session_factory, tenant_id=TENANT_A, admin_id=admin_id- )- async with tenant_session(session_factory, TENANT_A) as session:- await InvitationStore().revoke(session, invitation_id)- await session.commit()-- await _make_tenant(session_factory, TENANT_B)- invitee_id = await _make_member(- session_factory, name="too-late", tenant_id=TENANT_B, role="member"- )-- async with _client(- _app(session_factory),- _token(invitee_id, "[email protected]", TENANT_B),- ) as client:- response = await client.post("/invitations/accept", json={"token": token})-- assert response.status_code == 403- assert "revoked" in response.json()["detail"].lower()-- async def test_an_expired_invitation_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="expiry-setter", tenant_id=TENANT_A, role="owner"- )- _id, token = await self._mint(- session_factory,- tenant_id=TENANT_A,- admin_id=admin_id,- expires_in_hours=1,- )- # Force it into the past directly — the store only accepts a future- # `expires_at` implicitly by convention, not by constraint, so this is- # the straightforward way to get an already-expired row.- async with session_factory() as session:- result = await session.execute(select(Invitation))- invitation = result.scalars().one()- invitation.expires_at = datetime.now(UTC) - timedelta(hours=1) # type: ignore[assignment]- await session.commit()-- await _make_tenant(session_factory, TENANT_B)- invitee_id = await _make_member(- session_factory, name="too-slow", tenant_id=TENANT_B, role="member"- )-- async with _client(- _app(session_factory),- _token(invitee_id, "[email protected]", TENANT_B),- ) as client:- response = await client.post("/invitations/accept", json={"token": token})-- assert response.status_code == 403- assert "expired" in response.json()["detail"].lower()-- async def test_an_email_bound_invitation_refuses_a_different_address(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="picky-inviter", tenant_id=TENANT_A, role="owner"- )- _id, token = await self._mint(- session_factory,- tenant_id=TENANT_A,- admin_id=admin_id,- email="[email protected]",- )- await _make_tenant(session_factory, TENANT_B)- wrong_person = await _make_member(- session_factory,- name="wrong-person",- tenant_id=TENANT_B,- role="member",- email="[email protected]",- )-- async with _client(- _app(session_factory),- _token(wrong_person, "[email protected]", TENANT_B),- ) as client:- response = await client.post("/invitations/accept", json={"token": token})-- assert response.status_code == 403- assert "email" in response.json()["detail"].lower()-- async def test_an_email_bound_invitation_accepts_the_addressed_email(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- admin_id = await _make_member(- session_factory, name="picky-inviter2", tenant_id=TENANT_A, role="owner"- )- _id, token = await self._mint(- session_factory,- tenant_id=TENANT_A,- admin_id=admin_id,- email="[email protected]",- )- await _make_tenant(session_factory, TENANT_B)- right_person = await _make_member(- session_factory,- name="right-person",- tenant_id=TENANT_B,- role="member",- email="[email protected]",- )-- async with _client(- _app(session_factory),- _token(right_person, "[email protected]", TENANT_B),- ) as client:- response = await client.post("/invitations/accept", json={"token": token})-- assert response.status_code == 200, response.text---class TestMemberRoutes:- async def test_listing_shows_every_member_and_their_role(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="list-owner", tenant_id=TENANT_A, role="owner"- )- await _make_member(- session_factory, name="list-member", tenant_id=TENANT_A, role="member"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_A}/members")-- assert response.status_code == 200, response.text- roles = {row["name"]: row["role"] for row in response.json()}- assert roles == {"list-owner": "owner", "list-member": "member"}-- async def test_the_last_owner_cannot_be_demoted(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="sole-owner", tenant_id=TENANT_A, role="owner"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.patch(- f"/tenants/{TENANT_A}/members/{owner_id}", json={"role": "member"}- )-- assert response.status_code == 409-- async with session_factory() as session:- membership = await session.get(TenantMember, (TENANT_A, owner_id))- assert membership is not None- assert membership.role == "owner"-- async def test_an_owner_can_be_demoted_when_another_owner_remains(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="owner-one", tenant_id=TENANT_A, role="owner"- )- other_owner_id = await _make_member(- session_factory, name="owner-two", tenant_id=TENANT_A, role="owner"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.patch(- f"/tenants/{TENANT_A}/members/{other_owner_id}",- json={"role": "member"},- )-- assert response.status_code == 200, response.text- assert response.json()["role"] == "member"-- async def test_the_last_owner_cannot_be_removed(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="undeletable-owner", tenant_id=TENANT_A, role="owner"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.delete(f"/tenants/{TENANT_A}/members/{owner_id}")-- assert response.status_code == 409-- async with session_factory() as session:- assert await session.get(TenantMember, (TENANT_A, owner_id)) is not None-- async def test_removing_a_member_deletes_their_membership(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="remover", tenant_id=TENANT_A, role="owner"- )- target_id = await _make_member(- session_factory, name="removed", tenant_id=TENANT_A, role="member"- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")-- assert response.status_code == 200, response.text-- async with session_factory() as session:- assert await session.get(TenantMember, (TENANT_A, target_id)) is None-- async def test_removing_a_member_stops_their_api_key_working(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """The bite test: after removal, the credential the member minted in- this tenant no longer resolves to anything — not merely hidden, gone.- A live bearer-auth attempt with the same hash would fail at the very- first lookup `ApiKeyStore.get_by_hash` performs.- """- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="key-remover", tenant_id=TENANT_A, role="owner"- )- target_id = await _make_member(- session_factory, name="key-holder", tenant_id=TENANT_A, role="member"- )- key_hash = await _make_api_key(- session_factory, tenant_id=TENANT_A, user_id=target_id- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with session_factory() as session:- assert await ApiKeyStore().get_by_hash(session, key_hash) is not None-- async with _client(_app(session_factory), token) as client:- response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")- assert response.status_code == 200, response.text-- async with session_factory() as session:- assert await ApiKeyStore().get_by_hash(session, key_hash) is None-- async def test_a_member_who_owns_an_agent_here_cannot_be_removed(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- """An agent is not the member's private property to lose along with- their membership — it sits in rooms with other people, and deleting it- is not recoverable the way reminting a key is. Removal must refuse,- naming the agent, and this must not be a partial write: not the- membership, not the member's unrelated personal key, not the agent's- own key may be touched when the route 409s.- """- await _make_tenant(session_factory, TENANT_A)- owner_id = await _make_member(- session_factory, name="agent-remover", tenant_id=TENANT_A, role="owner"- )- target_id = await _make_member(- session_factory, name="agent-owner", tenant_id=TENANT_A, role="member"- )- agent_id, agent_name, agent_key_hash = await _make_agent_with_key(- session_factory, tenant_id=TENANT_A, owner_id=target_id- )- personal_key_hash = await _make_api_key(- session_factory, tenant_id=TENANT_A, user_id=target_id- )- token = _token(owner_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")-- assert response.status_code == 409, response.text- assert agent_name in response.json()["detail"]-- async with session_factory() as session:- assert await session.get(TenantMember, (TENANT_A, target_id)) is not None- assert await AgentStore().get(session, agent_id) is not None- assert await ApiKeyStore().get_by_hash(session, agent_key_hash) is not None- assert (- await ApiKeyStore().get_by_hash(session, personal_key_hash) is not None- )-- async def test_a_plain_member_cannot_remove_anyone(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- member_id = await _make_member(- session_factory, name="powerless", tenant_id=TENANT_A, role="member"- )- target_id = await _make_member(- session_factory, name="untouchable", tenant_id=TENANT_A, role="member"- )- token = _token(member_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.delete(f"/tenants/{TENANT_A}/members/{target_id}")-- assert response.status_code == 403---def _window() -> dict[str, str]:- now = datetime.now(UTC)- return {- "since": (now - timedelta(hours=1)).isoformat(),- "until": (now + timedelta(hours=1)).isoformat(),- }---class TestUsageRoute:- async def _spend(- self,- session_factory: async_sessionmaker[AsyncSession],- tenant_id: str,- amount: int,- ) -> None:- async with tenant_session(session_factory, tenant_id) as session:- await UsageStore().record(- session,- tenant_id=tenant_id,- metric=UsageMetric.MESSAGES,- client_id=f"client-of-{tenant_id}",- model="",- amount=amount,- )- await session.commit()-- async def test_an_admin_sees_their_workspaces_usage_only(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- await _make_tenant(session_factory, TENANT_B)- await self._spend(session_factory, TENANT_A, 3)- await self._spend(session_factory, TENANT_B, 40)- user_id = await _make_member(- session_factory, name="usage-admin", tenant_id=TENANT_A, role="admin"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_A}/usage", params=_window())-- assert response.status_code == 200- assert response.json() == [- {- "metric": "messages",- "client_id": f"client-of-{TENANT_A}",- "client_name": None,- "client_type": None,- "model": "",- "amount": 3,- }- ]-- async def test_a_plain_member_cannot_read_usage(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="usage-member", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_A}/usage", params=_window())-- assert response.status_code == 403-- async def test_an_admin_of_a_cannot_read_bs_usage(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- await _make_tenant(session_factory, TENANT_B)- user_id = await _make_member(- session_factory, name="usage-snoop", tenant_id=TENANT_A, role="admin"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_B}/usage", params=_window())-- assert response.status_code == 403-- async def test_a_window_without_a_timezone_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="usage-naive", tenant_id=TENANT_A, role="owner"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(- f"/tenants/{TENANT_A}/usage",- params={"since": "2026-01-01T00:00:00", "until": "2026-01-02T00:00:00"},- )-- assert response.status_code == 400- assert "timezone" in response.json()["detail"]-- async def test_an_empty_window_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="usage-empty", tenant_id=TENANT_A, role="owner"- )- token = _token(user_id, "[email protected]", TENANT_A)- window = _window()-- async with _client(_app(session_factory), token) as client:- response = await client.get(- f"/tenants/{TENANT_A}/usage",- params={"since": window["until"], "until": window["since"]},- )-- assert response.status_code == 400---class TestBudgetRoutes:- async def _admin(- self, session_factory: async_sessionmaker[AsyncSession], name: str- ) -> tuple[str, str]:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name=name, tenant_id=TENANT_A, role="admin"- )- return user_id, _token(user_id, f"{name}@example.invalid", TENANT_A)-- async def test_an_admin_sets_a_budget_and_sees_its_spend(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- user_id, token = await self._admin(session_factory, "budget-admin")- agent_id, agent_name, _ = await _make_agent_with_key(- session_factory, tenant_id=TENANT_A, owner_id=user_id- )- async with session_factory() as session:- agent = await AgentStore().get(session, agent_id)- assert agent is not None- await UsageStore().record(- session,- tenant_id=TENANT_A,- metric=UsageMetric.TURNS,- client_id=agent.client_id,- model="",- amount=3,- )- await session.commit()-- async with _client(_app(session_factory), token) as client:- created = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": agent_id,- "metric": "turns",- "model": "",- "amount_limit": 3,- "period_hours": 24,- },- )- listed = await client.get(f"/tenants/{TENANT_A}/budgets")-- assert created.status_code == 201- body = created.json()- assert body["agent_name"] == agent_name- assert (body["spent"], body["exhausted"]) == (3, True)- assert listed.json() == [body]-- async def test_a_second_budget_on_the_same_thing_is_a_conflict(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, token = await self._admin(session_factory, "budget-twice")- budget = {- "agent_id": None,- "metric": "messages",- "model": "",- "amount_limit": 100,- "period_hours": 24,- }-- async with _client(_app(session_factory), token) as client:- first = await client.post(f"/tenants/{TENANT_A}/budgets", json=budget)- second = await client.post(f"/tenants/{TENANT_A}/budgets", json=budget)-- assert first.status_code == 201- assert second.status_code == 409-- @pytest.mark.parametrize("metric", ["messages", "turns"])- async def test_a_budget_on_a_metric_counted_without_a_model_cannot_name_one(- self, session_factory: async_sessionmaker[AsyncSession], metric: str- ) -> None:- _, token = await self._admin(session_factory, f"budget-model-{metric}")-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": None,- "metric": metric,- "model": "some-model",- "amount_limit": 100,- "period_hours": 24,- },- )-- assert response.status_code == 422- assert "not counted per model" in response.text-- @pytest.mark.parametrize(- ("amount_limit", "period_hours"),- [(2**53, 24), (100, 8785), (0, 24), (100, 0)],- )- async def test_a_budget_past_the_bounds_is_refused(- self,- session_factory: async_sessionmaker[AsyncSession],- amount_limit: int,- period_hours: int,- ) -> None:- _, token = await self._admin(session_factory, "budget-bounds")- limits = {"amount_limit": amount_limit, "period_hours": period_hours}-- async with _client(_app(session_factory), token) as client:- created = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={"agent_id": None, "metric": "turns", "model": "", **limits},- )- within = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": None,- "metric": "turns",- "model": "",- "amount_limit": 100,- "period_hours": 24,- },- )- updated = await client.put(- f"/tenants/{TENANT_A}/budgets/{within.json()['id']}", json=limits- )-- assert created.status_code == 422- assert within.status_code == 201- assert updated.status_code == 422-- async def test_a_budget_for_another_workspaces_agent_is_not_found(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, token = await self._admin(session_factory, "budget-foreign")- await _make_tenant(session_factory, TENANT_B)- their_owner = await _make_member(- session_factory, name="budget-theirs", tenant_id=TENANT_B, role="owner"- )- their_agent, _, _ = await _make_agent_with_key(- session_factory, tenant_id=TENANT_B, owner_id=their_owner- )-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": their_agent,- "metric": "turns",- "model": "",- "amount_limit": 1,- "period_hours": 24,- },- )-- assert response.status_code == 404-- async def test_a_limit_that_is_not_positive_is_refused(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, token = await self._admin(session_factory, "budget-zero")-- async with _client(_app(session_factory), token) as client:- response = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": None,- "metric": "turns",- "model": "",- "amount_limit": 0,- "period_hours": 24,- },- )-- assert response.status_code == 422-- async def test_an_admin_changes_and_removes_a_budget(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, token = await self._admin(session_factory, "budget-edit")-- async with _client(_app(session_factory), token) as client:- created = await client.post(- f"/tenants/{TENANT_A}/budgets",- json={- "agent_id": None,- "metric": "output_tokens",- "model": "some-model",- "amount_limit": 1000,- "period_hours": 24,- },- )- budget_id = created.json()["id"]- updated = await client.put(- f"/tenants/{TENANT_A}/budgets/{budget_id}",- json={"amount_limit": 5000, "period_hours": 168},- )- deleted = await client.delete(f"/tenants/{TENANT_A}/budgets/{budget_id}")- again = await client.delete(f"/tenants/{TENANT_A}/budgets/{budget_id}")- listed = await client.get(f"/tenants/{TENANT_A}/budgets")-- assert updated.status_code == 200- assert (updated.json()["amount_limit"], updated.json()["period_hours"]) == (- 5000,- 168,- )- assert deleted.status_code == 204- assert again.status_code == 404- assert listed.json() == []-- async def test_a_plain_member_cannot_see_budgets(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- await _make_tenant(session_factory, TENANT_A)- user_id = await _make_member(- session_factory, name="budget-member", tenant_id=TENANT_A, role="member"- )- token = _token(user_id, "[email protected]", TENANT_A)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_A}/budgets")-- assert response.status_code == 403-- async def test_an_admin_of_a_cannot_touch_bs_budgets(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- _, token = await self._admin(session_factory, "budget-snoop")- await _make_tenant(session_factory, TENANT_B)-- async with _client(_app(session_factory), token) as client:- response = await client.get(f"/tenants/{TENANT_B}/budgets")-- assert response.status_code == 403diff --git a/core/tests/switch_core/session_activity/test_bridge_publisher.py b/core/tests/switch_core/session_activity/test_bridge_publisher.pyindex c0bf3f5fb..edef651f9 100644--- a/core/tests/switch_core/session_activity/test_bridge_publisher.py+++ b/core/tests/switch_core/session_activity/test_bridge_publisher.py@@ -177,7 +177,6 @@ async def _step(thread_id=ASKED,message_id=ASKED,occurred_at=datetime.now(UTC),- usage=[],)diff --git a/core/tests/switch_core/session_activity/test_isolation.py b/core/tests/switch_core/session_activity/test_isolation.pyindex 71c486d13..c1b8e08ed 100644--- a/core/tests/switch_core/session_activity/test_isolation.py+++ b/core/tests/switch_core/session_activity/test_isolation.py@@ -83,7 +83,6 @@ async def test_each_tenant_sees_only_its_own_activity_and_requests(rls_harness):thread_id=None,message_id=None,occurred_at=datetime.now(UTC),- usage=[],)await service.open_approval(tenant,diff --git a/core/tests/switch_core/session_activity/test_maintenance.py b/core/tests/switch_core/session_activity/test_maintenance.pyindex 40c5c09a9..ba67175fb 100644--- a/core/tests/switch_core/session_activity/test_maintenance.py+++ b/core/tests/switch_core/session_activity/test_maintenance.py@@ -50,7 +50,6 @@ async def test_a_pass_expires_overdue_requests_and_prunes_only_when_asked(thread_id=None,message_id=None,occurred_at=datetime.now(UTC),- usage=[],)past = datetime.now(UTC) - timedelta(days=30)await _backdate(session_factory, ApprovalRequest, expires_at=past)diff --git a/core/tests/switch_core/session_activity/test_routes.py b/core/tests/switch_core/session_activity/test_routes.pyindex e07e0bf35..ad33f217e 100644--- a/core/tests/switch_core/session_activity/test_routes.py+++ b/core/tests/switch_core/session_activity/test_routes.py@@ -10,7 +10,7 @@ from sqlalchemy import selectfrom switch_core.bridges.agent.api.activity_routes import routerfrom switch_core.bridges.agent.auth import get_agent_from_scopefrom switch_core.bridges.agent.dependencies import get_session_factory-from switch_core.db.models import Agent, ApprovalRequest, TenantUsage+from switch_core.db.models import Agent, ApprovalRequestfrom switch_core.session_activity.service import ApprovalOption, PlatformPersonfrom switch_core.sessions.contract import Answer, QuestionsResultfrom switch_core.sessions.errors import SessionError@@ -110,58 +110,6 @@ async def test_malformed_activity_is_a_422(client, overrides):assert response.status_code == 422-_USAGE = {- "model": "big",- "input_tokens": 10,- "output_tokens": 2,- "cache_read_tokens": 300,- "cache_write_tokens": 0,-}---def _ended_turn(**overrides):- return _activity(- **{- "item_id": "turn",- "kind": "turn",- "status": "completed",- "title": "",- "text": "",- **overrides,- }- )---async def test_an_ended_turn_row_carries_what_the_turn_spent(client, session_factory):- response = await client.post(- f"/agent-sessions/{SESSION}/activity", json=_ended_turn(usage=[_USAGE])- )- assert response.json() == {"recorded": True}- async with session_factory() as db:- rows = (await db.execute(select(TenantUsage.metric, TenantUsage.amount))).all()- assert sorted(rows) == [- ("cache_read_tokens", 300),- ("input_tokens", 10),- ("output_tokens", 2),- ("turns", 1),- ]--- "body",- [- _activity(usage=[_USAGE]),- _ended_turn(status="running", usage=[_USAGE]),- _ended_turn(usage=[{**_USAGE, "input_tokens": -1}]),- _ended_turn(usage=[{**_USAGE, "input_tokens": 2**53}]),- _ended_turn(usage=[{**_USAGE, "reasoning_tokens": 1}]),- ],-)-async def test_usage_anywhere_but_an_ended_turn_or_malformed_is_a_422(client, body):- response = await client.post(f"/agent-sessions/{SESSION}/activity", json=body)- assert response.status_code == 422--async def test_a_questions_request_over_http(client, service, people):opened = await client.post(f"/agent-sessions/{SESSION}/approvals",diff --git a/core/tests/switch_core/session_activity/test_service.py b/core/tests/switch_core/session_activity/test_service.pyindex 7085888b7..2ae265892 100644--- a/core/tests/switch_core/session_activity/test_service.py+++ b/core/tests/switch_core/session_activity/test_service.py@@ -3,17 +3,16 @@ from __future__ import annotationsfrom datetime import UTC, datetime, timedeltaimport pytest-from sqlalchemy import select, update+from sqlalchemy import updatefrom switch_core.addressing import owner_only_policy-from switch_core.db.models import ApprovalRequest, TenantUsage+from switch_core.db.models import ApprovalRequestfrom switch_core.session_activity.service import (ApprovalOption,PlatformPerson,Question,QuestionOption,SwitchUser,- TokenSpend,)from switch_core.sessions.contract import Answer, QuestionsResultfrom switch_core.sessions.errors import SessionError@@ -65,7 +64,6 @@ def _step(**overrides):thread_id=None,message_id=None,occurred_at=datetime(2026, 9, 23, 12, 0, tzinfo=UTC),- usage=[],)values.update(overrides)return values@@ -120,86 +118,6 @@ async def test_a_step_is_upserted_by_revision_and_announced_by_turn(service, chaassert all(change.row is None for change in announced)-def _turn(turn_id: str, revision: int, status: str, usage=()):- return _step(- turn_id=turn_id,- item_id="turn",- kind="turn",- revision=revision,- status=status,- title="",- text="",- usage=list(usage),- )---async def _turns_counted(session_factory) -> int:- async with session_factory() as db:- rows = await db.scalars(- select(TenantUsage.amount).where(TenantUsage.metric == "turns")- )- return sum(rows)---async def test_a_turn_is_counted_once_when_first_reported(service, session_factory):- # A turn is spent once it exists: its later statuses, a retried report and- # its steps are the same turn, and one that errors still cost model time.- await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))- await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))- await service.report_item(AGENT, SESSION, **_step(revision=2))- await service.report_item(AGENT, SESSION, **_turn("turn-1", 3, "error"))- assert await _turns_counted(session_factory) == 1-- await service.report_item(AGENT, SESSION, **_turn("turn-2", 4, "completed"))- assert await _turns_counted(session_factory) == 2---def _spend(model: str, input_tokens: int) -> TokenSpend:- return TokenSpend(- model=model,- input_tokens=input_tokens,- output_tokens=1,- cache_read_tokens=0,- cache_write_tokens=0,- )---async def _tokens_counted(session_factory) -> list[tuple[str, str, int]]:- async with session_factory() as db:- rows = await db.execute(- select(TenantUsage.metric, TenantUsage.model, TenantUsage.amount).where(- TenantUsage.metric != "turns"- )- )- return sorted(tuple(row) for row in rows)---async def test_a_turns_tokens_are_counted_once_when_it_first_ends(- service, session_factory-):- spent = [_spend("small", 7), _spend("big", 10)]- await service.report_item(AGENT, SESSION, **_turn("turn-1", 1, "running"))- await service.report_item(AGENT, SESSION, **_turn("turn-1", 2, "completed", spent))- # A retried report, and a later revision of an ended turn, spend nothing new.- await service.report_item(AGENT, SESSION, **_turn("turn-1", 2, "completed", spent))- await service.report_item(- AGENT, SESSION, **_turn("turn-1", 3, "interrupted", spent)- )- assert await _tokens_counted(session_factory) == [- ("input_tokens", "big", 10),- ("input_tokens", "small", 7),- ("output_tokens", "big", 1),- ("output_tokens", "small", 1),- ]---async def test_usage_on_a_turn_that_has_not_ended_is_refused(service):- with pytest.raises(SessionError, match="ended turn"):- await service.report_item(- AGENT, SESSION, **_turn("turn-1", 1, "running", [_spend("big", 1)])- )--async def test_a_turns_steps_are_read_in_the_order_first_reported(service):for item_id, kind, status in [("turn", "turn", "running"),diff --git a/core/tests/switch_core/transport/fake.py b/core/tests/switch_core/transport/fake.pyindex d385e09df..34d313b6d 100644--- a/core/tests/switch_core/transport/fake.py+++ b/core/tests/switch_core/transport/fake.py@@ -85,7 +85,6 @@ class FakeTransport:body: str,*,sender_name: str,- metered: bool,format: MessageFormat = "text",mentions: list[str] | None = None,thread_root_id: str | None = None,@@ -98,7 +97,6 @@ class FakeTransport:"room_id": room_id,"body": body,"sender_name": sender_name,- "metered": metered,"format": format,"mentions": mentions,"thread_root_id": thread_root_id,@@ -142,7 +140,6 @@ class FakeTransport:size: int,*,sender_name: str,- metered: bool,msgtype: str,caption: str | None = None,thread_root_id: str | None = None,@@ -158,7 +155,6 @@ class FakeTransport:"mimetype": mimetype,"size": size,"sender_name": sender_name,- "metered": metered,"msgtype": msgtype,"caption": caption,"thread_root_id": thread_root_id,diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex 5bdea7b80..a69c36a5d 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -17,25 +17,15 @@ import uuidfrom collections.abc import Iteratorimport pytest-from sqlalchemy import delete, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.db.models import (- TENANT_ZERO_ID,- Client,- ClientRoom,- Message,- Room,- Tenant,- TenantUsage,-)+from switch_core.db.models import TENANT_ZERO_ID, Client, ClientRoom, Room, Tenantfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.media_store import MediaStorefrom switch_core.db.stores.message_store import MessageStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.db.stores.usage_store import UsageStorefrom switch_core.observability.metrics import MetricsRegistry, install, uninstallfrom switch_core.provisioning.postgres import PostgresProvisioningfrom switch_core.tenant_context import current_tenant_id, tenant_scope@@ -195,7 +185,6 @@ def _transport(session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),- usage_store=UsageStore(),media_store=MediaStore(),listener=listener or _FakeListener(),invites=invites or InviteBus(),@@ -211,110 +200,6 @@ class TestConformsToThePort:assert isinstance(transport, MessageTransport)-class TestMetering:- """Every message a participant sends is counted against its tenant, in the- same write as the message, so the two cannot disagree."""-- async def _usage(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> list[tuple[str, str, int]]:- async with session_factory() as session:- rows = await session.scalars(select(TenantUsage))- return [(r.metric, r.client_id, r.amount) for r in rows]-- async def test_messages_and_media_are_counted_for_the_sender(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- async with session_factory() as session:- _, transport_room_id, client_id, user_id = await _make_room(session)- await session.commit()-- transport = _transport(session_factory, client_id=client_id, user_id=user_id)- await transport.send_message(- transport_room_id, "one", sender_name="a", metered=True- )- await transport.send_message(- transport_room_id, "two", sender_name="a", metered=True- )- await transport.send_media(- transport_room_id,- "blob://1",- "report.pdf",- "application/pdf",- 2048,- sender_name="a",- msgtype="m.file",- metered=True,- )-- assert await self._usage(session_factory) == [("messages", client_id, 3)]-- async def test_platform_events_are_not_counted(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Reports, runtime state and receipts are how Switch works, not- # something the tenant said, so they are not billed as messages.- async with session_factory() as session:- _, transport_room_id, client_id, user_id = await _make_room(session)- await session.commit()-- transport = _transport(session_factory, client_id=client_id, user_id=user_id)- await transport.send_event(- transport_room_id, "com.switch.report.tool_call", {"tool": "Bash"}- )-- assert await self._usage(session_factory) == []-- async def test_an_unmetered_send_is_stored_but_not_counted(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # What Switch posts on a participant's behalf — a greeting, a command- # reply, an automatic refusal — is not something it chose to say.- async with session_factory() as session:- room_id, transport_room_id, client_id, user_id = await _make_room(session)- await session.commit()-- transport = _transport(session_factory, client_id=client_id, user_id=user_id)- await transport.send_message(- transport_room_id, "unavailable", sender_name="a", metered=False- )- await transport.send_media(- transport_room_id,- "blob://1",- "report.pdf",- "application/pdf",- 2048,- sender_name="a",- msgtype="m.file",- metered=False,- )-- assert await self._usage(session_factory) == []- async with session_factory() as session:- stored = await session.scalars(- select(Message).where(Message.room_id == room_id)- )- assert len(list(stored)) == 2-- async def test_the_count_survives_the_room(- self, session_factory: async_sessionmaker[AsyncSession]- ) -> None:- # Deleting a room cascades to its messages; it must not refund them.- async with session_factory() as session:- room_id, transport_room_id, client_id, user_id = await _make_room(session)- await session.commit()-- transport = _transport(session_factory, client_id=client_id, user_id=user_id)- await transport.send_message(- transport_room_id, "spent", sender_name="a", metered=True- )- async with session_factory() as session:- await session.execute(delete(Room).where(Room.id == room_id))- await session.commit()-- assert await self._usage(session_factory) == [("messages", client_id, 1)]--class TestSending:async def test_a_message_becomes_a_row(self, session_factory: async_sessionmaker[AsyncSession]@@ -325,10 +210,7 @@ class TestSending:transport = _transport(session_factory, client_id=client_id, user_id=user_id)result = await transport.send_message(- transport_room_id,- "hello",- sender_name="agent one",- metered=True,+ transport_room_id, "hello", sender_name="agent one")async with session_factory() as session:@@ -357,16 +239,10 @@ class TestSending:transport = _transport(session_factory, client_id=client_id, user_id=user_id)first = await transport.send_message(- transport_room_id,- "one",- sender_name="agent one",- metered=True,+ transport_room_id, "one", sender_name="agent one")second = await transport.send_message(- transport_room_id,- "two",- sender_name="agent one",- metered=True,+ transport_room_id, "two", sender_name="agent one")async with session_factory() as session:@@ -390,7 +266,6 @@ class TestSending:"in the thread",sender_name="agent one",thread_root_id="root-1",- metered=True,)async with session_factory() as session:@@ -418,7 +293,6 @@ class TestSending:sender_name="agent one",msgtype="m.file",caption="the report",- metered=True,)async with session_factory() as session:@@ -488,10 +362,7 @@ class TestSending:transport = _transport(session_factory, client_id="c", user_id="@a:test")with pytest.raises(TransportError):await transport.send_message(- "!nowhere:test",- "hello",- sender_name="agent one",- metered=True,+ "!nowhere:test", "hello", sender_name="agent one")@@ -584,7 +455,6 @@ class TestMedia:session_factory=session_factory,room_store=RoomStore(),message_store=MessageStore(),- usage_store=UsageStore(),media_store=MediaStore(),listener=_FakeListener(),invites=InviteBus(),@@ -643,9 +513,7 @@ class TestReceiving:) -> None:transport, listener, received, room, _ = await self._receiving(session_factory)- sent = await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ sent = await transport.send_message(room, "hello", sender_name="agent one")await listener.announce(await _watched_room(transport))assert len(received.events) == 1@@ -672,9 +540,7 @@ class TestReceiving:listener = _FakeListener()writer = _transport(session_factory, client_id=client_id, user_id=user_id)- await writer.send_message(- room, "said before anyone listened", sender_name="a", metered=True- )+ await writer.send_message(room, "said before anyone listened", sender_name="a")received = _Received()reader = _transport(@@ -688,7 +554,7 @@ class TestReceiving:await listener.announce(switch_room_id)assert received.events == []- await writer.send_message(room, "said after", sender_name="a", metered=True)+ await writer.send_message(room, "said after", sender_name="a")await listener.announce(switch_room_id)await listener.announce(switch_room_id)@@ -708,7 +574,6 @@ class TestReceiving:12,sender_name="agent one",msgtype="m.file",- metered=True,)await listener.announce(await _watched_room(transport))@@ -903,9 +768,7 @@ class TestOneClientCannotStallAnother:self._tasks.append(asyncio.create_task(transport.receive_forever()))switch_room_id = await _watched_room(transport)- await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ await transport.send_message(room, "hello", sender_name="agent one")# The waker itself, rather than the fake's announce, which waits for# the reading it provokes.await transport._on_room_advanced(switch_room_id)@@ -936,9 +799,7 @@ class TestOneClientCannotStallAnother:self._tasks.append(asyncio.create_task(transport.receive_forever()))switch_room_id = await _watched_room(transport)- await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ await transport.send_message(room, "hello", sender_name="agent one")await transport._on_room_advanced(switch_room_id)await transport._on_room_advanced(switch_room_id)await transport._on_room_advanced(switch_room_id)@@ -1056,9 +917,7 @@ class TestHearingYourOwnArrival:talker = _transport(session_factory, client_id=other_id, user_id=other_user)await talker.join_room(later)- await talker.send_message(- later, "said before anyone joined", sender_name="a", metered=True- )+ await talker.send_message(later, "said before anyone joined", sender_name="a")listener = _FakeListener()received = _Received()@@ -1144,10 +1003,7 @@ class TestDeliveryBindsTheRoomsTenant:switch_room_id = await _watched_room(transport)await transport.send_message(- transport_room_id,- "hello",- sender_name="agent one",- metered=True,+ transport_room_id, "hello", sender_name="agent one")await listener.announce(switch_room_id)@@ -1388,8 +1244,8 @@ class TestATransportActsInItsClientsTenant:self._tasks.append(asyncio.create_task(transport.receive_forever()))await _watched_room(transport)- await transport.send_message(mxid_a, "in a", sender_name="puppet", metered=True)- await transport.send_message(mxid_b, "in b", sender_name="puppet", metered=True)+ await transport.send_message(mxid_a, "in a", sender_name="puppet")+ await transport.send_message(mxid_b, "in b", sender_name="puppet")for room_id in room_ids:await listener.announce(room_id)@@ -1446,9 +1302,7 @@ class TestATransportActsInItsClientsTenant:tenant_id=tenant_id,)with pytest.raises(TransportError, match="is not a Switch room"):- await transport.send_message(- elsewhere_mxid, "hello", sender_name="admin", metered=True- )+ await transport.send_message(elsewhere_mxid, "hello", sender_name="admin")async def test_the_schema_forbids_a_client_row_in_another_tenants_room(@@ -1541,9 +1395,7 @@ class TestWhatIsMeasured:) -> None:transport, listener, room = await self._receiving(session_factory)- await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ await transport.send_message(room, "hello", sender_name="agent one")await listener.announce(await _watched_room(transport))payloads = {p.name: p for p in _registry.collect()}@@ -1563,7 +1415,6 @@ class TestWhatIsMeasured:size=3,sender_name="agent one",msgtype="m.image",- metered=True,)await listener.announce(await _watched_room(transport))@@ -1578,9 +1429,7 @@ class TestWhatIsMeasured:) -> None:transport, listener, room = await self._receiving(session_factory)- await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ await transport.send_message(room, "hello", sender_name="agent one")await listener.announce(await _watched_room(transport))payload = next(@@ -1609,9 +1458,7 @@ class TestWhatIsMeasured:),)- await transport.send_message(- room, "hello", sender_name="agent one", metered=True- )+ await transport.send_message(room, "hello", sender_name="agent one")await listener.announce(await _watched_room(transport))# Swallowing the exception is what keeps the delivery loop alive for@@ -1634,10 +1481,7 @@ class TestWhatIsMeasured:with pytest.raises(Exception):await transport.send_message(- "!room-that-does-not-exist:test",- "hello",- sender_name="agent one",- metered=True,+ "!room-that-does-not-exist:test", "hello", sender_name="agent one")recorded = {payload.name for payload in _registry.collect()}@@ -1651,10 +1495,7 @@ class TestWhatIsMeasured:with pytest.raises(Exception):await transport.send_message(- "!room-that-does-not-exist:test",- "hello",- sender_name="agent one",- metered=True,+ "!room-that-does-not-exist:test", "hello", sender_name="agent one")payload = next(@@ -1741,9 +1582,7 @@ class TestBeingRemovedFromARoom:await _watched_room(member)# While a member, it hears the room.- await member.send_message(- room, "while a member", sender_name="agent one", metered=True- )+ await member.send_message(room, "while a member", sender_name="agent one")await listener.announce(room_id)assert [event.body for event in received.events] == ["while a member"]@@ -1754,9 +1593,7 @@ class TestBeingRemovedFromARoom:assert leaving[0] not in membersassert staying[0] in members- await member.send_message(- room, "after removal", sender_name="agent one", metered=True- )+ await member.send_message(room, "after removal", sender_name="agent one")await listener.announce(room_id)assert [event.body for event in received.events] == ["while a member"]@@ -1805,10 +1642,7 @@ class TestBeingRemovedFromARoom:provisioning = self._provisioning(session_factory, invites)await provisioning.kick_user(room, leaving[1])await member.send_message(- room,- "said while it was out",- sender_name="agent one",- metered=True,+ room, "said while it was out", sender_name="agent one")await listener.announce(room_id)@@ -1902,9 +1736,7 @@ class TestBeingRemovedFromARoom:await _watched_room(member)for i in range(4):- await member.send_message(- room, f"line {i}", sender_name="agent one", metered=True- )+ await member.send_message(room, f"line {i}", sender_name="agent one")await listener.announce(room_id)# The removal landed on the first delivery; the rest of the page is@@ -2061,9 +1893,7 @@ class TestBeingRemovedFromARoom:# More than one page, so the loop would come back for another.for i in range(_DELIVERY_PAGE + 25):- await member.send_message(- room, f"line {i}", sender_name="agent one", metered=True- )+ await member.send_message(room, f"line {i}", sender_name="agent one")await listener.announce(room_id)# The whole of page one, and none of page two.