diff --git a/backend/packages/harness/deerflow/agents/middlewares/dangling_tool_call_middleware.py b/backend/packages/harness/deerflow/agents/middlewares/dangling_tool_call_middleware.py index 94dcfefcad..e5762b900c 100644 --- a/backend/packages/harness/deerflow/agents/middlewares/dangling_tool_call_middleware.py +++ b/backend/packages/harness/deerflow/agents/middlewares/dangling_tool_call_middleware.py @@ -97,8 +97,9 @@ def _relabel_tool_call_ids(tool_calls: list, msg_index: int, source: str) -> tup The id is derived from the call's position so both the pairing pass and the model-bound message agree on it without threading state between them. - Returns the rewritten list, one ``{original, synthetic, name}`` claim entry per - relabelled call, and whether anything changed. + Returns the rewritten list, one ``{original, synthetic, name, executable}`` claim + entry per relabelled call, and whether anything changed. The executable flag + breaks ties between equally strong name matches. """ relabeled: list = [] assigned: list[dict] = [] @@ -110,7 +111,14 @@ def _relabel_tool_call_ids(tool_calls: list, msg_index: int, source: str) -> tup synthetic = f"{_SYNTHETIC_TOOL_CALL_ID_PREFIX}{msg_index}_{source}_{position}" relabeled.append({**tool_call, "id": synthetic}) changed = True - assigned.append({"original": tool_call.get("id"), "synthetic": synthetic, "name": _tool_call_name(tool_call)}) + assigned.append( + { + "original": tool_call.get("id"), + "synthetic": synthetic, + "name": _tool_call_name(tool_call), + "executable": source != "invalid", + } + ) return relabeled, assigned, changed @@ -130,7 +138,11 @@ def _claim_synthetic_id(open_calls: list[dict], result: ToolMessage, positional: Malformed originals are all equally empty, so they cannot identify their own result; ``open_calls`` is already scoped to the issuing turn. Within that turn the - result's name narrows the candidates, and only a *forced* choice is taken: + result's name narrows the candidates. An exact name match takes precedence + over candidates with missing names. Within the same name-match priority, + executable calls take precedence so an invalid same-name sibling cannot + steal or block their result (#7821). A persisted ToolMessage can still pair + with an invalid call (#2894). Among the remaining candidates: * one compatible call — its name, or being the turn's only call, identifies it; * several compatible calls — position identifies them, but only while ``positional`` @@ -146,7 +158,16 @@ def _claim_synthetic_id(open_calls: list[dict], result: ToolMessage, positional: what an unattributable result gets today — better than inventing a pairing. """ candidates = [position for position, entry in enumerate(open_calls) if _same_tool_call_id(entry["original"], result.tool_call_id) and _names_can_pair(entry["name"], result.name)] - if not candidates or (len(candidates) > 1 and not positional): + if not candidates: + return None + + if _valid_tool_name(result.name): + exact_matches = [position for position in candidates if _valid_tool_name(open_calls[position]["name"])] + candidates = exact_matches or candidates + + executable_matches = [position for position in candidates if open_calls[position]["executable"]] + candidates = executable_matches or candidates + if len(candidates) > 1 and not positional: return None return open_calls.pop(candidates[0])["synthetic"] diff --git a/backend/tests/test_dangling_tool_call_middleware.py b/backend/tests/test_dangling_tool_call_middleware.py index b924a87ca9..4950d02fd1 100644 --- a/backend/tests/test_dangling_tool_call_middleware.py +++ b/backend/tests/test_dangling_tool_call_middleware.py @@ -1135,6 +1135,107 @@ class TestMalformedToolCallIdRecovery: assert results[" call_1 "].content == "result" assert results[recovered_id].status == "error" + def test_invalid_sibling_result_does_not_disable_positional_pairing(self): + """A result only an invalid call can own must not turn positional pairing off. + + Two identical executable ``bash`` calls plus one invalid sibling, all with the + empty id, and three real results. The invalid call's own result is a legitimate + member of the turn, so the turn is fully accounted for and position still + identifies which result belongs to which executable call. Counting only + executable results in the denominator made this turn look incomplete, and all + three real outputs were dropped in favour of error placeholders. + """ + mw = DanglingToolCallMiddleware() + msgs = [ + AIMessage.model_construct( + content="", + type="ai", + tool_calls=[ + {"name": "bash", "args": {"cmd": "one"}, "id": ""}, + {"name": "bash", "args": {"cmd": "two"}, "id": ""}, + ], + invalid_tool_calls=[ + {"name": "bash", "args": "{", "id": "", "error": "Unterminated object"}, + ], + additional_kwargs={}, + response_metadata={}, + ), + ToolMessage(content="EXEC ONE", tool_call_id="", name="bash"), + ToolMessage(content="EXEC TWO", tool_call_id="", name="bash"), + ToolMessage(content="INVALID OWN OUTPUT", tool_call_id="", name="bash"), + ] + + patched = mw._build_patched_messages(msgs) + + assert patched is not None + results = {m.tool_call_id: m for m in patched[1:]} + contents = sorted(m.content for m in patched[1:]) + # Every real result survives; none is swapped for the interrupted placeholder. + assert contents == ["EXEC ONE", "EXEC TWO", "INVALID OWN OUTPUT"] + assert all(m.status != "error" for m in patched[1:]) + # The two executable calls keep their own outputs in call order. + (first, second) = (tc["id"] for tc in patched[0].tool_calls) + assert results[first].content == "EXEC ONE" + assert results[second].content == "EXEC TWO" + + @pytest.mark.parametrize("missing_name", [None, "", " "]) + def test_exact_name_wins_over_an_unnamed_executable_sibling(self, missing_name): + mw = DanglingToolCallMiddleware() + messages = [ + AIMessage.model_construct( + content="", + tool_calls=[_tc(missing_name, "")], + invalid_tool_calls=[_invalid_tc(name="read_file", tc_id="")], + ), + ToolMessage(content="PERSISTED OUTPUT", tool_call_id="", name="read_file"), + ] + + patched = mw._build_patched_messages(messages) + + assert patched is not None + assert patched[0].tool_calls[0]["name"] == "unknown_tool" + unnamed_id = patched[0].tool_calls[0]["id"] + named_id = patched[0].invalid_tool_calls[0]["id"] + results = {message.tool_call_id: message for message in patched[1:]} + assert results[named_id].content == "PERSISTED OUTPUT" + assert results[named_id].status == "success" + assert results[unnamed_id].status == "error" + + def test_executable_call_wins_over_a_same_name_invalid_sibling(self): + """An invalid sibling with the same name must not steal the real result (#7821). + + Both calls carry the empty id, so only the name and position can pair them. The + invalid call never executes, so its ToolMessage is this middleware's placeholder; + the executable call's result is the only real output in the turn. Dropping that + result and injecting an "interrupted" placeholder instead is the bug covered here. + """ + mw = DanglingToolCallMiddleware() + msgs = [ + AIMessage.model_construct( + content="", + type="ai", + tool_calls=[{"name": "ls", "args": {"path": "."}, "id": ""}], + invalid_tool_calls=[{"name": "ls", "args": "{", "id": "", "error": "Unterminated object"}], + additional_kwargs={}, + response_metadata={}, + ), + ToolMessage(content="REAL RESULT", tool_call_id="", name="ls"), + ] + + patched = mw._build_patched_messages(msgs) + + assert patched is not None + (executable_id,) = (tc["id"] for tc in patched[0].tool_calls) + (invalid_id,) = (tc["id"] for tc in patched[0].invalid_tool_calls) + results = {m.tool_call_id: m for m in patched[1:]} + + # The real output lands on the executable call, not on the sibling's placeholder. + assert results[executable_id].content == "REAL RESULT" + assert results[executable_id].status == "success" + # The invalid call still gets its own injected error placeholder. + assert results[invalid_id].status == "error" + assert "REAL RESULT" not in results[invalid_id].content + class TestWrapModelCall: def test_no_patch_passthrough(self):