diff --git a/backend/docs/API.md b/backend/docs/API.md index 3de19207b5..ae9aa59fc3 100644 --- a/backend/docs/API.md +++ b/backend/docs/API.md @@ -440,9 +440,11 @@ the next request without restarting the Gateway. IM channel runs get the same default unless a channel `session.config` sets `recursion_limit` (GitHub channel runs have their own floor; see [CONFIGURATION.md](CONFIGURATION.md#recursion-limits)); embedded -`DeerFlowClient` runs retain their own defaults and override paths. A run that -reaches the limit ends with status `error` and `stop_reason: "recursion_capped"`; -its stream `error` event and the `/wait` error envelope use the name +`DeerFlowClient` runs retain their own defaults and override paths. When the current graph +invocation has a terminal checkpoint at the limit, the Gateway finalizes the run +normally. A run with work remaining at the limit ends with status `error` and +`stop_reason: "recursion_capped"`. Its stream `error` event and the `/wait` +error envelope use the name `GraphRecursionError`, and the message lists up to five outputs the run created but did not present. diff --git a/backend/packages/harness/deerflow/runtime/journal.py b/backend/packages/harness/deerflow/runtime/journal.py index 8095d0ebb1..8b52d30db4 100644 --- a/backend/packages/harness/deerflow/runtime/journal.py +++ b/backend/packages/harness/deerflow/runtime/journal.py @@ -32,7 +32,8 @@ from uuid import UUID, uuid4 from langchain_core.callbacks import BaseCallbackHandler from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, HumanMessage, ToolMessage, messages_from_dict -from langgraph.types import Command +from langgraph.errors import GraphRecursionError +from langgraph.types import Command, StateSnapshot from deerflow.agents.human_input import read_human_input_response from deerflow.agents.middlewares.skill_usage import MAX_SKILL_SNAPSHOT_CHARS, SKILL_USAGES_KEY @@ -339,6 +340,7 @@ class RunJournal(BaseCallbackHandler): self._producer_lock = threading.Lock() self._pending_producer_callbacks = 0 self._track_tokens = track_token_usage + self.step_limit_root: UUID | None = None self._flush_threshold = flush_threshold self._progress_reporter = progress_reporter self._progress_flush_interval = progress_flush_interval @@ -512,7 +514,20 @@ class RunJournal(BaseCallbackHandler): ) self._flush_sync() - def on_chain_error(self, error: BaseException, *, run_id: UUID, **kwargs: Any) -> None: + def record_step_limit_outcome(self, error: GraphRecursionError, completed: StateSnapshot | None) -> None: + """Record the worker's resolved outcome using the usual root callback.""" + root_id, self.step_limit_root = self.step_limit_root, None + if root_id is None: + return + if completed is None: + self.on_chain_error(error, run_id=root_id) + else: + self.on_chain_end(completed.values, run_id=root_id) + + def on_chain_error(self, error: BaseException, *, run_id: UUID, parent_run_id: UUID | None = None, **kwargs: Any) -> None: + # The worker checks its own root checkpoint before recording this one outcome. + if run_id == self.step_limit_root and parent_run_id is None and isinstance(error, GraphRecursionError): + return self._put( event_type=RUN_ERROR_EVENT.event_type, category=RUN_ERROR_EVENT.category, diff --git a/backend/packages/harness/deerflow/runtime/runs/worker.py b/backend/packages/harness/deerflow/runtime/runs/worker.py index 9da2182cea..9739c1bee0 100644 --- a/backend/packages/harness/deerflow/runtime/runs/worker.py +++ b/backend/packages/harness/deerflow/runtime/runs/worker.py @@ -25,19 +25,20 @@ import sys import threading import time import weakref -from collections.abc import Callable, Coroutine, Mapping +from collections.abc import AsyncIterator, Callable, Coroutine, Mapping from contextlib import AbstractAsyncContextManager from contextvars import Context from dataclasses import dataclass, field from datetime import datetime from functools import lru_cache -from typing import Any, Final, Literal, cast +from typing import TYPE_CHECKING, Any, Final, Literal, cast +from uuid import uuid4 from deerflow_extension_api.agent_runs import AGENT_RUNS_CONTEXT_KEY from langchain_core.messages import AIMessage, AIMessageChunk from langgraph.checkpoint.base import empty_checkpoint from langgraph.errors import GraphRecursionError -from langgraph.types import Command, Overwrite +from langgraph.types import Command, Overwrite, StateSnapshot from deerflow.agents.goal_state import GoalEvaluation, GoalState from deerflow.agents.interaction_policy import RunInteractionPolicy, resolve_run_interaction_policy @@ -120,6 +121,10 @@ from .schemas import GOAL_RUN_HARD_STOP_REASONS as _GOAL_RUN_HARD_STOP_REASONS from .schemas import RunStatus, ThreadOperationKind from .store.base import canonical_run_created_at +if TYPE_CHECKING: + from deerflow.runtime.journal import RunJournal + + logger = logging.getLogger(__name__) _THREAD_INCARNATION_UNSET = object() _MISSING_BRIDGE_METHOD = object() @@ -368,6 +373,41 @@ _RUN_ERROR_NAME = "RunError" _RECURSION_CAPPED_LISTED_OUTPUTS = 5 +_GRAPH_INVOCATION_KEY = "deerflow_graph_invocation_id" + + +async def _graph_stream_events(stream: AsyncIterator[Any], accessor: CheckpointStateAccessor, thread_id: str, invocation_id: str, journal: RunJournal | None = None) -> AsyncIterator[Any]: + """Accept a step-boundary completion only with this invocation's idle root checkpoint.""" + try: + async for event in stream: + yield event + except GraphRecursionError as error: + completed = None + try: + if accessor.checkpointer is not None: + snapshot = await accessor.aget({"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}) + if ( + isinstance(snapshot, StateSnapshot) + and snapshot.metadata + and snapshot.metadata.get("source") == "loop" + and snapshot.metadata.get(_GRAPH_INVOCATION_KEY) == invocation_id + and not snapshot.next + and not snapshot.tasks + and not snapshot.interrupts + ): + completed = snapshot + except Exception: + logger.debug("Could not verify the checkpoint at the graph step limit", exc_info=True) + finally: + if journal is not None: + try: + journal.record_step_limit_outcome(error, completed) + except Exception: + logger.warning("Could not journal the graph step-limit outcome", exc_info=True) + if completed is None: + raise + + def _recursion_capped_message(recursion_limit: object, delivery_content: dict[str, Any] | None) -> str: """Say a run hit its step budget, listing outputs it created but never presented. @@ -1782,6 +1822,14 @@ async def run_agent( if input_control is not None: await input_control.inputs.reopen() file_tool_chunk_batcher = _LargeFileToolChunkBatcher() if "messages-tuple" in requested_modes else None + # A Goal continuation is a distinct graph invocation on the same run and thread. + invocation = uuid4() + invocation_id = invocation.hex + stream_config["metadata"] = {**(stream_config.get("metadata") or {}), _GRAPH_INVOCATION_KEY: invocation_id} + if journal is not None: + root_id = stream_config.get("run_id") or invocation + stream_config["run_id"] = root_id + journal.step_limit_root = root_id try: async with _checkpoint_thread_lock(thread_id): if len(lg_modes) == 1 and not stream_subgraphs: @@ -1790,7 +1838,7 @@ async def run_agent( stream = agent.astream(input_payload, config=stream_config, stream_mode=single_mode) broke_on_abort = False try: - async for chunk in stream: + async for chunk in _graph_stream_events(stream, accessor, thread_id, invocation_id, journal): if record.abort_event.is_set(): broke_on_abort = True logger.info("Run %s abort requested — stopping", run_id) @@ -1840,7 +1888,7 @@ async def run_agent( ) broke_on_abort = False try: - async for item in stream: + async for item in _graph_stream_events(stream, accessor, thread_id, invocation_id, journal): if record.abort_event.is_set(): broke_on_abort = True logger.info("Run %s abort requested — stopping", run_id) @@ -1892,6 +1940,8 @@ async def run_agent( else: logger.debug("Could not close agent stream for run %s", run_id, exc_info=True) finally: + if journal is not None: + journal.step_limit_root = None stream_error = sys.exception() if file_tool_chunk_batcher is not None: try: diff --git a/backend/tests/test_run_journal.py b/backend/tests/test_run_journal.py index 85ee2279ea..5dc1662ad1 100644 --- a/backend/tests/test_run_journal.py +++ b/backend/tests/test_run_journal.py @@ -15,6 +15,7 @@ from uuid import uuid4 import pytest from langchain_core.messages import AIMessage, HumanMessage from langchain_core.outputs import ChatGeneration, LLMResult +from langgraph.errors import GraphRecursionError from deerflow.runtime.events.store.base import RunEventStoreNotCommittedError from deerflow.runtime.events.store.memory import MemoryRunEventStore @@ -1996,16 +1997,18 @@ class TestIdentifyCaller: class TestChainErrorCallback: @pytest.mark.anyio - async def test_on_chain_error_writes_run_error(self, journal_setup): + @pytest.mark.parametrize("error", [ValueError("boom"), GraphRecursionError("boom")]) + async def test_on_chain_error_writes_run_error(self, journal_setup, error): j, store = journal_setup - j.on_chain_error(ValueError("boom"), run_id=uuid4()) + j.step_limit_root = uuid4() + j.on_chain_error(error, run_id=uuid4()) await asyncio.sleep(0.05) await j.flush() events = await store.list_events("t1", "r1") error_events = [e for e in events if e["event_type"] == "run.error"] assert len(error_events) == 1 assert "boom" in error_events[0]["content"] - assert error_events[0]["metadata"]["error_type"] == "ValueError" + assert error_events[0]["metadata"]["error_type"] == type(error).__name__ class TestTokenTrackingDisabled: diff --git a/backend/tests/test_run_recursion_capped.py b/backend/tests/test_run_recursion_capped.py index 30eecb746f..232198f3a5 100644 --- a/backend/tests/test_run_recursion_capped.py +++ b/backend/tests/test_run_recursion_capped.py @@ -10,11 +10,14 @@ from unittest.mock import patch import pytest from langchain.agents import create_agent +from langchain.agents.middleware import after_agent from langchain_core.language_models.chat_models import BaseChatModel from langchain_core.messages import AIMessage, HumanMessage from langchain_core.outputs import ChatGeneration, ChatResult from langchain_core.tools import tool from langgraph.checkpoint.memory import InMemorySaver +from langgraph.errors import GraphRecursionError +from langgraph.graph import END, START, StateGraph from pydantic import ConfigDict from deerflow.agents.thread_state import get_thread_state_schema @@ -32,9 +35,10 @@ from deerflow.runtime.user_context import get_effective_user_id, reset_current_u class _ToolLoopModel(BaseChatModel): - """Calls the writer on every turn, so the graph only stops at its recursion limit.""" + """Calls the writer until the configured final response, or forever.""" calls: list[int] + finish_on_call: int | None = None model_config = ConfigDict(arbitrary_types_allowed=True) @property @@ -47,11 +51,14 @@ class _ToolLoopModel(BaseChatModel): def _generate(self, messages, stop=None, run_manager=None, **kwargs): self.calls.append(len(self.calls) + 1) n = len(self.calls) + if n == self.finish_on_call: + return ChatResult(generations=[ChatGeneration(message=AIMessage(content="The report is ready."))]) message = AIMessage(content=f"Working on part {n}.", tool_calls=[{"id": f"w-{n}", "name": "write_part", "args": {"n": n}}]) return ChatResult(generations=[ChatGeneration(message=message)]) -async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool, checkpoint_mode: CheckpointChannelMode = "full") -> dict[str, Any]: +async def _run_at_limit(tmp_path: Path, *, with_goal: bool, checkpoint_mode: CheckpointChannelMode = "full", limit: int = 6, finish_on_call: int | None = None) -> dict[str, Any]: + exit_calls = [] evaluator_calls: list[Any] = [] published: list[tuple[str, Any]] = [] @@ -80,10 +87,15 @@ async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool, checkpoin (outputs / f"part-{n}.md").write_text(f"part {n}\n", encoding="utf-8") return f"wrote part-{n}.md" - model = _ToolLoopModel(calls=[]) + model = _ToolLoopModel(calls=[], finish_on_call=finish_on_call) # Snapshot every delta write so the cap lands on a stored messages snapshot. state_schema = get_thread_state_schema(checkpoint_mode, snapshot_frequency=1) - graph = create_agent(model=model, tools=[write_part], state_schema=state_schema, context_schema=dict, checkpointer=saver) + + @after_agent + def record_exit(state, runtime): + exit_calls.append(True) + + graph = create_agent(model=model, tools=[write_part], middleware=[record_exit] if finish_on_call else [], state_schema=state_schema, context_schema=dict, checkpointer=saver) app_config = AppConfig(sandbox=SandboxConfig(use="deerflow.sandbox.local:LocalSandboxProvider")) app_config.title.enabled = True app_config.memory.enabled = app_config.memory.injection_enabled = False @@ -96,17 +108,20 @@ async def _run_until_recursion_cap(tmp_path: Path, *, with_goal: bool, checkpoin ctx=worker.RunContext(checkpointer=saver, event_store=events, app_config=app_config, checkpoint_channel_mode=checkpoint_mode), agent_factory=lambda config: graph, graph_input={"messages": [HumanMessage(content="Write the report in parts.")]}, - config={"configurable": {"thread_id": record.thread_id}, "recursion_limit": 6}, + config={"configurable": {"thread_id": record.thread_id}, "recursion_limit": limit}, stream_modes=["values"], ) snapshot = await graph.aget_state({"configurable": {"thread_id": record.thread_id}}) - assert snapshot.values["title"] == "Write the report in parts." + if record.status == RunStatus.error: + assert snapshot.values["title"] == "Write the report in parts." goal = await read_thread_goal(saver, record.thread_id) recorded = await events.list_events(record.thread_id, record.run_id) finally: reset_current_user(token) return { "record": record, + "exit_calls": exit_calls, + "graph_outcomes": [event["event_type"] for event in recorded if event["event_type"] in {"run.end", "run.error"}], "goal": goal, "error_frames": [data for event, data in published if event == "error"], "deliveries": [event["content"] for event in recorded if event["event_type"] == "run.delivery"], @@ -131,7 +146,7 @@ def _no_network(monkeypatch): @pytest.mark.asyncio @pytest.mark.parametrize("checkpoint_mode", ["full", "delta"]) async def test_recursion_cap_reports_a_plain_stop_with_unpresented_outputs(tmp_path, checkpoint_mode): - result = await _run_until_recursion_cap(tmp_path, with_goal=False, checkpoint_mode=checkpoint_mode) + result = await _run_at_limit(tmp_path, with_goal=False, checkpoint_mode=checkpoint_mode) record = result["record"] assert record.status == RunStatus.error @@ -148,9 +163,50 @@ async def test_recursion_cap_reports_a_plain_stop_with_unpresented_outputs(tmp_p assert result["deliveries"][0]["enforcement"] == "advisory" +@pytest.mark.asyncio +@pytest.mark.parametrize("checkpoint_mode", ["full", "delta"]) +@pytest.mark.parametrize("limit", [5, 6]) +async def test_final_answer_at_the_step_limit_waits_for_cleanup(tmp_path, checkpoint_mode, limit): + result = await _run_at_limit(tmp_path, with_goal=False, checkpoint_mode=checkpoint_mode, limit=limit, finish_on_call=3) + record = result["record"] + assert result["model_calls"] == 3 + if limit == 5: + assert result["graph_outcomes"] == ["run.error"] + assert result["exit_calls"] == [] + assert record.status == RunStatus.error and record.stop_reason == "recursion_capped" + else: + assert result["graph_outcomes"] == ["run.end"] + assert result["exit_calls"] == [True] + assert record.status == RunStatus.success and record.stop_reason is None + assert result["error_frames"] == [] + + +@pytest.mark.asyncio +async def test_previous_idle_checkpoint_does_not_hide_a_new_cap(): + saver = InMemorySaver() + builder = StateGraph(dict) + builder.add_node("finish", lambda state: state) + builder.add_edge(START, "finish") + builder.add_edge("finish", END) + graph = builder.compile(checkpointer=saver) + accessor = worker.CheckpointStateAccessor.bind(graph, saver) + config = {"configurable": {"thread_id": "same-thread"}, "metadata": {worker._GRAPH_INVOCATION_KEY: "earlier-invocation"}} + await graph.ainvoke({"value": 1}, config) + snapshot = await accessor.aget(config) + assert snapshot.metadata["source"] == "loop" and not snapshot.next and not snapshot.tasks + + async def early_cap(): + yield "started" + raise GraphRecursionError("new invocation stopped") + + with pytest.raises(GraphRecursionError, match="new invocation stopped"): + async for _ in worker._graph_stream_events(early_cap(), accessor, "same-thread", "different-invocation"): + pass + + @pytest.mark.asyncio async def test_recursion_cap_stands_the_goal_down_without_an_evaluator_call(tmp_path): - result = await _run_until_recursion_cap(tmp_path, with_goal=True) + result = await _run_at_limit(tmp_path, with_goal=True) record, goal = result["record"], result["goal"] assert result["evaluator_calls"] == 0