refactor(goal): sustain one ReAct run until the goal closes (#6538)
* refactor(goal): sustain one ReAct run until the goal closes Keep active goals in the same runner beyond the ordinary iteration limit, with a final answer after successful closure. Remove cross-turn goal handoffs, continuation allowances and rollback bookkeeping while preserving input authorization, recovery, cancellation and terminal lifecycle ownership. Contributes to NAN-392 Co-authored-by: chengyongru <chengyongru.ai@gmail.com> * test(goal): consolidate sustained-run regression coverage Retain lifecycle, history, usage, provider-state privacy and checkpoint cancellation assertions in the existing long-run scenarios. Remove duplicate smoke cases and parameter combinations that do not exercise distinct behavior; keep real Gateway, authorization and generation regressions.
This commit is contained in:
1 parent
3545539128
commit
62c2ed4e7e
68 files changed
+2683
-1421
No files matched your search
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
@@ -14,6 +15,7 @@ from urllib.parse import quote
|
||||
import httpx
|
||||
import pytest
|
||||
import websockets
|
||||
from aiohttp import web
|
||||
|
||||
from nanobot.agent.subagent_sessions import SubagentSessions
|
||||
from nanobot.agent.subagent_status import SubagentStatus
|
||||
@@ -473,3 +475,201 @@ def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
|
||||
asyncio.run(assert_attach_state())
|
||||
finally:
|
||||
_stop_gateway(second)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stop_during_checkpoint", [False, True])
|
||||
async def test_real_gateway_goal_single_run_and_stop(tmp_path: Path, stop_during_checkpoint: bool) -> None:
|
||||
"""Exercise the actual gateway and WebSocket with a synthetic local model."""
|
||||
checkpoint_waiting = asyncio.Event()
|
||||
closing_request = asyncio.Event()
|
||||
release_close = asyncio.Event()
|
||||
requests: list[dict] = []
|
||||
|
||||
async def barrier(_request: web.Request) -> web.Response:
|
||||
checkpoint_waiting.set()
|
||||
return web.Response(text="ready")
|
||||
|
||||
async def model(request: web.Request) -> web.StreamResponse:
|
||||
payload = await request.json()
|
||||
is_title = any(
|
||||
"You write short, neutral chat titles" in str(message.get("content"))
|
||||
for message in payload.get("messages", [])
|
||||
)
|
||||
if is_title:
|
||||
text, reason, tool = "Synthetic goal", "stop", None
|
||||
else:
|
||||
requests.append(payload)
|
||||
number = len(requests)
|
||||
text, reason, tool = None, "tool_calls", None
|
||||
if number == 1:
|
||||
tool = ("create_goal", {"objective": "Verify the synthetic task."})
|
||||
elif number <= 16:
|
||||
tool = ("list_dir", {"path": "."})
|
||||
elif stop_during_checkpoint:
|
||||
assert number == 17
|
||||
assert "Handle this independent input" in str(payload["messages"])
|
||||
text, reason = "Handled independent input.", "content_filter"
|
||||
elif number == 17:
|
||||
closing_request.set()
|
||||
await release_close.wait()
|
||||
tool = ("update_goal", {"action": "complete", "recap": "Verified."})
|
||||
else:
|
||||
assert number == 18 and not payload.get("tools")
|
||||
text, reason = "Verified.", "stop"
|
||||
message: dict = {"role": "assistant", "content": text}
|
||||
if tool is not None:
|
||||
message["tool_calls"] = [{
|
||||
"id": f"call-{len(requests)}", "type": "function",
|
||||
"function": {"name": tool[0], "arguments": json.dumps(tool[1])},
|
||||
}]
|
||||
usage = {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
|
||||
if not payload.get("stream"):
|
||||
return web.json_response({
|
||||
"id": "synthetic", "object": "chat.completion", "created": 1,
|
||||
"model": "smoke-model", "choices": [{"index": 0, "message": message, "finish_reason": reason}],
|
||||
"usage": usage,
|
||||
})
|
||||
delta: dict = {"role": "assistant"}
|
||||
if text is not None:
|
||||
delta["content"] = text
|
||||
if tool is not None:
|
||||
delta["tool_calls"] = [{"index": 0, **message["tool_calls"][0]}]
|
||||
response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
|
||||
await response.prepare(request)
|
||||
for choice in (
|
||||
{"index": 0, "delta": delta, "finish_reason": None},
|
||||
{"index": 0, "delta": {}, "finish_reason": reason},
|
||||
):
|
||||
chunk = {"id": "synthetic", "object": "chat.completion.chunk", "created": 1,
|
||||
"model": "smoke-model", "choices": [choice], "usage": usage}
|
||||
await response.write(f"data: {json.dumps(chunk)}\n\n".encode())
|
||||
await response.write(b"data: [DONE]\n\n")
|
||||
return response
|
||||
|
||||
app = web.Application()
|
||||
app.router.add_get("/barrier", barrier)
|
||||
app.router.add_post("/v1/chat/completions", model)
|
||||
server = web.AppRunner(app)
|
||||
await server.setup()
|
||||
site = web.TCPSite(server, "127.0.0.1", 0)
|
||||
await site.start()
|
||||
assert site._server is not None and site._server.sockets # noqa: SLF001
|
||||
model_port = site._server.sockets[0].getsockname()[1] # noqa: SLF001
|
||||
ws_port, gateway_port = _free_port(), _free_port()
|
||||
home, workspace = tmp_path / "home", tmp_path / "workspace"
|
||||
home.mkdir()
|
||||
workspace.mkdir()
|
||||
config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"
|
||||
_write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)
|
||||
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
config["providers"]["custom"]["apiBase"] = f"http://127.0.0.1:{model_port}/v1"
|
||||
config_path.write_text(json.dumps(config), encoding="utf-8")
|
||||
launcher = """
|
||||
import asyncio, sys, urllib.request
|
||||
from nanobot.session.state import SessionState
|
||||
original = SessionState.checkpoint_view
|
||||
barrier_url = sys.argv[3]
|
||||
held = False
|
||||
async def checkpoint(self, session, payload):
|
||||
global held
|
||||
await original(self, session, payload)
|
||||
results = payload.get('completed_tool_results', [])
|
||||
if barrier_url and not held and results and results[-1].get('tool_call_id') == 'call-16':
|
||||
held = True
|
||||
def signal():
|
||||
with urllib.request.urlopen(barrier_url) as response:
|
||||
response.read()
|
||||
await asyncio.to_thread(signal)
|
||||
await asyncio.Event().wait()
|
||||
SessionState.checkpoint_view = checkpoint
|
||||
home, config = sys.argv[1:3]
|
||||
sys.argv = ['nanobot', '--home', home, 'gateway', '--config', config]
|
||||
from nanobot.cli.entry import main
|
||||
main()
|
||||
"""
|
||||
env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_")}
|
||||
env.update({"HOME": str(home), "USERPROFILE": str(home), "APPDATA": str(home),
|
||||
"LOCALAPPDATA": str(home), "TMP": str(tmp_path), "TEMP": str(tmp_path),
|
||||
"NO_PROXY": "localhost,127.0.0.1", "no_proxy": "localhost,127.0.0.1"})
|
||||
creationflags = subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
|
||||
process = None
|
||||
try:
|
||||
with log_path.open("wb") as log:
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-c", launcher, str(home), str(config_path),
|
||||
f"http://127.0.0.1:{model_port}/barrier" if stop_during_checkpoint else ""],
|
||||
cwd=Path(__file__).resolve().parents[2], env=env, stdout=log,
|
||||
stderr=subprocess.STDOUT, creationflags=creationflags,
|
||||
)
|
||||
bootstrap = await asyncio.to_thread(
|
||||
_wait_for_bootstrap, f"http://127.0.0.1:{ws_port}", process, log_path,
|
||||
)
|
||||
async with websockets.connect(bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=goal-e2e") as ws:
|
||||
await _recv_until(ws, "ready")
|
||||
await ws.send(json.dumps({"type": "new_chat"}))
|
||||
chat_id = (await _recv_until(ws, "attached"))["chat_id"]
|
||||
await _recv_until(ws, "session_updated")
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "/goal Verify the synthetic task",
|
||||
"webui": True, "turn_id": "goal-e2e"}))
|
||||
events: list[dict] = []
|
||||
|
||||
async def receive_until(predicate):
|
||||
async with asyncio.timeout(20):
|
||||
while True:
|
||||
event = json.loads(await ws.recv())
|
||||
events.append(event)
|
||||
if predicate(event):
|
||||
return event
|
||||
|
||||
if stop_during_checkpoint:
|
||||
await asyncio.wait_for(checkpoint_waiting.wait(), 20)
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "/stop", "webui": True}))
|
||||
end = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert end.get("outcome") == "cancelled"
|
||||
assert end["goal_state"]["status"] == "active"
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
|
||||
assert len(requests) == 16
|
||||
running = [event for event in events if event.get("event") == "goal_status" and event.get("status") == "running"]
|
||||
# Submitting Stop hydrates the current status before cancellation.
|
||||
assert {event.get("turn_id") for event in running} == {"goal-e2e"}
|
||||
assert running[0]["started_at"] > 0
|
||||
assert len({event["started_at"] for event in running}) == 1
|
||||
assert sum(event.get("event") == "turn_end" for event in events) == 1
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id,
|
||||
"content": "Handle this independent input", "webui": True,
|
||||
"turn_id": "follow-up"}))
|
||||
followup = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert followup.get("turn_id") == "follow-up"
|
||||
assert len(requests) == 17
|
||||
else:
|
||||
await asyncio.wait_for(closing_request.wait(), 20)
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "running")
|
||||
assert not any(event.get("event") == "turn_end" for event in events)
|
||||
release_close.set()
|
||||
end = await receive_until(lambda event: event.get("event") == "turn_end")
|
||||
assert end.get("turn_id") == "goal-e2e"
|
||||
assert not end["goal_state"]["active"]
|
||||
assert len(requests) == 18
|
||||
await receive_until(lambda event: event.get("event") == "goal_status" and event.get("status") == "idle")
|
||||
assert sum(event.get("event") == "goal_status" and event.get("status") == "running" for event in events) == 1
|
||||
assert sum(event.get("event") == "turn_end" for event in events) == 1
|
||||
assert any(event.get("event") == "goal_state" and event.get("goal_state", {}).get("active") for event in events)
|
||||
reconnect_bootstrap = await asyncio.to_thread(_get_bootstrap, f"http://127.0.0.1:{ws_port}/webui/bootstrap")
|
||||
async with websockets.connect(reconnect_bootstrap["ws_url"] + "?token=" + reconnect_bootstrap["token"] + "&client_id=goal-reconnect") as reconnected:
|
||||
await _recv_until(reconnected, "ready")
|
||||
await reconnected.send(json.dumps({"type": "attach", "chat_id": chat_id}))
|
||||
await _recv_until(reconnected, "attached")
|
||||
state = await _recv_until(reconnected, "goal_state")
|
||||
assert state["goal_state"] == {"active": False}
|
||||
finally:
|
||||
release_close.set()
|
||||
if process is not None and process.poll() is None:
|
||||
if sys.platform == "win32":
|
||||
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
|
||||
capture_output=True, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
else:
|
||||
process.terminate()
|
||||
process.wait(timeout=30)
|
||||
await server.cleanup()
|
||||
@@ -0,0 +1,130 @@
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.bus.outbound_events import GoalStateSyncEvent, TurnEndEvent
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventContext
|
||||
from nanobot.session.goal_state import GOAL_STATE_KEY, goal_state_runtime_lines
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.session.webui_turns import WebuiTurnCoordinator
|
||||
from nanobot.webui.goal_state import goal_state_ws_blob
|
||||
from nanobot.webui.session_projection import WebUISessionProjection
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_inactive_when_missing_or_completed():
|
||||
assert goal_state_ws_blob(None) == {"active": False}
|
||||
assert goal_state_ws_blob({}) == {"active": False}
|
||||
assert goal_state_ws_blob({GOAL_STATE_KEY: {"status": "completed", "objective": "x"}}) == {
|
||||
"active": False,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("current_goal", [None, {"status": "completed"}])
|
||||
def test_goal_state_ws_does_not_revive_superseded_legacy_goal(current_goal):
|
||||
metadata = {
|
||||
GOAL_STATE_KEY: current_goal,
|
||||
"thread_goal": {"status": "active", "objective": "Old goal"},
|
||||
}
|
||||
|
||||
assert goal_state_ws_blob(metadata) == {"active": False}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_active_shape():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "active",
|
||||
"objective": "Build feature.",
|
||||
"ui_summary": "feat",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": True,
|
||||
"status": "active",
|
||||
"ui_summary": "feat",
|
||||
"objective": "Build feature.",
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_blob_preserves_blocked_state_for_host_attention():
|
||||
meta = {
|
||||
GOAL_STATE_KEY: {
|
||||
"status": "blocked",
|
||||
"objective": "Deploy safely.",
|
||||
"ui_summary": "Approval required",
|
||||
"recap": "Production access is required.",
|
||||
},
|
||||
}
|
||||
assert goal_state_ws_blob(meta) == {
|
||||
"active": False,
|
||||
"status": "blocked",
|
||||
"ui_summary": "Approval required",
|
||||
"objective": "Deploy safely.",
|
||||
"recap": "Production access is required.",
|
||||
}
|
||||
|
||||
|
||||
def test_goal_state_ws_truncation_is_display_only_for_legacy_json():
|
||||
objective = "x" * 598 + " " + "finish the objective"
|
||||
summary = "s" * 130
|
||||
recap = "r" * 250
|
||||
legacy_goal = json.dumps({
|
||||
"status": "active",
|
||||
"objective": objective,
|
||||
"ui_summary": summary,
|
||||
"recap": recap,
|
||||
})
|
||||
metadata = {"thread_goal": legacy_goal}
|
||||
|
||||
assert goal_state_ws_blob(metadata) == {
|
||||
"active": True,
|
||||
"status": "active",
|
||||
"objective": "x" * 598 + "…",
|
||||
"ui_summary": summary[:120],
|
||||
"recap": recap[:240],
|
||||
}
|
||||
assert metadata["thread_goal"] == legacy_goal
|
||||
assert goal_state_runtime_lines(metadata) == [
|
||||
"Goal (active):", objective, f"Summary: {summary}",
|
||||
]
|
||||
|
||||
|
||||
async def test_long_goal_uses_same_display_snapshot_for_live_end_and_reconnect(tmp_path):
|
||||
sessions = SessionManager(tmp_path)
|
||||
bus = MessageBus()
|
||||
coordinator = WebuiTurnCoordinator(
|
||||
bus=bus, sessions=sessions, schedule_background=lambda coro: coro.close(),
|
||||
)
|
||||
coordinator.subscribe()
|
||||
key = "websocket:goal-view"
|
||||
objective = "x" * 700
|
||||
metadata = {GOAL_STATE_KEY: {"status": "active", "objective": objective}}
|
||||
expected = {"active": True, "status": "active", "objective": "x" * 600 + "…"}
|
||||
try:
|
||||
await sessions.state.get(key)
|
||||
await sessions.state.update_metadata(key, metadata)
|
||||
await bus.publish(GoalStateChanged(
|
||||
context=RuntimeEventContext(channel="websocket", chat_id="goal-view", session_key=key),
|
||||
session_metadata=metadata,
|
||||
))
|
||||
live_event = bus.outbound.get_nowait().event
|
||||
assert isinstance(live_event, GoalStateSyncEvent)
|
||||
assert live_event.goal_state == expected
|
||||
|
||||
await coordinator.handle_turn_end(
|
||||
InboundMessage(channel="websocket", sender_id="user", chat_id="goal-view", content="go"),
|
||||
session_key=key, latency_ms=None,
|
||||
)
|
||||
end_event = bus.outbound.get_nowait().event
|
||||
assert isinstance(end_event, TurnEndEvent)
|
||||
assert end_event.goal_state == expected
|
||||
|
||||
assert await WebUISessionProjection(sessions).hydration_events(key, "goal-view") == (
|
||||
{"event": "goal_state", "chat_id": "goal-view", "goal_state": expected},
|
||||
)
|
||||
stored = await sessions.state.read_metadata(key)
|
||||
assert stored is not None
|
||||
assert stored["metadata"][GOAL_STATE_KEY]["objective"] == objective
|
||||
finally:
|
||||
await sessions.state.aclose()
|
||||
@@ -101,7 +101,7 @@ async def test_hydration_events_restore_goal_and_running_turn(
|
||||
)
|
||||
|
||||
|
||||
async def test_hydration_events_are_quiet_without_actionable_state(
|
||||
async def test_hydration_clears_stale_goal_without_an_active_goal(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
sessions = MagicMock()
|
||||
@@ -115,7 +115,7 @@ async def test_hydration_events_are_quiet_without_actionable_state(
|
||||
assert await WebUISessionProjection(sessions).hydration_events(
|
||||
"websocket:chat-1",
|
||||
"chat-1",
|
||||
) == ()
|
||||
) == ({"event": "goal_state", "chat_id": "chat-1", "goal_state": {"active": False}},)
|
||||
|
||||
|
||||
async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop(
|
||||
@@ -157,4 +157,5 @@ async def test_hydration_yields_during_metadata_read_and_reads_live_turn_on_loop
|
||||
finally:
|
||||
release.set()
|
||||
events = await task
|
||||
assert events[0]["status"] == "running"
|
||||
assert events[0]["goal_state"] == {"active": False}
|
||||
assert events[1]["status"] == "running"
|
||||
Reference in new issue
Block a user