fix(runtime): preserve recovery history and prevent unsafe MCP replays (#6537)

* fix(recovery): preserve complete checkpoints and refresh cancellation drafts

Retain earlier tool rounds and consumed follow-ups until the transcript is committed, and classify a fresh session after cancelling active recovery. Keep history and follow-up acknowledgement atomic through the session owner.

* test(recovery): cover completion during cancellation handoff

* fix(gateway): preserve failure exit status after runtime crashes

Report uncaught gateway runtime failures as exit code 1 after the existing cleanup, just like startup failures. Remove the startup-only guard without changing controlled shutdown or supervisor policy.

Reuse lifecycle regression coverage for startup/runtime failure diagnostics and cleanup, and update runtime fault fixtures to expect failure.

Refs: NAN-394

* fix(recovery): make interrupted tool outcomes explicit

* fix(mcp): avoid unsafe replays and retain error states

Recover stale connections before non-replayable tool submissions, and report unknown outcomes without replaying calls after transport loss. Preserve structured error results for resource and prompt wrappers.

NAN-393
NAN-395

* test(recovery): assert unknown outcome guidance

* fix(runtime): revalidate replay contracts and preserve recovery input identity

Bind replay safety to each request session, adopt the rediscovered contract, and stop automatic replay when it loses its safety declaration. Treat cumulative checkpoints as uncommitted deltas rather than deduplicating independent inputs by text, retaining legacy single-batch recovery compatibility.

Extend the existing reconnect and same-text follow-up regressions, and align MCP privacy/proxy fixtures with preflight and explicitly safe replay without relaxing their privacy or routing assertions.

* fix(mcp): report unknown outcomes after submitted tool timeouts

Real HTTP response-loss probing with Codex exposed that the MCP SDK can surface a lost response as a timeout. Preserve preflight timeout semantics, but report possible completed effects after a non-replayable request has started. Never replay or weaken task cancellation.
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-02 17:55:14 +08:00
1 parent c1ed649b81
commit 384b763830
16 files changed
+815 -89

No files matched your search

+186
View File
@@ -13,6 +13,7 @@ from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.runtime_context import public_history_message
from nanobot.session.manager import SessionManager
from nanobot.session.recovery import (
PENDING_USER_TURN_KEY,
@@ -355,3 +356,188 @@ async def test_recovery_distinguishes_explicit_stop_from_gateway_shutdown(
assert RECOVERY_METADATA_KEY not in restored.metadata
finally:
await restarted.state.aclose()
def _recovery_loop(tmp_path, provider, sessions=None):
bus = MessageBus()
sessions = sessions or SessionManager(tmp_path)
recovery = RecoveryCoordinator(sessions, bus)
loop = AgentLoop(
bus=bus, provider=provider, workspace=tmp_path, model="test-model",
session_manager=sessions, recovery_admission=recovery,
turn_delivery_factory=TurnDeliveryFactory(bus, WebuiTurnRoutePolicy(sessions)),
)
return loop, recovery
@pytest.mark.parametrize(("boundary", "gateway_shutdown"), [
("awaiting_tools", False), ("tools_completed", False), ("final_response", False),
("awaiting_tools", True), ("tools_completed", True), ("final_response", True),
("completed", False),
])
async def test_multiround_recovery_keeps_completed_work_and_consumed_followup(
tmp_path, monkeypatch, boundary, gateway_shutdown,
):
from nanobot.session.recovery import pending_followups
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.can_resume_conversation_state.return_value = False
requests = []
responses = iter([
LLMResponse(content=None, tool_calls=[ToolCallRequest("A", "read_file", {"path": "A.txt"})]),
LLMResponse(content=None, tool_calls=[ToolCallRequest("B", "read_file", {"path": "B.txt"})]),
LLMResponse(content="Both results received."),
LLMResponse(content="Continued without repeating work."),
])
async def respond(**kwargs):
requests.append(deepcopy(kwargs["messages"]))
return next(responses)
provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
loop, recovery = _recovery_loop(tmp_path, provider)
first_tool = asyncio.Event()
release_first = asyncio.Event()
reached = asyncio.Event()
attempts = []
tool = loop.tools.get("read_file")
async def read(path, **kwargs):
attempts.append(path)
if path == "A.txt":
first_tool.set()
await release_first.wait()
elif boundary == "awaiting_tools":
reached.set()
await asyncio.Event().wait()
return f"result for {path}"
monkeypatch.setattr(tool, "execute", read)
checkpoint = loop._set_runtime_checkpoint
async def save_checkpoint(session, payload):
await checkpoint(session, payload)
if payload["iteration"] > 0 and payload["phase"] == boundary and boundary != "awaiting_tools":
reached.set()
await asyncio.Event().wait()
monkeypatch.setattr(loop, "_set_runtime_checkpoint", save_checkpoint)
request = InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="Read two notes",
metadata={"webui": True, "webui_turn_id": "initial"},
)
try:
await loop._dispatch_inbound(request)
await asyncio.wait_for(first_tool.wait(), 5)
await loop._dispatch_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="Keep both results",
metadata={"webui": True, "webui_turn_id": "followup"},
))
release_first.set()
if boundary == "completed":
await asyncio.gather(*loop._active_tasks[request.session_key])
else:
await asyncio.wait_for(reached.wait(), 5)
if gateway_shutdown:
loop.preserve_inflight_turns_on_shutdown()
else:
await loop._dispatch_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="/stop",
))
finally:
await loop.aclose()
sessions = SessionManager(tmp_path)
resumed, recovery = _recovery_loop(tmp_path, provider, sessions)
try:
await recovery.scan()
stored = await sessions.state.get(request.session_key)
tools = [row for row in stored.messages if row["role"] == "tool"]
assert [row["tool_call_id"] for row in tools] == ["A", "B"]
assert tools[0]["content"] == "result for A.txt"
if boundary == "awaiting_tools":
assert tools[1]["_recovery_interrupted"] is True
assert "outcome is unknown" in tools[1]["content"]
else:
assert tools[1]["content"] == "result for B.txt"
assert [public_history_message(row)["content"] for row in stored.messages if row["role"] == "user"] == [
"Read two notes", "Keep both results",
]
assert pending_followups(stored) == []
assert resumed.bus.inbound.empty()
calls = [call["id"] for row in stored.messages for call in row.get("tool_calls", [])]
assert calls == ["A", "B"]
if boundary in {"final_response", "completed"}:
assert stored.messages[-1]["content"] == "Both results received."
if gateway_shutdown and boundary in {"awaiting_tools", "tools_completed"}:
state = stored.metadata[RECOVERY_METADATA_KEY]
assert state["status"] == "awaiting_user"
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": state["recovery_id"]})
await resumed._dispatch_one(resumed.bus.inbound.get_nowait(), asyncio.Queue())
history = requests[-1]
assert [row["tool_call_id"] for row in history if row["role"] == "tool"] == ["A", "B"]
assert attempts == ["A.txt", "B.txt"]
finally:
await resumed.aclose()
async def test_new_input_waits_for_real_recovery_cancellation_before_reading_draft(tmp_path, monkeypatch):
provider = MagicMock(aclose=AsyncMock())
provider.get_default_model.return_value = "test-model"
provider.generation = GenerationSettings()
provider.can_resume_conversation_state.return_value = False
provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content=None, tool_calls=[ToolCallRequest("C", "read_file", {"path": "C.txt"})]),
LLMResponse(content="New input answered."),
])
loop, recovery = _recovery_loop(tmp_path, provider)
session = await loop.sessions.state.get("websocket:chat")
session.add_message("user", "Earlier request")
session.metadata["title"] = "Recovery handoff"
session.metadata[RECOVERY_METADATA_KEY] = {
"status": "awaiting_user", "recovery_id": "recover", "attempts": 0,
}
await loop.sessions.state.prepare_input(session)
entered = asyncio.Event()
cancelled = asyncio.Event()
async def read(**kwargs):
entered.set()
try:
await asyncio.Event().wait()
finally:
cancelled.set()
monkeypatch.setattr(loop.tools.get("read_file"), "execute", read)
coordinator = WebuiTurnCoordinator(loop.bus, loop.sessions, loop.schedule_background, recovery=recovery)
try:
with coordinator.connected():
await recovery.handle_action("continue", {"chat_id": "chat", "recovery_id": "recover"})
await loop._dispatch_inbound(loop.bus.inbound.get_nowait())
await asyncio.wait_for(entered.wait(), 5)
old_tasks = tuple(loop._active_tasks[session.key])
await loop._dispatch_inbound(InboundMessage(
channel="websocket", sender_id="user", chat_id="chat", content="Replace the old task",
metadata={"webui": True, "webui_turn_id": "new-input"},
))
assert cancelled.is_set()
assert all(task.done() for task in old_tasks)
await asyncio.gather(*loop._active_tasks[session.key])
finally:
await loop.aclose()
reopened = SessionManager(tmp_path)
try:
saved = await reopened.state.get(session.key)
assert [row["tool_call_id"] for row in saved.messages if row["role"] == "tool"] == ["C"]
assert [call["id"] for row in saved.messages for call in row.get("tool_calls", [])] == ["C"]
assert [public_history_message(row)["content"] for row in saved.messages if row["role"] == "user"] == [
"Earlier request", "Replace the old task",
]
assert saved.messages[-1]["content"] == "New input answered."
assert provider.chat_stream_with_retry.await_count == 2
assert RUNTIME_CHECKPOINT_KEY not in saved.metadata
finally:
await reopened.state.aclose()