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
@@ -11,8 +11,13 @@ from nanobot.bus.events import INBOUND_META_TURN_ID, InboundMessage
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.providers.base import GenerationSettings, LLMResponse
|
||||
from nanobot.runtime_context import public_history_message
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.recovery import PENDING_FOLLOWUP_ID_KEY, pending_followups
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.session.recovery import (
|
||||
PENDING_FOLLOWUP_ID_KEY,
|
||||
RUNTIME_CHECKPOINT_KEY,
|
||||
pending_followups,
|
||||
restore_runtime_checkpoint,
|
||||
)
|
||||
from nanobot.webui.recovery import RecoveryCoordinator
|
||||
|
||||
|
||||
@@ -76,7 +81,8 @@ async def test_late_consumption_commits_history_and_only_its_ids(tmp_path, monke
|
||||
await reopened.state.aclose()
|
||||
|
||||
|
||||
async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path):
|
||||
@pytest.mark.parametrize("recover_checkpoint", [False, True])
|
||||
async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(tmp_path, recover_checkpoint):
|
||||
sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
state = sessions.state
|
||||
try:
|
||||
@@ -84,10 +90,22 @@ async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(
|
||||
draft.add_message("user", "initial input")
|
||||
await state.prepare_input(draft)
|
||||
identifier = await state.queue_followup(draft.key, _input("consumed input", "follow-up"))
|
||||
_loop(sessions)._save_turn(draft, [
|
||||
projection = Session(key=draft.key) if recover_checkpoint else draft
|
||||
_loop(sessions)._save_turn(projection, [
|
||||
{"role": "user", "content": "consumed input", PENDING_FOLLOWUP_ID_KEY: identifier},
|
||||
{"role": "assistant", "content": "completed answer"},
|
||||
], skip=0)
|
||||
if recover_checkpoint:
|
||||
await state.checkpoint_view(draft, {
|
||||
"phase": "final_response",
|
||||
"preceding_messages": projection.messages[:-1],
|
||||
"assistant_message": projection.messages[-1],
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
"consumed_followup_ids": list(projection.consumed_followup_ids),
|
||||
})
|
||||
draft = await state.get(draft.key)
|
||||
assert restore_runtime_checkpoint(draft)
|
||||
with sqlite3.connect(sessions._store.path) as db:
|
||||
db.execute("""CREATE TRIGGER reject_ack BEFORE DELETE ON pending_inputs
|
||||
BEGIN SELECT RAISE(ABORT, 'failed follow-up commit'); END""")
|
||||
@@ -96,6 +114,7 @@ async def test_failed_followup_commit_rolls_back_history_and_ack_then_can_retry(
|
||||
for stored in (sessions.read_session_snapshot(draft.key), state.peek(draft.key)):
|
||||
assert [row["content"] for row in stored.messages] == ["initial input"]
|
||||
assert [item.content for item in pending_followups(stored)] == ["consumed input"]
|
||||
assert (RUNTIME_CHECKPOINT_KEY in stored.metadata) is recover_checkpoint
|
||||
with sqlite3.connect(sessions._store.path) as db:
|
||||
db.execute("DROP TRIGGER reject_ack")
|
||||
await state.finish_turn(draft)
|
||||
@@ -127,7 +146,8 @@ async def test_recovered_input_keeps_admission_identity_and_timestamp(tmp_path):
|
||||
await state.aclose()
|
||||
|
||||
|
||||
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path):
|
||||
@pytest.mark.parametrize("interrupt", [False, True], ids=["completed", "checkpoint-recovery"])
|
||||
async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit(tmp_path, monkeypatch, interrupt):
|
||||
import asyncio
|
||||
|
||||
provider = MagicMock(aclose=AsyncMock())
|
||||
@@ -136,9 +156,24 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
|
||||
provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="completed answer"))
|
||||
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path / "workspace", model="test-model")
|
||||
loop.sessions = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
# Plain-text inputs are valid without extension-provided runtime context.
|
||||
monkeypatch.setattr(loop, "_resolve_runtime_context_for_request", AsyncMock(return_value=[]))
|
||||
checkpoint_saved = asyncio.Event()
|
||||
checkpoint = loop._set_runtime_checkpoint
|
||||
|
||||
async def save_checkpoint(session, payload):
|
||||
await checkpoint(session, payload)
|
||||
checkpoint_saved.set()
|
||||
if interrupt:
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr(loop, "_set_runtime_checkpoint", save_checkpoint)
|
||||
try:
|
||||
draft = await loop.sessions.state.get("websocket:chat")
|
||||
draft.add_message("user", "initial input")
|
||||
draft.add_message(
|
||||
"user", "intentionally identical text", **{INBOUND_META_TURN_ID: "initial-input"},
|
||||
timestamp="2026-10-18T19:00:00",
|
||||
)
|
||||
await loop.sessions.state.prepare_input(draft)
|
||||
queue = asyncio.Queue()
|
||||
for turn_id in ("first-input", "second-input"):
|
||||
@@ -147,22 +182,46 @@ async def test_injected_inputs_keep_their_own_identity_through_runner_and_commit
|
||||
message.metadata[PENDING_FOLLOWUP_ID_KEY] = identifier
|
||||
queue.put_nowait(message)
|
||||
runtime = loop.llm_runtime()
|
||||
result = await loop._run_agent_loop(
|
||||
task = asyncio.create_task(loop._run_agent_loop(
|
||||
TranscriptInput(history=draft.get_history(), current_message=None),
|
||||
runtime=runtime, session=draft, pending_queue=queue,
|
||||
request_context=RequestContext(
|
||||
channel="websocket", chat_id="chat", session_key=draft.key,
|
||||
turn_id="active-run", runtime=runtime,
|
||||
),
|
||||
)
|
||||
loop._save_turn(draft, result.messages, skip=2)
|
||||
await loop.sessions.state.finish_turn(draft)
|
||||
stored = await loop.sessions.state.get(draft.key)
|
||||
injected = [row for row in stored.messages if row.get("role") == "user"][1:]
|
||||
assert [public_history_message(row)["content"] for row in injected] == ["intentionally identical text"] * 2
|
||||
assert [row[INBOUND_META_TURN_ID] for row in injected] == ["first-input", "second-input"]
|
||||
assert [row["timestamp"] for row in injected] == ["2026-10-18T19:00:00"] * 2
|
||||
assert pending_followups(stored) == []
|
||||
))
|
||||
try:
|
||||
await asyncio.wait_for(checkpoint_saved.wait(), 5)
|
||||
if interrupt:
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
assert len(pending_followups(await loop.sessions.state.get(draft.key))) == 2
|
||||
else:
|
||||
result = await task
|
||||
loop._save_turn(draft, result.messages, skip=2)
|
||||
await loop.sessions.state.finish_turn(draft)
|
||||
finally:
|
||||
if not task.done():
|
||||
task.cancel()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
provider.chat_stream_with_retry.assert_awaited_once()
|
||||
finally:
|
||||
await loop.aclose()
|
||||
|
||||
reopened = SessionManager(tmp_path / "workspace", sessions_root=tmp_path / "sessions")
|
||||
try:
|
||||
bus = MessageBus()
|
||||
recovery = RecoveryCoordinator(reopened, bus)
|
||||
await recovery.scan()
|
||||
stored = await reopened.state.get(draft.key)
|
||||
inputs = [row for row in stored.messages if row.get("role") == "user"]
|
||||
assert [public_history_message(row)["content"] for row in inputs] == ["intentionally identical text"] * 3
|
||||
assert [row[INBOUND_META_TURN_ID] for row in inputs] == ["initial-input", "first-input", "second-input"]
|
||||
assert [row["timestamp"] for row in inputs] == ["2026-10-18T19:00:00"] * 3
|
||||
assert pending_followups(stored) == []
|
||||
assert bus.inbound.empty()
|
||||
await recovery.scan()
|
||||
assert (await reopened.state.get(draft.key)).messages == stored.messages
|
||||
finally:
|
||||
await reopened.state.aclose()
|
||||
Reference in new issue
Block a user