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
Wake Switch's own reader only for command rows, and read only those (CHOO-3667)
Abel Dantascadd0fa3f874
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5fd9c4fe4..ff3673263 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -159,6 +159,12 @@ version of their own to them without also giving them a release of their own.compares it only when someone signs in.#### Changed+- **Switch's own reader is woken only by commands.** The process that holds+ a workspace's admin client read every row of every room to find the+ `!command` rows it answers. A new row's announcement now names its type,+ and that reader is woken for command rows only and reads only those, from+ a partial index on them. Its warnings for tags nobody can answer are+ already posted by the process that writes the message.- **The heads-up for tagging an agent that isn't in the room comes from theprocess that wrote the message, and costs nothing when every name taggedis one of the room's agents.** The admin's consumer, which reads everydiff --git a/core/switch_core/clients/command_consumer.py b/core/switch_core/clients/command_consumer.pyindex 5560b5216..6cceed7a7 100644--- a/core/switch_core/clients/command_consumer.py+++ b/core/switch_core/clients/command_consumer.py@@ -23,7 +23,7 @@ from switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.room_role_store import RoomRoleStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.events import CommandEvent+from switch_core.events import COMMAND_EVENT_TYPE, CommandEventfrom switch_core.transport import RoomRefif TYPE_CHECKING:@@ -36,18 +36,22 @@ DELETE_CONFIRM_SECONDS = 120.0class CommandConsumer(Consumer[SystemActor]):- """Reads every room for Switch itself, and answers through its SystemActor.+ """Reads every room's commands for Switch itself, and answers through its+ SystemActor.Handles the room/info/alias `!` commands (the admin-owned set) andrenders their results as admin messages. The heads-up for a message thattags an agent not in the room, or a role nobody live-holds, is posted by- the router once the message commits (`clients/mention_warnings.py`).+ the router once the message commits (`clients/mention_warnings.py`), so+ the command rows are all this reads, and it is woken for nothing else.Every admin message carries the admin marker so it renders natively perbridge and never triggers another member (loop-safe). The system is not anagent — it holds no Agent row — so it reasons purely from the stores."""+ ROW_TYPES = frozenset({COMMAND_EVENT_TYPE})+def __init__(self,*,diff --git a/core/switch_core/clients/consumer.py b/core/switch_core/clients/consumer.pyindex 73d548961..4f58a9825 100644--- a/core/switch_core/clients/consumer.py+++ b/core/switch_core/clients/consumer.py@@ -50,6 +50,11 @@ SYNC_BACKOFF_CAP = 60.0class Consumer[ActorT: Actor[Any]]:+ # The types of row this consumer acts on, or None for every row. One that+ # names them is woken only for those and reads past the rest+ # (`MessageTransport.receive_forever`).+ ROW_TYPES: frozenset[str] | None = None+def __init__(self, *, actor: ActorT) -> None:self.actor = actor# Rooms this consumer has already announced its actor's arrival in.@@ -117,7 +122,9 @@ class Consumer[ActorT: Actor[Any]]:retries = 0while self._running:try:- await self._transport.receive_forever(progress)+ await self._transport.receive_forever(+ progress, row_types=self.ROW_TYPES+ )retries = 0except Exception:if not self._running:diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 70dff1e2c..413dc228b 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -2453,6 +2453,14 @@ class Message(TenantScoped, Base):# across every room. The index above leads on the room, so it cannot# serve that and each pass would scan the whole table.Index("ix_messages_tenant_sent_at", "tenant_id", "sent_at"),+ # The rows Switch's own reader acts on (`CommandConsumer.ROW_TYPES`),+ # so it reads just those however far behind its cursor is.+ Index(+ "ix_messages_room_commands",+ "room_id",+ "seq",+ postgresql_where=text("event_type = 'com.switch.command'"),+ ),Index("ix_messages_thread_root","room_id",diff --git a/core/switch_core/db/notify_ddl.py b/core/switch_core/db/notify_ddl.pyindex 04403d15a..773fc38c8 100644--- a/core/switch_core/db/notify_ddl.py+++ b/core/switch_core/db/notify_ddl.py@@ -4,7 +4,9 @@ Delivery is the table announcing its own inserts, and a listener reading therows back.**The notification is a hint, never the payload.** It carries a room, a-position and a row id, and a consumer reads the row itself. That is what makes+position, a row id and the row's type, and a consumer reads the row itself.+The type lets a reader that acts on some kinds of row only be woken for those+(`MessageListener.subscribe`). That is what makesa lost notification cost latency instead of data: a consumer that keeps aposition can always ask what it has not seen, and one that never hearsanything is behind rather than wrong. Putting the message in the payload would@@ -53,7 +55,8 @@ BEGINjson_build_object('room_id', NEW.room_id,'seq', NEW.seq,- 'id', NEW.id+ 'id', NEW.id,+ 'type', NEW.event_type)::text);RETURN NULL;diff --git a/core/switch_core/db/stores/message_store.py b/core/switch_core/db/stores/message_store.pyindex 31313d92f..f6e292d2a 100644--- a/core/switch_core/db/stores/message_store.py+++ b/core/switch_core/db/stores/message_store.py@@ -157,22 +157,34 @@ class MessageStore:)return int(result.scalar_one()) + 1- async def head_seq(self, session: AsyncSession, room_id: str) -> int:+ async def head_seq(+ self,+ session: AsyncSession,+ room_id: str,+ *,+ types: Collection[str] | None = None,+ ) -> int:"""The room's current position, or 0 when nothing has been sent.What a subscriber starts from when it wants everything after nowrather than everything. Reconstructed history is numbered below zero,so an empty live log answers 0 whatever has been backfilled into it.+ With `types`, the position of the last row of those types."""- result = await session.execute(- select(func.coalesce(func.max(Message.seq), 0)).where(- Message.room_id == room_id- )+ query = select(func.coalesce(func.max(Message.seq), 0)).where(+ Message.room_id == room_id)+ if types is not None:+ query = query.where(Message.event_type.in_(list(types)))+ result = await session.execute(query)return max(int(result.scalar_one()), 0)async def head_seqs(- self, session: AsyncSession, room_ids: list[str]+ self,+ session: AsyncSession,+ room_ids: list[str],+ *,+ types: Collection[str] | None = None,) -> dict[str, int]:"""`head_seq` for many rooms in one query, 0 for a room with nothing sent.@@ -182,11 +194,12 @@ class MessageStore:"""if not room_ids:return {}- result = await session.execute(- select(Message.room_id, func.max(Message.seq))- .where(Message.room_id.in_(room_ids))- .group_by(Message.room_id)+ query = select(Message.room_id, func.max(Message.seq)).where(+ Message.room_id.in_(room_ids))+ if types is not None:+ query = query.where(Message.event_type.in_(list(types)))+ result = await session.execute(query.group_by(Message.room_id))heads = {room_id: max(int(seq or 0), 0) for room_id, seq in result.all()}return {room_id: heads.get(room_id, 0) for room_id in room_ids}@@ -222,7 +235,13 @@ class MessageStore:return result.scalar_one_or_none()async def list_for_room(- self, session: AsyncSession, room_id: str, *, after_seq: int, limit: int+ self,+ session: AsyncSession,+ room_id: str,+ *,+ after_seq: int,+ limit: int,+ types: Collection[str] | None = None,) -> list[Message]:"""Oldest first, from just after `after_seq`. Pass 0 to start.@@ -236,13 +255,16 @@ class MessageStore:the same cursor delivers nothing twice. Passing 0 also skipsreconstructed history, which is numbered below zero — a backfill isnot something to deliver.++ With `types`, only rows of those types, for a reader that acts on no+ others (`MessageListener.subscribe`)."""- result = await session.execute(- select(Message)- .where(Message.room_id == room_id, Message.seq > after_seq)- .order_by(Message.seq)- .limit(limit)+ query = select(Message).where(+ Message.room_id == room_id, Message.seq > after_seq)+ if types is not None:+ query = query.where(Message.event_type.in_(list(types)))+ result = await session.execute(query.order_by(Message.seq).limit(limit))return list(result.scalars().all())async def list_timeline(diff --git a/core/switch_core/events.py b/core/switch_core/events.pyindex ad0823109..5e4026488 100644--- a/core/switch_core/events.py+++ b/core/switch_core/events.py@@ -19,6 +19,9 @@ class SwitchEvent(BaseModel):# ── Command ───────────────────────────────────────────────────────────────────+# The `messages` row type a command is written as.+COMMAND_EVENT_TYPE = "com.switch.command"+class CommandEvent(SwitchEvent):command: strdiff --git a/core/switch_core/messages/notify.py b/core/switch_core/messages/notify.pyindex 44e0c4a87..567daaf0d 100644--- a/core/switch_core/messages/notify.py+++ b/core/switch_core/messages/notify.py@@ -37,7 +37,7 @@ import contextlibimport jsonimport loggingfrom collections.abc import Awaitable, Callable-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import TYPE_CHECKING, Anyfrom switch_core.db.notify_ddl import MESSAGE_CHANNEL@@ -81,6 +81,8 @@ class Announcement:room_id: strseq: intmessage_id: str+ # The row's type, or None from a database announcing without it.+ type: str | None = None@staticmethoddef parse(payload: str) -> Announcement | None:@@ -93,11 +95,15 @@ class Announcement:"""try:data = json.loads(payload)- return Announcement(+ announcement = Announcement(room_id=str(data["room_id"]),seq=int(data["seq"]),message_id=str(data["id"]),)+ row_type = data.get("type")+ if row_type is None:+ return announcement+ return replace(announcement, type=str(row_type))except (ValueError, TypeError, KeyError):logger.warning("Ignoring an unreadable message announcement: %r", payload[:200]@@ -112,10 +118,14 @@ class MessageListener:# A factory rather than an engine: reconnecting builds a fresh one, so# a connection that failed leaves nothing of itself behind.self._engine_factory = engine_factory- self._subscribers: dict[str, set[RoomWaker]] = {}+ # Room → each waker, with the row types it is woken for (None: all).+ self._subscribers: dict[str, dict[RoomWaker, frozenset[str] | None]] = {}# Room → the highest position announced but not yet handed on. This is# the coalescing buffer; see the module docstring.self._pending: dict[str, int] = {}+ # Room → the types of the rows behind that position, or None where one+ # of them is unknown (a wake-up of every subscriber).+ self._pending_types: dict[str, set[str] | None] = {}self._has_pending = asyncio.Event()self._tasks: list[asyncio.Task[None]] = []self._running = False@@ -125,7 +135,13 @@ class MessageListener:# ── Subscription ──────────────────────────────────────────────────────────- def subscribe(self, room_id: str, waker: RoomWaker) -> None:+ def subscribe(+ self,+ room_id: str,+ waker: RoomWaker,+ *,+ types: frozenset[str] | None = None,+ ) -> None:"""Ask to be woken when `room_id` advances.The waker is called with the room id and nothing else, because what it@@ -133,15 +149,20 @@ class MessageListener:once on subscribing too: a subscriber that starts mid-stream is behindby definition, and making it read immediately is cheaper than makingevery caller remember to.++ With `types`, it is woken only for rows of those types: a reader that+ acts on one kind of row is not made to read every row of a busy room+ to find it. A row whose type the announcement does not give wakes it+ as well, as does the wake-up on subscribing and on reconnecting."""- self._subscribers.setdefault(room_id, set()).add(waker)- self._mark(room_id, 0)+ self._subscribers.setdefault(room_id, {})[waker] = types+ self._mark(room_id, 0, None)def unsubscribe(self, room_id: str, waker: RoomWaker) -> None:wakers = self._subscribers.get(room_id)if wakers is None:return- wakers.discard(waker)+ wakers.pop(waker, None)if not wakers:del self._subscribers[room_id]@@ -230,17 +251,23 @@ class MessageListener:"""announcement = Announcement.parse(payload)if announcement is not None:- self._mark(announcement.room_id, announcement.seq)+ self._mark(announcement.room_id, announcement.seq, announcement.type)# ── Fan-out ───────────────────────────────────────────────────────────────- def _mark(self, room_id: str, seq: int) -> None:+ def _mark(self, room_id: str, seq: int, row_type: str | None = None) -> None:self._pending[room_id] = max(self._pending.get(room_id, 0), seq)+ types = self._pending_types.get(room_id, set())+ if types is None or row_type is None:+ self._pending_types[room_id] = None+ else:+ types.add(row_type)+ self._pending_types[room_id] = typesself._has_pending.set()def _wake_everything(self) -> None:for room_id in self._subscribers:- self._mark(room_id, 0)+ self._mark(room_id, 0, None)async def _fan_out_forever(self) -> None:while self._running:@@ -248,11 +275,14 @@ class MessageListener:self._has_pending.clear()rooms = list(self._pending)self._pending.clear()+ pending_types, self._pending_types = self._pending_types, {}for room_id in rooms:- await self._wake_room(room_id)+ await self._wake_room(room_id, pending_types.get(room_id))- async def _wake_room(self, room_id: str) -> None:- for waker in list(self._subscribers.get(room_id, ())):+ async def _wake_room(self, room_id: str, row_types: set[str] | None) -> None:+ for waker, types in list(self._subscribers.get(room_id, {}).items()):+ if types is not None and row_types is not None and not types & row_types:+ continuetry:await waker(room_id)except asyncio.CancelledError:diff --git a/core/switch_core/migrations/versions/f2a9c7d41e08_command_rows_for_the_admin_reader.py b/core/switch_core/migrations/versions/f2a9c7d41e08_command_rows_for_the_admin_reader.pynew file mode 100644index 000000000..8fd14fc02--- /dev/null+++ b/core/switch_core/migrations/versions/f2a9c7d41e08_command_rows_for_the_admin_reader.py@@ -0,0 +1,89 @@+"""Announce each message's type, and index the rooms' command rows++Switch's own reader (the admin client's `CommandConsumer`) acts on one kind of+row, the `com.switch.command` a person's `!command` is written as, and it was+woken for and read every row of every room to find them. The announcement of a+new row now names its type, so a reader can ask to be woken only for the types+it acts on, and a partial index on the command rows lets it read just those+however far behind its cursor is.++Not `CONCURRENTLY`, for the reason `b8f2d0c41e57` gives: revisions run in a+transaction. The index holds only command rows; a deployment whose `messages`+table is large can build it by hand first, and this becomes a no-op:++ CREATE INDEX CONCURRENTLY ix_messages_room_commands ON messages (room_id, seq)+ WHERE event_type = 'com.switch.command';++Expand only: a process from before this revision ignores the field it does not+read, and reads rooms as it did.++Revision ID: f2a9c7d41e08+Revises: b7e1d4c9a2f6+Create Date: 2026-10-31 00:00:00.000000+"""++from alembic import op++revision: str = "f2a9c7d41e08"+down_revision: str | None = "b7e1d4c9a2f6"+branch_labels = None+depends_on = None+expand_only: bool = True++_INDEX = "ix_messages_room_commands"+++def upgrade() -> None:+ op.execute(_WITH_TYPE)+ # `IF NOT EXISTS` so an index built by hand ahead of the upgrade is kept.+ op.execute(+ f"CREATE INDEX IF NOT EXISTS {_INDEX} ON messages (room_id, seq) "+ "WHERE event_type = 'com.switch.command'"+ )+++def downgrade() -> None:+ op.execute(f"DROP INDEX IF EXISTS {_INDEX}")+ op.execute(_WITHOUT_TYPE)+++# Frozen copies of `switch_core.db.notify_ddl` before and as of this revision;+# the live module may change later, this migration must not.+_WITH_TYPE = """+CREATE OR REPLACE FUNCTION switch_notify_message() RETURNS trigger AS $$+BEGIN+ IF NEW.seq <= 0 THEN+ RETURN NULL;+ END IF;+ PERFORM pg_notify(+ 'switch_message',+ json_build_object(+ 'room_id', NEW.room_id,+ 'seq', NEW.seq,+ 'id', NEW.id,+ 'type', NEW.event_type+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""++_WITHOUT_TYPE = """+CREATE OR REPLACE FUNCTION switch_notify_message() RETURNS trigger AS $$+BEGIN+ IF NEW.seq <= 0 THEN+ RETURN NULL;+ END IF;+ PERFORM pg_notify(+ 'switch_message',+ json_build_object(+ 'room_id', NEW.room_id,+ 'seq', NEW.seq,+ 'id', NEW.id+ )::text+ );+ RETURN NULL;+END;+$$ LANGUAGE plpgsql+"""diff --git a/core/switch_core/transport/port.py b/core/switch_core/transport/port.pyindex a7fc91e57..25daf2e15 100644--- a/core/switch_core/transport/port.py+++ b/core/switch_core/transport/port.py@@ -76,10 +76,15 @@ class MessageTransport(Protocol):"""Bind inbound callbacks. Call before `receive_forever`."""...- async def receive_forever(self, progress: DeliveryProgress) -> None:+ async def receive_forever(+ self,+ progress: DeliveryProgress,+ *,+ row_types: frozenset[str] | None = None,+ ) -> None:"""Deliver inbound events to the registered handlers until closed,starting each room where `progress` says and recording through it how- far the client got."""+ far the client got. With `row_types`, only events of those types."""...def held_back_released(self, room_id: str) -> None:diff --git a/core/switch_core/transport/postgres.py b/core/switch_core/transport/postgres.pyindex 60ee6936f..56e7d2b24 100644--- a/core/switch_core/transport/postgres.py+++ b/core/switch_core/transport/postgres.py@@ -280,6 +280,9 @@ class PostgresTransport:# been recorded through it.self._progress: DeliveryProgress | None = Noneself._recorded: dict[str, int] = {}+ # The row types the current receive is for, or None for every row+ # (`receive_forever`).+ self._row_types: frozenset[str] | None = None# Rooms this client has been told moved but has not read yet, and the# signal its delivery loop waits on. A set because a room that moved# twice while the loop was busy is still one read.@@ -304,17 +307,27 @@ class PostgresTransport:def register_handlers(self, handlers: TransportHandlers) -> None:self._handlers = handlers- async def receive_forever(self, progress: DeliveryProgress) -> None:+ async def receive_forever(+ self,+ progress: DeliveryProgress,+ *,+ row_types: frozenset[str] | None = None,+ ) -> None:"""Deliver the rows written to this client's rooms, until closed.Each room is read from where `progress` says, and progress is recordedthrough it as rows are handled. Ending finishes the row in hand firstand records it, so a reader that resumes from the record neitherrepeats nor skips it.++ With `row_types`, only rows of those types: the client is woken only+ when one is written and reads past the rest, so a reader that acts on+ one kind of row costs nothing for every other row of every room."""self._closed = asyncio.Event()self._stopping = Falseself._progress = progress+ self._row_types = row_types# Before the rooms are read, not after they are subscribed: reading# them and watching each is several round trips, and a removal rung# during those has no membership row for the caller to fall back to.@@ -650,7 +663,9 @@ class PostgresTransport:)else:seq = (await progress.resume(session, [room_id])).get(room_id)- head = await self._message_store.head_seq(session, room_id)+ head = await self._message_store.head_seq(+ session, room_id, types=self._row_types+ )except Exception:# A claim left behind would make every later `_watch` return# early on a room nothing is subscribed to.@@ -679,8 +694,10 @@ class PostgresTransport:says the client joined at `joined_at`."""self._cursors[room_id] = seqself._recorded[room_id] = seq- self._room_cache.attach(self.tenant_id, room_id, self)- self._listener.subscribe(room_id, self._on_room_advanced)+ if self._row_types is None:+ # A reader of some types reads its own rows (`_drain_room`).+ self._room_cache.attach(self.tenant_id, room_id, self)+ self._listener.subscribe(room_id, self._on_room_advanced, types=self._row_types)self._ephemeral.subscribe(transport_room_id, self._on_ephemeral)self._joined_at[room_id] = joined_at@@ -722,7 +739,9 @@ class PostgresTransport:session, self.client_id, list(claimed))places = await progress.resume(session, members)- heads = await self._message_store.head_seqs(session, list(members))+ heads = await self._message_store.head_seqs(+ session, list(members), types=self._row_types+ )except Exception:for room_id, transport_room_id in claimed.items():self._release_claim(room_id, transport_room_id)@@ -882,9 +901,12 @@ class PostgresTransport:cursor = self._cursors.get(room_id)if cursor is None or room_id not in self._watching:return- rows, done = await self._read_shared_page(- room_id, tenant_id, cursor, woken_at- )+ if self._row_types is None:+ rows, done = await self._read_shared_page(+ room_id, tenant_id, cursor, woken_at+ )+ else:+ rows, done = await self._read_page(room_id, tenant_id, cursor)if self._cursors.get(room_id) != cursor:# Removed and put back while waiting on the room's# shared read: these rows are from the old@@ -913,6 +935,7 @@ class PostgresTransport:room_id,after_seq=cursor,limit=DELIVERY_PAGE,+ types=self._row_types,)attachments = await self._message_store.attachments_for(session, [row.id for row in rows]diff --git a/core/tests/db_buffer.py b/core/tests/db_buffer.pyindex 2b9899484..d34ebb46c 100644--- a/core/tests/db_buffer.py+++ b/core/tests/db_buffer.py@@ -46,7 +46,13 @@ class QuietRooms:`MessageListener` instead (`tests/routing.py`, `room_bells`)."""- def subscribe(self, room_id: str, waker: Callable[[str], Awaitable[None]]) -> None:+ def subscribe(+ self,+ room_id: str,+ waker: Callable[[str], Awaitable[None]],+ *,+ types: frozenset[str] | None = None,+ ) -> None:return Nonedef unsubscribe(diff --git a/core/tests/switch_core/gateway/conftest.py b/core/tests/switch_core/gateway/conftest.pyindex dd09857cc..60de3a032 100644--- a/core/tests/switch_core/gateway/conftest.py+++ b/core/tests/switch_core/gateway/conftest.py@@ -82,7 +82,13 @@ class _FakeListener:def __init__(self) -> None:self.wakers: dict[str, set[Callable[[str], Awaitable[None]]]] = {}- def subscribe(self, room_id: str, waker: Callable[[str], Awaitable[None]]) -> None:+ def subscribe(+ self,+ room_id: str,+ waker: Callable[[str], Awaitable[None]],+ *,+ types: frozenset[str] | None = None,+ ) -> None:self.wakers.setdefault(room_id, set()).add(waker)def unsubscribe(diff --git a/core/tests/switch_core/messages/test_notify.py b/core/tests/switch_core/messages/test_notify.pyindex f6f98f4a6..e325952d1 100644--- a/core/tests/switch_core/messages/test_notify.py+++ b/core/tests/switch_core/messages/test_notify.py@@ -68,14 +68,19 @@ async def _make_room(session: AsyncSession) -> str:return room.id-async def _write(session: AsyncSession, room_id: str, seq: int) -> None:+async def _write(+ session: AsyncSession,+ room_id: str,+ seq: int,+ event_type: str = "m.room.message",+) -> None:session.add(Message(seq=seq,room_id=room_id,transport_event_id=f"$e{uuid.uuid4().hex[:8]}",sender_id="@a:test",- event_type="m.room.message",+ event_type=event_type,msgtype="m.text",body="hello",content={"body": "hello"},@@ -89,6 +94,13 @@ class TestParsingAnnouncements:announcement = Announcement.parse('{"room_id": "r1", "seq": 4, "id": "m1"}')assert announcement == Announcement(room_id="r1", seq=4, message_id="m1")+ def test_the_rows_type_comes_with_it(self) -> None:+ announcement = Announcement.parse(+ '{"room_id": "r1", "seq": 4, "id": "m1", "type": "com.switch.command"}'+ )+ assert announcement is not None+ assert announcement.type == "com.switch.command"+@pytest.mark.parametrize("payload", ["not json", "{}", '{"room_id": "r1", "seq": "no"}', "[]"])@@ -220,3 +232,52 @@ class TestDelivery:await asyncio.sleep(0.5)assert woken.rooms == []+++class TestAReaderOfSomeTypes:+ """Switch's own reader acts on command rows only, and was woken for every+ row of every room to find them."""++ _COMMANDS = frozenset({"com.switch.command"})++ async def test_it_is_woken_by_its_types_only(+ self,+ listener: MessageListener,+ session_factory: async_sessionmaker[AsyncSession],+ ) -> None:+ async with session_factory() as session:+ room_id = await _make_room(session)+ await session.commit()+ commands, everything = Woken(), Woken()+ listener.subscribe(room_id, commands, types=self._COMMANDS)+ listener.subscribe(room_id, everything)+ await commands.wait() # subscribing wakes once by design+ await everything.wait()+ commands.rooms.clear()+ everything.rooms.clear()++ async with session_factory() as session:+ await _write(session, room_id, 1)+ # Both are handed the room in the same pass: once the other reader has+ # been woken, this one has been passed over.+ await everything.wait()+ assert commands.rooms == []++ async with session_factory() as session:+ await _write(session, room_id, 2, "com.switch.command")+ await commands.wait()+ assert commands.rooms == [room_id]++ async def test_a_row_of_unknown_type_wakes_it(+ self, listener: MessageListener+ ) -> None:+ """What a database announcing no type, before its migration, sends."""+ commands = Woken()+ listener.subscribe("room-a", commands, types=self._COMMANDS)+ await commands.wait()+ commands.rooms.clear()++ listener._on_notify(None, 0, "", '{"room_id": "room-a", "seq": 3, "id": "m3"}')++ await commands.wait()+ assert commands.rooms == ["room-a"]diff --git a/core/tests/switch_core/transport/test_membership_signals.py b/core/tests/switch_core/transport/test_membership_signals.pyindex 29e8b1275..8644ff01f 100644--- a/core/tests/switch_core/transport/test_membership_signals.py+++ b/core/tests/switch_core/transport/test_membership_signals.py@@ -48,7 +48,9 @@ class _Listener:def __init__(self) -> None:self.wakers: dict[str, set[Any]] = {}- def subscribe(self, room_id: str, waker: Any) -> None:+ def subscribe(+ self, room_id: str, waker: Any, *, types: frozenset[str] | None = None+ ) -> None:self.wakers.setdefault(room_id, set()).add(waker)def unsubscribe(self, room_id: str, waker: Any) -> None:diff --git a/core/tests/switch_core/transport/test_postgres_transport.py b/core/tests/switch_core/transport/test_postgres_transport.pyindex b7860958d..daaeb9597 100644--- a/core/tests/switch_core/transport/test_postgres_transport.py+++ b/core/tests/switch_core/transport/test_postgres_transport.py@@ -166,9 +166,13 @@ class _FakeListener:def __init__(self) -> None:self.wakers: dict[str, set] = {}+ self.types: dict[str, frozenset[str] | None] = {}- def subscribe(self, room_id: str, waker) -> None:+ def subscribe(+ self, room_id: str, waker, *, types: frozenset[str] | None = None+ ) -> None:self.wakers.setdefault(room_id, set()).add(waker)+ self.types[room_id] = typesdef unsubscribe(self, room_id: str, waker) -> None:self.wakers.get(room_id, set()).discard(waker)@@ -902,6 +906,41 @@ class TestReceiving:# the internal one the listener announces.assert event.room_id == room+ async def test_a_reader_of_some_types_is_handed_only_those(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Switch's own reader acts on command rows only, and was handed every+ row of every room to find them."""+ async with session_factory() as session:+ _, room, client_id, user_id = await _make_room(session)+ await session.commit()+ listener = _FakeListener()+ received = _Received()+ reader = _transport(+ session_factory, client_id=client_id, user_id=user_id, listener=listener+ )+ reader.register_handlers(received.handlers())+ await reader.join_room(room)+ commands = frozenset({"com.switch.command"})+ task = asyncio.create_task(+ reader.receive_forever(FromHead(MessageStore()), row_types=commands)+ )+ self._tasks.append((task, reader))+ switch_room_id = await _watched_room(reader)+ assert listener.types[switch_room_id] == commands++ await reader.send_message(room, "before", sender_name="a", metered=True)+ sent = await reader.send_event(+ room,+ "com.switch.command",+ {"command": "help", "args": "", "user_id": user_id, "user_name": "a"},+ )+ await reader.send_message(room, "after", sender_name="a", metered=True)+ await listener.announce(switch_room_id)++ assert [event.event_id for event in received.events] == [sent.event_id] # type: ignore[attr-defined]+ assert isinstance(received.events[0], InboundCustomEvent)+async def test_the_cursor_starts_at_the_head_and_does_not_repeat(self, session_factory: async_sessionmaker[AsyncSession]) -> None: