Skip to content

Build and run agents you can see, understand and trust.

fix(app): stop stranding session inbox payloads until the next user turn (#2295)

DavdGao393e029df799
diff --git a/src/agentscope/app/_bus_ops.py b/src/agentscope/app/_bus_ops.py
index a17d43ec4..4cce280b2 100644
--- a/src/agentscope/app/_bus_ops.py
+++ b/src/agentscope/app/_bus_ops.py
@@ -136,6 +136,192 @@ async def enqueue_run_trigger(
await bus.publish(MessageBusKeys.wakeup_signal(), {})
+# ── session inbox hand-off ─────────────────────────────────────────────
+#
+# Three helpers implementing one protocol, whose only job is to make
+# sure a payload pushed to a session inbox is always consumed by *some*
+# run rather than sitting there until the next user turn.
+#
+# The naive version — "push, then wake the session unless it looks
+# busy" — loses entries: a run that already performed its last drain is
+# still busy (it is streaming, persisting, releasing its lock), so the
+# producer skips the wake-up while the run will never look again.
+#
+# The fix is to make two tiny critical sections mutually exclusive
+# under :meth:`MessageBusKeys.inbox_lock`:
+#
+# producer push entry → read consumer flag
+# consumer drain remaining entries → clear consumer flag
+#
+# Whichever runs first, the entry is covered. Producer first → the
+# consumer's drain sees the entry and keeps going. Consumer first →
+# the flag is already clear, so the producer enqueues a wake-up.
+# Because the wake-up is only produced when no consumer is registered,
+# it never spawns a run that has nothing to do.
+
+
+async def deliver_to_inbox(
+ bus: "MessageBus",
+ *,
+ user_id: str,
+ session_id: str,
+ agent_id: str,
+ payload: dict,
+) -> None:
+ """Push a payload to a session inbox and wake the session if no run
+ is currently consuming it.
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ user_id (`str`):
+ The owning user id.
+ session_id (`str`):
+ The session whose inbox receives the payload.
+ agent_id (`str`):
+ The agent that owns the session.
+ payload (`dict`):
+ JSON-serialisable payload, normally a serialised
+ :class:`~agentscope.message.HintBlock`.
+ """
+ async with bus.acquire_lock(
+ MessageBusKeys.inbox_lock(session_id),
+ ttl_secs=MessageBusKeys.INBOX_LOCK_TTL_SECS,
+ ):
+ await bus.queue_push(MessageBusKeys.inbox(session_id), payload)
+ consumer = await bus.registry_get(
+ MessageBusKeys.inbox_consumer(session_id),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ )
+
+ if consumer is None:
+ await enqueue_run_trigger(
+ bus,
+ user_id=user_id,
+ session_id=session_id,
+ agent_id=agent_id,
+ )
+
+
+async def register_inbox_consumer(bus: "MessageBus", session_id: str) -> None:
+ """Mark this run as the consumer of ``session_id``'s inbox.
+
+ Call once per run, as early as possible — any producer that pushes
+ after this point relies on this run draining the entry rather than
+ enqueueing its own wake-up.
+
+ The flag carries the same lease as a chat run, so a process that
+ dies mid-run stops suppressing wake-ups once the lease expires.
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ session_id (`str`):
+ The session being consumed.
+ """
+ await bus.registry_set(
+ MessageBusKeys.inbox_consumer(session_id),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ "1",
+ ttl_secs=MessageBusKeys.SESSION_RUN_TTL_SECS,
+ )
+
+
+async def has_pending_inbox_or_release(
+ bus: "MessageBus",
+ session_id: str,
+) -> bool:
+ """Report whether the inbox still holds anything, releasing the
+ consumer registration when it does not.
+
+ Call at the very end of a run, before it releases the session lock.
+ ``True`` means the run must go around once more — it stays
+ registered as the consumer, so producers keep deferring to it
+ instead of enqueuing their own wake-up. ``False`` means the run may
+ finish: the registration is gone, so the next producer wakes the
+ session itself.
+
+ The check reads by draining and putting everything straight back,
+ because the bus deliberately exposes no non-destructive peek. Both
+ halves happen under :meth:`MessageBusKeys.inbox_lock`, which every
+ producer also holds while pushing, so nothing can slip in between
+ and arrival order is preserved.
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ session_id (`str`):
+ The session being consumed.
+
+ Returns:
+ `bool`:
+ ``True`` when payloads remain to be consumed.
+ """
+ inbox = MessageBusKeys.inbox(session_id)
+ async with bus.acquire_lock(
+ MessageBusKeys.inbox_lock(session_id),
+ ttl_secs=MessageBusKeys.INBOX_LOCK_TTL_SECS,
+ ):
+ payloads: list[dict] = []
+ while True:
+ batch = await bus.queue_drain(inbox, max_count=100)
+ if not batch:
+ break
+ payloads.extend(payload for _entry_id, payload in batch)
+
+ if not payloads:
+ await bus.registry_del(
+ MessageBusKeys.inbox_consumer(session_id),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ )
+ return False
+
+ for payload in payloads:
+ await bus.queue_push(inbox, payload)
+ return True
+
+
+async def abandon_inbox_consumer(
+ bus: "MessageBus",
+ *,
+ user_id: str,
+ session_id: str,
+ agent_id: str,
+) -> None:
+ """Give up the consumer registration without having drained the
+ inbox, waking the session when payloads are still queued.
+
+ Used when a run ends abnormally — an interrupt, a cancelled task, a
+ failed turn. Producers deferred to this run while it was
+ registered, so it cannot simply drop the registration and leave
+ their payloads unattended.
+
+ Args:
+ bus (`MessageBus`):
+ The application message bus.
+ user_id (`str`):
+ The owning user id.
+ session_id (`str`):
+ The session being abandoned.
+ agent_id (`str`):
+ The agent that owns the session.
+ """
+ pending = await has_pending_inbox_or_release(bus, session_id)
+ if not pending:
+ return
+
+ await bus.registry_del(
+ MessageBusKeys.inbox_consumer(session_id),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ )
+ await enqueue_run_trigger(
+ bus,
+ user_id=user_id,
+ session_id=session_id,
+ agent_id=agent_id,
+ )
+
+
# ── enqueue_index_task ─────────────────────────────────────────────────
diff --git a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
index 18aa81acf..68f8e5854 100644
--- a/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
+++ b/src/agentscope/app/_manager/_scheduler/_scheduler_manager.py
@@ -11,8 +11,8 @@ from ....state import AgentState
from ....tool import ToolBase
from ...._logging import logger
from ._tools import ScheduleCreate, ScheduleDelete, ScheduleList, ScheduleView
-from ...message_bus import MessageBus, MessageBusKeys
-from ..._bus_ops import enqueue_run_trigger
+from ...message_bus import MessageBus
+from ..._bus_ops import deliver_to_inbox
from ...storage import (
StorageBase,
ScheduleRecord,
@@ -233,15 +233,12 @@ class SchedulerManager:
ensure_ascii=False,
),
)
- await message_bus.queue_push(
- MessageBusKeys.inbox(session.id),
- hint.model_dump(mode="json"),
- )
- await enqueue_run_trigger(
+ await deliver_to_inbox(
message_bus,
user_id=record.user_id,
session_id=session.id,
agent_id=record.agent_id,
+ payload=hint.model_dump(mode="json"),
)
logger.info(
diff --git a/src/agentscope/app/_manager/_wakeup_dispatcher.py b/src/agentscope/app/_manager/_wakeup_dispatcher.py
index 1144a6f03..d706dc057 100644
--- a/src/agentscope/app/_manager/_wakeup_dispatcher.py
+++ b/src/agentscope/app/_manager/_wakeup_dispatcher.py
@@ -12,13 +12,15 @@ funnels through this one serial consumer.
Each queue entry carries a ``kind`` that selects how a busy session is
handled:
-- ``wake`` (idle-session wake-up, ``input_msg=None``): skipped while the
- session is already running — the live run will drain the inbox.
-- ``resume`` (a parked HITL run being fed its result): must *not* be
- skipped while running, because the session is typically still running
- the parked tail at trigger time. It is re-queued after a short backoff
- until the parked run releases its session lock, then spawned with the
- carried input event.
+- ``wake`` (idle-session wake-up, ``input_msg=None``): produced only
+ when no run is registered as the session's inbox consumer, so it
+ always has something to deliver.
+- ``resume`` (a parked HITL run being fed its result): carries the
+ event the parked run is waiting for.
+
+No kind is ever dropped. A trigger whose session still holds its run
+lock is re-queued after a short backoff until the lock frees, then
+spawned.
All bus keys live on the :class:`MessageBus` base class (see
``enqueue_wakeup`` / ``enqueue_input``, ``dequeue_wakeups``,
@@ -54,10 +56,9 @@ _RESUME_INPUT_ADAPTER: TypeAdapter = TypeAdapter(
UserConfirmResultEvent | ExternalExecutionResultEvent | UserInterruptEvent,
)
-# Delay before re-queuing a ``resume`` trigger whose target session is
-# still running (the parked run is finishing and about to free its
-# lock). Short enough to feel instant to the user, long enough to avoid
-# a hot re-enqueue loop while the lock is held.
+# Delay before re-queuing a trigger whose target session still holds
+# its run lock. Short enough to feel instant to the user, long enough
+# to avoid a hot re-enqueue loop while the lock is held.
_RESUME_RETRY_BACKOFF_SECS = 0.1
@@ -274,19 +275,21 @@ class WakeupDispatcher:
if await self._bus.is_locked(
MessageBusKeys.session_lock(session_id),
):
- if carries_input:
- # The session is busy. Do NOT drop input-carrying triggers
- # — re-queue after a short backoff so they land once the
- # running turn releases its lock.
- self._schedule_input_retry(
- user_id,
- session_id,
- agent_id,
- kind,
- input_msg,
- )
- # ``wake`` triggers are safe to drop while running — the
- # live run drains the inbox itself.
+ # The session is busy, so nothing can be spawned right now:
+ # re-queue after a short backoff rather than dropping.
+ #
+ # ``wake`` needs this as much as the input-carrying kinds. A
+ # producer only enqueues one after finding no registered
+ # inbox consumer, which a finished run gives up *before* it
+ # releases the session lock — so a held lock is no evidence
+ # that anyone is still going to drain the inbox.
+ self._schedule_retry(
+ user_id,
+ session_id,
+ agent_id,
+ kind,
+ input_msg,
+ )
return
# Orphan guard: the queue is unaware of session lifecycle. A
@@ -338,24 +341,18 @@ class WakeupDispatcher:
)
except RuntimeError:
# A local run was registered between the running-check and
- # the spawn. For ``wake`` that run will drain the inbox; for
- # input-carrying kinds re-queue so the input is not lost.
- if carries_input:
- self._schedule_input_retry(
- user_id,
- session_id,
- agent_id,
- kind,
- input_msg,
- )
- else:
- logger.debug(
- "WakeupDispatcher: skipping wake trigger for session "
- "%s; a local run is already registered.",
- session_id,
- )
+ # the spawn. Re-queue so neither the carried input nor a
+ # queued inbox payload is stranded — that run may already be
+ # past its last drain.
+ self._schedule_retry(
+ user_id,
+ session_id,
+ agent_id,
+ kind,
+ input_msg,
+ )
- def _schedule_input_retry(
+ def _schedule_retry(
self,
user_id: str,
session_id: str,
diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.py
index cb6729571..3ba67483b 100644
--- a/src/agentscope/app/_service/_chat.py
+++ b/src/agentscope/app/_service/_chat.py
@@ -18,9 +18,12 @@ from typing import TYPE_CHECKING
from fastapi import HTTPException
from .._bus_ops import (
+ abandon_inbox_consumer,
enqueue_channel_output,
enqueue_run_trigger,
+ has_pending_inbox_or_release,
publish_session_event,
+ register_inbox_consumer,
)
from ..message_bus import MessageBus, MessageBusKeys
from ..rag.knowledge_base_manager import KnowledgeBaseManagerBase
@@ -816,161 +819,232 @@ optional):
agent_id=agent_id,
)
reply_msg: Msg | None = None
+ reply_msgs: list[Msg] = []
+ released = False
+ await register_inbox_consumer(self._message_bus, session_id)
try:
- if input_msg is None or isinstance(input_msg, (Msg, list)):
- # Case A: new reply (user message(s), or retrigger with
- # empty input)
- if isinstance(input_msg, (Msg, list)):
- input_msgs = (
- [input_msg]
- if isinstance(input_msg, Msg)
- else input_msg
- )
- for msg in input_msgs:
- await self._storage.upsert_message(
+ while True:
+ reply_msg = None
+ try:
+ if input_msg is None or isinstance(
+ input_msg,
+ (Msg, list),
+ ):
+ # Case A: new reply (user message(s), or
+ # retrigger with empty input)
+ if isinstance(input_msg, (Msg, list)):
+ input_msgs = (
+ [input_msg]
+ if isinstance(input_msg, Msg)
+ else input_msg
+ )
+ for msg in input_msgs:
+ await self._storage.upsert_message(
+ user_id,
+ session_id,
+ msg,
+ )
+
+ async for event in agent.reply_stream(
+ inputs=input_msg,
+ ):
+ # Apply to reply_msg FIRST (sync — never
+ # interrupted), so an interrupt in the
+ # awaits below can't lose this event.
+ if isinstance(event, ReplyStartEvent):
+ reply_msg = AssistantMsg(
+ id=event.reply_id,
+ name=event.name,
+ content=[],
+ )
+ elif reply_msg is not None:
+ reply_msg.append_event(event)
+ try:
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ event.model_dump(mode="json"),
+ )
+ await self._project_event(
+ user_id,
+ session_record,
+ agent_record,
+ event,
+ )
+ except asyncio.CancelledError:
+ # Interrupt landed here, not at
+ # ``__anext__``. Re-arm it so it is
+ # redelivered into the agent at the
+ # next ``__anext__`` (which runs its
+ # interruption cleanup) instead of
+ # abandoning the generator and
+ # dropping that cleanup.
+ current = asyncio.current_task()
+ if current is not None:
+ current.cancel()
+
+ else:
+ # Case B: continuation (UserConfirmResult
+ # / ExternalExecResult)
+ reply_msg = await self._storage.get_message(
user_id,
session_id,
- msg,
+ agent.state.reply_id,
)
- async for event in agent.reply_stream(inputs=input_msg):
- # Apply to reply_msg FIRST (sync — never
- # interrupted), so an interrupt in the awaits below
- # can't lose this event.
- if isinstance(event, ReplyStartEvent):
- reply_msg = AssistantMsg(
- id=event.reply_id,
- name=event.name,
- content=[],
+ if reply_msg is None:
+ logger.warning(
+ "Reply message %r not found in "
+ "storage for session %r; tool-call "
+ "state changes from the incoming "
+ "event will not be persisted.",
+ agent.state.reply_id,
+ session_id,
+ )
+ elif input_msg:
+ reply_msg.append_event(input_msg)
+
+ # Broadcast the applied decision so
+ # observers that didn't make it (other tabs,
+ # the channel card) close it.
+ if isinstance(
+ input_msg,
+ (
+ UserConfirmResultEvent,
+ ExternalExecutionResultEvent,
+ ),
+ ):
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ input_msg.model_dump(mode="json"),
+ )
+
+ # Emit a synthetic REPLY_START so SSE subscribers
+ # (frontend, channel gateway) can detect the
+ # continuation without requiring special handling.
+ #
+ # IMPORTANT: The frontend SSE handler must
+ # NOT clear its accumulated message buffer
+ # upon receiving a
+ # REPLY_START with the same reply_id as the current
+ # message. This event signals a continuation (e.g.
+ # after an approval flow), not a fresh reply.
+ continuation_start = ReplyStartEvent(
+ session_id=session_id,
+ reply_id=agent.state.reply_id,
+ name=agent_record.data.name,
)
- elif reply_msg is not None:
- reply_msg.append_event(event)
- try:
await publish_session_event(
self._message_bus,
session_id,
- event.model_dump(mode="json"),
+ continuation_start.model_dump(mode="json"),
)
- await self._project_event(
+
+ async for event in agent.reply_stream(
+ inputs=input_msg,
+ ):
+ # Apply to the persisted reply FIRST
+ # (synchronous), then publish/project —
+ # see Case A above.
+ if reply_msg is not None:
+ reply_msg.append_event(event)
+ try:
+ await publish_session_event(
+ self._message_bus,
+ session_id,
+ event.model_dump(mode="json"),
+ )
+ await self._project_event(
+ user_id,
+ session_record,
+ agent_record,
+ event,
+ )
+ except asyncio.CancelledError:
+ # See Case A: redirect an interrupt
+ # landing here back into the agent
+ # via the next ``__anext__``.
+ current = asyncio.current_task()
+ if current is not None:
+ current.cancel()
+
+ except Exception as e: # pylint: disable=broad-except
+ # CancelledError is a BaseException, so interrupts are
+ # unaffected. The lock is already held here, so the
+ # reporter is called directly.
+ if reply_msg is None:
+ # Failed before REPLY_START: nothing to close, so a
+ # fresh reply carries the failure instead.
+ await self._report_failure(
user_id,
- session_record,
- agent_record,
- event,
+ session_id,
+ agent_id,
+ e,
+ )
+ else:
+ await self._close_failed_reply(
+ session_id,
+ reply_msg,
+ e,
)
- except asyncio.CancelledError:
- # Interrupt landed here, not at ``__anext__``.
- # Re-arm it so it's redelivered into the agent at
- # the next ``__anext__`` (which runs its
- # interruption cleanup) instead of abandoning the
- # generator and dropping that cleanup.
- current = asyncio.current_task()
- if current is not None:
- current.cancel()
-
- else:
- # Case B: continuation (UserConfirmResult
- # / ExternalExecResult)
- reply_msg = await self._storage.get_message(
- user_id,
- session_id,
- agent.state.reply_id,
- )
- if reply_msg is None:
- logger.warning(
- "Reply message %r not found in storage for "
- "session %r; tool-call state changes from the "
- "incoming event will not be persisted.",
- agent.state.reply_id,
- session_id,
- )
- elif input_msg:
- reply_msg.append_event(input_msg)
-
- # Broadcast the applied decision so observers that
- # didn't make it (other tabs, the channel card) close it.
- if isinstance(
- input_msg,
- (UserConfirmResultEvent, ExternalExecutionResultEvent),
- ):
- await publish_session_event(
- self._message_bus,
- session_id,
- input_msg.model_dump(mode="json"),
- )
+ # A failed turn stops the run; whatever is still
+ # queued is handed to a fresh one by the
+ # ``released`` cleanup below.
+ if reply_msg is not None:
+ reply_msgs.append(reply_msg)
+ break
- # Emit a synthetic REPLY_START so SSE subscribers
- # (frontend, channel gateway) can detect the
- # continuation without requiring special handling.
- #
- # IMPORTANT: The frontend SSE handler must NOT clear
- # its accumulated message buffer upon receiving a
- # REPLY_START with the same reply_id as the current
- # message. This event signals a continuation (e.g.
- # after an approval flow), not a fresh reply.
- continuation_start = ReplyStartEvent(
- session_id=session_id,
- reply_id=agent.state.reply_id,
- name=agent_record.data.name,
- )
- await publish_session_event(
+ if reply_msg is not None:
+ reply_msgs.append(reply_msg)
+
+ # Still holding the session lock: anything that
+ # landed in the inbox after this turn's last drain
+ # is this run's to handle — no producer will have
+ # woken the session while it was registered as the
+ # consumer.
+ if not await has_pending_inbox_or_release(
self._message_bus,
session_id,
- continuation_start.model_dump(mode="json"),
- )
-
- async for event in agent.reply_stream(inputs=input_msg):
- # Apply to the persisted reply FIRST (synchronous),
- # then publish/project — see Case A above.
- if reply_msg is not None:
- reply_msg.append_event(event)
- try:
- await publish_session_event(
- self._message_bus,
- session_id,
- event.model_dump(mode="json"),
- )
- await self._project_event(
- user_id,
- session_record,
- agent_record,
- event,
- )
- except asyncio.CancelledError:
- # See Case A: redirect an interrupt landing here
- # back into the agent via the next ``__anext__``.
- current = asyncio.current_task()
- if current is not None:
- current.cancel()
+ ):
+ released = True
+ break
+ input_msg = None
- except Exception as e: # pylint: disable=broad-except
- # CancelledError is a BaseException, so interrupts are
- # unaffected. The lock is already held here, so the
- # reporter is called directly.
- if reply_msg is None:
- # Failed before REPLY_START: nothing to close, so a
- # fresh reply carries the failure instead.
- await self._report_failure(
- user_id,
- session_id,
- agent_id,
- e,
+ finally:
+ # An interrupt unwinds past the loop's own exit check, so
+ # the run may still be registered as the inbox consumer.
+ # Hand the registration back and wake the session when
+ # payloads are still queued, otherwise they would wait
+ # for an unrelated trigger.
+ if not released:
+ await abandon_inbox_consumer(
+ self._message_bus,
+ user_id=user_id,
+ session_id=session_id,
+ agent_id=agent_id,
)
- else:
- await self._close_failed_reply(session_id, reply_msg, e)
- finally:
+ # The last turn's reply is only in ``reply_msgs`` when the
+ # loop reached its own bookkeeping — an interrupt lands
+ # here instead, so add it now.
+ if reply_msg is not None and (
+ not reply_msgs or reply_msgs[-1] is not reply_msg
+ ):
+ reply_msgs.append(reply_msg)
+
# All persistence in a single coroutine, shielded from
# outer cancellation. Must complete BEFORE the session
# lock is released — otherwise another worker could
# acquire the lock and load a stale state from storage
# before this write lands.
async def _persist() -> None:
- if reply_msg is not None:
+ for msg in reply_msgs:
await self._storage.upsert_message(
user_id,
session_id,
- reply_msg,
+ msg,
)
await self._storage.update_session_state(
user_id=user_id,
diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.py
index 1973e0c0a..d4130154e 100644
--- a/src/agentscope/app/_tool/_agent_create.py
+++ b/src/agentscope/app/_tool/_agent_create.py
@@ -10,8 +10,7 @@ from pydantic import Field
from ._team_tool_base import _TeamToolBase
from .._types import SubAgentTemplate
-from ..message_bus import MessageBusKeys
-from .._bus_ops import enqueue_run_trigger
+from .._bus_ops import deliver_to_inbox
from ..storage import AgentData, AgentRecord, SessionConfig, TeamMember
from ..storage._utils import _ensure_team_members
from ...message import HintBlock, TextBlock, ToolResultState
@@ -546,15 +545,12 @@ optional):
ensure_ascii=False,
),
)
- await self._message_bus.queue_push(
- MessageBusKeys.inbox(worker_session.id),
- hint.model_dump(mode="json"),
- )
- await enqueue_run_trigger(
+ await deliver_to_inbox(
self._message_bus,
user_id=self._user_id,
session_id=worker_session.id,
agent_id=worker_agent.id,
+ payload=hint.model_dump(mode="json"),
)
return ToolChunk(
diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.py
index 1116a05ec..b6420dfb0 100644
--- a/src/agentscope/app/_tool/_agent_invite.py
+++ b/src/agentscope/app/_tool/_agent_invite.py
@@ -24,8 +24,7 @@ from pydantic import Field
from ._constants import HANDLE_LEN
from ._team_tool_base import _TeamToolBase
-from ..message_bus import MessageBusKeys
-from .._bus_ops import enqueue_run_trigger
+from .._bus_ops import deliver_to_inbox
from ..storage import SessionConfig, TeamMember
from ..storage._utils import _ensure_team_members
from ...message import HintBlock, TextBlock, ToolResultState
@@ -455,15 +454,12 @@ class AgentInvite(_TeamToolBase):
ensure_ascii=False,
),
)
- await self._message_bus.queue_push(
- MessageBusKeys.inbox(borrowed.id),
- hint.model_dump(mode="json"),
- )
- await enqueue_run_trigger(
+ await deliver_to_inbox(
self._message_bus,
user_id=self._user_id,
session_id=borrowed.id,
agent_id=invited.id,
+ payload=hint.model_dump(mode="json"),
)
return ToolChunk(
diff --git a/src/agentscope/app/_tool/_team_say.py b/src/agentscope/app/_tool/_team_say.py
index 7effe868f..7aeb00752 100644
--- a/src/agentscope/app/_tool/_team_say.py
+++ b/src/agentscope/app/_tool/_team_say.py
@@ -7,8 +7,7 @@ from pydantic import Field
from ._constants import HANDLE_LEN
from ._team_tool_base import _TeamToolBase
-from ..message_bus import MessageBusKeys
-from .._bus_ops import enqueue_run_trigger
+from .._bus_ops import deliver_to_inbox
from ..storage._utils import _ensure_team_members
from ...message import HintBlock, TextBlock, ToolResultState
from ...tool import ToolChunk, ParamsBase
@@ -326,15 +325,12 @@ class TeamSay(_TeamToolBase):
payload = hint.model_dump(mode="json")
for sid, aid in recipients:
- await self._message_bus.queue_push(
- MessageBusKeys.inbox(sid),
- payload,
- )
- await enqueue_run_trigger(
+ await deliver_to_inbox(
self._message_bus,
user_id=self._user_id,
session_id=sid,
agent_id=aid,
+ payload=payload,
)
count = len(recipients)
diff --git a/src/agentscope/app/message_bus/_keys.py b/src/agentscope/app/message_bus/_keys.py
index b20c267bb..b1d95da8b 100644
--- a/src/agentscope/app/message_bus/_keys.py
+++ b/src/agentscope/app/message_bus/_keys.py
@@ -150,12 +150,48 @@ class MessageBusKeys: # pylint: disable=too-many-public-methods
# ------------------------------------------------------------------
_INBOX = "agentscope:inbox:{sid}"
+ _INBOX_LOCK = "agentscope:inbox:lock:{sid}"
+ _INBOX_CONSUMER = "agentscope:inbox:consumer:{sid}"
+
+ INBOX_LOCK_TTL_SECS = 30
+ """Lease for the inbox hand-off lock. The critical sections it
+ guards are a single queue op plus a single registry op, so a lease
+ this short only ever matters when a process dies inside one."""
+
+ INBOX_CONSUMER_FIELD = "running"
+ """Field name inside the per-session inbox-consumer registry."""
@classmethod
def inbox(cls, session_id: str) -> str:
"""Per-session inbox drain-queue key."""
return cls._INBOX.format(sid=session_id)
+ @classmethod
+ def inbox_lock(cls, session_id: str) -> str:
+ """Per-session lock serialising inbox hand-off.
+
+ Held only around two tiny critical sections — the producer's
+ "push then read consumer flag" and the consumer's "drain then
+ clear consumer flag". Making those two mutually exclusive is
+ what stops an entry pushed just as a run finishes from being
+ both missed by that run and skipped by the producer's wake-up
+ decision.
+ """
+ return cls._INBOX_LOCK.format(sid=session_id)
+
+ @classmethod
+ def inbox_consumer(cls, session_id: str) -> str:
+ """Per-session registry recording whether a run is currently
+ consuming this inbox.
+
+ Deliberately **not** derived from
+ :meth:`session_lock` — the lock is still held while a finished
+ run persists its state, and during that window no further drain
+ will happen, so producers must already treat the session as
+ having no consumer.
+ """
+ return cls._INBOX_CONSUMER.format(sid=session_id)
+
# ------------------------------------------------------------------
# Run trigger queue (wakeup / resume)
# ------------------------------------------------------------------
diff --git a/src/agentscope/app/middleware/_tool_offload_middleware.py b/src/agentscope/app/middleware/_tool_offload_middleware.py
index 3c5845934..257e37316 100644
--- a/src/agentscope/app/middleware/_tool_offload_middleware.py
+++ b/src/agentscope/app/middleware/_tool_offload_middleware.py
@@ -34,8 +34,8 @@ from ...message import (
ToolResultState,
)
from ...agent import Agent
-from ..message_bus import MessageBus, MessageBusKeys
-from .._bus_ops import enqueue_run_trigger
+from ..message_bus import MessageBus
+from .._bus_ops import deliver_to_inbox
from ..._logging import logger
@@ -345,15 +345,12 @@ class ToolOffloadMiddleware(MiddlewareBase): # pylint: disable=abstract-method
tool_name,
session_id,
)
- await self._message_bus.queue_push(
- MessageBusKeys.inbox(session_id),
- hint.model_dump(mode="json"),
- )
- await enqueue_run_trigger(
+ await deliver_to_inbox(
self._message_bus,
user_id=self._user_id,
session_id=session_id,
agent_id=self._agent_id,
+ payload=hint.model_dump(mode="json"),
)
asyncio.create_task(_deliver_when_done())
diff --git a/tests/service_inbox_handoff_test.py b/tests/service_inbox_handoff_test.py
new file mode 100644
index 000000000..9cd0e1574
--- /dev/null
+++ b/tests/service_inbox_handoff_test.py
@@ -0,0 +1,162 @@
+# -*- coding: utf-8 -*-
+"""Tests for the session-inbox hand-off protocol in ``_bus_ops``.
+
+The protocol exists so a payload pushed to a session inbox is always
+consumed by *some* run, instead of sitting there until the next user
+turn. Producers and the finishing run coordinate through one lock:
+
+- :func:`deliver_to_inbox` pushes, then wakes the session only when no
+ run is registered as its consumer.
+- :func:`has_pending_inbox_or_release` lets a finishing run take one
+ more look and, finding nothing, stop being that consumer.
+
+The tests below cover both orderings of that race plus the abnormal
+exit path.
+"""
+import asyncio
+from contextlib import AsyncExitStack
+from unittest import IsolatedAsyncioTestCase
+
+from agentscope.app._bus_ops import (
+ abandon_inbox_consumer,
+ deliver_to_inbox,
+ has_pending_inbox_or_release,
+ register_inbox_consumer,
+)
+from agentscope.app.message_bus import InMemoryMessageBus, MessageBusKeys
+
+
+class TestInboxHandoff(IsolatedAsyncioTestCase):
+ """Producer / finishing-run hand-off around a session inbox."""
+
+ async def asyncSetUp(self) -> None:
+ self._stack = AsyncExitStack()
+ self.bus = await self._stack.enter_async_context(InMemoryMessageBus())
+ self.sid = "sess-1"
+
+ async def asyncTearDown(self) -> None:
+ await self._stack.aclose()
+
+ async def _wakeups(self) -> list[dict]:
+ """Drain and return the trigger queue payloads."""
+ entries = await self.bus.queue_drain(MessageBusKeys.wakeup_queue())
+ return [payload for _entry_id, payload in entries]
+
+ async def _deliver(self, text: str) -> None:
+ """Push one payload through the producer helper."""
+ await deliver_to_inbox(
+ self.bus,
+ user_id="u",
+ session_id=self.sid,
+ agent_id="a",
+ payload={"type": "hint", "hint": text},
+ )
+
+ async def test_no_consumer_pushes_and_wakes(self) -> None:
+ """With nobody consuming, a delivery enqueues a wake-up."""
+ await self._deliver("hello")
+
+ self.assertEqual(len(await self._wakeups()), 1)
+ entries = await self.bus.queue_drain(MessageBusKeys.inbox(self.sid))
+ self.assertEqual([p["hint"] for _i, p in entries], ["hello"])
+
+ async def test_registered_consumer_suppresses_wakeup(self) -> None:
+ """A registered consumer is expected to drain it itself, so no
+ wake-up is enqueued."""
+ await register_inbox_consumer(self.bus, self.sid)
+ await self._deliver("hello")
+
+ self.assertEqual(await self._wakeups(), [])
+
+ async def test_pending_payload_keeps_consumer_registered(self) -> None:
+ """A run finding leftovers stays the consumer and keeps them
+ queued, in arrival order, for its next turn."""
+ await register_inbox_consumer(self.bus, self.sid)
+ await self._deliver("first")
+ await self._deliver("second")
+
+ self.assertTrue(
+ await has_pending_inbox_or_release(self.bus, self.sid),
+ )
+ self.assertIsNotNone(
+ await self.bus.registry_get(
+ MessageBusKeys.inbox_consumer(self.sid),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ ),
+ )
+ entries = await self.bus.queue_drain(MessageBusKeys.inbox(self.sid))
+ self.assertEqual(
+ [p["hint"] for _i, p in entries],
+ ["first", "second"],
+ )
+
+ async def test_empty_inbox_releases_consumer(self) -> None:
+ """An empty inbox releases the registration, so the next
+ delivery wakes the session instead of deferring to this run."""
+ await register_inbox_consumer(self.bus, self.sid)
+
+ self.assertFalse(
+ await has_pending_inbox_or_release(self.bus, self.sid),
+ )
+ self.assertIsNone(
+ await self.bus.registry_get(
+ MessageBusKeys.inbox_consumer(self.sid),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ ),
+ )
+
+ await self._deliver("after release")
+ self.assertEqual(len(await self._wakeups()), 1)
+
+ async def test_delivery_during_release_is_not_stranded(self) -> None:
+ """The race this protocol exists for: a payload pushed just as a
+ run finishes is either seen by that run's last look or wakes the
+ session — never neither."""
+ await register_inbox_consumer(self.bus, self.sid)
+
+ release = asyncio.create_task(
+ has_pending_inbox_or_release(self.bus, self.sid),
+ )
+ deliver = asyncio.create_task(self._deliver("racing"))
+ pending, _ = await asyncio.gather(release, deliver)
+
+ wakeups = await self._wakeups()
+ # Exactly one of the two outcomes, never zero: either the run
+ # keeps going (it saw the payload), or a wake-up was enqueued.
+ self.assertEqual(pending, not wakeups)
+ # The payload itself is still queued for whoever handles it.
+ entries = await self.bus.queue_drain(MessageBusKeys.inbox(self.sid))
+ self.assertEqual([p["hint"] for _i, p in entries], ["racing"])
+
+ async def test_abandon_wakes_when_payloads_remain(self) -> None:
+ """A run that dies mid-turn hands its leftovers to a fresh run."""
+ await register_inbox_consumer(self.bus, self.sid)
+ await self._deliver("unhandled")
+
+ await abandon_inbox_consumer(
+ self.bus,
+ user_id="u",
+ session_id=self.sid,
+ agent_id="a",
+ )
+
+ self.assertEqual(len(await self._wakeups()), 1)
+ self.assertIsNone(
+ await self.bus.registry_get(
+ MessageBusKeys.inbox_consumer(self.sid),
+ MessageBusKeys.INBOX_CONSUMER_FIELD,
+ ),
+ )
+
+ async def test_abandon_with_empty_inbox_does_not_wake(self) -> None:
+ """Nothing left means nothing to hand over — and no empty run."""
+ await register_inbox_consumer(self.bus, self.sid)
+
+ await abandon_inbox_consumer(
+ self.bus,
+ user_id="u",
+ session_id=self.sid,
+ agent_id="a",
+ )
+
+ self.assertEqual(await self._wakeups(), [])
diff --git a/tests/service_wakeup_dispatcher_test.py b/tests/service_wakeup_dispatcher_test.py
index 03b456485..c945bf5b7 100644
--- a/tests/service_wakeup_dispatcher_test.py
+++ b/tests/service_wakeup_dispatcher_test.py
@@ -288,8 +288,8 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):
],
)
- async def test_active_session_skipped(self) -> None:
- """If the target session is already running, no chat run is
+ async def test_active_session_not_spawned_while_locked(self) -> None:
+ """While the target session holds its run lock, no chat run is
spawned for it."""
bus = _FakeBus()
chat = _FakeChatService()
@@ -470,6 +470,42 @@ class TestWakeupDispatcherDispatch(IsolatedAsyncioTestCase):
UserConfirmResultEvent,
)
+ async def test_wake_running_session_requeues_until_free(self) -> None:
+ """A ``wake`` whose target is still running is NOT dropped.
+
+ Producers only enqueue one after finding no registered inbox
+ consumer, and a finishing run gives that registration up before
+ releasing its session lock — so a held lock is no evidence that
+ anything is still going to drain the inbox. Dropping here is
+ what used to strand a payload until the next user turn.
+ """
+ bus = _FakeBus()
+ chat = _FakeChatService()
+ lock_key = MessageBus._SESSION_LOCK_KEY.format(sid="w2")
+ bus._locks.add(lock_key)
+
+ async with WakeupDispatcher(
+ message_bus=bus,
+ storage=_FakeStorage(),
+ chat_service=chat,
+ chat_run_registry=ChatRunRegistry(),
+ ):
+ await bus.queue_push(
+ MessageBusKeys.wakeup_queue(),
+ {"user_id": "u", "session_id": "w2", "agent_id": "wa2"},
+ )
+ await bus.publish(MessageBusKeys.wakeup_signal(), {})
+
+ await asyncio.sleep(0.25)
+ self.assertEqual(chat.calls, [])
+
+ bus._locks.discard(lock_key)
+ await asyncio.wait_for(chat.notify.wait(), timeout=2.0)
+
+ self.assertEqual(len(chat.calls), 1)
+ self.assertEqual(chat.calls[0]["session_id"], "w2")
+ self.assertIsNone(chat.calls[0]["input_msg"])
+
class TestWakeupDispatcherLifecycle(IsolatedAsyncioTestCase):
"""Tests covering the ``__aenter__`` / ``__aexit__`` ACM behaviour."""
diff --git a/tests/tool_offload_middleware_test.py b/tests/tool_offload_middleware_test.py
index 9e7bfc9b3..7bb6bfab6 100644
--- a/tests/tool_offload_middleware_test.py
+++ b/tests/tool_offload_middleware_test.py
@@ -5,7 +5,7 @@ import asyncio
import json
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
from pydantic import BaseModel
@@ -177,9 +177,15 @@ class ToolOffloadMiddlewareTest(IsolatedAsyncioTestCase):
`tuple[Agent, ToolOffloadMiddleware]`:
The configured agent and the middleware instance.
"""
+ # No run is registered as this session's inbox consumer, so a
+ # completed background tool is expected to wake the session.
+ # ``spec`` alone would hand back a truthy sentinel and make the
+ # delivery look like somebody was already going to drain it.
+ message_bus = MagicMock(spec=MessageBus)
+ message_bus.registry_get = AsyncMock(return_value=None)
middleware = ToolOffloadMiddleware(
bg_manager=self.bg_manager,
- message_bus=MagicMock(spec=MessageBus),
+ message_bus=message_bus,
user_id="u",
agent_id="a",
timeout_secs=timeout_secs,