fix: preserve subtask request attribution after restart (#6247)
* fix: preserve request origin across recovery continuations * fix: bind request origin to each continuation * fix: capture origin when queuing continuation messages * chore: remove redundant request context comment * fix: persist origin for independent system turns
This commit is contained in:
1 parent
6d84786efa
commit
33ff520d12
7 files changed
+266
-5
No files matched your search
+16
-2
@@ -92,10 +92,13 @@ from nanobot.session.model_selection import (
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUP_ID_KEY,
|
||||
RECOVERY_INBOUND_METADATA_KEY,
|
||||
REQUEST_ORIGIN_METADATA_KEY,
|
||||
RecoveryAdmission,
|
||||
RequestOrigin,
|
||||
acknowledge_pending_followups,
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
request_origin_from_metadata,
|
||||
restore_pending_interruption,
|
||||
restore_runtime_checkpoint,
|
||||
)
|
||||
@@ -730,6 +733,17 @@ class AgentLoop:
|
||||
|
||||
async def _request_context_for_turn(self, ctx: TurnContext) -> RequestContext:
|
||||
assert ctx.session is not None
|
||||
origin: RequestOrigin = {
|
||||
"message_id": ctx.msg.metadata.get("message_id"),
|
||||
"turn_id": ctx.delivery.route.turn_id or ctx.turn_id,
|
||||
}
|
||||
if turn_continuation.internal_continuation_inbound(ctx.msg.metadata):
|
||||
origin = request_origin_from_metadata(ctx.msg.metadata) or origin
|
||||
if origin != request_origin_from_metadata(ctx.session.metadata):
|
||||
ctx.session.metadata[REQUEST_ORIGIN_METADATA_KEY] = origin
|
||||
if ctx.original_user_text is None:
|
||||
# No new user row will persist this turn's owner before execution.
|
||||
self.sessions.save(ctx.session)
|
||||
scope = await self.runner.prepare_prompt(
|
||||
self.workspace_scopes.for_turn,
|
||||
channel=ctx.delivery.route.channel,
|
||||
@@ -739,14 +753,14 @@ class AgentLoop:
|
||||
return RequestContext(
|
||||
channel=ctx.delivery.route.channel,
|
||||
chat_id=ctx.delivery.route.chat_id,
|
||||
message_id=ctx.msg.metadata.get("message_id"),
|
||||
message_id=origin["message_id"],
|
||||
session_key=ctx.session_key,
|
||||
original_user_text=ctx.original_user_text,
|
||||
runtime=ctx.runtime,
|
||||
metadata=dict(ctx.msg.metadata or {}),
|
||||
attributes=dict(ctx.attributes),
|
||||
sender_id=ctx.msg.sender_id,
|
||||
turn_id=ctx.delivery.route.turn_id or ctx.turn_id,
|
||||
turn_id=origin["turn_id"],
|
||||
workspace=scope.project_path,
|
||||
workspace_scope=scope,
|
||||
log_content=ctx.session.policy.log_content and not ctx.ephemeral,
|
||||
|
||||
@@ -6,7 +6,7 @@ import asyncio
|
||||
import json
|
||||
from collections.abc import Iterable, Mapping
|
||||
from datetime import datetime
|
||||
from typing import Any, Protocol, cast
|
||||
from typing import Any, Protocol, TypedDict, cast
|
||||
from uuid import uuid4
|
||||
|
||||
from loguru import logger
|
||||
@@ -16,6 +16,7 @@ from nanobot.session.manager import Session
|
||||
|
||||
RUNTIME_CHECKPOINT_KEY = "runtime_checkpoint"
|
||||
PENDING_USER_TURN_KEY = "pending_user_turn"
|
||||
REQUEST_ORIGIN_METADATA_KEY = "request_origin"
|
||||
RECOVERY_METADATA_KEY = "webui_recovery"
|
||||
RECOVERY_INBOUND_METADATA_KEY = "_webui_recovery_id"
|
||||
PENDING_FOLLOWUPS_KEY = "pending_user_followups"
|
||||
@@ -30,6 +31,26 @@ KNOWN_CHECKPOINT_PHASES = frozenset(
|
||||
)
|
||||
|
||||
|
||||
class RequestOrigin(TypedDict):
|
||||
message_id: str | None
|
||||
turn_id: str
|
||||
|
||||
|
||||
def request_origin_from_metadata(metadata: Mapping[str, Any]) -> RequestOrigin | None:
|
||||
"""Read the request identity carried by continuation or recovery metadata."""
|
||||
value = metadata.get(REQUEST_ORIGIN_METADATA_KEY)
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
origin = cast(dict[str, object], value)
|
||||
message_id = origin.get("message_id")
|
||||
turn_id = origin.get("turn_id")
|
||||
if message_id is not None and not isinstance(message_id, str):
|
||||
return None
|
||||
if not isinstance(turn_id, str) or not turn_id:
|
||||
return None
|
||||
return {"message_id": message_id, "turn_id": turn_id}
|
||||
|
||||
|
||||
class RecoveryAdmission(Protocol):
|
||||
"""Narrow AgentLoop boundary for explicit recovery validation."""
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from nanobot.session.goal_state import (
|
||||
sustained_goal_active,
|
||||
sustained_goal_turn,
|
||||
)
|
||||
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.agent.loop import TurnContext
|
||||
@@ -129,6 +130,12 @@ async def maybe_continue_turn(ctx: TurnContext) -> bool:
|
||||
ctx.msg.metadata,
|
||||
run_started_at=ctx.visible_run_started_at,
|
||||
)
|
||||
request = ctx.request_context
|
||||
assert request is not None and request.turn_id is not None
|
||||
metadata[REQUEST_ORIGIN_METADATA_KEY] = {
|
||||
"message_id": request.message_id,
|
||||
"turn_id": request.turn_id,
|
||||
}
|
||||
content = _goal_continuation_prompt(ctx.session.metadata)
|
||||
messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
|
||||
_increment_goal_continuation_round(ctx.session.metadata)
|
||||
|
||||
@@ -27,12 +27,14 @@ from nanobot.session.recovery import (
|
||||
PENDING_USER_TURN_KEY,
|
||||
RECOVERY_INBOUND_METADATA_KEY,
|
||||
RECOVERY_METADATA_KEY,
|
||||
REQUEST_ORIGIN_METADATA_KEY,
|
||||
RUNTIME_CHECKPOINT_KEY,
|
||||
UNCERTAIN_TOOL_PHASES,
|
||||
append_recovery_interruption,
|
||||
discard_runtime_checkpoint,
|
||||
pending_followups,
|
||||
recovery_state_from_metadata,
|
||||
request_origin_from_metadata,
|
||||
restore_pending_interruption,
|
||||
restore_runtime_checkpoint,
|
||||
runtime_checkpoint_is_well_formed,
|
||||
@@ -389,6 +391,7 @@ class RecoveryCoordinator:
|
||||
state: Mapping[str, Any],
|
||||
) -> None:
|
||||
recovery_id = cast(str, state["recovery_id"])
|
||||
origin = request_origin_from_metadata(session.metadata)
|
||||
await self.bus.publish_inbound(
|
||||
InboundMessage(
|
||||
channel="websocket",
|
||||
@@ -405,6 +408,7 @@ class RecoveryCoordinator:
|
||||
RECOVERY_INBOUND_METADATA_KEY: recovery_id,
|
||||
turn_continuation.INTERNAL_CONTINUATION_META: True,
|
||||
turn_continuation.SKIP_USER_PERSIST_META: True,
|
||||
**({REQUEST_ORIGIN_METADATA_KEY: origin} if origin is not None else {}),
|
||||
},
|
||||
session_key_override=session.key,
|
||||
require_existing_session=True,
|
||||
|
||||
@@ -2,20 +2,25 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from agent.session_helpers import save_completed_subagent
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.turn_delivery import TurnDeliveryFactory
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
RECOVERY_METADATA_KEY,
|
||||
REQUEST_ORIGIN_METADATA_KEY,
|
||||
)
|
||||
from nanobot.session.turn_continuation import INTERNAL_CONTINUATION_META
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator, WebuiTurnRoutePolicy
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -64,3 +69,143 @@ async def test_recovery_continuation_runs_without_a_sustained_goal(
|
||||
await loop._dispatch_one(continuation, asyncio.Queue())
|
||||
|
||||
process_message.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("late_result", [False, True], ids=["user_request", "late_subagent_result"])
|
||||
async def test_recovery_preserves_turn_origin_until_the_next_user_turn(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, late_result: bool,
|
||||
) -> None:
|
||||
monkeypatch.setattr("nanobot.webui.transcript.get_webui_dir", lambda: tmp_path / "webui")
|
||||
monkeypatch.setattr("nanobot.webui.session_list_index.get_webui_dir", lambda: tmp_path / "webui")
|
||||
bus = MessageBus()
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
provider.get_default_model.return_value = "test-model"
|
||||
provider.generation = GenerationSettings()
|
||||
provider.can_resume_conversation_state.return_value = False
|
||||
entered = asyncio.Event()
|
||||
model_calls = 0
|
||||
persisted_origin = None
|
||||
|
||||
async def interrupted(**kwargs):
|
||||
nonlocal model_calls, persisted_origin
|
||||
model_calls += 1
|
||||
if model_calls == 1:
|
||||
persisted_origin = SessionManager(tmp_path).get_or_create(request.session_key).metadata[
|
||||
REQUEST_ORIGIN_METADATA_KEY
|
||||
]
|
||||
if late_result and model_calls == 1:
|
||||
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
"read-result", "read_file", {"path": str(tmp_path / "result.txt")},
|
||||
)])
|
||||
entered.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(loop.sessions))
|
||||
coordinator = WebuiTurnCoordinator(bus, loop.sessions, loop.schedule_background)
|
||||
request = InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Inspect configuration",
|
||||
metadata={"webui": True, "webui_turn_id": "user-request", "message_id": "user-message"},
|
||||
)
|
||||
loop.sessions.get_or_create(request.session_key).metadata["title"] = "Configuration"
|
||||
with coordinator.connected():
|
||||
if late_result:
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content="Background check started"), LLMResponse(content="New request answered"),
|
||||
])
|
||||
await loop._dispatch_one(request, asyncio.Queue())
|
||||
await loop._dispatch_one(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="New request B",
|
||||
metadata={"webui": True, "webui_turn_id": "request-b", "message_id": "message-b"},
|
||||
), asyncio.Queue())
|
||||
save_completed_subagent(loop, "task-a", request.session_key)
|
||||
request = InboundMessage(
|
||||
channel="system", sender_id="subagent", chat_id=request.session_key,
|
||||
content="Background check for the original request completed",
|
||||
session_key_override=request.session_key,
|
||||
metadata={
|
||||
"injected_event": "subagent_result", "subagent_task_id": "task-a",
|
||||
"origin_message_id": "user-message",
|
||||
},
|
||||
)
|
||||
(tmp_path / "result.txt").write_text("Configuration verified", encoding="utf-8")
|
||||
existing_tasks = set(loop.subagents.statuses_for_session(request.session_key))
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=interrupted)
|
||||
delivery = loop.turn_delivery_factory.create(request, request.session_key)
|
||||
expected_origin = {
|
||||
"message_id": None if late_result else "user-message",
|
||||
"turn_id": delivery.route.turn_id,
|
||||
}
|
||||
recorder = WebUITranscriptRecorder()
|
||||
|
||||
async def record_progress(content, **kwargs):
|
||||
recorder.prepare_and_append(
|
||||
"chat", {"event": "message", "chat_id": "chat", "text": content, "kind": "progress"},
|
||||
metadata=delivery.route.metadata, phase="activity",
|
||||
)
|
||||
|
||||
task = asyncio.create_task(loop._process_message(
|
||||
request, delivery=delivery, on_progress=record_progress,
|
||||
))
|
||||
try:
|
||||
await asyncio.wait_for(entered.wait(), 5)
|
||||
finally:
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
await loop.aclose()
|
||||
|
||||
bus = MessageBus()
|
||||
sessions = SessionManager(tmp_path)
|
||||
recovery = RecoveryCoordinator(sessions, bus)
|
||||
await recovery.scan()
|
||||
state = sessions.get_or_create(request.session_key).metadata[RECOVERY_METADATA_KEY]
|
||||
assert state["status"] == "awaiting_user"
|
||||
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
|
||||
continuation = bus.inbound.get_nowait()
|
||||
|
||||
provider.chat_stream_with_retry = AsyncMock(side_effect=[
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
"delegate", "subagent", {"action": "create", "task": "Inspect configuration", "wait": True},
|
||||
)]),
|
||||
LLMResponse(content="Configuration verified"),
|
||||
LLMResponse(content="Inspection complete"),
|
||||
LLMResponse(content=None, tool_calls=[ToolCallRequest(
|
||||
"delegate-next", "subagent", {"action": "create", "task": "Inspect logs", "wait": True},
|
||||
)]),
|
||||
LLMResponse(content="Logs verified"),
|
||||
LLMResponse(content="Log inspection complete"),
|
||||
])
|
||||
loop = AgentLoop(
|
||||
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
|
||||
session_manager=sessions, recovery_admission=recovery,
|
||||
)
|
||||
loop.turn_delivery_factory = TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions))
|
||||
coordinator = WebuiTurnCoordinator(bus, sessions, loop.schedule_background, recovery=recovery)
|
||||
try:
|
||||
with coordinator.connected():
|
||||
await loop._dispatch_one(continuation, asyncio.Queue())
|
||||
statuses = loop.subagents.statuses_for_session(request.session_key)
|
||||
children = [status for task_id, status in statuses.items() if task_id not in existing_tasks]
|
||||
assert len(children) == 1
|
||||
child = children[0]
|
||||
assert child.state == "done"
|
||||
assert child.origin_message_id == expected_origin["message_id"]
|
||||
assert child.origin_turn_id == expected_origin["turn_id"]
|
||||
assert persisted_origin == expected_origin
|
||||
assert continuation.metadata["webui_turn_id"] == f"recovery:{state['recovery_id']}"
|
||||
assert sessions.get_or_create(request.session_key).metadata[RECOVERY_METADATA_KEY]["status"] == "recovered"
|
||||
with coordinator.connected():
|
||||
await loop._dispatch_one(InboundMessage(
|
||||
channel="websocket", sender_id="user", chat_id="chat", content="Inspect logs",
|
||||
metadata={"webui": True, "webui_turn_id": "next-request", "message_id": "next-message"},
|
||||
), asyncio.Queue())
|
||||
statuses = loop.subagents.statuses_for_session(request.session_key)
|
||||
assert {
|
||||
(status.origin_message_id, status.origin_turn_id)
|
||||
for task_id, status in statuses.items() if task_id not in existing_tasks
|
||||
} == {
|
||||
(expected_origin["message_id"], expected_origin["turn_id"]), ("next-message", "next-request"),
|
||||
}
|
||||
finally:
|
||||
await loop.aclose()
|
||||
@@ -21,6 +21,7 @@ from nanobot.session.goal_state import GOAL_STATE_KEY
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUPS_KEY,
|
||||
REQUEST_ORIGIN_METADATA_KEY,
|
||||
pending_followups,
|
||||
record_pending_followup,
|
||||
)
|
||||
@@ -556,3 +557,63 @@ async def test_goal_continuation_after_followup_keeps_control_identity(loop, com
|
||||
finally:
|
||||
loop.stop()
|
||||
await asyncio.wait_for(run_task, timeout=3)
|
||||
|
||||
|
||||
async def test_queued_continuation_keeps_its_origin_after_another_chat_runs(loop):
|
||||
loop._unified_session = True
|
||||
loop.max_iterations = 1
|
||||
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
|
||||
loop.tools.execute = AsyncMock(return_value="ok")
|
||||
key = "unified:default"
|
||||
session = loop.sessions.get_or_create(key)
|
||||
session.metadata[GOAL_STATE_KEY] = {"status": "active", "objective": "Finish the goal"}
|
||||
loop.sessions.save(session)
|
||||
requests = []
|
||||
persisted_origin = None
|
||||
|
||||
async def chat(**kwargs):
|
||||
nonlocal persisted_origin
|
||||
context = current_request_context()
|
||||
requests.append((context.chat_id, context.message_id, context.turn_id))
|
||||
if len(requests) == 1:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="feishu", sender_id="user", chat_id="chat-b", content="Inspect B first",
|
||||
metadata={"message_id": "message-b"},
|
||||
))
|
||||
async with asyncio.timeout(3):
|
||||
while loop._pending_queues[key].empty():
|
||||
await asyncio.sleep(0)
|
||||
elif len(requests) == 3:
|
||||
persisted = SessionManager(loop.workspace).get_or_create(key)
|
||||
persisted_origin = persisted.metadata[REQUEST_ORIGIN_METADATA_KEY]
|
||||
await loop.tools.get("message").execute(content="Continuation reply")
|
||||
session.metadata[GOAL_STATE_KEY]["status"] = "complete"
|
||||
return LLMResponse(content="done")
|
||||
return LLMResponse(content="working", finish_reason="tool_calls", tool_calls=[
|
||||
ToolCallRequest(id=f"call-{len(requests)}", name="noop", arguments={}),
|
||||
])
|
||||
|
||||
loop.provider.chat_stream_with_retry = chat
|
||||
worker = asyncio.create_task(loop.run())
|
||||
try:
|
||||
await loop.bus.publish_inbound(InboundMessage(
|
||||
channel="feishu", sender_id="user", chat_id="chat-a", content="Start the goal",
|
||||
metadata={"message_id": "message-a"},
|
||||
))
|
||||
async with asyncio.timeout(5):
|
||||
while not requests or key in loop._pending_queues:
|
||||
await asyncio.sleep(0.01)
|
||||
assert [request[:2] for request in requests] == [
|
||||
("chat-a", "message-a"), ("chat-b", "message-b"), ("chat-a", "message-a"),
|
||||
]
|
||||
assert requests[2][2] == requests[0][2]
|
||||
assert persisted_origin == {"message_id": "message-a", "turn_id": requests[0][2]}
|
||||
replies = []
|
||||
while not loop.bus.outbound.empty():
|
||||
reply = loop.bus.outbound.get_nowait()
|
||||
if reply.content == "Continuation reply":
|
||||
replies.append((reply.chat_id, reply.metadata.get("message_id")))
|
||||
assert replies == [("chat-a", "message-a")]
|
||||
finally:
|
||||
loop.stop()
|
||||
await asyncio.wait_for(worker, timeout=3)
|
||||
@@ -7,12 +7,14 @@ from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.session.goal_state import (
|
||||
GOAL_STATE_KEY,
|
||||
explicit_goal_requested,
|
||||
sustained_goal_turn,
|
||||
)
|
||||
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
|
||||
from nanobot.session.turn_continuation import (
|
||||
INTERNAL_CONTINUATION_KIND_META,
|
||||
INTERNAL_CONTINUATION_META,
|
||||
@@ -60,6 +62,9 @@ async def test_maybe_continue_turn_queues_internal_message():
|
||||
},
|
||||
),
|
||||
session_key="feishu:c1",
|
||||
request_context=RequestContext(
|
||||
channel="feishu", chat_id="c1", message_id="msg-1", turn_id="turn-1",
|
||||
),
|
||||
pending_queue=pending,
|
||||
stop_reason="max_iterations",
|
||||
final_content="paused",
|
||||
@@ -80,6 +85,10 @@ async def test_maybe_continue_turn_queues_internal_message():
|
||||
assert internal_continuation_pending(ctx.msg.metadata)
|
||||
assert queued.metadata["webui"] is True
|
||||
assert queued.metadata["message_id"] == "msg-1"
|
||||
assert queued.metadata[REQUEST_ORIGIN_METADATA_KEY] == {
|
||||
"message_id": "msg-1", "turn_id": "turn-1",
|
||||
}
|
||||
assert REQUEST_ORIGIN_METADATA_KEY not in ctx.msg.metadata
|
||||
assert queued.metadata["origin_message_id"] == "msg-0"
|
||||
assert queued.metadata["_wants_stream"] is True
|
||||
assert not explicit_goal_requested(queued.metadata)
|
||||
|
||||
Reference in new issue
Block a user