Skip to content

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

fix(core): let two concurrent adds of one agent to a room both succeed

raullopez-sandboxdceb7fd14e5d
diff --git a/core/switch_core/db/stores/room_store.py b/core/switch_core/db/stores/room_store.py
index 7ed4fa8dd..e91ce9b15 100644
--- a/core/switch_core/db/stores/room_store.py
+++ b/core/switch_core/db/stores/room_store.py
@@ -6,7 +6,6 @@ from sqlalchemy import (
ColumnElement,
delete,
exists,
- insert,
literal,
or_,
select,
@@ -369,12 +368,14 @@ class RoomStore:
`join_event_listeners` is the subset of `agent_ids` that should receive
`room_join` events in this room. Any agent not in that set keeps the
column default (off) — agents are opted in to join events explicitly.
+ An agent already in the room is left as it is, so two concurrent adds
+ of the same agent both succeed.
"""
if not agent_ids:
return
listeners = join_event_listeners or set()
await session.execute(
- insert(room_agents),
+ pg_insert(room_agents).on_conflict_do_nothing(),
[
{
"room_id": room_id,
diff --git a/core/tests/switch_core/db/stores/test_room_store.py b/core/tests/switch_core/db/stores/test_room_store.py
index c0ccad45b..54df1a9d4 100644
--- a/core/tests/switch_core/db/stores/test_room_store.py
+++ b/core/tests/switch_core/db/stores/test_room_store.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import uuid
import pytest
@@ -220,3 +221,30 @@ class TestDelete:
assert await session.get(Agent, agent_id) is not None
tasks = await session.execute(select(Task).where(Task.room_id == room_id))
assert tasks.scalars().all() == []
+
+
+class TestAddAgents:
+ async def test_two_concurrent_adds_of_one_agent_both_succeed(
+ self, session_factory: async_sessionmaker[AsyncSession]
+ ) -> None:
+ store = RoomStore()
+ async with session_factory() as session:
+ owner = User(name="owner", email="[email protected]", role="admin")
+ session.add(owner)
+ await session.flush()
+ room = await _make_room(session, "!double-add:switch.local")
+ agent = await _make_agent(session, owner.id)
+ await session.commit()
+
+ async with session_factory() as first, session_factory() as second:
+ await store.add_agents(first, room.id, [agent.id])
+ # Waits on the first's uncommitted row, then finds it there.
+ racing = asyncio.create_task(store.add_agents(second, room.id, [agent.id]))
+ await asyncio.sleep(0.2)
+ assert not racing.done()
+ await first.commit()
+ await racing
+ await second.commit()
+
+ async with session_factory() as session:
+ assert await store.get_agent_ids(session, room.id) == [agent.id]