mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(harness): compare tool output, not per-call bytes, in loop detection (#8531)
* fix(harness): compare tool output, not per-call bytes, in loop detection Loop detection counts a repeated call only while its result is unchanged, and it hashed the stored ToolMessage content to decide that. Two common kinds of results change on every call even when the tool returned the same data: - langchain-core's create_*_block helpers, which every MCP result goes through, give each content block a fresh lc_<uuid> id; - an output that ToolOutputBudgetMiddleware externalizes is replaced by a preview naming a file derived from the tool call id. An identical call to such a tool never matched an earlier one, so the warning and the forced stop never fired and a stuck run went on to the recursion limit. A result is now fingerprinted without content block ids, and the budget middleware records the fingerprint of the output it replaced in its transform-trail entry (source_sha256), which loop detection compares instead of the preview. * fix(harness): keep ids outside standard content blocks in result fingerprints Only a standard LangChain content block gets a generated per-call id. A dict of another kind in a ToolMessage list can carry an id that is the data that changed, so the result fingerprint now keeps it. --------- Co-authored-by: HYYAlex <232531662+HYYAlex@users.noreply.github.com>
This commit is contained in:
parent
cd9fbf2967
commit
fc0d4bd7bc
@ -31,6 +31,13 @@ from being counted. Frequency thresholds only emit INFO metrics with
|
||||
or set a stop reason. The hash warning and hard-stop behavior remains scoped to
|
||||
identical calls whose results show no progress.
|
||||
|
||||
A result is compared by the data the tool returned. The `id` of a standard
|
||||
LangChain content block is ignored, because LangChain generates a fresh one for
|
||||
each block it builds (every MCP result has them); an `id` anywhere else is part
|
||||
of the data. A result that `ToolOutputBudgetMiddleware`
|
||||
replaced is compared by the `source_sha256` its transform-trail entry records
|
||||
for the replaced output, because the preview names a per-call file.
|
||||
|
||||
The lead agent applies the subagent call limit before loop detection, so the
|
||||
detector reconciles results against the admitted batch. A successful
|
||||
`write_file` or `str_replace` invalidates the predicted result for older
|
||||
|
||||
@ -94,6 +94,7 @@ from deerflow.agents.middlewares.model_response import is_empty_stop_response
|
||||
from deerflow.agents.middlewares.tool_call_args import pair_tool_call_results
|
||||
from deerflow.agents.middlewares.tool_call_metadata import clone_ai_message_with_tool_calls
|
||||
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY
|
||||
from deerflow.agents.middlewares.tool_transform_meta import tool_content_fingerprint, tool_result_source_digest
|
||||
from deerflow.runtime.events.catalog import MIDDLEWARE_LOOP_DETECTION_TAG
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@ -291,8 +292,13 @@ def _tool_result_hash(result: ToolMessage) -> str | None:
|
||||
path, digest = read_mark.get("path"), read_mark.get("hash")
|
||||
if isinstance(path, str) and path and isinstance(digest, str) and len(digest) == 64 and all(char in "0123456789abcdefABCDEF" for char in digest):
|
||||
version = (path, digest.lower())
|
||||
# Compare the data the tool returned, not per-call bytes around it: a budget
|
||||
# replacement names a per-call externalized file, and converted content
|
||||
# blocks (every MCP result) carry a fresh random block id.
|
||||
source_digest = tool_result_source_digest(result)
|
||||
try:
|
||||
blob = json.dumps((result.content, version), sort_keys=True, allow_nan=False)
|
||||
data = source_digest if source_digest is not None else tool_content_fingerprint(result.content)
|
||||
blob = json.dumps((data, version), sort_keys=True, allow_nan=False)
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
return None
|
||||
return hashlib.sha256(blob.encode()).hexdigest()
|
||||
|
||||
@ -48,7 +48,7 @@ from deerflow.agents.middlewares.skill_usage import MAX_SKILL_SNAPSHOT_CHARS, SK
|
||||
from deerflow.agents.middlewares.tool_call_args import ToolCallOccurrence, pair_tool_call_results, rewrite_messages_tool_call_args
|
||||
from deerflow.agents.middlewares.tool_output_synopsis import render_tool_output_preview
|
||||
from deerflow.agents.middlewares.tool_result_meta import TOOL_META_KEY
|
||||
from deerflow.agents.middlewares.tool_transform_meta import append_tool_transform
|
||||
from deerflow.agents.middlewares.tool_transform_meta import append_tool_transform, tool_content_fingerprint
|
||||
from deerflow.community.ragflow.sources import budget_source_artifact
|
||||
from deerflow.config.summarization_config import DEFAULT_SKILL_FILE_READ_TOOL_NAMES
|
||||
from deerflow.config.tool_output_config import ToolOutputConfig
|
||||
@ -739,9 +739,15 @@ def _patch_tool_message(
|
||||
new_kwargs.pop(TOOL_OUTPUT_BLOB_KEY, None)
|
||||
if budgeted is not None and budgeted.blob_metadata is not None:
|
||||
new_kwargs[TOOL_OUTPUT_BLOB_KEY] = budgeted.blob_metadata
|
||||
# The replacement can name a per-call file, so record what it replaced:
|
||||
# identical outputs of repeated calls must still compare equal.
|
||||
try:
|
||||
source_sha256 = tool_content_fingerprint(msg.content)
|
||||
except (TypeError, ValueError, RecursionError):
|
||||
source_sha256 = None
|
||||
if citation_result is not None and budgeted is not None and budgeted.transform_kind == "externalized":
|
||||
append_tool_transform(new_kwargs, "externalized", by="ToolOutputBudgetMiddleware")
|
||||
append_tool_transform(new_kwargs, transform_kind, by="ToolOutputBudgetMiddleware")
|
||||
append_tool_transform(new_kwargs, "externalized", by="ToolOutputBudgetMiddleware", source_sha256=source_sha256)
|
||||
append_tool_transform(new_kwargs, transform_kind, by="ToolOutputBudgetMiddleware", source_sha256=source_sha256)
|
||||
update["additional_kwargs"] = new_kwargs
|
||||
return msg.model_copy(update=update)
|
||||
|
||||
|
||||
@ -9,14 +9,32 @@ final visible bytes.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.messages.content import KNOWN_BLOCK_TYPES
|
||||
|
||||
TOOL_TRANSFORMS_KEY = "deerflow_tool_transforms"
|
||||
_SHA256_HEX_LENGTH = 64
|
||||
_HEX_DIGITS = frozenset("0123456789abcdef")
|
||||
|
||||
|
||||
def append_tool_transform(additional_kwargs: dict, kind: str, *, by: str, version: str = "1") -> None:
|
||||
def append_tool_transform(additional_kwargs: dict, kind: str, *, by: str, version: str = "1", source_sha256: str | None = None) -> None:
|
||||
"""Append one transform entry.
|
||||
|
||||
``source_sha256`` names the content the transform replaced, for observers
|
||||
that compare results across calls: a replacement can embed per-call data
|
||||
(an externalized file path, for example), so its bytes are not a stable
|
||||
identity for the output the tool returned.
|
||||
"""
|
||||
trail = additional_kwargs.get(TOOL_TRANSFORMS_KEY)
|
||||
if not isinstance(trail, list):
|
||||
trail = []
|
||||
additional_kwargs[TOOL_TRANSFORMS_KEY] = [*trail, {"kind": kind, "by": by, "version": version}]
|
||||
entry = {"kind": kind, "by": by, "version": version}
|
||||
if source_sha256 is not None:
|
||||
entry["source_sha256"] = source_sha256
|
||||
additional_kwargs[TOOL_TRANSFORMS_KEY] = [*trail, entry]
|
||||
|
||||
|
||||
def read_tool_transforms(message: object) -> tuple[dict[str, str], ...]:
|
||||
@ -25,3 +43,33 @@ def read_tool_transforms(message: object) -> tuple[dict[str, str], ...]:
|
||||
if not isinstance(trail, list):
|
||||
return ()
|
||||
return tuple(entry for entry in trail if isinstance(entry, dict) and isinstance(entry.get("kind"), str))
|
||||
|
||||
|
||||
def tool_result_source_digest(message: object) -> str | None:
|
||||
"""Digest of the content the first recorded content replacement started from."""
|
||||
for entry in read_tool_transforms(message):
|
||||
digest = entry.get("source_sha256")
|
||||
if isinstance(digest, str) and len(digest) == _SHA256_HEX_LENGTH and set(digest) <= _HEX_DIGITS:
|
||||
return digest
|
||||
return None
|
||||
|
||||
|
||||
def tool_content_fingerprint(content: Any) -> str:
|
||||
"""sha256 of ToolMessage content without per-call block identity.
|
||||
|
||||
langchain-core's ``create_*_block`` helpers (used by every MCP result
|
||||
conversion) stamp a fresh ``lc_<uuid>`` id on each content block, so two
|
||||
identical results never serialize the same. Those ids are not tool data.
|
||||
Only standard content blocks lose their ``id``: in any other dict it can be
|
||||
the data that changed.
|
||||
"""
|
||||
if isinstance(content, list):
|
||||
content = [_without_block_id(block) for block in content]
|
||||
return hashlib.sha256(json.dumps(content, sort_keys=True, allow_nan=False).encode()).hexdigest()
|
||||
|
||||
|
||||
def _without_block_id(block: Any) -> Any:
|
||||
block_type = block.get("type") if isinstance(block, dict) else None
|
||||
if not isinstance(block_type, str) or block_type not in KNOWN_BLOCK_TYPES:
|
||||
return block
|
||||
return {key: value for key, value in block.items() if key != "id"}
|
||||
|
||||
@ -8,12 +8,15 @@ import pytest
|
||||
from langchain.agents import create_agent
|
||||
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
|
||||
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
||||
from langchain_core.messages.content import create_text_block
|
||||
from langchain_core.tools import tool
|
||||
from pydantic import PrivateAttr
|
||||
|
||||
from deerflow.agents.middlewares.loop_detection_middleware import LoopDetectionMiddleware
|
||||
from deerflow.agents.middlewares.read_before_write_middleware import READ_MARK_KEY, ReadBeforeWriteMiddleware
|
||||
from deerflow.agents.middlewares.subagent_limit_middleware import SubagentLimitMiddleware
|
||||
from deerflow.agents.middlewares.tool_output_budget_middleware import ToolOutputBudgetMiddleware
|
||||
from deerflow.agents.thread_state import ThreadState
|
||||
|
||||
|
||||
class _ScriptedModel(FakeMessagesListChatModel):
|
||||
@ -32,8 +35,8 @@ def _call(name, args, call_id="call_0"):
|
||||
return {"name": name, "args": args, "id": call_id}
|
||||
|
||||
|
||||
async def _invoke(graph, async_mode, context):
|
||||
state = {"messages": [("user", "Continue until the requested work is complete.")]}
|
||||
async def _invoke(graph, async_mode, context, **extra_state):
|
||||
state = {"messages": [("user", "Continue until the requested work is complete.")], **extra_state}
|
||||
if async_mode:
|
||||
return await graph.ainvoke(state, context=context, config={"recursion_limit": 100})
|
||||
return graph.invoke(state, context=context, config={"recursion_limit": 100})
|
||||
@ -249,6 +252,69 @@ async def test_unchanged_results_and_changing_errors_still_stop(async_mode, fail
|
||||
assert context["stop_reason"] == "loop_capped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_mode", [False, True])
|
||||
async def test_unchanged_block_results_stop_despite_fresh_block_ids(async_mode):
|
||||
executions = []
|
||||
|
||||
@tool
|
||||
def browser_snapshot() -> list[dict]:
|
||||
"""Return the same page snapshot on every call."""
|
||||
executions.append(len(executions) + 1)
|
||||
# MCP result conversion builds blocks with create_text_block, which
|
||||
# stamps a fresh lc_<uuid> id on every block.
|
||||
return [create_text_block("- button 'Next' [ref=e12]")]
|
||||
|
||||
responses = [AIMessage(content="", tool_calls=[_call("browser_snapshot", {}, f"call_{index}")]) for index in range(6)]
|
||||
model = _ScriptedModel(responses=responses)
|
||||
graph = create_agent(model=model, tools=[browser_snapshot], middleware=[LoopDetectionMiddleware()])
|
||||
context = {"thread_id": "snapshots", "run_id": "snapshots"}
|
||||
|
||||
result = await _invoke(graph, async_mode, context)
|
||||
|
||||
tool_results = [message for message in result["messages"] if isinstance(message, ToolMessage)]
|
||||
assert len({message.content[0]["id"] for message in tool_results}) == len(tool_results)
|
||||
assert len(executions) == 4
|
||||
assert len(_warnings(model)) == 1
|
||||
assert not result["messages"][-1].tool_calls
|
||||
assert context["stop_reason"] == "loop_capped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("async_mode", [False, True])
|
||||
@pytest.mark.parametrize("page_changes", [False, True])
|
||||
async def test_externalized_results_compare_the_output_not_the_preview(tmp_path, async_mode, page_changes):
|
||||
fetches = []
|
||||
|
||||
@tool
|
||||
def web_fetch(url: str) -> str:
|
||||
"""Fetch a page large enough to be externalized."""
|
||||
fetches.append(url)
|
||||
revision = len(fetches) if page_changes else 1
|
||||
return f"Revision {revision}\n" + "Lorem ipsum dolor sit amet.\n" * 1000
|
||||
|
||||
responses = [AIMessage(content="", tool_calls=[_call("web_fetch", {"url": "https://example.com"}, f"call_{index}")]) for index in range(6)]
|
||||
model = _ScriptedModel(responses=[*responses, AIMessage(content="Done.")])
|
||||
graph = create_agent(model=model, tools=[web_fetch], middleware=[ToolOutputBudgetMiddleware(), LoopDetectionMiddleware()], state_schema=ThreadState)
|
||||
context = {"thread_id": "fetches", "run_id": "fetches"}
|
||||
|
||||
result = await _invoke(graph, async_mode, context, thread_data={"outputs_path": str(tmp_path)})
|
||||
|
||||
# Every preview names a per-call file, so the visible results always differ.
|
||||
previews = [message.content for message in result["messages"] if isinstance(message, ToolMessage)]
|
||||
assert all("output saved to" in preview for preview in previews)
|
||||
assert len(set(previews)) == len(previews)
|
||||
if page_changes:
|
||||
assert len(fetches) == 6
|
||||
assert result["messages"][-1].content == "Done."
|
||||
assert not _warnings(model)
|
||||
assert context.get("stop_reason") is None
|
||||
else:
|
||||
assert len(fetches) == 4
|
||||
assert len(_warnings(model)) == 1
|
||||
assert context["stop_reason"] == "loop_capped"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_repeated_result_cycle_still_stops():
|
||||
executions = []
|
||||
|
||||
@ -45,6 +45,7 @@ from deerflow.agents.middlewares.tool_output_budget_middleware import (
|
||||
_tool_message_over_budget,
|
||||
)
|
||||
from deerflow.agents.middlewares.tool_output_synopsis import build_tool_output_synopsis
|
||||
from deerflow.agents.middlewares.tool_transform_meta import tool_content_fingerprint, tool_result_source_digest
|
||||
from deerflow.config.app_config import AppConfig
|
||||
from deerflow.config.sandbox_config import SandboxConfig
|
||||
from deerflow.config.tool_output_config import ToolOutputConfig
|
||||
@ -1042,6 +1043,16 @@ class TestWrapToolCallExternalize:
|
||||
with open(os.path.join(storage_dir, files[0]), encoding="utf-8") as f:
|
||||
assert f.read() == content
|
||||
|
||||
def test_identical_outputs_record_the_same_source_digest(self):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
mw = ToolOutputBudgetMiddleware(config=ToolOutputConfig(externalize_min_chars=100))
|
||||
content = "x" * 500
|
||||
results = [mw.wrap_tool_call(_make_request(tool_call_id=call_id, outputs_path=tmpdir), lambda _, call_id=call_id: _tm(content, name="remote_executor", tool_call_id=call_id)) for call_id in ("tc-1", "tc-2")]
|
||||
|
||||
# Each call names its own file; the trail records what both replaced.
|
||||
assert results[0].content != results[1].content
|
||||
assert tool_result_source_digest(results[0]) == tool_result_source_digest(results[1]) == tool_content_fingerprint(content)
|
||||
|
||||
|
||||
class TestToolOutputBlobPersistence:
|
||||
def test_host_externalization_stamps_durable_blob_ref(self, monkeypatch, tmp_path):
|
||||
|
||||
@ -5,12 +5,16 @@ entry, so a consumer classifies raw -> visible transforms from facts instead of
|
||||
sniffing output wording.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from langchain_core.messages import ToolMessage
|
||||
from langchain_core.messages.content import create_text_block
|
||||
|
||||
from deerflow.agents.middlewares.tool_transform_meta import (
|
||||
TOOL_TRANSFORMS_KEY,
|
||||
append_tool_transform,
|
||||
read_tool_transforms,
|
||||
tool_content_fingerprint,
|
||||
tool_result_source_digest,
|
||||
)
|
||||
|
||||
|
||||
@ -39,6 +43,33 @@ def test_read_drops_entries_without_a_string_kind():
|
||||
assert read_tool_transforms(message) == ({"kind": "ok", "by": "m"},)
|
||||
|
||||
|
||||
def test_source_digest_comes_from_the_first_replacement():
|
||||
kwargs: dict = {}
|
||||
append_tool_transform(kwargs, "sanitized", by="ToolResultSanitizationMiddleware")
|
||||
append_tool_transform(kwargs, "externalized", by="ToolOutputBudgetMiddleware", source_sha256="a" * 64)
|
||||
append_tool_transform(kwargs, "truncated", by="ToolOutputBudgetMiddleware", source_sha256="b" * 64)
|
||||
assert "source_sha256" not in kwargs[TOOL_TRANSFORMS_KEY][0]
|
||||
assert tool_result_source_digest(ToolMessage(content="preview", tool_call_id="1", additional_kwargs=kwargs)) == "a" * 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize("digest", [None, "", "a" * 63, "g" * 64, 123, ["a" * 64]])
|
||||
def test_source_digest_ignores_malformed_persisted_values(digest):
|
||||
trail = [{"kind": "externalized", "by": "ToolOutputBudgetMiddleware", "source_sha256": digest}]
|
||||
message = ToolMessage(content="preview", tool_call_id="1", additional_kwargs={TOOL_TRANSFORMS_KEY: trail})
|
||||
assert tool_result_source_digest(message) is None
|
||||
|
||||
|
||||
def test_content_fingerprint_ignores_block_ids_but_not_data():
|
||||
first, second = ([create_text_block("page")] for _ in range(2))
|
||||
assert first[0]["id"] != second[0]["id"]
|
||||
assert tool_content_fingerprint(first) == tool_content_fingerprint(second)
|
||||
assert tool_content_fingerprint([create_text_block("other page")]) != tool_content_fingerprint(first)
|
||||
assert tool_content_fingerprint("page") != tool_content_fingerprint("other page")
|
||||
# Outside a standard content block an id can be the data that changed.
|
||||
assert tool_content_fingerprint([{"id": "row-1", "status": "pending"}]) != tool_content_fingerprint([{"id": "row-2", "status": "pending"}])
|
||||
assert tool_content_fingerprint([{"type": ["text"], "id": "a"}]) != tool_content_fingerprint([{"type": ["text"], "id": "b"}])
|
||||
|
||||
|
||||
def test_mcp_source_projection_is_credential_free_and_defaults_transport():
|
||||
from langchain_core.tools import tool as make_tool
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user