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:
chengyongruandchengyongru authored and GitHub committed 2026-11-03 22:47:00 +08:00
1 parent 3545539128
commit 62c2ed4e7e
68 files changed
+2683 -1421

No files matched your search

+1 -33
View File
@@ -1,8 +1,7 @@
"""Session metadata helpers for explicit sustained goals.
Tools set ``metadata[GOAL_STATE_KEY]``. Reads accept the legacy session key ``thread_goal``
for older sessions. Callers use ``goal_state_runtime_lines`` and ``goal_state_ws_blob`` without
importing tool implementations.
for older sessions. Callers can read the goal without importing tool implementations.
"""
from __future__ import annotations
@@ -15,7 +14,6 @@ GOAL_COMMAND = "/goal"
MAX_GOAL_OBJECTIVE_CHARS = 4000
# Older builds stored the same JSON blob under this key.
_LEGACY_GOAL_STATE_SESSION_KEY = "thread_goal"
_MAX_OBJECTIVE_WS = 600
def _session_goal_raw(metadata: Mapping[str, Any] | None) -> Any:
@@ -51,15 +49,6 @@ def explicit_goal_requested(message_metadata: Mapping[str, Any] | None) -> bool:
return str(message_metadata.get("original_command") or "").strip() == GOAL_COMMAND
def sustained_goal_turn(
metadata: Mapping[str, Any] | None,
*,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""True when this turn should use sustained-goal runtime limits."""
return sustained_goal_active(metadata) or explicit_goal_requested(message_metadata)
def parse_goal_state(blob: Any) -> dict[str, Any] | None:
if blob is None:
return None
@@ -91,24 +80,3 @@ def goal_state_runtime_lines(metadata: Mapping[str, Any] | None) -> list[str]:
if hint:
out.append(f"Summary: {hint}")
return out
def goal_state_ws_blob(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
"""JSON-safe snapshot for WebSocket ``goal_state`` events (one chat_id per frame)."""
goal = parse_goal_state(_session_goal_raw(metadata)) if metadata else None
if isinstance(goal, dict) and goal.get("status") in {"active", "blocked"}:
status = str(goal.get("status"))
objective = str(goal.get("objective") or "").strip()
if len(objective) > _MAX_OBJECTIVE_WS:
objective = objective[:_MAX_OBJECTIVE_WS].rstrip() + "…"
summary = str(goal.get("ui_summary") or "").strip()[:120]
blob: dict[str, Any] = {"active": status == "active", "status": status}
if summary:
blob["ui_summary"] = summary
if objective:
blob["objective"] = objective
recap = str(goal.get("recap") or "").strip()[:240]
if recap:
blob["recap"] = recap
return blob
return {"active": False}
+17 -6
View File
@@ -42,13 +42,11 @@ _FORK_VOLATILE_METADATA_KEYS = {
"_stopped_at_iteration_limit",
PARENT_SESSION_KEY,
SESSION_TYPE_KEY,
"goal_state",
"pending_user_turn",
"pending_user_followups",
"runtime_checkpoint",
"session_handle",
"webui_recovery",
"thread_goal",
"title",
"title_user_edited",
}
@@ -374,7 +372,10 @@ class SessionInfo(TypedDict):
path: str
def fork_session(source: Session, target_key: str, before_user_index: int) -> Session | None:
def fork_session(
source: Session, target_key: str, before_user_index: int,
*, exclude_metadata: frozenset[str] = frozenset(),
) -> Session | None:
"""Build a portable fork ending before the requested visible user message."""
if before_user_index < 0:
return None
@@ -394,7 +395,7 @@ def fork_session(source: Session, target_key: str, before_user_index: int) -> Se
return None
metadata = deepcopy(source.metadata)
for key in _FORK_VOLATILE_METADATA_KEYS:
for key in _FORK_VOLATILE_METADATA_KEYS | exclude_metadata:
metadata.pop(key, None)
last_consolidated = min(source.last_archived, len(copied))
@@ -432,15 +433,23 @@ class SessionManager:
self._store.initialize()
self._delete_observer: Callable[[str], None] | None = None
self.types = SessionTypes()
self._generation_exclusions: set[str] = set()
self._state: SessionState | None = None
def exclude_generation_metadata(self, keys: frozenset[str]) -> None:
"""Register feature metadata that cannot cross a fork or reset."""
self._generation_exclusions.update(keys)
@property
def state(self) -> SessionState:
"""The asynchronous owner of session state transitions."""
if self._state is None:
from nanobot.session.state import SessionState
self._state = SessionState(self._store, on_delete=self._notify_delete, types=self.types)
self._state = SessionState(
self._store, on_delete=self._notify_delete, types=self.types,
generation_exclusions=self._generation_exclusions,
)
return self._state
def _notify_delete(self, key: str) -> None:
@@ -555,7 +564,9 @@ class SessionManager:
source = self._store.load(source_key)
if source is None:
return None
target = fork_session(source, target_key, before_user_index)
target = fork_session(
source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),
)
if target is not None:
self._store.save(target)
self._store.copy_history_prefix(source_key, target, before_user_index)
+19 -2
View File
@@ -53,12 +53,16 @@ class SessionState:
workers: int = _DEFAULT_WORKERS,
on_delete: Callable[[str], None] | None = None,
types: SessionTypes | None = None,
generation_exclusions: set[str] | None = None,
) -> None:
if capacity < 1:
raise ValueError("session operation capacity must be positive")
if workers < 1:
raise ValueError("session operation worker count must be positive")
self._types = types if types is not None else SessionTypes()
self._generation_exclusions: set[str] = (
generation_exclusions if generation_exclusions is not None else set()
)
self._store = store
self._on_delete = on_delete
self._snapshots: dict[str, Session] = {}
@@ -426,6 +430,15 @@ class SessionState:
return self._draft(session)
return await self._execute(key, read, write=False)
async def read_header(self, key: str) -> Session | None:
"""Read committed identity and metadata without creating a session."""
def read() -> Session | None:
session = self._load(key, history=False)
if session is None:
return None
return replace(session, messages=[], provider_state=None, _baseline=None)
return await self._execute(key, read, write=False)
async def get(self, key: str) -> Session:
"""Read an existing conversation; create missing state on the writer."""
return await self._get(key, history=True)
@@ -661,7 +674,7 @@ class SessionState:
await self._submit_draft(session)
async def finish_turn(self, session: Session) -> None:
"""Commit the assembled transcript and clear its recovery markers."""
"""Commit the assembled transcript and clear its recovery checkpoint."""
session.metadata.pop(_PENDING_KEY, None)
session.metadata.pop(_CHECKPOINT_KEY, None)
await self._submit_draft(session)
@@ -997,7 +1010,9 @@ class SessionState:
source = self._load(source_key)
if source is None:
return None
target = fork_session(source, target_key, before_user_index)
target = fork_session(
source, target_key, before_user_index, exclude_metadata=frozenset(self._generation_exclusions),
)
if target is None:
return None
if title:
@@ -1145,6 +1160,8 @@ class SessionState:
session.metadata = deepcopy(old.metadata)
for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"):
session.metadata.pop(name, None)
for name in self._generation_exclusions:
session.metadata.pop(name, None)
if session.policy.persist:
self._store.delete(key, preserve_archive=True)
self._commit(session)
+8 -260
View File
@@ -1,51 +1,23 @@
"""Internal turn continuation helpers.
This module keeps budget-boundary continuation policy out of ``AgentLoop``.
The loop calls a small set of helpers; those helpers decide whether an internal
continuation is allowed and, when it is, queue the next turn directly.
"""
"""Bookkeeping for explicit recovery inputs and ordinary iteration-limit stops."""
from __future__ import annotations
import dataclasses
from typing import TYPE_CHECKING, Any, Mapping, MutableMapping
from loguru import logger
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from nanobot.session.goal_state import (
goal_state_runtime_lines,
sustained_goal_active,
sustained_goal_turn,
)
from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY
if TYPE_CHECKING:
from nanobot.agent.loop import TurnContext
from nanobot.agent.tools.context import RequestContext
from nanobot.session.state import SessionState
INTERNAL_CONTINUATION_META = "_internal_continuation"
INTERNAL_CONTINUATION_KIND_META = "_internal_continuation_kind"
INTERNAL_CONTINUATION_RUN_STARTED_AT_META = "_internal_continuation_run_started_at"
SKIP_USER_PERSIST_META = "_skip_user_persist"
_ITERATION_LIMIT_META = "_stopped_at_iteration_limit"
_GOAL_CONTINUATION_KIND = "sustained_goal"
_GOAL_CONTINUATION_SENDER = "system:continuation"
_GOAL_CONTINUATION_ROUNDS_KEY = "_sustained_goal_continuation_rounds"
_MAX_GOAL_CONTINUATION_ROUNDS = 12
_STRIPPED_INBOUND_META_KEYS = {
"goal_requested",
"original_command",
}
def record_iteration_limit(
metadata: MutableMapping[str, Any], stop_reason: str, *, continuation_pending: bool,
) -> None:
"""Remember a terminal budget stop, not an internal continuation handoff."""
if stop_reason == "max_iterations" and not continuation_pending:
def record_iteration_limit(metadata: MutableMapping[str, Any], stop_reason: str) -> None:
"""Remember an ordinary execution stopped at its iteration limit."""
if stop_reason == "max_iterations":
metadata[_ITERATION_LIMIT_META] = True
else:
metadata.pop(_ITERATION_LIMIT_META, None)
@@ -73,245 +45,21 @@ async def iteration_limit_context(
def internal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:
"""True for an inbound message created by an internal continuation policy."""
return bool(metadata and metadata.get(INTERNAL_CONTINUATION_META) is True)
def sustained_goal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool:
"""True only for an internal continuation owned by sustained-goal policy."""
return bool(
internal_continuation_inbound(metadata)
and metadata
and metadata.get(INTERNAL_CONTINUATION_KIND_META) == _GOAL_CONTINUATION_KIND
)
def internal_continuation_run_started_at(metadata: Mapping[str, Any] | None) -> float | None:
"""Return the user-visible run start propagated across continuation slices."""
if not metadata:
return None
value = metadata.get(INTERNAL_CONTINUATION_RUN_STARTED_AT_META)
if not isinstance(value, int | float):
return None
started_at = float(value)
return started_at if started_at > 0 else None
def should_persist_user_message(metadata: Mapping[str, Any] | None) -> bool:
"""Return whether this inbound message should be persisted as user input."""
if metadata and metadata.get(SKIP_USER_PERSIST_META) is True:
return False
return not internal_continuation_inbound(metadata)
def should_stream_budget_response(
*,
stop_reason: str,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""Return whether the budget-boundary response should be sent to the user."""
if stop_reason != "max_iterations":
return True
return should_finalize_on_max_iterations(
pending_queue_available=pending_queue_available,
session_metadata=session_metadata,
message_metadata=message_metadata,
)
def should_finalize_on_max_iterations(
*,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
"""Return whether a max-iteration boundary should produce a final response.
When a sustained goal can continue internally, the current runner slice
should stop without spending an extra no-tools finalization call. The next
queued continuation slice owns the eventual user-visible response.
"""
return not (
pending_queue_available
and _goal_continuation_available(
session_metadata,
message_metadata=message_metadata,
)
)
async def maybe_continue_turn(
ctx: TurnContext, *, session_metadata: Mapping[str, Any],
) -> bool:
"""Queue an internal continuation for *ctx* when policy allows it."""
if ctx.session is None or ctx.pending_queue is None:
return False
if not _continuation_available(
stop_reason=ctx.stop_reason,
pending_queue_available=True,
session_metadata=session_metadata,
message_metadata=ctx.msg.metadata,
):
return False
metadata = _internal_continuation_metadata(
ctx.msg.metadata,
run_started_at=ctx.visible_run_started_at,
)
request = ctx.request_context
assert request is not None and request.turn_id is not None
metadata[REQUEST_ORIGIN_METADATA_KEY] = {
"message_id": request.message_id,
"turn_id": request.turn_id,
}
content = _goal_continuation_prompt(session_metadata)
messages = _strip_terminal_assistant(ctx.all_messages, ctx.final_content)
_increment_goal_continuation_round(ctx.session.metadata)
logger.info("Turn budget reached; scheduling internal continuation")
ctx.final_content = ""
ctx.all_messages = messages
ctx.suppress_response = True
await ctx.pending_queue.put(
dataclasses.replace(
ctx.msg,
sender_id=_GOAL_CONTINUATION_SENDER,
content=content,
media=[],
metadata=metadata,
session_key_override=ctx.session_key,
)
)
return True
def prepare_save_boundary(ctx: TurnContext) -> None:
"""Prepare continuation bookkeeping and the history append boundary."""
if ctx.session is not None:
clear_internal_continuation_state(ctx.session.metadata)
assert ctx.transcript_input is not None
ctx.save_skip = _save_skip_for_turn(
message_metadata=ctx.msg.metadata,
initial_message_count=ctx.transcript_input.message_count,
input_persisted_early=ctx.input_persisted_early,
)
def _continuation_available(
*,
stop_reason: str,
pending_queue_available: bool,
session_metadata: Mapping[str, Any] | None,
message_metadata: Mapping[str, Any] | None = None,
) -> bool:
if stop_reason != "max_iterations" or not pending_queue_available:
return False
return _goal_continuation_available(
session_metadata,
message_metadata=message_metadata,
)
def clear_internal_continuation_state(metadata: MutableMapping[str, Any]) -> None:
"""Reset policy bookkeeping once its owning runtime mode is inactive."""
if not sustained_goal_active(metadata):
reset_goal_continuation_rounds(metadata)
def reset_goal_continuation_rounds(metadata: MutableMapping[str, Any]) -> None:
"""Start a newly created or replaced goal with a fresh continuation budget."""
metadata.pop(_GOAL_CONTINUATION_ROUNDS_KEY, None)
def _save_skip_for_turn(
*,
message_metadata: Mapping[str, Any] | None,
initial_message_count: int,
input_persisted_early: bool,
def save_skip_for_turn(
*, message_metadata: Mapping[str, Any] | None,
initial_message_count: int, input_persisted_early: bool,
) -> int:
if message_metadata and message_metadata.get(SKIP_USER_PERSIST_META) is True:
return initial_message_count
if internal_continuation_inbound(message_metadata):
return initial_message_count
if not input_persisted_early:
return initial_message_count - 1
return initial_message_count
def _goal_continuation_available(
session_metadata: Mapping[str, Any] | None,
*,
message_metadata: Mapping[str, Any] | None = None,
max_rounds: int = _MAX_GOAL_CONTINUATION_ROUNDS,
) -> bool:
if not sustained_goal_turn(session_metadata, message_metadata=message_metadata):
return False
if not sustained_goal_active(session_metadata):
return False
try:
rounds = int((session_metadata or {}).get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)
except (TypeError, ValueError):
rounds = 0
return rounds < max(0, max_rounds)
def _increment_goal_continuation_round(session_metadata: MutableMapping[str, Any]) -> None:
try:
rounds = int(session_metadata.get(_GOAL_CONTINUATION_ROUNDS_KEY) or 0)
except (TypeError, ValueError):
rounds = 0
session_metadata[_GOAL_CONTINUATION_ROUNDS_KEY] = rounds + 1
def _internal_continuation_metadata(
message_metadata: Mapping[str, Any] | None,
*,
run_started_at: float | None = None,
) -> dict[str, Any]:
metadata = dict(message_metadata or {})
metadata[INTERNAL_CONTINUATION_META] = True
metadata[INTERNAL_CONTINUATION_KIND_META] = _GOAL_CONTINUATION_KIND
if run_started_at is not None:
metadata[INTERNAL_CONTINUATION_RUN_STARTED_AT_META] = float(run_started_at)
for key in _STRIPPED_INBOUND_META_KEYS:
metadata.pop(key, None)
return metadata
def _goal_continuation_prompt(metadata: Mapping[str, Any] | None) -> str:
lines = goal_state_runtime_lines(metadata)
if lines:
goal = "\n".join(lines)
return (
"Continue the active sustained goal after the previous turn reached "
"its tool-call budget.\n\n"
f"{goal}\n\n"
"Continue from the saved context. Do not mention the continuation "
"boundary to the user. Use tools as needed, and call update_goal "
"with action='complete' when the objective is truly finished."
)
return (
"Continue the active sustained goal after the previous turn reached "
"its tool-call budget. Continue from the saved context. Do not mention "
"the continuation boundary to the user. Use tools as needed, and call "
"update_goal with action='complete' when the objective is truly finished."
)
def _strip_terminal_assistant(
messages: list[dict[str, Any]],
final_content: str | None,
) -> list[dict[str, Any]]:
if not messages:
return messages
last = messages[-1]
if last.get("role") != "assistant":
return messages
if final_content is None or last.get("content") != final_content:
return messages
if last.get("tool_calls"):
return messages
return messages[:-1]
return initial_message_count if input_persisted_early else initial_message_count - 1
+1 -1
View File
@@ -40,7 +40,6 @@ from nanobot.providers.base import LLMProvider, LLMUsage
from nanobot.providers.fallback_provider import FallbackModelObserver, FallbackModelSelection
from nanobot.runtime_context import public_history_message
from nanobot.session.display_history import HISTORY_GENERATION_METADATA_KEY
from nanobot.session.goal_state import goal_state_ws_blob
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.session.manager import Session, SessionManager
from nanobot.session.session_handles import session_handle_for_name
@@ -51,6 +50,7 @@ from nanobot.session.session_messages import (
from nanobot.session.sqlite_store import SessionConflictError
from nanobot.utils.helpers import strip_think, truncate_text
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.webui.goal_state import goal_state_ws_blob
from nanobot.webui.metadata import (
WEBSOCKET_TURN_OWNER_METADATA_KEY,
WEBUI_TURN_METADATA_KEY,