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
fix(collab): prevent duplicate Switch room on Slack channel provisioning (CHOO-1660) (#61)
Louis Amaudruzcbc03c04aabd
diff --git a/core/switch_core/bridges/collaboration/bridge_core.py b/core/switch_core/bridges/collaboration/bridge_core.pyindex 164765712..397f35b3b 100644--- a/core/switch_core/bridges/collaboration/bridge_core.py+++ b/core/switch_core/bridges/collaboration/bridge_core.py@@ -12,6 +12,7 @@ from nio import (RoomMessageText,RoomSendError,)+from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.aliases import AliasError, validate_alias_format@@ -104,6 +105,13 @@ class BridgeCore:self._puppet_matrix_ids: set[str] = set()self._channel_locks: dict[str, asyncio.Lock] = {}self._puppet_locks: dict[str, asyncio.Lock] = {}+ # Channels Switch is itself provisioning right now (outbound room+ # creation / bridge change). The bot auto-joins a channel the instant+ # it is created, which fires an inbound join before the room↔channel+ # mapping is committed — auto-room-creation for such a channel would+ # spawn a duplicate room. Handlers skip adoption while a channel is in+ # this set. See begin_provisioning / end_provisioning.+ self._provisioning_channels: set[str] = set()@propertydef adapter(self) -> CollaborationAdapter:@@ -545,6 +553,20 @@ class BridgeCore:# ── Auto-room creation ────────────────────────────────────────────────────+ async def _adopt_existing_room(self, channel_id: str) -> tuple[str, str] | None:+ """If a room already exists in the DB for this channel on this bridge,+ register it in the in-memory map and return its (room_id,+ matrix_room_id). Returns None if no such room exists. Idempotent."""+ async with self._session_factory() as session:+ room = await self._room_store.get_by_external_channel(+ session, self._bridge_id, channel_id+ )+ if room is None:+ return None+ self.add_room_mapping(room.id, room.matrix_room_id, channel_id)+ logger.debug("Adopted existing room %s for channel %s", room.id, channel_id)+ return (room.id, room.matrix_room_id)+async def _create_room_for_channel(self,*,@@ -554,6 +576,24 @@ class BridgeCore:sender_name: str | None = None,channel_name: str | None = None,) -> tuple[str, str] | None:+ # Callers hold the per-channel lock. Guard against provisioning a+ # duplicate room for a channel that is already (or is being) bridged:+ # 1. Switch is itself provisioning this channel right now — the mapping+ # is on its way; do not race it with a second room.+ # 2. A room already exists for this channel in the DB (committed by a+ # concurrent create_room, or present since a prior run but not yet+ # loaded into the in-memory map). Adopt it instead of creating.+ if channel_id in self._provisioning_channels:+ logger.debug(+ "Skipping auto-room-creation for channel %s: Switch is provisioning it",+ channel_id,+ )+ return self._channel_to_room.get(channel_id)++ existing = await self._adopt_existing_room(channel_id)+ if existing is not None:+ return existing+agent_ids = await self._resolve_agents_for_channel(channel_id, channel_type)bridge_name = self._bridge_display_name@@ -578,6 +618,22 @@ class BridgeCore:try:result = await self._room_service.create_room(config)+ except IntegrityError:+ # Backstop: the (bridge_id, external_channel_id) unique index+ # rejected a concurrent duplicate. Adopt the room that won the race.+ logger.warning(+ "Duplicate room creation for channel %s rejected by unique "+ "constraint; adopting existing room",+ channel_id,+ )+ adopted = await self._adopt_existing_room(channel_id)+ if adopted is None:+ logger.error(+ "Unique constraint rejected room for channel %s but no "+ "existing room found to adopt",+ channel_id,+ )+ return adoptedexcept Exception:logger.exception("Failed to auto-create room for channel %s", channel_id)return None@@ -1157,6 +1213,19 @@ class BridgeCore:# ── Room mapping management ──────────────────────────────────────────────+ def begin_provisioning(self, external_channel_id: str) -> None:+ """Mark a channel as being provisioned by Switch itself, so inbound+ join/message handlers do not auto-create a duplicate room for it in the+ window between the channel existing (bot auto-joins → inbound join+ fires) and the room↔channel mapping being committed. The caller must+ record this before awaiting anything after the channel is created, and+ clear it with end_provisioning once the mapping is established."""+ self._provisioning_channels.add(external_channel_id)++ def end_provisioning(self, external_channel_id: str) -> None:+ """Clear the provisioning marker set by begin_provisioning. Idempotent."""+ self._provisioning_channels.discard(external_channel_id)+def add_room_mapping(self, room_id: str, matrix_room_id: str, external_channel_id: str) -> None:diff --git a/core/switch_core/db/models.py b/core/switch_core/db/models.pyindex 72a5b9c80..43c4b1f7e 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -226,6 +226,17 @@ room_skills = Table(class Room(Base):__tablename__ = "rooms"+ __table_args__ = (+ # A bridged channel maps to at most one Switch room. Partial so that+ # internal-only rooms (external_channel_id IS NULL) are unconstrained.+ Index(+ "uq_rooms_bridge_external_channel",+ "bridge_id",+ "external_channel_id",+ unique=True,+ postgresql_where=text("external_channel_id IS NOT NULL"),+ ),+ )id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)matrix_room_id: Mapped[str] = mapped_column(Text, unique=True, nullable=False)diff --git a/core/switch_core/migrations/versions/d5e6f7a8b9c0_rooms_unique_bridge_channel.py b/core/switch_core/migrations/versions/d5e6f7a8b9c0_rooms_unique_bridge_channel.pynew file mode 100644index 000000000..b096d5bae--- /dev/null+++ b/core/switch_core/migrations/versions/d5e6f7a8b9c0_rooms_unique_bridge_channel.py@@ -0,0 +1,81 @@+"""unique (bridge_id, external_channel_id) on rooms; dedupe existing (CHOO-1660)++Backstop for the Slack-bridge duplicate-room race: a channel must map to at+most one Switch room. Before adding the constraint we non-destructively+detach any pre-existing duplicates — keeping the earliest-created room per+(bridge_id, external_channel_id) bridged and turning the rest into+internal-only rooms (bridge_id / channel_type / external_channel_id cleared).+Rooms are never deleted, so no messages or memberships are lost.++Revision ID: d5e6f7a8b9c0+Revises: e4f5a6b7c8d9+Create Date: 2026-07-24 00:00:00.000000++"""++import logging+from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers, used by Alembic.+revision: str = "d5e6f7a8b9c0"+down_revision: str | None = "e4f5a6b7c8d9"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++logger = logging.getLogger("alembic.runtime.migration")++_INDEX_NAME = "uq_rooms_bridge_external_channel"++# Later duplicates per (bridge_id, external_channel_id) — everything except the+# earliest-created room in each group. created_at then id give a deterministic+# order so the same room is chosen as canonical on every run.+_SELECT_DUPLICATES = sa.text(+ """+ SELECT id FROM (+ SELECT id,+ ROW_NUMBER() OVER (+ PARTITION BY bridge_id, external_channel_id+ ORDER BY created_at ASC, id ASC+ ) AS rn+ FROM rooms+ WHERE bridge_id IS NOT NULL AND external_channel_id IS NOT NULL+ ) ranked+ WHERE rn > 1+ """+)++_DETACH_DUPLICATES = sa.text(+ """+ UPDATE rooms+ SET bridge_id = NULL, channel_type = NULL, external_channel_id = NULL+ WHERE id = ANY(:ids)+ """+)+++def upgrade() -> None:+ conn = op.get_bind()+ duplicate_ids = [row[0] for row in conn.execute(_SELECT_DUPLICATES)]+ if duplicate_ids:+ logger.warning(+ "Detaching %d duplicate bridged room(s) into internal-only rooms "+ "before adding the unique channel constraint: %s",+ len(duplicate_ids),+ ", ".join(duplicate_ids),+ )+ conn.execute(_DETACH_DUPLICATES, {"ids": duplicate_ids})++ op.create_index(+ _INDEX_NAME,+ "rooms",+ ["bridge_id", "external_channel_id"],+ unique=True,+ postgresql_where=sa.text("external_channel_id IS NOT NULL"),+ )+++def downgrade() -> None:+ op.drop_index(_INDEX_NAME, table_name="rooms")diff --git a/core/switch_core/room_service.py b/core/switch_core/room_service.pyindex 5046e1bf8..c4454e9cd 100644--- a/core/switch_core/room_service.py+++ b/core/switch_core/room_service.py@@ -338,53 +338,66 @@ class RoomService:channel_type=channel_type,)- matrix_room_id = await self._matrix_admin.create_room(- config.name, config.description- )+ # Guard the channel from the moment it exists until the room↔channel+ # mapping is registered. Creating the channel makes the bot auto-join+ # it, which fires an inbound join; without this guard that join would+ # not see the not-yet-committed mapping and would auto-create a second+ # room for the same channel (CHOO-1660).+ if bridge_core and external_channel_id:+ bridge_core.begin_provisioning(external_channel_id)+ try:+ matrix_room_id = await self._matrix_admin.create_room(+ config.name, config.description+ )- room = Room(- matrix_room_id=matrix_room_id,- name=config.name,- description=config.description,- channel_type=channel_type,- bridge_id=config.bridge_id,- external_channel_id=external_channel_id,- admin_mode=config.admin_mode,- instructions=config.instructions,- protection_config=config.protection_config,- observe_config=config.observe_config,- created_by=config.created_by,- owner_id=config.owner_id,- read_visibility=config.read_visibility,- write_visibility=config.write_visibility,- )+ room = Room(+ matrix_room_id=matrix_room_id,+ name=config.name,+ description=config.description,+ channel_type=channel_type,+ bridge_id=config.bridge_id,+ external_channel_id=external_channel_id,+ admin_mode=config.admin_mode,+ instructions=config.instructions,+ protection_config=config.protection_config,+ observe_config=config.observe_config,+ created_by=config.created_by,+ owner_id=config.owner_id,+ read_visibility=config.read_visibility,+ write_visibility=config.write_visibility,+ )- async with self._session_factory() as session:- await self._room_store.create(session, room)- if config.group_id is not None:- await self._room_store.set_group(session, room.id, config.group_id)- if agent_ids:- await self._room_store.add_agents(- session,- room.id,- agent_ids,- join_event_listeners=join_event_listeners,- )- for spec in config.roles or []:- session.add(- RoomRole(- room_id=room.id,- name=spec.name,- instructions=spec.instructions,- exclusive=spec.exclusive,+ async with self._session_factory() as session:+ await self._room_store.create(session, room)+ if config.group_id is not None:+ await self._room_store.set_group(session, room.id, config.group_id)+ if agent_ids:+ await self._room_store.add_agents(+ session,+ room.id,+ agent_ids,+ join_event_listeners=join_event_listeners,)- )- if config.aliases:- await self._seed_aliases(session, room.id, agent_ids, config)- await session.commit()+ for spec in config.roles or []:+ session.add(+ RoomRole(+ room_id=room.id,+ name=spec.name,+ instructions=spec.instructions,+ exclusive=spec.exclusive,+ )+ )+ if config.aliases:+ await self._seed_aliases(session, room.id, agent_ids, config)+ await session.commit()- if bridge_core and external_channel_id:- bridge_core.add_room_mapping(room.id, matrix_room_id, external_channel_id)+ if bridge_core and external_channel_id:+ bridge_core.add_room_mapping(+ room.id, matrix_room_id, external_channel_id+ )+ finally:+ if bridge_core and external_channel_id:+ bridge_core.end_provisioning(external_channel_id)# Invite the bridge client before the agent clients so it is joined (and# thus replicating) before any agent can post — otherwise messages sent@@ -831,17 +844,23 @@ class RoomService:channel_type=resolved_channel_type,)- async with self._session_factory() as session:- await self._room_store.update_bridge(- session,- room_id,- bridge_id=bridge_id,- channel_type=resolved_channel_type,- external_channel_id=external_channel_id,- )- await session.commit()+ # Guard the new channel until its mapping is registered, so the bot's+ # auto-join does not spawn a duplicate room (CHOO-1660).+ new_bridge.begin_provisioning(external_channel_id)+ try:+ async with self._session_factory() as session:+ await self._room_store.update_bridge(+ session,+ room_id,+ bridge_id=bridge_id,+ channel_type=resolved_channel_type,+ external_channel_id=external_channel_id,+ )+ await session.commit()- new_bridge.add_room_mapping(room_id, matrix_room_id, external_channel_id)+ new_bridge.add_room_mapping(room_id, matrix_room_id, external_channel_id)+ finally:+ new_bridge.end_provisioning(external_channel_id)await self._matrix_admin.invite_to_room(matrix_room_id, new_bridge._bridge_client_matrix_user_id)diff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.pynew file mode 100644index 000000000..e12480ad9--- /dev/null+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_duplicate_room_race.py@@ -0,0 +1,194 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import Any++from sqlalchemy.exc import IntegrityError++from switch_core.bridges.collaboration.bridge_core import BridgeCore+from switch_core.bridges.collaboration.models import InboundAppJoin++# CHOO-1660: creating a Slack-bridged room provisions a channel; the bot+# auto-joins it and fires an inbound app-join BEFORE create_room commits the+# room<->channel mapping. Without a guard, that join concluded "no room yet"+# and auto-created a SECOND room for the same channel. These tests pin the+# guard, the idempotent DB adoption, and the unique-constraint backstop.+++def _make_bridge(**overrides: Any) -> BridgeCore:+ """A BridgeCore with only the attributes the auto-room-creation path+ touches, so the real methods run without the full dependency graph."""+ created_configs: list[Any] = []+ room = SimpleNamespace(id="room-uuid", matrix_room_id="!m:switch.local")++ async def create_room(config: Any) -> SimpleNamespace:+ created_configs.append(config)+ return SimpleNamespace(room=room)++ class _Adapter:+ async def admin_message(self, *a: Any, **k: Any) -> str:+ return "C1:1.1"++ async def _resolve_agents_for_channel(+ channel_id: str, channel_type: str+ ) -> list[str]:+ return []++ async def _adopt_existing_room(channel_id: str) -> tuple[str, str] | None:+ return None++ bridge = BridgeCore.__new__(BridgeCore)+ bridge._provisioning_channels = set()+ bridge._channel_to_room = {}+ bridge._room_to_channel = {}+ bridge._channel_locks = {}+ bridge._bridge_id = "bridge-1"+ bridge._bridge_display_name = "Switch"+ bridge._adapter = _Adapter() # type: ignore[assignment]+ bridge._room_service = SimpleNamespace(create_room=create_room) # type: ignore[assignment]+ # Instance attrs shadow the class methods so the DB is never touched.+ bridge._resolve_agents_for_channel = _resolve_agents_for_channel # type: ignore[assignment]+ bridge._adopt_existing_room = _adopt_existing_room # type: ignore[assignment]+ bridge._created_configs = created_configs # type: ignore[attr-defined]+ for name, value in overrides.items():+ setattr(bridge, name, value)+ return bridge+++async def test_begin_end_provisioning_tracks_channel() -> None:+ bridge = _make_bridge()+ bridge.begin_provisioning("C1")+ assert "C1" in bridge._provisioning_channels+ bridge.end_provisioning("C1")+ assert "C1" not in bridge._provisioning_channels+ # Idempotent — clearing an untracked channel is a no-op, not an error.+ bridge.end_provisioning("C1")+++async def test_provisioning_channel_is_not_re_created() -> None:+ # The channel Switch is provisioning has no mapping yet: the handler must+ # NOT create a second room; it defers to the in-flight create_room.+ bridge = _make_bridge(_provisioning_channels={"C1"})++ result = await BridgeCore._create_room_for_channel(+ bridge,+ channel_id="C1",+ channel_type="channel_public",+ channel_name="general",+ )++ assert result is None+ assert bridge._created_configs == []+++async def test_provisioning_channel_returns_existing_mapping() -> None:+ bridge = _make_bridge(+ _provisioning_channels={"C1"},+ _channel_to_room={"C1": ("room-x", "!x:switch.local")},+ )++ result = await BridgeCore._create_room_for_channel(+ bridge,+ channel_id="C1",+ channel_type="channel_public",+ )++ assert result == ("room-x", "!x:switch.local")+ assert bridge._created_configs == []+++async def test_existing_db_room_is_adopted_not_recreated() -> None:+ async def _adopt(channel_id: str) -> tuple[str, str] | None:+ return ("adopted-room", "!adopted:switch.local")++ bridge = _make_bridge(_adopt_existing_room=_adopt)++ result = await BridgeCore._create_room_for_channel(+ bridge,+ channel_id="C1",+ channel_type="channel_public",+ )++ assert result == ("adopted-room", "!adopted:switch.local")+ # Adopted the existing room instead of creating a duplicate.+ assert bridge._created_configs == []+++async def test_integrity_error_falls_back_to_existing_room() -> None:+ # Backstop: the unique index rejected a concurrent duplicate at commit.+ # The loser adopts the winner rather than surfacing the IntegrityError.+ calls = {"adopt": 0}++ async def _adopt(channel_id: str) -> tuple[str, str] | None:+ calls["adopt"] += 1+ # First call (top-of-method re-check) finds nothing; the row is+ # committed by the racing winner only by the time the except runs.+ return ("winner-room", "!winner:switch.local") if calls["adopt"] > 1 else None++ async def create_room(config: Any) -> SimpleNamespace:+ raise IntegrityError("INSERT INTO rooms", {}, Exception("duplicate key"))++ bridge = _make_bridge(+ _adopt_existing_room=_adopt,+ _room_service=SimpleNamespace(create_room=create_room),+ )++ result = await BridgeCore._create_room_for_channel(+ bridge,+ channel_id="C1",+ channel_type="channel_public",+ )++ assert result == ("winner-room", "!winner:switch.local")+ assert calls["adopt"] == 2+++async def test_app_join_during_provisioning_creates_no_room() -> None:+ # End-to-end race path: the app-join handler fires while create_room is+ # still provisioning the channel. It must not spawn a duplicate room.+ bridge = _make_bridge(_provisioning_channels={"C1"})++ await BridgeCore._handle_app_joined_channel(+ bridge,+ InboundAppJoin(+ channel_id="C1",+ channel_type="channel_public",+ channel_name="general",+ ),+ )++ assert bridge._created_configs == []+++async def test_adopt_existing_room_registers_mapping() -> None:+ # The real _adopt_existing_room: a DB hit registers the in-memory mapping+ # and returns the room, so subsequent lookups short-circuit.+ room = SimpleNamespace(id="db-room", matrix_room_id="!db:switch.local")++ class _Session:+ async def __aenter__(self) -> _Session:+ return self++ async def __aexit__(self, *a: Any) -> None:+ return None++ class _RoomStore:+ async def get_by_external_channel(+ self, session: Any, bridge_id: str, channel_id: str+ ) -> Any:+ return room if channel_id == "C1" else None++ bridge = BridgeCore.__new__(BridgeCore)+ bridge._channel_to_room = {}+ bridge._room_to_channel = {}+ bridge._bridge_id = "bridge-1"+ bridge._session_factory = _Session # type: ignore[assignment]+ bridge._room_store = _RoomStore() # type: ignore[assignment]++ result = await bridge._adopt_existing_room("C1")++ assert result == ("db-room", "!db:switch.local")+ assert bridge._channel_to_room["C1"] == ("db-room", "!db:switch.local")++ # No room for an unmapped channel.+ assert await bridge._adopt_existing_room("C2") is Nonediff --git a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.pyindex c285549ef..733097c73 100644--- a/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py+++ b/core/tests/switch_core/bridges/collaboration/test_bridge_no_agents_notice.py@@ -45,11 +45,17 @@ def _fake_bridge(*, agent_ids: list[str]): # noqa: ANN202def add_room_mapping(room_id: str, matrix_room_id: str, channel_id: str) -> None:pass+ async def _adopt_existing_room(channel_id: str) -> tuple[str, str] | None:+ return None+return SimpleNamespace(_adapter=_Adapter(),_room_service=_RoomService(),_resolve_agents_for_channel=_resolve_agents_for_channel,+ _adopt_existing_room=_adopt_existing_room,add_room_mapping=add_room_mapping,+ _provisioning_channels=set(),+ _channel_to_room={},_bridge_display_name="Switch",_bridge_id="bridge-1",notices=notices,diff --git a/core/tests/switch_core/test_room_service_change_bridge.py b/core/tests/switch_core/test_room_service_change_bridge.pyindex e4a09bc3e..de1d1c3eb 100644--- a/core/tests/switch_core/test_room_service_change_bridge.py+++ b/core/tests/switch_core/test_room_service_change_bridge.py@@ -101,6 +101,12 @@ class _FakeBridgeCore:def remove_room_mapping(self, room_id: str, matrix_room_id: str) -> None:self._events.append(("remove_room_mapping", room_id))+ def begin_provisioning(self, external_channel_id: str) -> None:+ self._events.append(("begin_provisioning", external_channel_id))++ def end_provisioning(self, external_channel_id: str) -> None:+ self._events.append(("end_provisioning", external_channel_id))+class _FakeLifecycle:def __init__(self, bridges: dict[str, Any]) -> None: