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

+4
View File
@@ -1048,6 +1048,10 @@ class AgentLoop:
if session is None or ephemeral:
return
public_payload = dict(payload)
preceding = Session(key=session.key)
self._save_turn(preceding, public_payload["preceding_messages"], skip=0)
public_payload["preceding_messages"] = preceding.messages
public_payload["consumed_followup_ids"] = sorted(preceding.consumed_followup_ids)
private_state = public_payload.pop("provider_state", None)
public_payload.pop(self._PROVIDER_STATE_CHECKPOINT_VERSION_KEY, None)
if "provider_state" in payload and (
+17 -1
View File
@@ -222,6 +222,7 @@ class AgentRunner:
await self._emit_checkpoint(
spec,
checkpoint,
messages,
)
self._append_injected_messages(messages, injections)
if real_injection:
@@ -549,6 +550,7 @@ class AgentRunner:
"completed_tool_results": [],
"pending_tool_calls": [tc.to_openai_tool_call() for tc in response.tool_calls],
},
messages,
)
await hook.before_execute_tools(context)
@@ -609,6 +611,7 @@ class AgentRunner:
model_messages=checkpoint_model_messages,
),
},
messages,
)
empty_content_retries = 0
length_recovery_parts.clear()
@@ -832,6 +835,7 @@ class AgentRunner:
"pending_tool_calls": [],
"provider_state": conversation_state.checkpoint(messages),
},
messages,
)
if length_recovery_parts:
final_content = (
@@ -1405,10 +1409,22 @@ class AgentRunner:
self,
spec: AgentRunSpec,
payload: dict[str, Any],
messages: list[dict[str, Any]],
) -> None:
callback = spec.checkpoint_callback
if callback is not None:
await callback(payload)
if spec.transcript_input is not None:
start = spec.transcript_input.message_count
else:
assert spec.initial_messages is not None
start = len(spec.initial_messages)
# Replacing the checkpoint must retain every earlier round of this
# run, including follow-ups consumed since the accepted input.
batch_size = 1 + len(payload["completed_tool_results"])
await callback({
**payload,
"preceding_messages": messages[start:len(messages) - batch_size],
})
@staticmethod
def _append_final_message(messages: list[dict[str, Any]], content: str | None) -> None:
+65 -18
View File
@@ -36,9 +36,8 @@ if TYPE_CHECKING:
from nanobot.agent.tools.mcp_oauth import MCPOAuthHandlers
from nanobot.config.schema import Config, MCPServerConfig
# Transient connection errors that warrant a single retry.
# These typically happen when an MCP server restarts or a network
# connection is interrupted between calls.
# Transient stream failures. Retrying also requires an operation safe to replay
# or proof that the tool request has not started.
_TRANSIENT_EXC_NAMES: frozenset[str] = frozenset((
"ClosedResourceError",
"BrokenResourceError",
@@ -522,10 +521,14 @@ class _MCPWrapperBase(Tool):
_session: ClientSession
_server_name: str
_name: str
_replay_safe: bool
def _set_mcp_connection(self, session: ClientSession, server_name: str) -> None:
def _set_mcp_connection(
self, session: ClientSession, server_name: str, *, replay_safe: bool,
) -> None:
self._session = session
self._server_name = server_name
self._replay_safe = replay_safe
self._reconnect: _ReconnectCallback | None = None
def set_reconnect_handler(self, reconnect: _ReconnectCallback) -> None:
@@ -540,14 +543,13 @@ class _MCPWrapperBase(Tool):
if already_refreshed or not _is_session_terminated(exc) or self._reconnect is None:
return False
logger.warning(
"MCP {} '{}' session terminated; reconnecting server '{}' before retry",
"MCP {} '{}' session terminated; reconnecting server '{}'",
capability_kind,
self._name,
self._server_name,
)
refreshed_tool = await self._reconnect(self._server_name, self._name, self)
refreshed_session = getattr(refreshed_tool, "_session", None)
if refreshed_session is None:
if not isinstance(refreshed_tool, _MCPWrapperBase):
logger.warning(
"MCP {} '{}' could not refresh session for server '{}'",
capability_kind,
@@ -555,12 +557,23 @@ class _MCPWrapperBase(Tool):
self._server_name,
)
return False
self._session = refreshed_session
self._session = refreshed_tool._session
self._replay_safe = refreshed_tool._replay_safe
return True
def _unknown_tool_outcome(self, reason: str) -> ToolResult:
logger.warning(
"MCP tool '{}' {}; outcome unknown, not replaying", self._name, reason,
)
return ToolResult.error(
f"(MCP tool call outcome is unknown; {reason}. The operation "
"may have completed and was not replayed after this failure. Check its outcome before "
"retrying to avoid duplicate side effects.)"
)
async def _request_with_recovery(
self,
request: Callable[[], Awaitable[_MCPResultT]],
request: Callable[[ClientSession], Awaitable[_MCPResultT]],
timeout: float,
capability_kind: Literal["tool", "resource", "prompt"],
) -> _MCPResultT | ToolResult:
@@ -569,10 +582,30 @@ class _MCPWrapperBase(Tool):
operation = f"{capability_kind} {'read' if capability_kind == 'resource' else 'call'}"
refreshed_session = False
retried = False
request_started = False
async def attempt(session: ClientSession, replay_safe: bool) -> _MCPResultT:
nonlocal request_started
if not replay_safe and self._reconnect is not None:
# Repair stale sessions before submitting a non-replayable call.
# A failed ping proves that this attempt never called the tool;
# an exception from call_tool itself cannot provide that proof.
await session.send_ping()
request_started = True
return await request(session)
while True:
# Keep the declaration bound to the actual session used by this
# attempt, even if another call reconnects this wrapper meanwhile.
session, replay_safe = self._session, self._replay_safe
if request_started and not replay_safe:
return self._unknown_tool_outcome("no longer permits safe replay after reconnect")
try:
return await asyncio.wait_for(request(), timeout=timeout)
# Preflight and submission share the existing per-attempt timeout.
return await asyncio.wait_for(attempt(session, replay_safe), timeout=timeout)
except asyncio.TimeoutError:
if request_started and not replay_safe:
return self._unknown_tool_outcome(f"timed out after {timeout}s")
logger.warning(
"MCP {} '{}' timed out after {}s", capability_kind, self._name, timeout
)
@@ -584,6 +617,10 @@ class _MCPWrapperBase(Tool):
logger.warning("MCP {} '{}' was cancelled by server/SDK", capability_kind, self._name)
return ToolResult.error(f"(MCP {operation} was cancelled)")
except Exception as exc:
if request_started and not replay_safe and (
_is_session_terminated(exc) or isinstance(exc, httpx.TransportError)
):
return self._unknown_tool_outcome(f"lost its response ({type(exc).__name__})")
if await self._refresh_session_after_termination(
exc, refreshed_session, capability_kind
):
@@ -673,13 +710,23 @@ class MCPToolWrapper(_MCPWrapperBase):
tool_def: MCPToolDefinition,
tool_timeout: int = 30,
):
self._set_mcp_connection(session, server_name)
self._original_name = tool_def.name
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_{tool_def.name}")
self._description = tool_def.description or tool_def.name
raw_schema = tool_def.inputSchema or {"type": "object", "properties": {}}
self._parameters = _normalize_schema_for_openai(raw_schema)
self._tool_timeout = tool_timeout
# Replay is opt-in through explicit server declarations, not inferred
# from names or destructiveHint=False (additive writes can duplicate).
# This trusts the server's contract; it is not client-side deduplication
# and does not change tool permissions or concurrency classification.
annotations = getattr(tool_def, "annotations", None)
self._set_mcp_connection(
session, server_name,
replay_safe=annotations is not None and (
annotations.readOnlyHint is True or annotations.idempotentHint is True
),
)
@property
def name(self) -> str:
@@ -695,7 +742,7 @@ class MCPToolWrapper(_MCPWrapperBase):
async def execute(self, **kwargs: Any) -> str:
result = await self._request_with_recovery(
lambda: self._session.call_tool(self._original_name, arguments=kwargs),
lambda session: session.call_tool(self._original_name, arguments=kwargs),
self._tool_timeout,
"tool",
)
@@ -781,7 +828,7 @@ class MCPResourceWrapper(_MCPWrapperBase):
resource_def: Resource,
resource_timeout: int = 30,
):
self._set_mcp_connection(session, server_name)
self._set_mcp_connection(session, server_name, replay_safe=True)
self._uri = resource_def.uri
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_resource_{resource_def.name}")
desc = resource_def.description or resource_def.name
@@ -813,12 +860,12 @@ class MCPResourceWrapper(_MCPWrapperBase):
from mcp import types
result = await self._request_with_recovery(
lambda: self._session.read_resource(self._uri),
lambda session: session.read_resource(self._uri),
self._resource_timeout,
"resource",
)
if isinstance(result, ToolResult):
return str(result)
return result
parts: list[str] = []
for block in result.contents:
if isinstance(block, types.TextResourceContents):
@@ -842,7 +889,7 @@ class MCPPromptWrapper(_MCPWrapperBase):
prompt_def: Prompt,
prompt_timeout: int = 30,
):
self._set_mcp_connection(session, server_name)
self._set_mcp_connection(session, server_name, replay_safe=True)
self._prompt_name = prompt_def.name
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_prompt_{prompt_def.name}")
desc = prompt_def.description or prompt_def.name
@@ -887,12 +934,12 @@ class MCPPromptWrapper(_MCPWrapperBase):
from mcp import types
result = await self._request_with_recovery(
lambda: self._session.get_prompt(self._prompt_name, arguments=kwargs),
lambda session: session.get_prompt(self._prompt_name, arguments=kwargs),
self._prompt_timeout,
"prompt",
)
if isinstance(result, ToolResult):
return str(result)
return result
parts: list[str] = []
for message in result.messages:
content = message.content
+1 -6
View File
@@ -992,7 +992,6 @@ def _run_claimed_gateway(
tasks: list[asyncio.Task[Any]] = []
shutdown_task: asyncio.Task[Any] | None = None
runtime_tasks: asyncio.Future[list[Any]] | None = None
startup_complete = False
shutdown_event = asyncio.Event()
cli_terminal._ensure_interactive_tty_mode()
restore_shutdown_handlers = _install_gateway_shutdown_handlers(
@@ -1096,7 +1095,6 @@ def _run_claimed_gateway(
name="nanobot-webui-dev-server",
))
runtime_tasks = asyncio.gather(*tasks)
startup_complete = True
shutdown_task = asyncio.create_task(
shutdown_event.wait(),
name="nanobot-gateway-shutdown",
@@ -1118,10 +1116,7 @@ def _run_claimed_gateway(
console.print("\n[red]Error: Gateway crashed unexpectedly[/red]")
console.print(traceback.format_exc())
if not startup_complete:
# Do not report a successful gateway command when startup
# failed before any runtime task or listener was created.
raise typer.Exit(1)
raise typer.Exit(1)
finally:
try:
if shutdown_task and not shutdown_task.done():
+52 -9
View File
@@ -215,6 +215,33 @@ def _checkpoint_tool_call_ids(
return ids if len(ids) == len(set(ids)) else None
def _checkpoint_prefix_is_complete(value: object) -> bool:
if not isinstance(value, list):
return False
pending: set[str] = set()
for value_row in cast(list[object], value):
if not isinstance(value_row, dict):
return False
row = cast(dict[str, Any], value_row)
role = row.get("role")
if role == "tool":
call_id = row.get("tool_call_id")
if not isinstance(call_id, str) or call_id not in pending:
return False
pending.remove(call_id)
elif role in ("user", "assistant"):
if pending:
return False
if role == "assistant" and row.get("tool_calls") is not None:
ids = _checkpoint_tool_call_ids(row["tool_calls"])
if ids is None:
return False
pending.update(ids)
else:
return False
return not pending
def runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:
"""Return whether a checkpoint is safe to offer for continuation.
@@ -222,6 +249,8 @@ def runtime_checkpoint_is_well_formed(checkpoint: Mapping[str, Any]) -> bool:
Continue is stricter: silently dropping a malformed tool result could make
the model repeat an external side effect.
"""
if not _checkpoint_prefix_is_complete(checkpoint.get("preceding_messages", [])):
return False
assistant_value = cast(object, checkpoint.get("assistant_message"))
if not isinstance(assistant_value, dict):
return False
@@ -294,7 +323,11 @@ def restore_runtime_checkpoint(session: Session) -> bool:
completed = cast(list[object], completed_value) if isinstance(completed_value, list) else []
pending = cast(list[object], pending_value) if isinstance(pending_value, list) else []
restored: list[dict[str, Any]] = []
preceding = data.get("preceding_messages", [])
restored = (
[dict(cast(dict[str, Any], row)) for row in cast(list[object], preceding) if isinstance(row, dict)]
if isinstance(preceding, list) else []
)
if isinstance(assistant, dict):
assistant_row = cast(dict[str, Any], assistant)
else:
@@ -331,21 +364,31 @@ def restore_runtime_checkpoint(session: Session) -> bool:
"role": "tool",
"tool_call_id": tool_call_id,
"name": name if isinstance(name, str) and name else "tool",
"content": "Error: Task interrupted before this tool finished.",
"content": "Error: Task interrupted; this tool's outcome is unknown. Check its effects before retrying.",
"timestamp": datetime.now().isoformat(),
"_recovery_interrupted": True,
}
)
overlap = 0
for size in range(min(len(session.messages), len(restored)), 0, -1):
if all(
_checkpoint_message_key(left) == _checkpoint_message_key(right)
for left, right in zip(session.messages[-size:], restored[:size])
):
overlap = size
break
# Cumulative checkpoints contain only the delta after accepted input. The
# owner commits it and clears the checkpoint in one transaction, so none of
# it is already in history. Equal text can belong to distinct user inputs.
# Only legacy single-batch checkpoints may overlap a materialized tail.
if "preceding_messages" not in data:
for size in range(min(len(session.messages), len(restored)), 0, -1):
if all(
_checkpoint_message_key(left) == _checkpoint_message_key(right)
for left, right in zip(session.messages[-size:], restored[:size])
):
overlap = size
break
session.messages.extend(restored[overlap:])
followup_ids = data.get("consumed_followup_ids", [])
if isinstance(followup_ids, list) and followup_ids:
session.consumed_followup_ids |= {
value for value in cast(list[object], followup_ids) if isinstance(value, str)
}
assistant_data = cast(dict[str, Any], assistant) if isinstance(assistant, dict) else None
synchronized = (
+6
View File
@@ -143,6 +143,12 @@ class RecoveryCoordinator:
state = recovery_state_from_metadata(session.metadata)
if state and state["status"] in {"resuming", "awaiting_user", "failed"}:
await self._cancel_active_recovery(message.session_key)
# Cancellation may have committed the checkpoint or completed the
# recovery. Classify a fresh owner draft after that handoff.
session = await self.sessions.state.get(message.session_key)
state = recovery_state_from_metadata(session.metadata)
if not state or state["status"] not in {"resuming", "awaiting_user", "failed"}:
return True
if state.get("reason") != "model_request_failed":
restore_runtime_checkpoint(session)
if not restore_pending_interruption(session, superseded=True):