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
Keep what a post checks first until a signal says it changed (CHOO-3667)
Abel Dantasf6754e29ed09
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6bba22851..b61d5afa5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -159,6 +159,15 @@ version of their own to them without also giving them a release of their own.compares it only when someone signs in.#### Changed+- **A post's first checks are kept until a signal says they changed.**+ Every post checks that its agent is in the room and that no budget+ covering it has run out, and a controller relaying it checks the+ membership again: two transactions per post. Each process now keeps those+ answers as it keeps a controller token's rows. Triggers on `room_agents`,+ `rooms` and `usage_budgets` signal every change, so an answer is kept while+ the signal connection listens and for `AGENT_AUTH_CACHE_TTL_SECONDS`+ otherwise. A refusal is never kept. `ROOM_ACCESS_CACHE_MAX_ENTRIES`+ (20,000) bounds what is kept.- **An agent's stream reads in one database session per pass, and pooledconnections are no longer pinged before use.** A pass that delivered amessage opened a session for each of its reads, six pool checkouts and sixdiff --git a/core/switch_core/bridges/agent/app.py b/core/switch_core/bridges/agent/app.pyindex 7a22cd167..7a164f2fb 100644--- a/core/switch_core/bridges/agent/app.py+++ b/core/switch_core/bridges/agent/app.py@@ -24,6 +24,7 @@ from switch_core.bridges.agent.mcp import create_mcp_appfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer+from switch_core.bridges.agent.room_access_cache import RoomAccessCachefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -114,6 +115,7 @@ def create_agent_bridge_app(trust_client: TrustClient,gateway_ui: GatewayUi | None,connections: AgentConnectionRegistry | None = None,+ room_access: RoomAccessCache | None = None,telemetry: TelemetryService | None = None,) -> tuple[FastAPI, AgentCore]:# One registry for the whole process: the live connection set is the source@@ -149,6 +151,7 @@ def create_agent_bridge_app(config=config,approval_outcomes=approval_outcomes,trust_client=trust_client,+ room_access=room_access,telemetry=telemetry,)diff --git a/core/switch_core/bridges/agent/controller_auth_cache.py b/core/switch_core/bridges/agent/controller_auth_cache.pyindex 7a74b35b0..c8e75bb44 100644--- a/core/switch_core/bridges/agent/controller_auth_cache.py+++ b/core/switch_core/bridges/agent/controller_auth_cache.py@@ -1,12 +1,10 @@from __future__ import annotations-import timefrom collections import OrderedDictfrom collections.abc import Iterable-from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any-from switch_core.bridges.agent.protocol.liveness import HEARTBEAT_TTL_SECONDS+from switch_core.bridges.agent.held_rows import Entry, HeldRows, ReadTicketfrom switch_core.db.auth_rows_notify_ddl import (AGENT_CHANGED_SIGNAL,CONTROLLER_AUTH_CHANGED_SIGNAL,@@ -18,30 +16,7 @@ if TYPE_CHECKING:from switch_core.signals import SignalBus-@dataclass(frozen=True)-class ReadTicket:- """Taken before a read and handed back with what it read, so the cache- can tell whether anything it was told while the read was in flight makes- the read stale."""-- generation: int- # The signal bus's listening connection when the read began, or None if- # it was not listening then.- listening: int | None---@dataclass-class _Entry[V]:- tenant_id: str- value: V- expires_at: float- # The listening connection the entry was read under, while it is the one- # listening, keeps the entry past `expires_at`. None for a read made while- # the bus did not listen.- held_under: int | None---class ControllerAuthCache:+class ControllerAuthCache(HeldRows):"""A memo of the two reads a controller access token costs.A controller token is a signed JWT, so verifying it needs no database. But@@ -89,87 +64,68 @@ class ControllerAuthCache:def __init__(self, *, ttl_seconds: float, max_entries: int, max_agents: int | None = None) -> None:- if ttl_seconds < 0:- raise ValueError(f"ttl_seconds must not be negative, got {ttl_seconds!r}")- if ttl_seconds >= HEARTBEAT_TTL_SECONDS:- raise ValueError(- f"ttl_seconds must stay below the agent heartbeat TTL of "- f"{HEARTBEAT_TTL_SECONDS}s, got {ttl_seconds!r}"- )+ super().__init__(ttl_seconds=ttl_seconds)if max_entries < 1:raise ValueError(f"max_entries must be at least 1, got {max_entries!r}")if max_agents is not None and max_agents < 1:raise ValueError(f"max_agents must be at least 1, got {max_agents!r}")- self._ttl = ttl_secondsself._max_controllers = max_entriesself._max_agents = max_agents if max_agents is not None else max_entries# Keyed by id alone: controller and agent ids are unique across# tenants, so a signal naming one finds its entry without a scan.- self._controllers: OrderedDict[str, _Entry[ControllerPrincipal]] = OrderedDict()- self._agents: OrderedDict[str, _Entry[Agent]] = OrderedDict()- # Bumped by every invalidation. A reader takes a ticket before going- # to the database and hands it back with what it read; a read that- # straddled an invalidation is not stored.- self._generation = 0- self._bus: SignalBus | None = None+ self._controllers: OrderedDict[str, Entry[ControllerPrincipal]] = OrderedDict()+ self._agents: OrderedDict[str, Entry[Agent]] = OrderedDict()def follow(self, bus: SignalBus) -> None:"""Keep entries while `bus` listens, and drop the ones its signalsname."""- self._bus = bus+ self.listen_on(bus)bus.handle(AGENT_CHANGED_SIGNAL, self._on_agent_changed)bus.handle(CONTROLLER_AUTH_CHANGED_SIGNAL, self._on_controller_changed)- @property- def enabled(self) -> bool:- return self._ttl > 0-- def ticket(self) -> ReadTicket:- return ReadTicket(generation=self._generation, listening=self._listening())-def controller(self, tenant_id: str, controller_id: str) -> ControllerPrincipal | None:- return self._get(self._controllers, tenant_id, controller_id)+ return self.get(self._controllers, tenant_id, controller_id)def put_controller(self, principal: ControllerPrincipal, ticket: ReadTicket) -> None:- if not self._fresh(ticket):+ if not self.fresh(ticket):return- self._put(+ self.put(self._controllers,self._max_controllers,principal.tenant_id,principal.controller_id,principal,- self._held_under(ticket),+ self.held_under(ticket),)def agent(self, tenant_id: str, agent_id: str) -> Agent | None:- return self._get(self._agents, tenant_id, agent_id)+ return self.get(self._agents, tenant_id, agent_id)def put_agents(self, tenant_id: str, agents: Iterable[Agent], ticket: ReadTicket) -> None:- if not self._fresh(ticket):+ if not self.fresh(ticket):return- held_under = self._held_under(ticket)+ held_under = self.held_under(ticket)for agent in agents:- self._put(+ self.put(self._agents, self._max_agents, tenant_id, agent.id, agent, held_under)def invalidate_controller(self, controller_id: str) -> None:- self._generation += 1+ self.invalidated()self._controllers.pop(controller_id, None)def invalidate_agent(self, agent_id: str) -> None:- self._generation += 1+ self.invalidated()self._agents.pop(agent_id, None)def clear(self) -> None:- self._generation += 1+ self.invalidated()self._controllers.clear()self._agents.clear()@@ -178,54 +134,3 @@ class ControllerAuthCache:def _on_controller_changed(self, signal: dict[str, Any]) -> None:self.invalidate_controller(signal["controller_id"])-- def _listening(self) -> int | None:- bus = self._bus- if bus is None or not bus.connected.is_set():- return None- return bus.listens-- def _fresh(self, ticket: ReadTicket) -> bool:- """Whether what the ticket's read found may be stored: nothing it- could have read was invalidated while it was in flight."""- return self.enabled and ticket.generation == self._generation-- def _held_under(self, ticket: ReadTicket) -> int | None:- """The listening connection to keep the read's entries under, if the- same one listened through the whole read; None keeps them for the TTL- only."""- listening = self._listening()- return listening if ticket.listening == listening else None-- def _get[V](- self, entries: OrderedDict[str, _Entry[V]], tenant_id: str, key: str- ) -> V | None:- entry = entries.get(key)- if entry is None or entry.tenant_id != tenant_id:- return None- if entry.expires_at <= time.monotonic() and (- entry.held_under is None or entry.held_under != self._listening()- ):- del entries[key]- return None- entries.move_to_end(key)- return entry.value-- def _put[V](- self,- entries: OrderedDict[str, _Entry[V]],- bound: int,- tenant_id: str,- key: str,- value: V,- held_under: int | None,- ) -> None:- entries[key] = _Entry(- tenant_id=tenant_id,- value=value,- expires_at=time.monotonic() + self._ttl,- held_under=held_under,- )- entries.move_to_end(key)- while len(entries) > bound:- entries.popitem(last=False)diff --git a/core/switch_core/bridges/agent/dependencies.py b/core/switch_core/bridges/agent/dependencies.pyindex 20fe20cf3..b31a3c540 100644--- a/core/switch_core/bridges/agent/dependencies.py+++ b/core/switch_core/bridges/agent/dependencies.py@@ -9,6 +9,7 @@ from switch_core.bridges.agent.api_key_cache import ApiKeyCachefrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.protocol.event_buffer import EventBuffer+from switch_core.bridges.agent.room_access_cache import RoomAccessCachefrom switch_core.bridges.collaboration.lifecycle_service import (CollaborationBridgeLifecycleService,)@@ -54,6 +55,7 @@ def init_dependencies(config: Any,approval_outcomes: ApprovalOutcomes,trust_client: TrustClient,+ room_access: RoomAccessCache | None = None,telemetry: TelemetryService | None = None,) -> None:_state["agent_store"] = agent_store@@ -93,6 +95,7 @@ def init_dependencies(config=config,approval_outcomes=approval_outcomes,trust_client=trust_client,+ room_access=room_access,telemetry=telemetry,)diff --git a/core/switch_core/bridges/agent/held_rows.py b/core/switch_core/bridges/agent/held_rows.pynew file mode 100644index 000000000..9f59f4e72--- /dev/null+++ b/core/switch_core/bridges/agent/held_rows.py@@ -0,0 +1,142 @@+"""Rows a process keeps for as long as a signal would tell it they changed.++A row read on every request, and written rarely, can be kept in memory if+every write to it is announced. Triggers announce them (`notify_ddl.py` and its+siblings) on the signal bus, which every process listens to; a process drops+what a signal names. But a signal is only heard while the bus listens: one+sent while the bus was reconnecting reaches nobody. So a row is kept past a+short TTL only while the connection the bus listened on when the row was read+is still the one listening, and a row read while the bus was not listening,+or across a reconnect, lasts the TTL and no longer.++`HeldRows` is that bookkeeping, shared by the caches built on it+(`ControllerAuthCache`, `RoomAccessCache`): the TTL, the hold, and the+generation that keeps a read which straddled an invalidation from being+stored. A reader takes a `ReadTicket` before going to the database and hands+it back with what it read.+"""++from __future__ import annotations++import time+from collections import OrderedDict+from dataclasses import dataclass+from typing import TYPE_CHECKING++from switch_core.bridges.agent.protocol.liveness import HEARTBEAT_TTL_SECONDS++if TYPE_CHECKING:+ from switch_core.signals import SignalBus+++@dataclass(frozen=True)+class ReadTicket:+ """Taken before a read and handed back with what it read, so the cache+ can tell whether anything it was told while the read was in flight makes+ the read stale."""++ generation: int+ # The signal bus's listening connection when the read began, or None if+ # it was not listening then.+ listening: int | None+++@dataclass+class Entry[V]:+ tenant_id: str+ value: V+ expires_at: float+ # The listening connection the entry was read under, while it is the one+ # listening, keeps the entry past `expires_at`. None for a read made while+ # the bus did not listen.+ held_under: int | None+++class HeldRows:+ """The TTL, the hold and the generation of a cache of rows.++ A `ttl_seconds` of 0 disables it. The TTL is refused at or above the+ heartbeat TTL: an entry outliving it would outlive a revocation that the+ connections it guards are held to.+ """++ def __init__(self, *, ttl_seconds: float) -> None:+ if ttl_seconds < 0:+ raise ValueError(f"ttl_seconds must not be negative, got {ttl_seconds!r}")+ if ttl_seconds >= HEARTBEAT_TTL_SECONDS:+ raise ValueError(+ f"ttl_seconds must stay below the agent heartbeat TTL of "+ f"{HEARTBEAT_TTL_SECONDS}s, got {ttl_seconds!r}"+ )+ self._ttl = ttl_seconds+ # Bumped by every invalidation. A read that straddled one is not+ # stored.+ self._generation = 0+ self._bus: SignalBus | None = None++ @property+ def enabled(self) -> bool:+ return self._ttl > 0++ def listen_on(self, bus: SignalBus) -> None:+ """Keep entries read while `bus` listens for as long as it does; the+ caller registers the handlers that drop what its signals name."""+ self._bus = bus++ def ticket(self) -> ReadTicket:+ return ReadTicket(generation=self._generation, listening=self._listening())++ def invalidated(self) -> None:+ """Something was dropped: no read in flight may store what it read."""+ self._generation += 1++ def _listening(self) -> int | None:+ bus = self._bus+ if bus is None or not bus.connected.is_set():+ return None+ return bus.listens++ def fresh(self, ticket: ReadTicket) -> bool:+ """Whether what the ticket's read found may be stored: nothing it+ could have read was invalidated while it was in flight."""+ return self.enabled and ticket.generation == self._generation++ def held_under(self, ticket: ReadTicket) -> int | None:+ """The listening connection to keep the read's entries under, if the+ same one listened through the whole read; None keeps them for the TTL+ only."""+ listening = self._listening()+ return listening if ticket.listening == listening else None++ def get[K, V](+ self, entries: OrderedDict[K, Entry[V]], tenant_id: str, key: K+ ) -> V | None:+ entry = entries.get(key)+ if entry is None or entry.tenant_id != tenant_id:+ return None+ if entry.expires_at <= time.monotonic() and (+ entry.held_under is None or entry.held_under != self._listening()+ ):+ del entries[key]+ return None+ entries.move_to_end(key)+ return entry.value++ def put[K, V](+ self,+ entries: OrderedDict[K, Entry[V]],+ bound: int,+ tenant_id: str,+ key: K,+ value: V,+ held_under: int | None,+ ) -> None:+ entries[key] = Entry(+ tenant_id=tenant_id,+ value=value,+ expires_at=time.monotonic() + self._ttl,+ held_under=held_under,+ )+ entries.move_to_end(key)+ while len(entries) > bound:+ entries.popitem(last=False)diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 4ca938067..3623d3c92 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -66,6 +66,7 @@ from switch_core.bridges.agent.protocol.types import (ToolCallReport,ToolSpec,)+from switch_core.bridges.agent.room_access_cache import RoomAccessCachefrom switch_core.bridges.collaboration.adapter import (AgentIdentity,AgentIdentityConflict,@@ -336,6 +337,9 @@ class AgentCore:# Same reason: a minimal test instance gets a client that allows everything# rather than one that needs real config to construct.trust_client: TrustClient = NullTrustClient()+ # Same reason: a minimal test instance keeps nothing and reads every+ # check from the database. The server supplies the process's one cache.+ room_access: RoomAccessCache = RoomAccessCache(ttl_seconds=0, max_entries=1)# Told (tenant_id, agent_id) just before an agent is deleted, while its row# still exists. Set by the process wiring when something outside Core keeps# state about agents that a cascade alone would drop without telling anyone.@@ -380,9 +384,12 @@ class AgentCore:config: SwitchConfig,approval_outcomes: ApprovalOutcomes,trust_client: TrustClient,+ room_access: RoomAccessCache | None = None,telemetry: TelemetryService | None = None,) -> None:self.telemetry = telemetry+ if room_access is not None:+ self.room_access = room_accessself.trust_client = trust_clientself.approval_outcomes = approval_outcomes# Pairs session start with session end. Held here because the handler@@ -1450,6 +1457,11 @@ class AgentCore: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."""+ tenant_id = current_tenant_id()+ if tenant_id is not None:+ held = self.room_access.member(tenant_id, agent_id, room_id)+ if held is not None:+ return heldasync with self.session_factory() as session:return await self._room_member_in(session, agent_id, room_id)@@ -1457,23 +1469,41 @@ class AgentCore:"""`require_room_member`, and raise `BudgetExceeded` if the agent hasreached a budget covering it. One session for both, so a post stillcosts one pool checkout."""+ tenant_id = require_tenant_id()+ access = self.room_access+ room = access.member(tenant_id, agent_id, room_id)+ if room is not None and access.unbudgeted(tenant_id, agent_id):+ return roomasync 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+ if room is None:+ room = await self._room_member_in(session, agent_id, room_id)+ ticket = access.ticket()+ covered = await self.budget_guard.require_within(+ session, tenant_id=tenant_id, agent_id=agent_id)+ if not covered:+ access.put_unbudgeted(tenant_id, agent_id, ticket)return roomasync def _room_member_in(self, session: AsyncSession, agent_id: str, room_id: str) -> RoomDescriptor:+ tenant_id = current_tenant_id()+ if tenant_id is not None:+ held = self.room_access.member(tenant_id, agent_id, room_id)+ if held is not None:+ return held+ ticket = self.room_access.ticket()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 = foundif not is_member:raise PermissionError("Agent is not a member of this room")- return _describe_room(room)+ described = _describe_room(room)+ if tenant_id is not None:+ self.room_access.put_member(tenant_id, agent_id, described, ticket)+ return describedasync def list_rooms(self, agent_id: str, *, include_archived: bool = Falsediff --git a/core/switch_core/bridges/agent/room_access_cache.py b/core/switch_core/bridges/agent/room_access_cache.pynew file mode 100644index 000000000..a0c6ea7af--- /dev/null+++ b/core/switch_core/bridges/agent/room_access_cache.py@@ -0,0 +1,129 @@+from __future__ import annotations++from collections import OrderedDict+from typing import TYPE_CHECKING, Any++from switch_core.bridges.agent.held_rows import Entry, HeldRows, ReadTicket+from switch_core.db.room_access_notify_ddl import (+ BUDGETS_CHANGED_SIGNAL,+ ROOM_AGENT_CHANGED_SIGNAL,+ ROOM_CHANGED_SIGNAL,+)++if TYPE_CHECKING:+ from switch_core.bridges.agent.protocol.types import RoomDescriptor+ from switch_core.signals import SignalBus+++class RoomAccessCache(HeldRows):+ """What a post, and a context read, check before anything else.++ Every post checks that its agent is in the room, which reads the room's+ row and the agent's `room_agents` row, and that no budget covering the+ agent has run out; a controller relaying an operation checks the+ membership once more, for the room it names. These rows are read on every+ post and written rarely, so each process keeps:++ - **an agent's membership of a room**, with the room's descriptor, while+ the agent is a member;+ - **that no budget covers an agent**, which is the case unless its tenant+ has set one.++ For how long, `HeldRows` says: while the signal connection listens, until+ a trigger's signal names them (`db/room_access_notify_ddl.py`), and for+ the TTL otherwise. A refusal is never kept, so an agent that is not a+ member, a missing room, or a budget that covers the agent always reaches+ the database; and a read that straddled an invalidation stores nothing.+ """++ def __init__(self, *, ttl_seconds: float, max_entries: int) -> None:+ super().__init__(ttl_seconds=ttl_seconds)+ if max_entries < 1:+ raise ValueError(f"max_entries must be at least 1, got {max_entries!r}")+ self._max_entries = max_entries+ self._members: OrderedDict[tuple[str, str], Entry[RoomDescriptor]] = (+ OrderedDict()+ )+ self._unbudgeted: OrderedDict[str, Entry[bool]] = OrderedDict()++ def follow(self, bus: SignalBus) -> None:+ """Keep entries while `bus` listens, and drop the ones its signals+ name."""+ self.listen_on(bus)+ bus.handle(ROOM_AGENT_CHANGED_SIGNAL, self._on_room_agent_changed)+ bus.handle(ROOM_CHANGED_SIGNAL, self._on_room_changed)+ bus.handle(BUDGETS_CHANGED_SIGNAL, self._on_budgets_changed)++ def member(+ self, tenant_id: str, agent_id: str, room_id: str+ ) -> RoomDescriptor | None:+ """The room, if the agent is known to be one of its members."""+ return self.get(self._members, tenant_id, (agent_id, room_id))++ def put_member(+ self,+ tenant_id: str,+ agent_id: str,+ room: RoomDescriptor,+ ticket: ReadTicket,+ ) -> None:+ if not self.fresh(ticket):+ return+ self.put(+ self._members,+ self._max_entries,+ tenant_id,+ (agent_id, room.id),+ room,+ self.held_under(ticket),+ )++ def unbudgeted(self, tenant_id: str, agent_id: str) -> bool:+ """Whether no budget is known to cover the agent."""+ return self.get(self._unbudgeted, tenant_id, agent_id) is True++ def put_unbudgeted(self, tenant_id: str, agent_id: str, ticket: ReadTicket) -> None:+ if not self.fresh(ticket):+ return+ self.put(+ self._unbudgeted,+ self._max_entries,+ tenant_id,+ agent_id,+ True,+ self.held_under(ticket),+ )++ def invalidate_member(self, agent_id: str, room_id: str) -> None:+ self.invalidated()+ self._members.pop((agent_id, room_id), None)++ def invalidate_room(self, room_id: str) -> None:+ # A room's descriptor changes rarely (a rename, an archive), so its+ # members' entries are found by looking at all of them.+ self.invalidated()+ for key in [key for key in self._members if key[1] == room_id]:+ del self._members[key]++ def invalidate_budgets(self, tenant_id: str) -> None:+ self.invalidated()+ for key in [+ key+ for key, entry in self._unbudgeted.items()+ if entry.tenant_id == tenant_id+ ]:+ del self._unbudgeted[key]++ def clear(self) -> None:+ self.invalidated()+ self._members.clear()+ self._unbudgeted.clear()++ def _on_room_agent_changed(self, signal: dict[str, Any]) -> None:+ self.invalidate_member(signal["agent_id"], signal["room_id"])++ def _on_room_changed(self, signal: dict[str, Any]) -> None:+ self.invalidate_room(signal["room_id"])++ def _on_budgets_changed(self, signal: dict[str, Any]) -> None:+ self.invalidate_budgets(signal["tenant_id"])diff --git a/core/switch_core/budgets.py b/core/switch_core/budgets.pyindex c9739583a..14165f789 100644--- a/core/switch_core/budgets.py+++ b/core/switch_core/budgets.py@@ -60,16 +60,15 @@ class BudgetGuard:async def require_within(self, session: AsyncSession, *, tenant_id: str, agent_id: str- ) -> None:+ ) -> bool:"""Raise `BudgetExceeded` if the agent has reached any budget coveringit. 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- ]+ that is how long the agent is actually stopped for. Returns whether+ any budget covers the agent."""+ standings = await self._store.standings(+ session, tenant_id=tenant_id, agent_id=agent_id+ )+ exhausted = [standing for standing in standings if standing.exhausted]if exhausted:raise BudgetExceeded(max(exhausted, key=lambda s: s.resets_at))+ return bool(standings)diff --git a/core/switch_core/config.py b/core/switch_core/config.pyindex e0ede2d17..377e976a4 100644--- a/core/switch_core/config.py+++ b/core/switch_core/config.py@@ -791,6 +791,11 @@ class SwitchConfig(BaseSettings):# evicted past it. Every process sees requests for every controller's# agents, so it needs room for all the agents controllers run.controller_auth_cache_max_agents: int = Field(default=20_000, ge=1)+ # Bound on what each process keeps of the checks a post makes first (an+ # agent's membership of a room, and that no budget covers it), the oldest+ # evicted past it. Kept as the controller-token cache keeps its rows, for+ # `AGENT_AUTH_CACHE_TTL_SECONDS` or while the signal connection listens.+ room_access_cache_max_entries: int = Field(default=20_000, ge=1)# AGENT_MANAGEMENT_ENABLED, replaced by the `agent_management` feature flag.# Read only to refuse a deployment that still turns it on, which woulddiff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 5cb372cb9..f7f21fa54 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -53,6 +53,17 @@ from switch_core.db.notify_ddl import (DROP_NOTIFY_TRIGGER,)from switch_core.db.rls_ddl import attach_row_level_security+from switch_core.db.room_access_notify_ddl import (+ CREATE_BUDGETS_NOTIFY_FUNCTION,+ CREATE_BUDGETS_NOTIFY_TRIGGER,+ CREATE_ROOM_AGENT_NOTIFY_FUNCTION,+ CREATE_ROOM_AGENT_NOTIFY_TRIGGER,+ CREATE_ROOM_NOTIFY_FUNCTION,+ CREATE_ROOM_NOTIFY_TRIGGER,+ DROP_BUDGETS_NOTIFY_TRIGGER,+ DROP_ROOM_AGENT_NOTIFY_TRIGGER,+ DROP_ROOM_NOTIFY_TRIGGER,+)from switch_core.db.session_activity_notify_ddl import (CREATE_ACTIVITY_TRIGGER,CREATE_APPROVAL_INSERT_TRIGGER,@@ -4506,3 +4517,30 @@ attach_row_level_security(Base.metadata)# `create_all` built without them is not the schema the server runs against.# After the tables, not before — see `db/tenant_lookup.py`.attach_tenant_lookups(Base.metadata)+++# The triggers that signal every process when an agent joins or leaves a room,+# a room's descriptor changes or a tenant's budgets do, so each process drops+# what it kept of them for the checks every post makes. As for the triggers+# above, `create_all` builds them for the tests and real databases get them+# from a migration. The SQL lives in `db/room_access_notify_ddl.py`.+for _table, _ddls, _drop in (+ (+ room_agents,+ (CREATE_ROOM_AGENT_NOTIFY_FUNCTION, CREATE_ROOM_AGENT_NOTIFY_TRIGGER),+ DROP_ROOM_AGENT_NOTIFY_TRIGGER,+ ),+ (+ Room.__table__,+ (CREATE_ROOM_NOTIFY_FUNCTION, CREATE_ROOM_NOTIFY_TRIGGER),+ DROP_ROOM_NOTIFY_TRIGGER,+ ),+ (+ UsageBudget.__table__,+ (CREATE_BUDGETS_NOTIFY_FUNCTION, CREATE_BUDGETS_NOTIFY_TRIGGER),+ DROP_BUDGETS_NOTIFY_TRIGGER,+ ),+):+ for _ddl in _ddls:+ event.listen(_table, "after_create", DDL(_ddl).execute_if(dialect="postgresql"))+ event.listen(_table, "before_drop", DDL(_drop).execute_if(dialect="postgresql"))diff --git a/core/switch_core/db/room_access_notify_ddl.py b/core/switch_core/db/room_access_notify_ddl.pynew file mode 100644index 000000000..96fb7fcea--- /dev/null+++ b/core/switch_core/db/room_access_notify_ddl.py@@ -0,0 +1,158 @@+"""The triggers that announce changes to what a post or a context read checks+first, as signals.++Every post an agent makes checks that the agent is in the room, reading the+room's row and the agent's `room_agents` row, and that no budget covering the+agent has run out. A controller relaying the post checks the membership once+more, for the room it names. Each process keeps the rows those checks read+(`RoomAccessCache`) for as long as its signal connection listens and no signal+says they changed. Memberships are written from several places (a join, an+invitation, room provisioning, a room or agent deleted with its rows), so, as+`membership_notify_ddl.py` argues for `client_rooms`, a trigger is the one+place none of them can skip.++`room_agent.changed` names the tenant, the room and the agent, for a+membership added or removed. `room.changed` names the tenant and the room, when+a column the room's descriptor carries changes and when the room is deleted;+the room's other columns send nothing. `budgets.changed` names the tenant, for+any change to its budgets. None carries a sender process, so every process+handles them, the writer's included, and `NOTIFY` is delivered on commit.++The migration that installs these carries its own copy, frozen as it was+written; this copy is what `create_all` builds for the tests.+"""++from __future__ import annotations++from switch_core.signals import SIGNAL_CHANNEL++ROOM_AGENT_CHANGED_SIGNAL = "room_agent.changed"+ROOM_CHANGED_SIGNAL = "room.changed"+BUDGETS_CHANGED_SIGNAL = "budgets.changed"++ROOM_AGENT_NOTIFY_FUNCTION_NAME = "switch_notify_room_agent_changed"+ROOM_AGENT_NOTIFY_TRIGGER_NAME = "room_agents_notify_changed"+ROOM_NOTIFY_FUNCTION_NAME = "switch_notify_room_changed"+ROOM_NOTIFY_TRIGGER_NAME = "rooms_notify_changed"+BUDGETS_NOTIFY_FUNCTION_NAME = "switch_notify_budgets_changed"+BUDGETS_NOTIFY_TRIGGER_NAME = "usage_budgets_notify_changed"++CREATE_ROOM_AGENT_NOTIFY_FUNCTION = f"""+CREATE OR REPLACE FUNCTION {ROOM_AGENT_NOTIFY_FUNCTION_NAME}() RETURNS trigger AS $$+DECLARE+ changed room_agents;+BEGIN+ IF TG_OP = 'INSERT' THEN+ changed := NEW;+ ELSE+ changed := OLD;+ END IF;+ PERFORM pg_notify(+ '{SIGNAL_CHANNEL}',+ json_build_object(+ 'kind', '{ROOM_AGENT_CHANGED_SIGNAL}',+ 'tenant_id', changed.tenant_id,+ 'room_id', changed.room_id,+ 'agent_id', changed.agent_id+ )::text+ );+ IF TG_OP = 'UPDATE' THEN+ PERFORM pg_notify(+ '{SIGNAL_CHANNEL}',+ json_build_object(+ 'kind', '{ROOM_AGENT_CHANGED_SIGNAL}',+ 'tenant_id', NEW.tenant_id,+ 'room_id', NEW.room_id,+ 'agent_id', NEW.agent_id+ )::text+ );+ END IF;+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_ROOM_AGENT_NOTIFY_TRIGGER = f"""+CREATE TRIGGER {ROOM_AGENT_NOTIFY_TRIGGER_NAME}+ AFTER INSERT OR UPDATE OF room_id, agent_id OR DELETE ON room_agents+ FOR EACH ROW EXECUTE FUNCTION {ROOM_AGENT_NOTIFY_FUNCTION_NAME}()+"""++CREATE_ROOM_NOTIFY_FUNCTION = f"""+CREATE OR REPLACE FUNCTION {ROOM_NOTIFY_FUNCTION_NAME}() RETURNS trigger AS $$+DECLARE+ changed rooms;+BEGIN+ IF TG_OP = 'DELETE' THEN+ changed := OLD;+ ELSIF NEW.matrix_room_id IS NOT DISTINCT FROM OLD.matrix_room_id+ AND NEW.name IS NOT DISTINCT FROM OLD.name+ AND NEW.description IS NOT DISTINCT FROM OLD.description+ AND NEW.bridge_id IS NOT DISTINCT FROM OLD.bridge_id+ AND NEW.archived_at IS NOT DISTINCT FROM OLD.archived_at THEN+ RETURN NULL;+ ELSE+ changed := NEW;+ END IF;+ PERFORM pg_notify(+ '{SIGNAL_CHANNEL}',+ json_build_object(+ 'kind', '{ROOM_CHANGED_SIGNAL}',+ 'tenant_id', changed.tenant_id,+ 'room_id', changed.id+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_ROOM_NOTIFY_TRIGGER = f"""+CREATE TRIGGER {ROOM_NOTIFY_TRIGGER_NAME}+ AFTER UPDATE OF matrix_room_id, name, description, bridge_id, archived_at+ OR DELETE ON rooms+ FOR EACH ROW EXECUTE FUNCTION {ROOM_NOTIFY_FUNCTION_NAME}()+"""++CREATE_BUDGETS_NOTIFY_FUNCTION = f"""+CREATE OR REPLACE FUNCTION {BUDGETS_NOTIFY_FUNCTION_NAME}() RETURNS trigger AS $$+DECLARE+ changed usage_budgets;+BEGIN+ IF TG_OP = 'DELETE' THEN+ changed := OLD;+ ELSE+ changed := NEW;+ END IF;+ PERFORM pg_notify(+ '{SIGNAL_CHANNEL}',+ json_build_object(+ 'kind', '{BUDGETS_CHANGED_SIGNAL}',+ 'tenant_id', changed.tenant_id+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_BUDGETS_NOTIFY_TRIGGER = f"""+CREATE TRIGGER {BUDGETS_NOTIFY_TRIGGER_NAME}+ AFTER INSERT OR UPDATE OR DELETE ON usage_budgets+ FOR EACH ROW EXECUTE FUNCTION {BUDGETS_NOTIFY_FUNCTION_NAME}()+"""++DROP_ROOM_AGENT_NOTIFY_TRIGGER = (+ f"DROP TRIGGER IF EXISTS {ROOM_AGENT_NOTIFY_TRIGGER_NAME} ON room_agents"+)+DROP_ROOM_AGENT_NOTIFY_FUNCTION = (+ f"DROP FUNCTION IF EXISTS {ROOM_AGENT_NOTIFY_FUNCTION_NAME}()"+)+DROP_ROOM_NOTIFY_TRIGGER = f"DROP TRIGGER IF EXISTS {ROOM_NOTIFY_TRIGGER_NAME} ON rooms"+DROP_ROOM_NOTIFY_FUNCTION = f"DROP FUNCTION IF EXISTS {ROOM_NOTIFY_FUNCTION_NAME}()"+DROP_BUDGETS_NOTIFY_TRIGGER = (+ f"DROP TRIGGER IF EXISTS {BUDGETS_NOTIFY_TRIGGER_NAME} ON usage_budgets"+)+DROP_BUDGETS_NOTIFY_FUNCTION = (+ f"DROP FUNCTION IF EXISTS {BUDGETS_NOTIFY_FUNCTION_NAME}()"+)diff --git a/core/switch_core/main.py b/core/switch_core/main.pyindex a1025feea..756e55a24 100644--- a/core/switch_core/main.py+++ b/core/switch_core/main.py@@ -49,6 +49,7 @@ from switch_core.bridges.agent.registration_bootstrap import (RETIRED_KEY_TYPE,ensure_bootstrap_owner,)+from switch_core.bridges.agent.room_access_cache import RoomAccessCachefrom switch_core.bridges.collaboration.adapter import PlatformAdapterfrom switch_core.bridges.collaboration.bridge_signals import BridgeSignalsfrom switch_core.bridges.collaboration.discord.adapter import (@@ -1034,6 +1035,12 @@ async def run(config: SwitchConfig, process_id: str) -> None:)# ── FastAPI apps ─────────────────────────────────────────────────────────+ # What every post checks first, kept until a signal says it changed.+ room_access = RoomAccessCache(+ ttl_seconds=config.agent_auth_cache_ttl_seconds,+ max_entries=config.room_access_cache_max_entries,+ )+ room_access.follow(signal_bus)agent_bridge_app, protocol = create_agent_bridge_app(agent_store=agent_store,agent_session_store=agent_session_store,@@ -1053,6 +1060,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:),controller_auth=management.authenticator if management is not None else None,connections=connections,+ room_access=room_access,telemetry=telemetry,trust_client=trust_client,gateway_ui=(diff --git a/core/switch_core/migrations/versions/4103210581d6_room_access_notify.py b/core/switch_core/migrations/versions/4103210581d6_room_access_notify.pynew file mode 100644index 000000000..588a2875b--- /dev/null+++ b/core/switch_core/migrations/versions/4103210581d6_room_access_notify.py@@ -0,0 +1,153 @@+"""room_access_notify: signal every switch-core process when an agent joins or+leaves a room, a room's descriptor changes, or a tenant's budgets do++Every process keeps what a post checks first: that the agent is in the room,+with the room's descriptor, and whether any budget covers the agent. These+triggers send `room_agent.changed` when a `room_agents` row is added or+removed, `room.changed` when a column of a room's descriptor changes or the+room is deleted, and `budgets.changed` for any change to a tenant's budgets,+so every process drops what it kept of them.++Expand only: a process from before this revision has no handler for these+signals and skips them, as it does any kind it does not know.++Revision ID: 4103210581d6+Revises: bad5099ef32b+Create Date: 2026-11-01 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "4103210581d6"+down_revision: str | None = "bad5099ef32b"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True++# Copies of the DDL in `db/room_access_notify_ddl.py`, written out here so this+# migration keeps creating the same objects if that module changes.+CREATE_ROOM_AGENT_NOTIFY_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_notify_room_agent_changed() RETURNS trigger AS $$+DECLARE+ changed room_agents;+BEGIN+ IF TG_OP = 'INSERT' THEN+ changed := NEW;+ ELSE+ changed := OLD;+ END IF;+ PERFORM pg_notify(+ 'switch_signal',+ json_build_object(+ 'kind', 'room_agent.changed',+ 'tenant_id', changed.tenant_id,+ 'room_id', changed.room_id,+ 'agent_id', changed.agent_id+ )::text+ );+ IF TG_OP = 'UPDATE' THEN+ PERFORM pg_notify(+ 'switch_signal',+ json_build_object(+ 'kind', 'room_agent.changed',+ 'tenant_id', NEW.tenant_id,+ 'room_id', NEW.room_id,+ 'agent_id', NEW.agent_id+ )::text+ );+ END IF;+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_ROOM_AGENT_NOTIFY_TRIGGER = """+CREATE TRIGGER room_agents_notify_changed+ AFTER INSERT OR UPDATE OF room_id, agent_id OR DELETE ON room_agents+ FOR EACH ROW EXECUTE FUNCTION switch_notify_room_agent_changed()+"""++CREATE_ROOM_NOTIFY_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_notify_room_changed() RETURNS trigger AS $$+DECLARE+ changed rooms;+BEGIN+ IF TG_OP = 'DELETE' THEN+ changed := OLD;+ ELSIF NEW.matrix_room_id IS NOT DISTINCT FROM OLD.matrix_room_id+ AND NEW.name IS NOT DISTINCT FROM OLD.name+ AND NEW.description IS NOT DISTINCT FROM OLD.description+ AND NEW.bridge_id IS NOT DISTINCT FROM OLD.bridge_id+ AND NEW.archived_at IS NOT DISTINCT FROM OLD.archived_at THEN+ RETURN NULL;+ ELSE+ changed := NEW;+ END IF;+ PERFORM pg_notify(+ 'switch_signal',+ json_build_object(+ 'kind', 'room.changed',+ 'tenant_id', changed.tenant_id,+ 'room_id', changed.id+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_ROOM_NOTIFY_TRIGGER = """+CREATE TRIGGER rooms_notify_changed+ AFTER UPDATE OF matrix_room_id, name, description, bridge_id, archived_at+ OR DELETE ON rooms+ FOR EACH ROW EXECUTE FUNCTION switch_notify_room_changed()+"""++CREATE_BUDGETS_NOTIFY_FUNCTION = """+CREATE OR REPLACE FUNCTION switch_notify_budgets_changed() RETURNS trigger AS $$+DECLARE+ changed usage_budgets;+BEGIN+ IF TG_OP = 'DELETE' THEN+ changed := OLD;+ ELSE+ changed := NEW;+ END IF;+ PERFORM pg_notify(+ 'switch_signal',+ json_build_object(+ 'kind', 'budgets.changed',+ 'tenant_id', changed.tenant_id+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++CREATE_BUDGETS_NOTIFY_TRIGGER = """+CREATE TRIGGER usage_budgets_notify_changed+ AFTER INSERT OR UPDATE OR DELETE ON usage_budgets+ FOR EACH ROW EXECUTE FUNCTION switch_notify_budgets_changed()+"""+++def upgrade() -> None:+ op.execute(CREATE_ROOM_AGENT_NOTIFY_FUNCTION)+ op.execute(CREATE_ROOM_AGENT_NOTIFY_TRIGGER)+ op.execute(CREATE_ROOM_NOTIFY_FUNCTION)+ op.execute(CREATE_ROOM_NOTIFY_TRIGGER)+ op.execute(CREATE_BUDGETS_NOTIFY_FUNCTION)+ op.execute(CREATE_BUDGETS_NOTIFY_TRIGGER)+++def downgrade() -> None:+ op.execute("DROP TRIGGER IF EXISTS usage_budgets_notify_changed ON usage_budgets")+ op.execute("DROP FUNCTION IF EXISTS switch_notify_budgets_changed()")+ op.execute("DROP TRIGGER IF EXISTS rooms_notify_changed ON rooms")+ op.execute("DROP FUNCTION IF EXISTS switch_notify_room_changed()")+ op.execute("DROP TRIGGER IF EXISTS room_agents_notify_changed ON room_agents")+ op.execute("DROP FUNCTION IF EXISTS switch_notify_room_agent_changed()")diff --git a/core/tests/switch_core/bridges/agent/test_controller_auth_cache.py b/core/tests/switch_core/bridges/agent/test_controller_auth_cache.pyindex cad8f18f8..4c9172002 100644--- a/core/tests/switch_core/bridges/agent/test_controller_auth_cache.py+++ b/core/tests/switch_core/bridges/agent/test_controller_auth_cache.py@@ -15,7 +15,7 @@ from typing import Anyimport pytest-from switch_core.bridges.agent import controller_auth_cache as module+from switch_core.bridges.agent import held_rows as modulefrom switch_core.bridges.agent.auth import ControllerPrincipalfrom switch_core.bridges.agent.controller_auth_cache import ControllerAuthCachefrom switch_core.bridges.agent.protocol.controller_presence import (diff --git a/core/tests/switch_core/bridges/agent/test_room_access_cache.py b/core/tests/switch_core/bridges/agent/test_room_access_cache.pynew file mode 100644index 000000000..08a51f180--- /dev/null+++ b/core/tests/switch_core/bridges/agent/test_room_access_cache.py@@ -0,0 +1,126 @@+"""What a post checks first, kept on its own: the hold and the TTL come from+`HeldRows` (`test_controller_auth_cache.py` pins them); these pin what the+signals drop, and what is never kept.++Against Postgres, with the triggers and a real signal bus, in+`tests/switch_core/management/test_room_access_cache.py`.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from switch_core.bridges.agent import held_rows+from switch_core.bridges.agent.protocol.types import RoomDescriptor+from switch_core.bridges.agent.room_access_cache import RoomAccessCache+from switch_core.db.room_access_notify_ddl import (+ BUDGETS_CHANGED_SIGNAL,+ ROOM_AGENT_CHANGED_SIGNAL,+ ROOM_CHANGED_SIGNAL,+)+++class _Clock:+ def __init__(self) -> None:+ self.now = 1000.0++ def __call__(self) -> float:+ return self.now+++def clock(monkeypatch: pytest.MonkeyPatch) -> _Clock:+ fake = _Clock()+ monkeypatch.setattr(held_rows, "time", SimpleNamespace(monotonic=fake))+ return fake+++def _room(room_id: str = "r1") -> RoomDescriptor:+ return RoomDescriptor(+ id=room_id,+ name=room_id,+ description="",+ transport_room_id=f"!{room_id}",+ matrix_room_id=f"!{room_id}",+ )+++class _Bus:+ """What `follow` needs of the signal bus."""++ def __init__(self) -> None:+ self.handlers: dict[str, object] = {}+ self.connected = SimpleNamespace(is_set=lambda: False)+ self.listens = 0++ def handle(self, kind: str, handler: object) -> None:+ self.handlers[kind] = handler+++def test_a_membership_is_kept_for_its_tenant_until_the_ttl(clock: _Clock) -> None:+ cache = RoomAccessCache(ttl_seconds=5, max_entries=8)+ cache.put_member("t1", "a1", _room(), cache.ticket())++ assert cache.member("t1", "a1", "r1") == _room()+ assert cache.member("t2", "a1", "r1") is None+ assert cache.member("t1", "a2", "r1") is None+ clock.now += 5+ assert cache.member("t1", "a1", "r1") is None+++def test_the_signals_drop_what_they_name(clock: _Clock) -> None:+ cache = RoomAccessCache(ttl_seconds=5, max_entries=8)+ bus = _Bus()+ cache.follow(bus) # type: ignore[arg-type]+ for agent_id, room_id in (("a1", "r1"), ("a2", "r1"), ("a1", "r2")):+ cache.put_member("t1", agent_id, _room(room_id), cache.ticket())+ for agent_id in ("a1", "a2"):+ cache.put_unbudgeted("t1", agent_id, cache.ticket())+ cache.put_unbudgeted("t2", "a3", cache.ticket())++ bus.handlers[ROOM_AGENT_CHANGED_SIGNAL]( # type: ignore[operator]+ {"tenant_id": "t1", "room_id": "r2", "agent_id": "a1"}+ )+ assert cache.member("t1", "a1", "r2") is None+ assert cache.member("t1", "a1", "r1") is not None++ bus.handlers[ROOM_CHANGED_SIGNAL]({"tenant_id": "t1", "room_id": "r1"}) # type: ignore[operator]+ assert cache.member("t1", "a1", "r1") is None+ assert cache.member("t1", "a2", "r1") is None++ bus.handlers[BUDGETS_CHANGED_SIGNAL]({"tenant_id": "t1"}) # type: ignore[operator]+ assert not cache.unbudgeted("t1", "a1")+ assert not cache.unbudgeted("t1", "a2")+ assert cache.unbudgeted("t2", "a3")+++def test_a_read_that_straddled_a_signal_is_not_kept(clock: _Clock) -> None:+ cache = RoomAccessCache(ttl_seconds=5, max_entries=8)+ ticket = cache.ticket()+ cache.invalidate_member("a1", "r1")++ cache.put_member("t1", "a1", _room(), ticket)+ cache.put_unbudgeted("t1", "a1", ticket)++ assert cache.member("t1", "a1", "r1") is None+ assert not cache.unbudgeted("t1", "a1")+++def test_it_keeps_no_more_than_its_bound(clock: _Clock) -> None:+ cache = RoomAccessCache(ttl_seconds=5, max_entries=2)+ for room_id in ("r1", "r2", "r3"):+ cache.put_member("t1", "a1", _room(room_id), cache.ticket())++ assert cache.member("t1", "a1", "r1") is None+ assert cache.member("t1", "a1", "r3") is not None+++def test_a_ttl_of_zero_keeps_nothing(clock: _Clock) -> None:+ cache = RoomAccessCache(ttl_seconds=0, max_entries=8)+ cache.put_member("t1", "a1", _room(), cache.ticket())+ cache.put_unbudgeted("t1", "a1", cache.ticket())++ assert cache.member("t1", "a1", "r1") is None+ assert not cache.unbudgeted("t1", "a1")diff --git a/core/tests/switch_core/management/test_controller_auth_cache.py b/core/tests/switch_core/management/test_controller_auth_cache.pyindex f24feb409..80885744f 100644--- a/core/tests/switch_core/management/test_controller_auth_cache.py+++ b/core/tests/switch_core/management/test_controller_auth_cache.py@@ -25,7 +25,7 @@ from sqlalchemy.ext.asyncio import ()from sqlalchemy.pool import NullPool-from switch_core.bridges.agent import controller_auth_cache+from switch_core.bridges.agent import held_rowsfrom switch_core.bridges.agent.auth import BearerAuthMiddlewarefrom switch_core.db.auth_rows_notify_ddl import (AGENT_CHANGED_SIGNAL,@@ -326,7 +326,7 @@ async def test_while_the_bus_listens_a_hit_outlives_the_ttl(assert await act_as(mw, controller, agent_id) == (200, None)an_hour_on = time.monotonic() + 3600monkeypatch.setattr(- controller_auth_cache, "time", SimpleNamespace(monotonic=lambda: an_hour_on)+ held_rows, "time", SimpleNamespace(monotonic=lambda: an_hour_on))with counting(listening.session_factory) as reads:diff --git a/core/tests/switch_core/management/test_room_access_cache.py b/core/tests/switch_core/management/test_room_access_cache.pynew file mode 100644index 000000000..6c6cb47dc--- /dev/null+++ b/core/tests/switch_core/management/test_room_access_cache.py@@ -0,0 +1,196 @@+"""What a post checks first, kept until a signal says it changed: against+Postgres, with the triggers, and a real signal bus where a test needs one.++A second check of the same membership, or of a post by an agent no budget+covers, reaches no database; a membership removed, a room archived or a+budget set is heard by every process, which then reads again.+"""++from __future__ import annotations++import asyncio+from collections.abc import Callable++import pytest+from sqlalchemy import delete, func, insert, update+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.bridges.agent.room_access_cache import RoomAccessCache+from switch_core.db.models import TENANT_ZERO_ID, Room, UsageBudget, room_agents+from switch_core.db.session_scope import tenant_session+from tests.session_counting import CountingSessionFactory+from tests.switch_core.bridges.agent.protocol.test_pool_checkouts import (+ _seed,+ _service,+)+from tests.switch_core.management.harness import Harness+from tests.switch_core.management.test_controller_auth_cache import heard, listening++__all__ = ["listening"]+++def _kept(+ session_factory: async_sessionmaker[AsyncSession],+) -> tuple[AgentCore, RoomAccessCache, CountingSessionFactory]:+ counting = CountingSessionFactory(session_factory)+ service = _service(counting)+ service.room_access = RoomAccessCache(ttl_seconds=5, max_entries=64)+ return service, service.room_access, counting+++async def _budget(+ session_factory: async_sessionmaker[AsyncSession], agent_id: str | None+) -> None:+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ await session.execute(+ insert(UsageBudget).values(+ agent_id=agent_id,+ metric="messages",+ model="",+ amount_limit=5,+ period_hours=24,+ )+ )+ await session.commit()+++async def _until(condition: Callable[[], bool]) -> None:+ for _ in range(500):+ if condition():+ return+ await asyncio.sleep(0.01)+ raise AssertionError("never happened")+++async def test_a_second_check_reaches_no_database(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ service, cache, counting = _kept(session_factory)++ first = await service.require_room_poster(member_id, room_id)+ opened = counting.opened+ again = await service.require_room_poster(member_id, room_id)+ member = await service.require_room_member(member_id, room_id)++ assert opened == 1+ assert counting.opened == 1+ assert first == again == member+ assert cache.unbudgeted(TENANT_ZERO_ID, member_id)+++async def test_a_post_by_an_agent_a_budget_covers_is_checked_every_time(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ await _budget(session_factory, member_id)+ service, cache, counting = _kept(session_factory)++ for _ in range(2):+ await service.require_room_poster(member_id, room_id)++ assert counting.opened == 2+ assert cache.member(TENANT_ZERO_ID, member_id, room_id) is not None+ assert not cache.unbudgeted(TENANT_ZERO_ID, member_id)+++async def test_a_refusal_is_never_kept(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ room_id, _, outsider_id = await _seed(session_factory)+ service, cache, counting = _kept(session_factory)++ for _ in range(2):+ with pytest.raises(PermissionError):+ await service.require_room_member(outsider_id, room_id)++ assert counting.opened == 2+ assert cache.member(TENANT_ZERO_ID, outsider_id, room_id) is None++[email protected]("change", ["leave", "archive", "budget"])+async def test_a_change_made_where_nothing_announces_it_is_heard(+ listening: Harness, change: str+) -> None:+ """Made straight in the database, as an operator in psql would: the+ triggers tell every process."""+ room_id, member_id, _ = await _seed(listening.session_factory)+ service, cache, _ = _kept(listening.session_factory)+ cache.follow(listening.bus)+ # The seed's own signals arrive after it commits, and a check read while+ # one arrives is not kept, so the check is made until one is.+ for _ in range(100):+ await service.require_room_poster(member_id, room_id)+ if cache.member(TENANT_ZERO_ID, member_id, room_id) is not None:+ break+ await asyncio.sleep(0.02)+ assert cache.member(TENANT_ZERO_ID, member_id, room_id) is not None+ assert cache.unbudgeted(TENANT_ZERO_ID, member_id)++ if change == "budget":+ await _budget(listening.session_factory, None)+ await _until(lambda: not cache.unbudgeted(TENANT_ZERO_ID, member_id))+ return+ async with tenant_session(listening.session_factory, TENANT_ZERO_ID) as session:+ if change == "leave":+ await session.execute(+ delete(room_agents).where(+ room_agents.c.room_id == room_id,+ room_agents.c.agent_id == member_id,+ )+ )+ else:+ await session.execute(+ update(Room).where(Room.id == room_id).values(archived_at=func.now())+ )+ await session.commit()++ await _until(lambda: cache.member(TENANT_ZERO_ID, member_id, room_id) is None)+ if change == "leave":+ with pytest.raises(PermissionError):+ await service.require_room_poster(member_id, room_id)+ else:+ room = await service.require_room_member(member_id, room_id)+ assert room.archived+++async def test_the_triggers_send_what_a_check_depends_on(+ session_factory: async_sessionmaker[AsyncSession], postgres_url: str+) -> None:+ room_id, member_id, _ = await _seed(session_factory)+ # One transaction each: identical notifications sent in one transaction+ # are delivered once.+ changes = [+ # A column no check reads: nothing.+ update(Room).where(Room.id == room_id).values(instructions="be brief"),+ update(Room).where(Room.id == room_id).values(name="renamed"),+ delete(room_agents).where(room_agents.c.agent_id == member_id),+ insert(room_agents).values(room_id=room_id, agent_id=member_id),+ insert(UsageBudget).values(+ agent_id=member_id,+ metric="messages",+ model="",+ amount_limit=5,+ period_hours=1,+ ),+ ]++ async with heard(postgres_url) as signals:+ for change in changes:+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ await session.execute(change)+ await session.commit()++ room_agent = {+ "kind": "room_agent.changed",+ "tenant_id": TENANT_ZERO_ID,+ "room_id": room_id,+ "agent_id": member_id,+ }+ assert signals == [+ {"kind": "room.changed", "tenant_id": TENANT_ZERO_ID, "room_id": room_id},+ room_agent,+ room_agent,+ {"kind": "budgets.changed", "tenant_id": TENANT_ZERO_ID},+ ]