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(chats): one room per create request across processes

raullopez-sandboxcf03ab893002
diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.py
index ac0d44b27..6b20857fd 100644
--- a/core/switch_core/chats/service.py
+++ b/core/switch_core/chats/service.py
@@ -42,6 +42,7 @@ from sqlalchemy import (
update,
)
from sqlalchemy.dialects.postgresql import insert as pg_insert
+from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.addressing import allows_on_behalf_of, parse_policy
@@ -1233,13 +1234,7 @@ class ChatService:
)
await session.commit()
operation_id = self._operation_id(tenant_id, user.id, request_id)
- found = (
- await session.execute(
- select(Room).where(
- Room.metadata_["chat_operation_id"].astext == operation_id
- )
- )
- ).scalar_one_or_none()
+ found = await self._room_of_operation(session, operation_id)
if found is None:
names = ", ".join(
[agent.name for agent in agents]
@@ -1273,7 +1268,18 @@ class ChatService:
)
except ValueError as exc:
raise ChatError(422, "CHAT_NOT_CREATED", str(exc)) from exc
- room = created.room
+ except IntegrityError:
+ # The same request made the room first, on another process.
+ async with tenant_session(
+ self.session_factory, tenant_id
+ ) as session:
+ found = await self._room_of_operation(session, operation_id)
+ if found is None:
+ raise
+ room = found
+ await self._room_service.reconcile_room(room)
+ else:
+ room = created.room
else:
room = found
await self._room_service.reconcile_room(room)
@@ -1300,6 +1306,17 @@ class ChatService:
self._start_session(agents[0].id, room.id)
return room
+ async def _room_of_operation(
+ self, session: AsyncSession, operation_id: str
+ ) -> Room | None:
+ return (
+ await session.execute(
+ select(Room).where(
+ Room.metadata_["chat_operation_id"].astext == operation_id
+ )
+ )
+ ).scalar_one_or_none()
+
async def stage_upload(
self,
tenant_id: str,
diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.py
index aa89a9cc9..70dff1e2c 100644
--- a/core/switch_core/db/models.py
+++ b/core/switch_core/db/models.py
@@ -934,6 +934,15 @@ class Room(TenantScoped, Base):
# A run is listed, checked and stopped by its root on every agent
# create and every look at Recently used.
Index("ix_rooms_run_id", "run_id"),
+ # One room per Switch Console create request, whichever process or
+ # retry gets there first.
+ Index(
+ "uq_rooms_chat_operation_id",
+ "tenant_id",
+ text("(metadata ->> 'chat_operation_id')"),
+ unique=True,
+ postgresql_where=text("metadata ? 'chat_operation_id'"),
+ ),
UniqueConstraint(
"tenant_id", "matrix_room_id", name="uq_rooms_tenant_matrix_room_id"
),
diff --git a/core/switch_core/migrations/versions/f4a9c2e7b153_rooms_chat_operation_unique.py b/core/switch_core/migrations/versions/f4a9c2e7b153_rooms_chat_operation_unique.py
new file mode 100644
index 000000000..47befcf90
--- /dev/null
+++ b/core/switch_core/migrations/versions/f4a9c2e7b153_rooms_chat_operation_unique.py
@@ -0,0 +1,49 @@
+"""rooms: one room per Switch Console create request
+
+A partial unique index on `(tenant_id, metadata->>'chat_operation_id')`, so a
+create retried on another process cannot make a second room for the same
+request. Refuses to run while duplicates exist rather than choosing one.
+
+Revision ID: f4a9c2e7b153
+Revises: e2c7b9a4d816
+Create Date: 2026-10-26 00:00:00.000000
+
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "f4a9c2e7b153"
+down_revision: str | Sequence[str] | None = "e2c7b9a4d816"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ duplicates = op.get_bind().scalar(
+ sa.text(
+ "SELECT count(*) FROM (SELECT 1 FROM rooms "
+ "WHERE metadata ? 'chat_operation_id' "
+ "GROUP BY tenant_id, metadata ->> 'chat_operation_id' "
+ "HAVING count(*) > 1) d"
+ )
+ )
+ if duplicates:
+ raise RuntimeError(
+ f"rooms: {duplicates} Switch Console create request(s) made more "
+ "than one room. Delete or archive the extra rooms (same "
+ "metadata->>'chat_operation_id') and upgrade again."
+ )
+ op.create_index(
+ "uq_rooms_chat_operation_id",
+ "rooms",
+ ["tenant_id", sa.text("(metadata ->> 'chat_operation_id')")],
+ unique=True,
+ postgresql_where=sa.text("metadata ? 'chat_operation_id'"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("uq_rooms_chat_operation_id", table_name="rooms")
diff --git a/core/tests/switch_core/gateway/test_chats_groups.py b/core/tests/switch_core/gateway/test_chats_groups.py
index 835cf5360..798928034 100644
--- a/core/tests/switch_core/gateway/test_chats_groups.py
+++ b/core/tests/switch_core/gateway/test_chats_groups.py
@@ -13,11 +13,18 @@ import pytest
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistry
from switch_core.bridges.agent.registration_bootstrap import (
BOOTSTRAP_OWNER_MARKER_META_KEY,
)
-from switch_core.db.models import Agent, Message, Room, User, room_agents
-from tests.switch_core.gateway.conftest import _Harness
+from switch_core.chats.service import ChatService
+from switch_core.db.models import Agent, Client, Message, Room, User, room_agents
+from tests.switch_core.gateway.conftest import (
+ _chat_service,
+ _FakeActivityListener,
+ _FakeListener,
+ _Harness,
+)
from tests.switch_core.gateway.test_chats_routes import (
_code,
_events_of,
@@ -885,3 +892,88 @@ async def test_an_ordinary_member_leaves_without_managing(chats: _Harness) -> No
)
assert left.status_code == 204
assert await _reads(chats, chats.bob, room_id) == 403
+
+
+# ── Creating across processes ────────────────────────────────────────────────
+
+
+def _second_process(chats: _Harness) -> ChatService:
+ service, _ = _chat_service(
+ chats.factory,
+ lifecycle=chats.lifecycle,
+ listener=_FakeListener(),
+ activity=_FakeActivityListener(),
+ connections=AgentConnectionRegistry(),
+ )
+ return service
+
+
+async def test_one_create_on_two_processes_makes_one_room(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ other = _second_process(chats)
+ both_looked = asyncio.Barrier(2)
+ for service in (chats.service, other):
+ look = service._room_of_operation
+
+ async def look_then_wait(
+ session: AsyncSession, operation_id: str, look=look
+ ) -> Room | None:
+ found = await look(session, operation_id)
+ if found is None:
+ await both_looked.wait()
+ return found
+
+ monkeypatch.setattr(service, "_room_of_operation", look_then_wait)
+
+ def create(service: ChatService) -> Any:
+ return service.create_chat(
+ "00000000-0000-0000-0000-000000000000",
+ chats.alice,
+ agent_ids=[agent.id],
+ member_user_ids=[chats.bob.id],
+ kind=None,
+ name=None,
+ request_id="c1",
+ greeting=None,
+ )
+
+ first, second = await asyncio.gather(create(chats.service), create(other))
+ assert first.id == second.id
+ async with chats.factory() as session:
+ assert await session.scalar(select(func.count()).select_from(Room)) == 1
+ assert await _reads(chats, chats.bob, first.id) == 200
+
+
+async def test_a_create_cut_off_before_its_people_joined_finishes_on_retry(
+ chats: _Harness, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ agent = await chats.agent("helper", owner=chats.alice)
+ join = chats.service._join
+ async with chats.factory() as session:
+ bob_client = await chats.service.member_client(session, chats.bob.id)
+ assert bob_client is None
+
+ async def join_but_not_bob(tenant_id: str, room: Room, client: Client) -> None:
+ if client.user_id == chats.bob.id:
+ raise RuntimeError("cut off")
+ await join(tenant_id, room, client)
+
+ monkeypatch.setattr(chats.service, "_join", join_but_not_bob)
+ body = {"agentId": agent.id, "memberUserIds": [chats.bob.id], "requestId": "c1"}
+ with pytest.raises(RuntimeError, match="cut off"):
+ await chats.client.post("/chats", json=body, headers=chats.as_user(chats.alice))
+ monkeypatch.setattr(chats.service, "_join", join)
+
+ retried = await chats.client.post(
+ "/chats", json=body, headers=chats.as_user(chats.alice)
+ )
+ assert retried.status_code == 200, retried.text
+ room_id = retried.json()["chat"]["roomId"]
+ assert sorted(retried.json()["chat"]["memberUserIds"]) == sorted(
+ [chats.alice.id, chats.bob.id]
+ )
+ async with chats.factory() as session:
+ assert await session.scalar(select(func.count()).select_from(Room)) == 1
+ assert await _reads(chats, chats.bob, room_id) == 200