The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): make the pre-call dedup pass variant-aware; widen batch regression coverage (#93251)
Tekniumfaa2399e2b3f
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex fc5b055a037..52f790148bb 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3826,6 +3826,14 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]# that reuses the id re-arms that id first.seen_assistant_call_ids: set = set()outstanding_call_ids: set = set()+ # Variant → full variant-set of the tool_call it belongs to, so answering+ # or deduping one variant consumes its siblings too. A Codex/Responses+ # tool_call registers BOTH ``id`` (fc_...) and ``call_id`` (call_...)+ # (#55626/#58168); tracking only the coalesced id here made a result+ # keyed on the OTHER variant look like it answered no outstanding call,+ # so this pass deleted the very result step 2's variant-aware matching+ # had just preserved (issue #93251 — whole parallel batches vanished).+ dedup_id_siblings: Dict[str, set] = {}deduped: List[Dict[str, Any]] = []removed_dupes = 0for msg in messages:@@ -3833,13 +3841,14 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]if role == "assistant" and msg.get("tool_calls"):kept_tcs = []for tc in msg.get("tool_calls") or []:- cid = _ra().AIAgent._get_tool_call_id_static(tc)- if cid and cid in seen_assistant_call_ids:+ variants = _tool_call_id_variants(tc)+ if variants and variants & seen_assistant_call_ids:removed_dupes += 1continue- if cid:+ for cid in variants:seen_assistant_call_ids.add(cid)outstanding_call_ids.add(cid)+ dedup_id_siblings[cid] = variantskept_tcs.append(tc)if kept_tcs:msg = {**msg, "tool_calls": kept_tcs}@@ -3852,11 +3861,13 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]removed_dupes += 1continueif cid:- # Answered: this id is no longer outstanding, so a second- # result replaying it is still caught above.- outstanding_call_ids.discard(cid)- # A reused id must be re-armable by the next assistant call.- seen_assistant_call_ids.discard(cid)+ # Answered: consume EVERY variant of the matched call so a+ # second result replaying either sibling is still caught+ # above, and the ids are re-armable by the next assistant+ # call that reuses them.+ for sibling in dedup_id_siblings.get(cid, {cid}):+ outstanding_call_ids.discard(sibling)+ seen_assistant_call_ids.discard(sibling)deduped.append(msg)else:deduped.append(msg)diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex 6d26e3bbc4d..0c4efd702a8 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -2514,7 +2514,9 @@ class TestSanitizerStripsOrphanedToolCalls:"""Negative control: registering both id and call_id must notover-relax orphan detection. A genuinely orphaned tool_call (noresult matching either id variant) is still stripped, while a valid- dual-id pair in the same window survives."""+ dual-id pair in the same window survives. A trailing user turn keeps+ the assistant message out of the in-flight protection window (#79278),+ which intentionally preserves a still-pending trailing call."""msgs = [{"role": "assistant",@@ -2535,6 +2537,7 @@ class TestSanitizerStripsOrphanedToolCalls:],},{"role": "tool", "tool_call_id": "call_1", "content": "result"},+ {"role": "user", "content": "next question"},]sanitized = compressor._sanitize_tool_pairs(msgs)diff --git a/tests/run_agent/test_message_sequence_repair.py b/tests/run_agent/test_message_sequence_repair.pyindex c344636e0e8..461e9104874 100644--- a/tests/run_agent/test_message_sequence_repair.py+++ b/tests/run_agent/test_message_sequence_repair.py@@ -654,3 +654,84 @@ def test_repair_keeps_both_results_for_two_codex_calls_mixed_keys():assert repairs == 0assert [m["content"] for m in messages if m.get("role") == "tool"] == ["r1", "r2"]+++def test_sanitize_dedup_pass_keeps_batch_results_keyed_on_divergent_id():+ """The step-3 dedup pass must not delete real results whose tool_call_id+ matches the non-coalesced id variant.++ A parallel batch of Codex/Responses-style tool_calls carries divergent+ ``id`` (fc_...) and ``call_id`` (call_...). Step 2's variant-aware+ matching preserves results keyed on either variant, but the dedup pass+ tracked only the coalesced (call_id||id) value in+ ``outstanding_call_ids`` — so every result keyed on ``id`` looked like it+ answered no outstanding call and was deleted wholesale. Whole parallel+ batches vanished with no stub at all (#93251, #55626 class).+ """+ from agent.agent_runtime_helpers import sanitize_api_messages++ messages = [+ {"role": "user", "content": "task"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": f"fc_{i}", "call_id": f"call_{i}", "type": "function",+ "function": {"name": "terminal", "arguments": "{}"}}+ for i in range(4)+ ]},+ ] + [+ {"role": "tool", "tool_call_id": f"fc_{i}", "content": f"REAL {i}"}+ for i in range(4)+ ]++ out = sanitize_api_messages(messages)++ tool_msgs = [m for m in out if m.get("role") == "tool"]+ assert [m["content"] for m in tool_msgs] == [+ "REAL 0", "REAL 1", "REAL 2", "REAL 3",+ ], "real batch results must survive the dedup pass"+ assert not any("Result unavailable" in m["content"] for m in tool_msgs)+++def test_sanitize_dedup_pass_still_drops_result_replayed_on_sibling_id():+ """Variant-aware dedup must still drop a SECOND result for an+ already-answered call even when the replay uses the OTHER id variant+ (strict providers 400 on duplicate tool_call_id)."""+ from agent.agent_runtime_helpers import sanitize_api_messages++ messages = [+ {"role": "user", "content": "task"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "fc_1", "call_id": "call_1", "type": "function",+ "function": {"name": "f", "arguments": "{}"}},+ ]},+ {"role": "tool", "tool_call_id": "fc_1", "content": "first"},+ {"role": "tool", "tool_call_id": "call_1", "content": "sibling replay"},+ ]++ out = sanitize_api_messages(messages)++ tool_msgs = [m for m in out if m.get("role") == "tool"]+ assert [m["content"] for m in tool_msgs] == ["first"]+++def test_sanitize_dedup_pass_rearms_constant_llamacpp_id():+ """llama.cpp emits one constant id for every call; a fresh assistant call+ re-arms the id so the second round's result still survives (#58327+ outstanding-call semantics must be preserved by the variant-set change)."""+ from agent.agent_runtime_helpers import sanitize_api_messages++ messages = [+ {"role": "user", "content": "task"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "call_K", "type": "function",+ "function": {"name": "f", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "call_K", "content": "round1"},+ {"role": "assistant", "content": "", "tool_calls": [+ {"id": "call_K", "type": "function",+ "function": {"name": "f", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "call_K", "content": "round2"},+ ]++ out = sanitize_api_messages(messages)++ tool_msgs = [m for m in out if m.get("role") == "tool"]+ assert [m["content"] for m in tool_msgs] == ["round1", "round2"]