fix(agent): serialize session inbox processing
This commit is contained in:
1 parent
56f7afcfe4
commit
4e2173c9eb
7 files changed
+486
-359
No files matched your search
+96
-80
@@ -29,12 +29,7 @@ from nanobot.agent.cron_turns import CronTurnCoordinator
|
||||
from nanobot.agent.hook import AgentHook, AgentTurnHookFactory
|
||||
from nanobot.agent.memory import Consolidator
|
||||
from nanobot.agent.model_runtime import ModelRuntimeResolver
|
||||
from nanobot.agent.runner import (
|
||||
_MAX_INJECTIONS_PER_TURN,
|
||||
AgentRunner,
|
||||
AgentRunResult,
|
||||
AgentRunSpec,
|
||||
)
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunResult, AgentRunSpec
|
||||
from nanobot.agent.subagent import SubagentManager
|
||||
from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context
|
||||
from nanobot.agent.tools.exec_session import ExecSessionManager
|
||||
@@ -403,9 +398,9 @@ class AgentLoop:
|
||||
self._session_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = (
|
||||
weakref.WeakValueDictionary()
|
||||
)
|
||||
# Per-session pending queues for mid-turn message injection.
|
||||
# When a session has an active task, new messages for that session
|
||||
# are routed here instead of creating a new task.
|
||||
# A queue is installed before its single session worker is scheduled.
|
||||
# It remains the only admission path until that worker atomically
|
||||
# observes the queue empty and removes it.
|
||||
self._pending_queues: dict[str, asyncio.Queue[InboundMessage]] = {}
|
||||
self._preserve_inflight_turns_on_shutdown = False
|
||||
self._deferred_automation_turns: dict[str, list[InboundMessage]] = {}
|
||||
@@ -983,13 +978,25 @@ class AgentLoop:
|
||||
|
||||
async def _drain_pending(
|
||||
*,
|
||||
limit: int = _MAX_INJECTIONS_PER_TURN,
|
||||
first_msg: InboundMessage | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Drain only messages that are already available."""
|
||||
"""Drain one atomic snapshot of messages already available."""
|
||||
if pending_queue is None:
|
||||
return []
|
||||
|
||||
# Capture the boundary before converting any message. Conversion
|
||||
# resolves runtime context and may await, so reading until QueueEmpty
|
||||
# afterwards would let later arrivals leak into this model step.
|
||||
pending_messages: list[InboundMessage] = []
|
||||
if first_msg is not None:
|
||||
pending_messages.append(first_msg)
|
||||
snapshot_size = pending_queue.qsize()
|
||||
for _ in range(snapshot_size):
|
||||
try:
|
||||
pending_messages.append(pending_queue.get_nowait())
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
|
||||
async def _to_user_message(pending_msg: InboundMessage) -> dict[str, Any]:
|
||||
content = pending_msg.content
|
||||
image_paths = pending_msg.media if pending_msg.media else None
|
||||
@@ -1057,27 +1064,15 @@ class AgentLoop:
|
||||
row[PENDING_FOLLOWUP_ID_KEY] = followup_id
|
||||
return row
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
if first_msg is not None:
|
||||
items.append(await _to_user_message(first_msg))
|
||||
while len(items) < limit:
|
||||
try:
|
||||
items.append(await _to_user_message(pending_queue.get_nowait()))
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
|
||||
return items
|
||||
return [await _to_user_message(pending_msg) for pending_msg in pending_messages]
|
||||
|
||||
terminal_wait_deadline: float | None = None
|
||||
|
||||
async def _wait_for_pending(
|
||||
*,
|
||||
limit: int = _MAX_INJECTIONS_PER_TURN,
|
||||
) -> list[dict[str, Any]]:
|
||||
async def _wait_for_pending() -> list[dict[str, Any]]:
|
||||
"""Wait for a pending result only when the runner is ready to exit."""
|
||||
nonlocal terminal_wait_deadline
|
||||
|
||||
items = await _drain_pending(limit=limit)
|
||||
items = await _drain_pending()
|
||||
if (
|
||||
items
|
||||
or pending_queue is None
|
||||
@@ -1102,7 +1097,7 @@ class AgentLoop:
|
||||
)
|
||||
return []
|
||||
|
||||
return await _drain_pending(limit=limit, first_msg=msg)
|
||||
return await _drain_pending(first_msg=msg)
|
||||
|
||||
request_ctx = request_context or RequestContext(
|
||||
channel="cli",
|
||||
@@ -1345,27 +1340,19 @@ class AgentLoop:
|
||||
self.commands.dispatch,
|
||||
)
|
||||
continue
|
||||
pending_msg = routed_msg
|
||||
session = self.sessions.get_or_create(effective_key)
|
||||
followup_id = record_pending_followup(session, pending_msg)
|
||||
if followup_id is not None:
|
||||
pending_msg = dataclasses.replace(
|
||||
pending_msg,
|
||||
metadata={
|
||||
**pending_msg.metadata,
|
||||
PENDING_FOLLOWUP_ID_KEY: followup_id,
|
||||
},
|
||||
)
|
||||
self.sessions.save(session)
|
||||
pending_msg = self._journal_pending_message(effective_key, routed_msg)
|
||||
self._pending_queues[effective_key].put_nowait(pending_msg)
|
||||
logger.info(
|
||||
"Routed follow-up message to pending queue for session {}",
|
||||
effective_key,
|
||||
)
|
||||
continue
|
||||
# Compute the effective session key before dispatching
|
||||
# This ensures /stop command can find tasks correctly when unified session is enabled
|
||||
task = asyncio.create_task(self._dispatch(msg))
|
||||
# Install the queue before scheduling its worker. Every later
|
||||
# message now has one FIFO path even if this task has not run yet.
|
||||
pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
pending.put_nowait(routed_msg)
|
||||
self._pending_queues[effective_key] = pending
|
||||
task = asyncio.create_task(self._run_session_queue(effective_key, pending))
|
||||
self._track_active_task(effective_key, task)
|
||||
finally:
|
||||
await self.aclose()
|
||||
@@ -1380,11 +1367,77 @@ class AgentLoop:
|
||||
"""
|
||||
self._preserve_inflight_turns_on_shutdown = True
|
||||
|
||||
def _journal_pending_message(
|
||||
self,
|
||||
session_key: str,
|
||||
msg: InboundMessage,
|
||||
) -> InboundMessage:
|
||||
"""Persist a recoverable WebUI follow-up before adding it to the inbox."""
|
||||
session = self.sessions.get_or_create(session_key)
|
||||
followup_id = record_pending_followup(session, msg)
|
||||
if followup_id is None:
|
||||
return msg
|
||||
pending_msg = dataclasses.replace(
|
||||
msg,
|
||||
metadata={
|
||||
**msg.metadata,
|
||||
PENDING_FOLLOWUP_ID_KEY: followup_id,
|
||||
},
|
||||
)
|
||||
self.sessions.save(session)
|
||||
return pending_msg
|
||||
|
||||
async def _dispatch(self, msg: InboundMessage) -> None:
|
||||
"""Process a message: per-session serial, cross-session concurrent."""
|
||||
"""Submit one direct caller message through the per-session FIFO."""
|
||||
session_key = self._effective_session_key(msg)
|
||||
if session_key != msg.session_key:
|
||||
msg = dataclasses.replace(msg, session_key_override=session_key)
|
||||
|
||||
pending = self._pending_queues.get(session_key)
|
||||
if pending is not None:
|
||||
pending.put_nowait(self._journal_pending_message(session_key, msg))
|
||||
return
|
||||
|
||||
new_pending: asyncio.Queue[InboundMessage] = asyncio.Queue()
|
||||
new_pending.put_nowait(msg)
|
||||
self._pending_queues[session_key] = new_pending
|
||||
await self._run_session_queue(session_key, new_pending)
|
||||
|
||||
async def _run_session_queue(
|
||||
self,
|
||||
session_key: str,
|
||||
pending: asyncio.Queue[InboundMessage],
|
||||
) -> None:
|
||||
"""Run the sole worker for a session until its inbox is empty."""
|
||||
try:
|
||||
while self._pending_queues.get(session_key) is pending:
|
||||
try:
|
||||
msg = pending.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
try:
|
||||
await self._dispatch_one(msg, pending)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Session worker failed one message for {}; continuing FIFO",
|
||||
session_key,
|
||||
)
|
||||
finally:
|
||||
owns_queue = self._pending_queues.get(session_key) is pending
|
||||
if owns_queue:
|
||||
self._pending_queues.pop(session_key, None)
|
||||
if owns_queue and self._running and session_key not in self._discarding_sessions:
|
||||
await self._publish_next_deferred_automation_turn(session_key)
|
||||
|
||||
async def _dispatch_one(
|
||||
self,
|
||||
msg: InboundMessage,
|
||||
pending: asyncio.Queue[InboundMessage],
|
||||
) -> None:
|
||||
"""Process one root message while later inputs remain in its session inbox."""
|
||||
session_key = self._effective_session_key(msg)
|
||||
recovery_task_registered = False
|
||||
recovery_admission = self._recovery_admission
|
||||
current_task: asyncio.Task[Any] | None = None
|
||||
@@ -1404,18 +1457,9 @@ class AgentLoop:
|
||||
gate = self._concurrency_gate or nullcontext()
|
||||
|
||||
delivery = self.turn_delivery_factory.unrouted(msg, session_key)
|
||||
pending: asyncio.Queue[InboundMessage] | None = None
|
||||
completion_published = False
|
||||
try:
|
||||
async with lock, gate:
|
||||
# Only the task that owns the session lock may publish the
|
||||
# active mid-turn injection queue for this session.
|
||||
# The global inbound bus is already unbounded. Keep the session queue
|
||||
# unbounded too so every message has one FIFO path; a bounded queue
|
||||
# would need a second dispatch path whose lock waiters can overtake
|
||||
# older messages left here.
|
||||
pending = asyncio.Queue()
|
||||
self._pending_queues[session_key] = pending
|
||||
try:
|
||||
delivery = self.turn_delivery_factory.create(
|
||||
msg,
|
||||
@@ -1483,33 +1527,8 @@ class AgentLoop:
|
||||
for _, coordinator in self._automation_turn_coordinators:
|
||||
coordinator.complete(msg, error=exc)
|
||||
finally:
|
||||
# Drain any messages still in the pending queue and re-publish
|
||||
# them to the bus so they are processed as fresh inbound messages
|
||||
# rather than silently lost. Only remove our own queue; a
|
||||
# later task waiting on the lock must not be able to steal
|
||||
# cleanup ownership.
|
||||
queue = None
|
||||
if self._pending_queues.get(session_key) is pending:
|
||||
queue = self._pending_queues.pop(session_key, None)
|
||||
else:
|
||||
queue = pending
|
||||
if queue is not None:
|
||||
leftover = 0
|
||||
while True:
|
||||
try:
|
||||
item = queue.get_nowait()
|
||||
except asyncio.QueueEmpty:
|
||||
break
|
||||
await self.bus.publish_inbound(item)
|
||||
leftover += 1
|
||||
if leftover:
|
||||
logger.info(
|
||||
"Re-published {} leftover message(s) to bus for session {}",
|
||||
leftover, session_key,
|
||||
)
|
||||
if not turn_continuation.internal_continuation_pending(msg.metadata):
|
||||
await delivery.idle()
|
||||
await self._publish_next_deferred_automation_turn(session_key)
|
||||
except asyncio.CancelledError:
|
||||
if not completion_published and normalize_command_text(msg.content).lower() == "/compact":
|
||||
await delivery.complete(None, publish_completion=True)
|
||||
@@ -1521,9 +1540,6 @@ class AgentLoop:
|
||||
and recovery_admission is not None
|
||||
):
|
||||
recovery_admission.unregister_recovery_task(session_key, current_task)
|
||||
if pending is None:
|
||||
await delivery.idle()
|
||||
await self._publish_next_deferred_automation_turn(session_key)
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""Stop active work, then close resources owned by the agent loop.
|
||||
|
||||
+43
-63
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import inspect
|
||||
import time
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from copy import deepcopy
|
||||
@@ -60,7 +59,7 @@ from nanobot.utils.runtime import (
|
||||
|
||||
ContinuationCallback = Callable[[], str | None]
|
||||
CheckpointCallback = Callable[[dict[str, Any]], Awaitable[None]]
|
||||
InjectionCallback = Callable[..., Awaitable[Iterable[Any] | None]]
|
||||
InjectionCallback = Callable[[], Awaitable[Iterable[Any] | None]]
|
||||
|
||||
_DEFAULT_ERROR_MESSAGE = "Sorry, I encountered an error calling the AI model."
|
||||
_ARREARAGE_ERROR_MESSAGE = (
|
||||
@@ -70,8 +69,6 @@ _ARREARAGE_ERROR_MESSAGE = (
|
||||
_PERSISTED_MODEL_ERROR_PLACEHOLDER = "[Assistant reply unavailable due to model error.]"
|
||||
_MAX_EMPTY_RETRIES = 2
|
||||
_MAX_LENGTH_RECOVERIES = 3
|
||||
_MAX_INJECTIONS_PER_TURN = 3
|
||||
_MAX_INJECTION_CYCLES = 5
|
||||
|
||||
|
||||
def _restore_outer_whitespace(content: str, original: str | None) -> str:
|
||||
@@ -164,19 +161,11 @@ class AgentRunner:
|
||||
iteration: int | None = None,
|
||||
allow_continuation: bool = False,
|
||||
wait_at_terminal: bool = False,
|
||||
drain_callback: bool = True,
|
||||
) -> tuple[bool, int]:
|
||||
"""Drain pending injections. Returns (should_continue, updated_cycles).
|
||||
|
||||
If injections are found and we haven't exceeded _MAX_INJECTION_CYCLES,
|
||||
append them to *messages* (and emit a checkpoint if *assistant_message*
|
||||
and *iteration* are both provided) and return (True, cycles+1) so the
|
||||
caller continues the iteration loop. Otherwise return (False, cycles).
|
||||
"""
|
||||
injections: list[dict[str, Any]] = []
|
||||
real_injection = False
|
||||
if injection_cycles < _MAX_INJECTION_CYCLES:
|
||||
injections = await self._drain_injections(spec)
|
||||
real_injection = bool(injections)
|
||||
"""Append one pending-input snapshot and return whether execution continues."""
|
||||
injections = await self._drain_injections(spec) if drain_callback else []
|
||||
real_injection = bool(injections)
|
||||
if not injections and allow_continuation and assistant_message is not None:
|
||||
continuation = self._build_continuation_message(spec)
|
||||
if continuation is not None:
|
||||
@@ -184,7 +173,7 @@ class AgentRunner:
|
||||
if (
|
||||
not injections
|
||||
and wait_at_terminal
|
||||
and injection_cycles < _MAX_INJECTION_CYCLES
|
||||
and drain_callback
|
||||
):
|
||||
injections = await self._drain_injections(spec, terminal=True)
|
||||
real_injection = bool(injections)
|
||||
@@ -214,8 +203,8 @@ class AgentRunner:
|
||||
self._append_injected_messages(messages, injections)
|
||||
if real_injection:
|
||||
logger.info(
|
||||
"Injected {} follow-up message(s) {} ({}/{})",
|
||||
len(injections), phase, injection_cycles, _MAX_INJECTION_CYCLES,
|
||||
"Injected {} follow-up message(s) {} (snapshot {})",
|
||||
len(injections), phase, injection_cycles,
|
||||
)
|
||||
else:
|
||||
logger.info("Injected caller-requested continuation {}", phase)
|
||||
@@ -241,13 +230,7 @@ class AgentRunner:
|
||||
*,
|
||||
terminal: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Drain pending user messages via the injection callback.
|
||||
|
||||
Returns normalized user messages (capped by
|
||||
``_MAX_INJECTIONS_PER_TURN``), or an empty list when there is
|
||||
nothing to inject. Messages beyond the cap are logged so they
|
||||
are not silently lost.
|
||||
"""
|
||||
"""Drain one pending-input snapshot via the injection callback."""
|
||||
callback = (
|
||||
spec.terminal_injection_callback
|
||||
if terminal
|
||||
@@ -256,18 +239,7 @@ class AgentRunner:
|
||||
if callback is None:
|
||||
return []
|
||||
try:
|
||||
signature = inspect.signature(callback)
|
||||
accepts_limit = (
|
||||
"limit" in signature.parameters
|
||||
or any(
|
||||
parameter.kind is inspect.Parameter.VAR_KEYWORD
|
||||
for parameter in signature.parameters.values()
|
||||
)
|
||||
)
|
||||
if accepts_limit:
|
||||
items = await callback(limit=_MAX_INJECTIONS_PER_TURN)
|
||||
else:
|
||||
items = await callback()
|
||||
items = await callback()
|
||||
except Exception:
|
||||
logger.exception("injection_callback failed")
|
||||
return []
|
||||
@@ -286,13 +258,6 @@ class AgentRunner:
|
||||
content = getattr(item, "content") if hasattr(item, "content") else str(item)
|
||||
if self._has_injection_content(content):
|
||||
injected_messages.append({"role": "user", "content": content})
|
||||
if len(injected_messages) > _MAX_INJECTIONS_PER_TURN:
|
||||
dropped = len(injected_messages) - _MAX_INJECTIONS_PER_TURN
|
||||
logger.warning(
|
||||
"Injection callback returned {} messages, capping to {} ({} dropped)",
|
||||
len(injected_messages), _MAX_INJECTIONS_PER_TURN, dropped,
|
||||
)
|
||||
injected_messages = injected_messages[:_MAX_INJECTIONS_PER_TURN]
|
||||
return injected_messages
|
||||
|
||||
@staticmethod
|
||||
@@ -433,6 +398,18 @@ class AgentRunner:
|
||||
)
|
||||
|
||||
for iteration in range(spec.max_iterations):
|
||||
# The session inbox cuts a finite snapshot before every model call.
|
||||
# This includes follow-ups that arrived before the first request and
|
||||
# messages received while the previous request or tools were running.
|
||||
drained_before_request, injection_cycles = await self._try_drain_injections(
|
||||
spec,
|
||||
messages,
|
||||
None,
|
||||
injection_cycles,
|
||||
phase="before model call",
|
||||
)
|
||||
if drained_before_request:
|
||||
had_injections = True
|
||||
context = AgentHookContext(
|
||||
iteration=iteration,
|
||||
messages=messages,
|
||||
@@ -568,13 +545,6 @@ class AgentRunner:
|
||||
)
|
||||
empty_content_retries = 0
|
||||
length_recovery_parts.clear()
|
||||
# Checkpoint 1: drain injections after tools, before next LLM call
|
||||
_drained, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after tool execution",
|
||||
)
|
||||
if _drained:
|
||||
had_injections = True
|
||||
await hook.after_iteration(context)
|
||||
continue
|
||||
|
||||
@@ -687,6 +657,10 @@ class AgentRunner:
|
||||
# Check for mid-turn injections BEFORE signaling stream end.
|
||||
# If injections are found we keep the stream alive (resuming=True)
|
||||
# so streaming channels don't prematurely finalize the card.
|
||||
can_make_followup_request = (
|
||||
iteration + 1 < spec.max_iterations
|
||||
or spec.finalize_on_max_iterations
|
||||
)
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, assistant_message, injection_cycles,
|
||||
conversation_state=conversation_state,
|
||||
@@ -700,6 +674,7 @@ class AgentRunner:
|
||||
and response.finish_reason
|
||||
not in {"error", "length", "refusal", "content_filter"}
|
||||
),
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -727,6 +702,7 @@ class AgentRunner:
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after LLM error",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -746,6 +722,7 @@ class AgentRunner:
|
||||
should_continue, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after empty response",
|
||||
drain_callback=can_make_followup_request,
|
||||
)
|
||||
if should_continue:
|
||||
had_injections = True
|
||||
@@ -789,19 +766,22 @@ class AgentRunner:
|
||||
break
|
||||
else:
|
||||
stop_reason = "max_iterations"
|
||||
# Drain any remaining injections so they are appended to the
|
||||
# conversation history instead of being re-published as
|
||||
# independent inbound messages by _dispatch's finally block.
|
||||
# We include them before the no-tools finalization pass so the
|
||||
# final response can account for every known follow-up.
|
||||
drained_after_max_iterations, injection_cycles = await self._try_drain_injections(
|
||||
spec, messages, None, injection_cycles,
|
||||
phase="after max_iterations",
|
||||
)
|
||||
if drained_after_max_iterations:
|
||||
had_injections = True
|
||||
terminal_content = None
|
||||
if spec.finalize_on_max_iterations:
|
||||
# The no-tools finalization is a real model boundary, so include
|
||||
# exactly the inputs waiting before that request. Without this
|
||||
# request, leave them in the session inbox for its worker.
|
||||
drained_after_max_iterations, injection_cycles = (
|
||||
await self._try_drain_injections(
|
||||
spec,
|
||||
messages,
|
||||
None,
|
||||
injection_cycles,
|
||||
phase="before max-iterations finalization",
|
||||
)
|
||||
)
|
||||
if drained_after_max_iterations:
|
||||
had_injections = True
|
||||
terminal_content, usage = await self._try_finalize_after_max_iterations(
|
||||
spec,
|
||||
hook,
|
||||
|
||||
Reference in new issue
Block a user