Skip to content

The agent that grows with you

fix(slack): concurrent slash commands of one session reach the gateway in arrival order

Teknium0815b4ed4a47
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index 27fa637e09b..d0b0ff1a439 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -54,9 +54,11 @@ from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
try: # sibling modules; support both package and flat plugin-dir import
from .block_kit import render_blocks, sanitize_blocks
+ from .adapter_slash_lane import SlashHandoffLanes
from .adapter_slash_payload import slash_command_text, slash_thread_id
except ImportError: # pragma: no cover - plugin loaded outside package context
from block_kit import render_blocks, sanitize_blocks # type: ignore
+ from adapter_slash_lane import SlashHandoffLanes # type: ignore
from adapter_slash_payload import slash_command_text, slash_thread_id # type: ignore
@@ -1121,6 +1123,7 @@ class SlackAdapter(BasePlatformAdapter):
# Slash-command contexts so send() can route the first reply ephemerally. Keyed
# (team_id, channel_id, user_id), two-part when no team id → {"response_url", "ts"}.
self._slash_command_contexts: dict[tuple[str, ...], dict[str, Any]] = {}
+ self._slash_lanes = SlashHandoffLanes() # arrival order of one session's slashes
# Native streaming state per _stream_key: {"ts", "draft_id", "sent", "started", "base"}.
# ``sent`` is the raw pre-mrkdwn text of the whole segment; the API is append-only so
# deltas diff against it. ``base`` is where this Slack message starts inside ``sent``
@@ -6100,21 +6103,28 @@ class SlackAdapter(BasePlatformAdapter):
cmd = resolve_command(event.get_command() or "")
controls_running_turn = cmd is not None and (
cmd.busy_policy == "interrupt_then_dispatch" or cmd.name in ("approve", "deny", "pause"))
+ lane = ahead = handed_off = None
if not rejected and not controls_running_turn:
- source.chat_name = await self._resolve_channel_name(channel_id, team_id=team_id)
- source.user_name = await self._resolve_user_name(user_id, chat_id=channel_id, team_id=team_id)
- # Stash response_url so the first reply for this channel+user goes ephemeral. COMMAND
- # events only: free-form "/hermes <question>" replies must stay public.
- response_url = command.get("response_url", "")
- if response_url and user_id and channel_id and text.startswith("/"):
- self._stash_slash_context(team_id, channel_id, user_id, response_url)
- # ContextVar lets send() match the right response_url under
- # concurrent slashes from multiple users.
- _slash_user_id_token = _slash_user_id.set(user_id or None)
+ lane = self._event_session_key(event) # slot taken before any lookup is awaited
+ ahead, handed_off = self._slash_lanes.reserve(lane)
+ # ContextVar lets send() match the right response_url under concurrent slashes.
+ slash_user_token = _slash_user_id.set(user_id or None)
try:
+ if lane is not None:
+ source.chat_name = await self._resolve_channel_name(channel_id, team_id=team_id)
+ source.user_name = await self._resolve_user_name(user_id, chat_id=channel_id, team_id=team_id)
+ if ahead is not None:
+ await asyncio.wait((ahead,))
+ # Stash response_url so the first reply for this channel+user goes ephemeral. COMMAND
+ # events only: free-form "/hermes <question>" replies must stay public.
+ response_url = command.get("response_url", "")
+ if response_url and user_id and channel_id and text.startswith("/"):
+ self._stash_slash_context(team_id, channel_id, user_id, response_url)
+ # The slot opens once handle_message returns: the gateway may suspend before queueing.
await self.handle_message(event)
finally:
- _slash_user_id.reset(_slash_user_id_token)
+ _slash_user_id.reset(slash_user_token)
+ self._slash_lanes.release(lane, ahead, handed_off)
def _stash_slash_context(
self, team_id: str, channel_id: str, user_id: str, response_url: str) -> None:
diff --git a/plugins/platforms/slack/adapter_slash_lane.py b/plugins/platforms/slack/adapter_slash_lane.py
new file mode 100644
index 00000000000..563cd43c6c2
--- /dev/null
+++ b/plugins/platforms/slack/adapter_slash_lane.py
@@ -0,0 +1,38 @@
+"""Per-session handoff order for Slack slash commands.
+
+Bolt runs slash callbacks concurrently and a slash awaits its name lookups before the handoff, so
+a cold ``users.info`` on an earlier slash would let a later one reach the gateway first (two
+``/queue`` land in the FIFO swapped). A slash reserves its session's slot before any lookup and
+hands over only after the slash ahead of it returned from ``handle_message``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+
+class SlashHandoffLanes:
+ def __init__(self) -> None:
+ # Session key -> future of the newest slash still on its way through handle_message.
+ self.tails: dict[str, asyncio.Future[None]] = {}
+
+ def reserve(self, key: str) -> tuple[asyncio.Future[None] | None, asyncio.Future[None]]:
+ """Take the session's next slot; returns (slot ahead, this slot). Call before any await."""
+ ahead = self.tails.get(key)
+ self.tails[key] = handed_off = asyncio.get_running_loop().create_future()
+ return ahead, handed_off
+
+ def release(self, key: str | None, ahead: asyncio.Future | None, handed_off: asyncio.Future | None) -> None:
+ """Open the slot once this slash is done. Cancelled while waiting: the slash behind it
+ still waits for the one ahead, or it reaches the gateway before unfinished earlier work."""
+ if ahead is not None and not ahead.done():
+ ahead.add_done_callback(lambda _f: self._open(key, handed_off))
+ else:
+ self._open(key, handed_off)
+
+ def _open(self, key: str | None, handed_off: asyncio.Future | None) -> None:
+ if handed_off is None or handed_off.done():
+ return
+ handed_off.set_result(None)
+ if self.tails.get(key) is handed_off:
+ del self.tails[key]
diff --git a/tests/plugins/platforms/slack/test_slash_command_channel_prompt.py b/tests/plugins/platforms/slack/test_slash_command_channel_prompt.py
index f8708ccf020..a7e18f9d5fb 100644
--- a/tests/plugins/platforms/slack/test_slash_command_channel_prompt.py
+++ b/tests/plugins/platforms/slack/test_slash_command_channel_prompt.py
@@ -8,6 +8,7 @@ message flipped them back: two agent rebuilds and two prompt-cache misses per sl
and neither did the turn a ``/goal <text>`` kickoff queues.
"""
+import asyncio
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -115,3 +116,30 @@ async def test_slash_that_starts_no_turn_costs_no_slack_lookup(channel_id, autho
adapter._app.client.users_info.assert_not_awaited()
adapter._app.client.conversations_info.assert_not_awaited()
assert adapter.handle_message.await_count == reaches_runner
+
+
+async def test_concurrent_slashes_reach_the_gateway_in_arrival_order():
+ """Two ``/hermes queue`` slashes through the Bolt listener: the first is held on a cold
+ ``users.info`` while the second's lookup is warm. They still reach the gateway in arrival
+ order, and a ``/stop`` sent meanwhile is handed over at once, not behind the held lookup."""
+ adapter, entered, release = _adapter("C_OPS"), asyncio.Event(), asyncio.Event()
+
+ async def users_info(**_kwargs):
+ if not entered.is_set():
+ entered.set()
+ await release.wait()
+ return {"user": {"profile": {"display_name": "Alice"}, "real_name": "Alice"}}
+
+ adapter._app.client.users_info = AsyncMock(side_effect=users_info)
+ base = {"command": "/hermes", "user_id": "U_ALICE", "channel_id": "C_OPS", "team_id": "T1"}
+ first = asyncio.create_task(adapter._handle_hermes_command(AsyncMock(), {**base, "text": "queue first"}))
+ await asyncio.wait_for(entered.wait(), 5)
+ second = asyncio.create_task(adapter._handle_hermes_command(AsyncMock(), {**base, "text": "queue second"}))
+ await asyncio.wait_for(adapter._handle_hermes_command(AsyncMock(), {**base, "text": "stop"}), 5)
+ handed = lambda: [c.args[0].text for c in adapter.handle_message.await_args_list]
+ assert handed() == ["/stop"]
+ release.set()
+ await asyncio.wait_for(asyncio.gather(first, second), 5)
+ assert handed() == ["/stop", "/queue first", "/queue second"]
+ assert not adapter._slash_lanes.tails