fix(todo): address malformed write_todos call ids before results exist (#8354)

* fix(todo): address malformed write_todos call ids before results exist

The base TodoListMiddleware builds one error ToolMessage per parallel
write_todos call from tool_calls[*]["id"], and the tool node does the same
for a single call. A missing or non-string id raised a pydantic
ValidationError and aborted the run before the model could retry; empty and
repeated ids created results the next request cannot address, which
backend/AGENTS.md forbids.

TodoMiddleware.after_model now gives those calls synthetic ids and returns the
same message with those ids (the messages reducer substitutes by message id),
so the base hook and the tool node build valid results that pair with the
call. Only structured tool_calls are relabelled; well-formed ids are left
untouched.

* fix(todo): relabel provider tool-call surfaces and reserve other-tool ids

Addresses review on #8354:

- Relabelling is now occurrence-aware and rewrites the provider's own
  surfaces (additional_kwargs.tool_calls and tool_use content blocks) as well
  as structured tool_calls, so a duplicate id no longer leaves extra blocks
  pointing at the old id in the next request.
- Ids used by a non-write_todos call are reserved before a write_todos id is
  retained, so a todo call sharing an id with another tool is relabelled and
  every emitted result has a unique address.

Tests cover provider surfaces matching the structured ids and a shared
echo/write_todos id; both fail on the previous head.

* fix(todo): preserve tool-call IDs in provider retries

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
哈基米 2026-11-23 06:46:39 +08:00 committed by GitHub
parent 917fc4599e
commit 0ee78e1ea6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 366 additions and 3 deletions

View File

@ -22,6 +22,7 @@ suppress reminders in later Goal continuation turns of the same run.
""" """
import threading import threading
from collections import defaultdict, deque
from collections.abc import Awaitable, Callable, Iterable, Mapping from collections.abc import Awaitable, Callable, Iterable, Mapping
from typing import Any, Literal, override from typing import Any, Literal, override
@ -186,6 +187,113 @@ def _has_tool_call_intent_or_error(message: AIMessage) -> bool:
return response_metadata.get("finish_reason") in _TOOL_CALL_FINISH_REASONS return response_metadata.get("finish_reason") in _TOOL_CALL_FINISH_REASONS
_SYNTHETIC_WRITE_TODOS_ID_PREFIX = "deerflow_write_todos_synthetic_"
def _usable_call_id(value: object) -> str | None:
return value if isinstance(value, str) and value.strip() else None
def _relabel_provider_tool_call_ids(
message: AIMessage,
calls: list[dict[str, Any]],
occurrence_plans: dict[str | None, list[str]],
) -> AIMessage:
"""Rename each todo occurrence in the original provider blocks and raw calls."""
invalid_arguments = {(_usable_call_id(call.get("id")), args) for call in message.invalid_tool_calls if isinstance(call, dict) and call.get("name") == "write_todos" and ((args := call.get("args")) is None or isinstance(args, str))}
def _rewrite(entries: list[Any], *, raw: bool) -> list[Any]:
pending = {call_id: deque(ids) for call_id, ids in occurrence_plans.items()}
rewritten: list[Any] = []
for entry in entries:
if not isinstance(entry, dict):
rewritten.append(entry)
continue
details = entry
id_key = "id"
if raw:
function = entry.get("function")
if isinstance(function, dict):
details = function
elif entry.get("type") == "function_call":
# Responses has a separate item id, even if the call id is missing.
if "call_id" in entry or "arguments" in entry:
id_key = "call_id"
elif entry.get("type") not in ("tool_use", "tool_call", "tool_call_chunk"):
rewritten.append(entry)
continue
original = _usable_call_id(entry.get(id_key))
remaining = pending.get(original)
arguments = details.get("arguments", details.get("args", details.get("input")))
is_invalid = (arguments is None or isinstance(arguments, str)) and (original, arguments) in invalid_arguments
if details.get("name") == "write_todos" and remaining and not is_invalid:
new_id = remaining.popleft()
if new_id != entry.get(id_key):
entry = {**entry, id_key: new_id}
rewritten.append(entry)
return rewritten
update: dict[str, Any] = {"tool_calls": calls}
additional_kwargs = message.additional_kwargs
raw_calls = additional_kwargs.get("tool_calls")
if isinstance(raw_calls, list):
update["additional_kwargs"] = {**additional_kwargs, "tool_calls": _rewrite(raw_calls, raw=True)}
if isinstance(message.content, list):
update["content"] = _rewrite(message.content, raw=False)
# A Responses continuation would replay the server's uncorrected call IDs.
response_id = message.response_metadata.get("id")
if isinstance(response_id, str) and response_id.startswith("resp_"):
update["response_metadata"] = {key: value for key, value in message.response_metadata.items() if key != "id"}
return message.model_copy(update=update)
def _normalize_write_todos_ids(message: AIMessage) -> AIMessage | None:
"""Return *message* with addressable ``write_todos`` call ids, or None.
The base ``TodoListMiddleware.after_model`` builds a ``ToolMessage`` per
parallel ``write_todos`` call from ``tool_calls[*]["id"]``, and the tool
node does the same for a single call. A missing or non-string id raises a
pydantic validation error there and aborts the run; an empty id is
accepted but cannot be matched to its result, and a repeated id makes the
results ambiguous. ``backend/AGENTS.md`` requires addressable call ids, so
give those calls synthetic ids and replace the message in place (same
message id, so the reducer substitutes it).
Reserve ids from other valid calls and invalid calls in the response.
DanglingToolCallMiddleware can produce results for invalid calls too.
"""
calls = list(message.tool_calls or [])
todo_positions = [position for position, call in enumerate(calls) if call.get("name") == "write_todos"]
if not todo_positions:
return None
other_calls = [call for call in calls if call.get("name") != "write_todos"]
seen = {call_id for call in [*other_calls, *message.invalid_tool_calls] if isinstance(call, dict) and (call_id := _usable_call_id(call.get("id"))) is not None}
used = seen | {call_id for call in calls if (call_id := _usable_call_id(call.get("id"))) is not None}
changed = False
occurrence_plans: dict[str | None, list[str]] = defaultdict(list)
for position in todo_positions:
call = calls[position]
original = _usable_call_id(call.get("id"))
call_id = original
if call_id is None or call_id in seen:
call_id = f"{_SYNTHETIC_WRITE_TODOS_ID_PREFIX}{position}"
while call_id in used:
call_id += "_"
used.add(call_id)
calls[position] = {**call, "id": call_id}
changed = True
seen.add(call_id)
occurrence_plans[original].append(call_id)
return _relabel_provider_tool_call_ids(message, calls, occurrence_plans) if changed else None
class TodoMiddleware(TodoListMiddleware): class TodoMiddleware(TodoListMiddleware):
"""Extends TodoListMiddleware with `write_todos` context-loss detection. """Extends TodoListMiddleware with `write_todos` context-loss detection.
@ -446,10 +554,21 @@ class TodoMiddleware(TodoListMiddleware):
if any(termination_metadata.get(marker) for marker in _COMPLETION_REMINDER_RESPONSE_STOP_MARKERS.values()): if any(termination_metadata.get(marker) for marker in _COMPLETION_REMINDER_RESPONSE_STOP_MARKERS.values()):
return None return None
# 1. Preserve base class logic (parallel write_todos detection). # 1. Preserve base class logic (parallel write_todos detection). Give
base_result = super().after_model(state, runtime) # malformed call ids synthetic ones first: the base builds ToolMessages
# from them, and the tool node does the same for a single call, so a
# missing or duplicated id would abort the run with a validation error.
normalized_ai = _normalize_write_todos_ids(last_ai) if last_ai is not None else None
base_state = state
if normalized_ai is not None:
base_state = {**state, "messages": [normalized_ai if item is last_ai else item for item in messages]}
base_result = super().after_model(base_state, runtime)
if base_result is not None: if base_result is not None:
return base_result if normalized_ai is None:
return base_result
return {**base_result, "messages": [normalized_ai, *(base_result.get("messages") or [])]}
if normalized_ai is not None:
return {"messages": [normalized_ai]}
# 2. Only intervene when the agent wants to exit cleanly. Tool-call # 2. Only intervene when the agent wants to exit cleanly. Tool-call
# intent or tool-call parse errors should be handled by the tool path # intent or tool-call parse errors should be handled by the tool path

View File

@ -12,12 +12,16 @@ from langchain.agents import create_agent
from langchain.agents.middleware import TodoListMiddleware from langchain.agents.middleware import TodoListMiddleware
from langchain.agents.middleware.types import ModelRequest from langchain.agents.middleware.types import ModelRequest
from langchain.tools import tool from langchain.tools import tool
from langchain_anthropic import ChatAnthropic
from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel from langchain_core.language_models.fake_chat_models import FakeMessagesListChatModel
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.outputs import ChatGeneration, ChatResult from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_openai import ChatOpenAI
from langchain_openai.chat_models.base import _convert_dict_to_message
from langgraph.checkpoint.memory import InMemorySaver from langgraph.checkpoint.memory import InMemorySaver
from pydantic import PrivateAttr from pydantic import PrivateAttr
from deerflow.agents.middlewares.dangling_tool_call_middleware import DanglingToolCallMiddleware
from deerflow.agents.middlewares.model_length_finish_reason_middleware import ( from deerflow.agents.middlewares.model_length_finish_reason_middleware import (
ModelLengthFinishReasonMiddleware, ModelLengthFinishReasonMiddleware,
) )
@ -319,6 +323,246 @@ class TestToolCallIntentOrError:
assert tool_related_fields <= {"tool_calls", "invalid_tool_calls"} assert tool_related_fields <= {"tool_calls", "invalid_tool_calls"}
class TestWriteTodosIdNormalization:
"""Malformed write_todos ids must be addressable before the tool result exists.
The base TodoListMiddleware builds one error ToolMessage per parallel
write_todos call from ``tool_calls[*]["id"]``; the tool node does the same
for a single call. A missing or non-string id used to raise a pydantic
ValidationError, aborting a plan-mode run before the model could retry;
empty and repeated ids yield results the next request cannot address.
"""
@staticmethod
def _state(calls: list[dict[str, Any]]) -> dict[str, Any]:
return {"messages": [AIMessage(id="ai-1", content="", tool_calls=calls)]}
@pytest.mark.parametrize("invoke_async", [False, True], ids=["sync", "async"])
def test_parallel_missing_ids_are_normalized_before_the_base_hook(self, invoke_async):
mw = TodoMiddleware()
state = self._state(
[
{"name": "write_todos", "id": None, "args": {"todos": []}},
{"name": "write_todos", "id": "", "args": {"todos": []}},
]
)
runtime = _make_runtime()
result = asyncio.run(mw.aafter_model(state, runtime)) if invoke_async else mw.after_model(state, runtime)
ai, *errors = result["messages"]
assert ai.id == "ai-1"
ids = [call["id"] for call in ai.tool_calls]
assert all(isinstance(call_id, str) and call_id for call_id in ids)
assert len(set(ids)) == 2
assert [message.tool_call_id for message in errors] == ids
assert all(message.status == "error" for message in errors)
def test_single_missing_id_is_normalized_for_the_tool_node(self):
mw = TodoMiddleware()
state = self._state([{"name": "write_todos", "id": None, "args": {"todos": []}}])
result = mw.after_model(state, _make_runtime())
assert len(result["messages"]) == 1
call_id = result["messages"][0].tool_calls[0]["id"]
assert isinstance(call_id, str) and call_id
def test_duplicate_ids_are_made_unique(self):
mw = TodoMiddleware()
state = self._state(
[
{"name": "write_todos", "id": "dup", "args": {"todos": []}},
{"name": "write_todos", "id": "dup", "args": {"todos": []}},
]
)
result = mw.after_model(state, _make_runtime())
ai, *errors = result["messages"]
assert ai.tool_calls[0]["id"] == "dup"
assert len({call["id"] for call in ai.tool_calls}) == 2
assert [message.tool_call_id for message in errors] == [call["id"] for call in ai.tool_calls]
def test_whitespace_only_ids_are_treated_as_missing(self):
mw = TodoMiddleware()
state = self._state(
[
{"name": "write_todos", "id": " ", "args": {"todos": []}},
{"name": "write_todos", "id": None, "args": {"todos": []}},
]
)
result = mw.after_model(state, _make_runtime())
ids = [call["id"] for call in result["messages"][0].tool_calls]
assert all(call_id.strip() for call_id in ids)
assert len(set(ids)) == 2
def test_synthetic_ids_avoid_other_tools_in_the_message(self):
mw = TodoMiddleware()
state = self._state(
[
{"name": "write_todos", "id": None, "args": {"todos": []}},
{"name": "echo", "id": "deerflow_write_todos_synthetic_0", "args": {}},
{"name": "write_todos", "id": None, "args": {"todos": []}},
]
)
result = mw.after_model(state, _make_runtime())
ai = result["messages"][0]
ids = [call["id"] for call in ai.tool_calls]
assert ids[1] == "deerflow_write_todos_synthetic_0"
assert ids[0] != ids[1] and ids[2] != ids[1]
assert len(set(ids)) == 3
def test_id_shared_with_another_tool_is_relabelled(self):
mw = TodoMiddleware()
state = self._state(
[
{"name": "echo", "id": "dup", "args": {}},
{"name": "write_todos", "id": "dup", "args": {"todos": []}},
]
)
result = mw.after_model(state, _make_runtime())
ai = result["messages"][0]
ids = [call["id"] for call in ai.tool_calls]
assert ids[0] == "dup"
assert ids[1] != "dup"
assert ids[1].startswith("deerflow_write_todos_synthetic_")
def test_provider_tool_call_surfaces_are_relabelled_by_occurrence(self):
mw = TodoMiddleware()
content = [
{"type": "tool_use", "id": "dup", "name": "write_todos", "input": {}},
{"type": "tool_use", "id": "dup", "name": "write_todos", "input": {}},
]
raw_calls = [
{"id": "dup", "type": "function", "function": {"name": "write_todos", "arguments": "{}"}},
{"id": "dup", "type": "function", "function": {"name": "write_todos", "arguments": "{}"}},
]
message = AIMessage(
id="ai-2",
content=content,
tool_calls=[
{"name": "write_todos", "id": "dup", "args": {"todos": []}},
{"name": "write_todos", "id": "dup", "args": {"todos": []}},
],
additional_kwargs={"tool_calls": raw_calls},
)
result = mw.after_model({"messages": [message]}, _make_runtime())
ai = result["messages"][0]
structured = [call["id"] for call in ai.tool_calls]
assert structured[0] == "dup"
assert structured[1] != "dup"
assert [block["id"] for block in ai.content if block["type"] == "tool_use"] == structured
assert [call["id"] for call in ai.additional_kwargs["tool_calls"]] == structured
@staticmethod
def _retry_messages(message: AIMessage) -> list[Any]:
model = _CapturingFakeMessagesListChatModel(responses=[message, AIMessage(content="Done.")])
graph = create_agent(model=model, tools=[], middleware=[DanglingToolCallMiddleware(), TodoMiddleware()])
graph.invoke({"messages": [HumanMessage(content="Write a plan.")]})
assert len(model.seen_messages) == 2
return model.seen_messages[1]
@pytest.mark.parametrize("use_previous_response_id", [False, True])
def test_openai_responses_retry_keeps_item_ids_and_pairs_calls_with_results(self, use_previous_response_id):
content = [{"type": "function_call", "id": item_id, "call_id": "call_dup", "name": "write_todos", "arguments": '{"todos":[]}'} for item_id in ("fc_first", "fc_second")]
message = AIMessage(
content=content,
response_metadata={"id": "resp_original", "model_provider": "openai"},
tool_calls=[{"name": "write_todos", "id": "call_dup", "args": {"todos": []}} for _ in content],
)
retry = self._retry_messages(message)
adapter = ChatOpenAI(model="gpt-5", api_key="test", use_responses_api=True, use_previous_response_id=use_previous_response_id)
payload = adapter._get_request_payload(retry)
assert "previous_response_id" not in payload
calls = [item for item in payload["input"] if item["type"] == "function_call"]
results = [item["call_id"] for item in payload["input"] if item["type"] == "function_call_output"]
assert [call["id"] for call in calls] == ["fc_first", "fc_second"]
assert [call["call_id"] for call in calls] == results == ["call_dup", "deerflow_write_todos_synthetic_1"]
assert [block["call_id"] for block in message.content] == ["call_dup", "call_dup"]
@pytest.mark.parametrize("id_fields", [{"id": None}, {}], ids=["null", "missing"])
def test_anthropic_retry_rewrites_idless_tool_use_blocks(self, id_fields):
todos = [{"todos": []}, {"todos": [{"content": "Plan", "status": "pending"}]}]
content = [
{"type": "tool_use", "id": "", "name": "write_todos", "input": todos[0]},
{"type": "tool_use", "name": "write_todos", "input": todos[1], **id_fields},
]
message = AIMessage(
content=content,
tool_calls=[{"name": "write_todos", "id": call_id, "args": args} for call_id, args in zip(("", None), todos, strict=True)],
)
retry = self._retry_messages(message)
adapter = ChatAnthropic(model="claude-sonnet-4-5", api_key="test")
payload = adapter._get_request_payload(retry)
blocks = [block for item in payload["messages"] for block in item["content"] if isinstance(block, dict)]
calls = [block for block in blocks if block["type"] == "tool_use"]
results = [block["tool_use_id"] for block in blocks if block["type"] == "tool_result"]
assert [call["input"] for call in calls] == todos
assert [call["id"] for call in calls] == results == ["deerflow_write_todos_synthetic_0", "deerflow_write_todos_synthetic_1"]
@pytest.mark.parametrize(
("invalid_name", "todo_id", "invalid_id"),
[
("echo", "call_dup", "call_dup"),
("write_todos", "call_dup", "call_dup"),
("echo", None, "deerflow_write_todos_synthetic_0"),
],
)
def test_chat_completions_retry_reserves_ids_of_invalid_calls(self, invalid_name, todo_id, invalid_id):
raw_calls = [
{"type": "function", "id": invalid_id, "function": {"name": invalid_name, "arguments": "{"}},
{"type": "function", "id": todo_id, "function": {"name": "write_todos", "arguments": '{"todos":[]}'}},
]
message = _convert_dict_to_message({"role": "assistant", "content": None, "tool_calls": raw_calls})
assert isinstance(message, AIMessage)
assert [call["id"] for call in message.invalid_tool_calls] == [invalid_id]
# Some integrations keep the raw provider calls alongside the decoded calls.
message = message.model_copy(update={"additional_kwargs": {"tool_calls": raw_calls}})
retry = self._retry_messages(message)
adapter = ChatOpenAI(model="gpt-4o", api_key="test", use_responses_api=False)
payload = adapter._get_request_payload(retry)
calls = [call for item in payload["messages"] for call in item.get("tool_calls", [])]
results = [item["tool_call_id"] for item in payload["messages"] if item["role"] == "tool"]
repaired_id = "deerflow_write_todos_synthetic_0"
if invalid_id == repaired_id:
repaired_id += "_"
assert [call["id"] for call in calls] == [repaired_id, invalid_id]
assert set(results) == {repaired_id, invalid_id}
assert len(results) == 2
retry_raw_calls = next(item for item in retry if isinstance(item, AIMessage)).additional_kwargs["tool_calls"]
assert [call["id"] for call in retry_raw_calls] == [invalid_id, repaired_id]
assert [call["id"] for call in raw_calls] == [invalid_id, todo_id]
def test_well_formed_ids_are_left_to_the_base_hook(self):
mw = TodoMiddleware()
state = self._state(
[
{"name": "write_todos", "id": "a", "args": {"todos": []}},
{"name": "write_todos", "id": "b", "args": {"todos": []}},
]
)
result = mw.after_model(state, _make_runtime())
assert all(message.tool_call_id in {"a", "b"} for message in result["messages"])
assert not any(hasattr(message, "tool_calls") for message in result["messages"])
class TestAfterModel: class TestAfterModel:
def test_all_middleware_stop_reason_writes_have_an_explicit_todo_policy(self): def test_all_middleware_stop_reason_writes_have_an_explicit_todo_policy(self):
middleware_dir = Path(__file__).resolve().parents[1] / "packages/harness/deerflow/agents/middlewares" middleware_dir = Path(__file__).resolve().parents[1] / "packages/harness/deerflow/agents/middlewares"