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:
1 parent
c1ed649b81
commit
384b763830
16 files changed
+815
-89
No files matched your search
@@ -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 = (
|
||||
|
||||
Reference in new issue
Block a user