Skip to content

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

perf(core): tell an agent's rooms of a rename in one session and one query

raullopez-sandboxa274d69c6c42
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index c52cbeae2..55ce86376 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -202,9 +202,7 @@ class ChatService:
weakref.WeakValueDictionary()
)
self._membership_watchers: dict[tuple[str, str], set[MembershipWatcher]] = {}
- self._agent_room_listeners: tuple[
- Callable[[str, str, list[str]], None], ...
- ] = ()
+ self._agent_room_listeners: tuple[Callable[[str, list[str]], None], ...] = ()
self._tasks: set[asyncio.Task[None]] = set()
# Where a change to people's chats made here is announced to the
# other processes, once wired (`use_signals`).
@@ -593,12 +591,10 @@ class ChatService:
[room_id],
)
- def on_agent_room_changed(
- self, listener: Callable[[str, str, list[str]], None]
- ) -> None:
- """Call `listener(tenant_id, room_id, [])` for each room an agent is in
+ def on_agent_room_changed(self, listener: Callable[[str, list[str]], None]) -> None:
+ """Call `listener(tenant_id, room_ids)` with every room an agent is in
when its name, display name or icon changes (`room_changes`), so
- whoever shows the room reads it again. It must not block."""
+ whoever shows those rooms reads them again. It must not block."""
self._agent_room_listeners = (*self._agent_room_listeners, listener)
def room_changed(self, tenant_id: str, room_id: str, client_ids: list[str]) -> None:
@@ -647,12 +643,11 @@ class ChatService:
)
).scalars()
)
- for room_id in room_ids:
- for listener in self._agent_room_listeners:
- try:
- listener(tenant_id, room_id, [])
- except Exception:
- logger.exception("Agent room listener failed for room %s", room_id)
+ for listener in self._agent_room_listeners:
+ try:
+ listener(tenant_id, room_ids)
+ except Exception:
+ logger.exception("Agent room listener failed for agent %s", agent_id)
if not self.agent_chats_enabled:
return
async with tenant_session(self.session_factory, tenant_id) as session:
diff --git a/core/switch_core/main.py b/core/switch_core/main.py
index e5c07b093..a1025feea 100644
--- a/core/switch_core/main.py
+++ b/core/switch_core/main.py
@@ -1176,7 +1176,7 @@ async def run(config: SwitchConfig, process_id: str) -> None:
room_service.on_room_agents_changed(chat_service.sync_room)
protocol.set_room_agents_listener(room_service.room_agents_changed)
protocol.set_agent_profile_listener(chat_service.agent_changed)
- chat_service.on_agent_room_changed(room_changes.room_changed)
+ chat_service.on_agent_room_changed(room_changes.rooms_changed)
room_service.on_room_changed(chat_service.room_changed)
# ── Connector app credentials ─────────────────────────────────────────────
diff --git a/core/switch_core/room_changes.py b/core/switch_core/room_changes.py
index 39d6fa99d..0dc30981c 100644
--- a/core/switch_core/room_changes.py
+++ b/core/switch_core/room_changes.py
@@ -22,7 +22,16 @@ import asyncio
import logging
from typing import TYPE_CHECKING
-from sqlalchemy import Result, or_, select, union
+from sqlalchemy import (
+ CompoundSelect,
+ Result,
+ Select,
+ String,
+ column,
+ select,
+ union,
+ values,
+)
from switch_core.chats import MEMBER_CLIENT_TYPE
from switch_core.db.models import (
@@ -38,6 +47,8 @@ from switch_core.db.session_scope import tenant_session
from switch_core.user_changes import ROOM
if TYPE_CHECKING:
+ from collections.abc import Mapping
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.user_changes import UserChangePublisher
@@ -70,7 +81,23 @@ class RoomChanges:
self._pending[key].update(client_ids)
return
self._pending[key] = set(client_ids)
- task = asyncio.create_task(self._publish(tenant_id, room_id))
+ self._start(tenant_id, [room_id])
+
+ def rooms_changed(self, tenant_id: str, room_ids: list[str]) -> None:
+ """`room_changed` for many rooms at once (an agent in each was
+ renamed), read in one session and one query however many there are.
+ A room whose window is open already is told with that window."""
+ opened = []
+ for room_id in dict.fromkeys(room_ids):
+ key = (tenant_id, room_id)
+ if key not in self._pending:
+ self._pending[key] = set()
+ opened.append(room_id)
+ if opened:
+ self._start(tenant_id, opened)
+
+ def _start(self, tenant_id: str, room_ids: list[str]) -> None:
+ task = asyncio.create_task(self._publish(tenant_id, room_ids))
self._tasks.add(task)
task.add_done_callback(self._finished)
@@ -83,48 +110,67 @@ class RoomChanges:
exc_info=task.exception(),
)
- async def _publish(self, tenant_id: str, room_id: str) -> None:
+ async def _publish(self, tenant_id: str, room_ids: list[str]) -> None:
try:
await asyncio.sleep(self._window_seconds)
finally:
- client_ids = sorted(self._pending.pop((tenant_id, room_id)))
+ changed = {
+ room_id: sorted(self._pending.pop((tenant_id, room_id)))
+ for room_id in room_ids
+ }
async with tenant_session(self._session_factory, tenant_id) as session:
- user_ids = await people_concerned(session, room_id, client_ids)
- for user_id in user_ids:
- self._publisher.publish(tenant_id, user_id, ROOM, room_id)
+ concerned = await people_concerned(session, changed)
+ for room_id, user_ids in concerned.items():
+ for user_id in user_ids:
+ self._publisher.publish(tenant_id, user_id, ROOM, room_id)
async def people_concerned(
- session: AsyncSession, room_id: str, client_ids: list[str]
-) -> list[str]:
- """The room's owner, the people in it and behind `client_ids`, and the
- owners of its agents."""
- present = set(client_ids) | set(
- (
- await session.execute(
- select(ClientRoom.client_id).where(ClientRoom.room_id == room_id)
- )
- ).scalars()
- )
- found: Result[tuple[str | None]] = await session.execute(
+ session: AsyncSession, changed: Mapping[str, list[str]]
+) -> dict[str, list[str]]:
+ """For each room in `changed`: its owner, the people in it and behind
+ the client ids it maps to, and the owners of its agents. One query."""
+ room_ids = list(changed)
+ present: Select[tuple[str, str]] | CompoundSelect = select(
+ ClientRoom.room_id, ClientRoom.client_id
+ ).where(ClientRoom.room_id.in_(room_ids))
+ named = [
+ (room_id, client_id)
+ for room_id, client_ids in changed.items()
+ for client_id in client_ids
+ ]
+ if named:
+ present = union(
+ present,
+ select(
+ values(
+ column("room_id", String), column("client_id", String), name="named"
+ ).data(named)
+ ),
+ )
+ here = present.subquery()
+ found: Result[tuple[str, str | None]] = await session.execute(
union(
- select(Room.owner_id).where(Room.id == room_id),
- select(Client.user_id).where(
- Client.id.in_(present), Client.type == MEMBER_CLIENT_TYPE
+ select(Room.id, Room.owner_id).where(Room.id.in_(room_ids)),
+ select(here.c.room_id, Client.user_id)
+ .join(Client, Client.id == here.c.client_id)
+ .where(Client.type == MEMBER_CLIENT_TYPE),
+ select(here.c.room_id, ExternalUserClaim.user_id)
+ .join(ExternalUser, ExternalUser.client_id == here.c.client_id)
+ .join(
+ ExternalUserClaim,
+ ExternalUserClaim.external_user_id == ExternalUser.id,
),
- select(ExternalUserClaim.user_id)
- .join(ExternalUser, ExternalUser.id == ExternalUserClaim.external_user_id)
- .where(ExternalUser.client_id.in_(present)),
- select(Agent.owner_id).where(
- or_(
- Agent.id.in_(
- select(room_agents.c.agent_id).where(
- room_agents.c.room_id == room_id
- )
- ),
- Agent.client_id.in_(present),
- )
+ select(here.c.room_id, Agent.owner_id).join(
+ Agent, Agent.client_id == here.c.client_id
),
+ select(room_agents.c.room_id, Agent.owner_id)
+ .join(Agent, Agent.id == room_agents.c.agent_id)
+ .where(room_agents.c.room_id.in_(room_ids)),
)
)
- return sorted({user_id for user_id in found.scalars() if user_id is not None})
+ concerned: dict[str, set[str]] = {room_id: set() for room_id in room_ids}
+ for room_id, user_id in found.tuples():
+ if user_id is not None:
+ concerned[room_id].add(user_id)
+ return {room_id: sorted(users) for room_id, users in concerned.items()}
diff --git a/core/tests/switch_core/db/stores/test_room_store_involves.py b/core/tests/switch_core/db/stores/test_room_store_involves.py
index 4252891c8..fb180ca7b 100644
--- a/core/tests/switch_core/db/stores/test_room_store_involves.py
+++ b/core/tests/switch_core/db/stores/test_room_store_involves.py
@@ -103,10 +103,11 @@ async def test_a_person_reads_the_rooms_they_take_part_in_and_no_other(
await store.involved_room_ids(session, alice.id, [*expected, unrelated.id])
== expected
)
- assert await people_concerned(session, discord.id, []) == [alice.id]
- assert set(await people_concerned(session, with_agent.id, [])) == {
- alice.id,
- bob.id,
- }
- # Someone who just left is named by the client they left with.
- assert alice.id in await people_concerned(session, unrelated.id, [member.id])
+ concerned = await people_concerned(
+ session,
+ # Someone who just left is named by the client they left with.
+ {discord.id: [], with_agent.id: [], unrelated.id: [member.id]},
+ )
+ assert concerned[discord.id] == [alice.id]
+ assert set(concerned[with_agent.id]) == {alice.id, bob.id}
+ assert alice.id in concerned[unrelated.id]
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index d660abbce..335eb117e 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -1309,13 +1309,14 @@ async def test_changes_to_a_room_within_a_window_make_one_read_and_one_notice_ea
reads: list[list[str]] = []
async def counted(
- session: AsyncSession, room: str, client_ids: list[str]
- ) -> list[str]:
- reads.append(client_ids)
- return await people_concerned(session, room, client_ids)
+ session: AsyncSession, changed: dict[str, list[str]]
+ ) -> dict[str, list[str]]:
+ reads.append(changed[room_id])
+ return await people_concerned(session, changed)
monkeypatch.setattr(room_changes_module, "people_concerned", counted)
+ changes.rooms_changed(TENANT, [room_id])
for _ in range(5):
changes.room_changed(TENANT, room_id, [])
# The last change in the window names a client that just left.
@@ -1339,7 +1340,7 @@ async def test_renaming_an_agent_tells_everyone_who_sees_its_rooms(
changes = RoomChanges(
session_factory=chats.factory, publisher=published, window_seconds=0.0
)
- chats.service.on_agent_room_changed(changes.room_changed)
+ chats.service.on_agent_room_changed(changes.rooms_changed)
agent = await chats.agent("renamed", owner=chats.admin)
room_id = await chats.new_chat(chats.alice, agent, "c1")
assert (await chats.invite(chats.alice, room_id, chats.bob)).status_code == 200
@@ -1362,6 +1363,38 @@ async def test_renaming_an_agent_tells_everyone_who_sees_its_rooms(
await events.stream.aclose() # type: ignore[attr-defined]
+async def test_renaming_an_agent_in_many_rooms_reads_them_in_one_query(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ published = _Published()
+ changes = RoomChanges(
+ session_factory=chats.factory, publisher=published, window_seconds=0.0
+ )
+ chats.service.on_agent_room_changed(changes.rooms_changed)
+ agent = await chats.agent("busy", owner=chats.admin)
+ rooms = [await chats.new_chat(chats.alice, agent, f"c{n}") for n in range(6)]
+ assert (await chats.invite(chats.alice, rooms[0], chats.bob)).status_code == 200
+ reads: list[list[str]] = []
+
+ async def counted(
+ session: AsyncSession, changed: dict[str, list[str]]
+ ) -> dict[str, list[str]]:
+ reads.append(sorted(changed))
+ return await people_concerned(session, changed)
+
+ monkeypatch.setattr(room_changes_module, "people_concerned", counted)
+
+ await chats.service.agent_changed(TENANT, agent.id)
+ assert len(changes._tasks) == 1
+ await asyncio.gather(*changes._tasks)
+ assert reads == [sorted(rooms)]
+ expected = {
+ (user, ROOM, r) for r in rooms for user in (chats.alice.id, chats.admin.id)
+ }
+ expected.add((chats.bob.id, ROOM, rooms[0]))
+ assert set(published.notices) == expected
+
+
async def test_only_a_manager_renames_a_group_and_everyone_sees_it(
chats: _Harness, monkeypatch: pytest.MonkeyPatch
) -> None: