Skip to content

The agent that grows with you

fix(compression): register both id/call_id variants in _sanitize_tool_pairs

srojk3452fb5081cc64
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 151c0856cd1..2a9e0b16a2c 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -5688,11 +5688,34 @@ This compaction should PRIORITISE preserving all information related to the focu
@staticmethod
def _get_tool_call_id(tc) -> str:
- """Extract the call ID from a tool_call entry (dict or SimpleNamespace)."""
+ """Extract the canonical call ID from a tool_call entry (dict or
+ SimpleNamespace), for logging/display only. Matching logic must use
+ :meth:`_tool_call_id_variants` instead — see its docstring."""
if isinstance(tc, dict):
return tc.get("call_id", "") or tc.get("id", "") or ""
return getattr(tc, "call_id", "") or getattr(tc, "id", "") or ""
+ @staticmethod
+ def _tool_call_id_variants(tc) -> set:
+ """Return every id variant a tool result might reference *tc* by.
+
+ A tool result's ``tool_call_id`` may be keyed on either ``id`` or
+ ``call_id`` depending on which code path built it — in the Codex
+ Responses API format they are distinct (``id`` is the ``fc_...``
+ response-item id, ``call_id`` is the ``call_...`` function-call id).
+ Matching on a single value (the old ``call_id || id`` precedence)
+ misclassified a genuinely matching pair as orphaned whenever the
+ result used the field that precedence didn't pick, dropping BOTH the
+ valid result and its tool_call. Registering the superset of both ids
+ is the same fix #58168 applied to ``repair_message_sequence``'s
+ known-id set.
+ """
+ if isinstance(tc, dict):
+ get = tc.get
+ else:
+ get = lambda key: getattr(tc, key, None)
+ return {v for v in (get("id"), get("call_id")) if v}
+
def _sanitize_tool_pairs(self, messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Fix orphaned tool_call / tool_result pairs after compression.
@@ -5719,9 +5742,7 @@ This compaction should PRIORITISE preserving all information related to the focu
for msg in messages:
if msg.get("role") == "assistant":
for tc in msg.get("tool_calls") or []:
- cid = self._get_tool_call_id(tc)
- if cid:
- surviving_call_ids.add(cid)
+ surviving_call_ids |= self._tool_call_id_variants(tc)
result_call_ids: set = set()
for msg in messages:
@@ -5744,8 +5765,11 @@ This compaction should PRIORITISE preserving all information related to the focu
# were dropped. Stripping is preferred over inserting stub results
# because stubs can be dropped by downstream repair_message_sequence
# when call_id != id (Codex Responses API format), re-exposing orphans.
- missing_results = surviving_call_ids - result_call_ids
- if missing_results:
+ # A tool_call survives if ANY of its id variants still has a
+ # matching result — checking only one variant per side is exactly
+ # the mismatch this method exists to avoid.
+ stripped_count = 0
+ if surviving_call_ids - result_call_ids:
# --- In-flight tool chain protection (issue #79278) -------------
# A strip here must distinguish a *pending* tool_call (the model's
# live request whose result the executor has not yet appended) from
@@ -5790,8 +5814,9 @@ This compaction should PRIORITISE preserving all information related to the focu
tcs = msg.get("tool_calls")
if not tcs:
continue
- kept = [tc for tc in tcs if self._get_tool_call_id(tc) not in missing_results]
+ kept = [tc for tc in tcs if self._tool_call_id_variants(tc) & result_call_ids]
if len(kept) != len(tcs):
+ stripped_count += len(tcs) - len(kept)
if kept:
msg["tool_calls"] = kept
else:
@@ -5801,10 +5826,10 @@ This compaction should PRIORITISE preserving all information related to the focu
content = msg.get("content")
if not content or (isinstance(content, str) and not content.strip()):
msg["content"] = "(tool call removed)"
- if not self.quiet_mode:
+ if stripped_count and not self.quiet_mode:
logger.info(
"Compression sanitizer: stripped %d orphaned tool_call(s) from assistant messages",
- len(missing_results),
+ stripped_count,
)
return messages
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 164f54a6521..6d26e3bbc4d 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -2477,6 +2477,72 @@ class TestSanitizerStripsOrphanedToolCalls:
assert not asst.get("tool_calls")
# No stub tool messages (which would have call_id != id mismatch)
+ def test_sanitizer_keeps_valid_pair_matching_on_id_not_call_id(self, compressor):
+ """A genuinely matching Codex-format pair must survive when the
+ result's tool_call_id matches ``id`` rather than ``call_id`` (#58168
+ class). ``_get_tool_call_id``'s ``call_id || id`` precedence picks
+ ``call_id`` first, so building the known-id set from a single value
+ per tool_call misclassified this valid pair as orphaned on BOTH
+ sides — dropping the result AND stripping the tool_call, even though
+ neither was actually orphaned."""
+ msgs = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "fc_777",
+ "call_id": "call_777",
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ },
+ ],
+ },
+ {"role": "tool", "tool_call_id": "fc_777", "content": "result"},
+ ]
+
+ sanitized = compressor._sanitize_tool_pairs(msgs)
+
+ asst = next(m for m in sanitized if m.get("role") == "assistant")
+ assert asst.get("tool_calls"), "valid tool_call must not be stripped"
+ assert asst["tool_calls"][0]["id"] == "fc_777"
+ tool_msgs = [m for m in sanitized if m.get("role") == "tool"]
+ assert len(tool_msgs) == 1, "valid tool result must not be dropped as orphaned"
+ assert tool_msgs[0]["tool_call_id"] == "fc_777"
+
+ def test_sanitizer_still_drops_genuine_orphan_with_dual_ids(self, compressor):
+ """Negative control: registering both id and call_id must not
+ over-relax orphan detection. A genuinely orphaned tool_call (no
+ result matching either id variant) is still stripped, while a valid
+ dual-id pair in the same window survives."""
+ msgs = [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "fc_1",
+ "call_id": "call_1",
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ },
+ {
+ "id": "fc_2",
+ "call_id": "call_2",
+ "type": "function",
+ "function": {"name": "search", "arguments": "{}"},
+ },
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "result"},
+ ]
+
+ sanitized = compressor._sanitize_tool_pairs(msgs)
+
+ asst = next(m for m in sanitized if m.get("role") == "assistant")
+ surviving_ids = {tc["id"] for tc in asst.get("tool_calls") or []}
+ assert surviving_ids == {"fc_1"}
+
class TestSanitizerPreservesInFlightToolChain:
"""Issue #79278: an in-flight tool call chain must survive compression.