The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: spill oversized tool outputs before a Codex zero-event reconnect and log the size delta
teknium187de11b70051
diff --git a/agent/codex_runtime.py b/agent/codex_runtime.pyindex 600c9348b54..cdce3f87c18 100644--- a/agent/codex_runtime.py+++ b/agent/codex_runtime.py@@ -57,6 +57,43 @@ def _codex_request_failure_details(error: BaseException) -> tuple[int | None, streturn request_body_bytes, " <- ".join(exception_classes)+def _prune_zero_event_retry_payload(api_kwargs: dict, attempt: int, attempts: int) -> dict:+ """#95429 criterion 3: a reconnect after an attempt that produced no stream event must not resend+ a pathological payload unchanged. Inline ``function_call_output`` strings over the per-result+ threshold (results that escaped commit-time persistence) are spilled through the standard+ policy -- bounded preview + recoverable ``<persisted-output>`` reference -- and ONE log line+ records the size delta. When nothing is prunable the resend is logged as unchanged. The+ caller's kwargs are never mutated; only the retried wire payload changes."""+ from tools.budget_config import DEFAULT_BUDGET+ from tools.tool_result_storage import maybe_persist_tool_result++ items = api_kwargs.get("input")+ if not isinstance(items, list):+ return api_kwargs+ before = len(json.dumps(items, default=str).encode("utf-8"))+ if before <= DEFAULT_BUDGET.turn_budget:+ return api_kwargs+ pruned_items, pruned = [], 0+ for item in items:+ output = item.get("output") if isinstance(item, dict) and item.get("type") == "function_call_output" else None+ if isinstance(output, str):+ replaced = maybe_persist_tool_result(content=output, tool_name="codex_zero_event_retry",+ tool_use_id=str(item.get("call_id") or "call"),+ config=DEFAULT_BUDGET, threshold=DEFAULT_BUDGET.default_result_size)+ if replaced != output:+ item, pruned = {**item, "output": replaced}, pruned + 1+ pruned_items.append(item)+ if not pruned:+ logger.warning("Codex zero-event retry (attempt %s/%s): no prunable tool output; resending payload "+ "unchanged (serialized_input_bytes=%s, model=%s)", attempt, attempts, before, api_kwargs.get("model"))+ return api_kwargs+ after = len(json.dumps(pruned_items, default=str).encode("utf-8"))+ logger.warning("Codex zero-event retry (attempt %s/%s): spilled %d oversized tool output(s) before reconnect, "+ "serialized_input_bytes=%s -> %s (model=%s)", attempt, attempts, pruned, before, after,+ api_kwargs.get("model"))+ return {**api_kwargs, "input": pruned_items}++def _coerce_usage_int(value: Any) -> int:if isinstance(value, bool):return 0@@ -1011,6 +1048,8 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_deltaelse "Codex Responses stream transport failed mid-iteration (attempt %s/%s); retrying. %s error=%s",attempt + 1, max_stream_retries + 1, agent._client_log_context(), exc,)+ if not intercepted_events: # zero-event attempt: never resend a pathological payload silently+ api_kwargs = _prune_zero_event_retry_payload(api_kwargs, attempt + 1, max_stream_retries + 1)continueexcept RuntimeError:# "No terminal response"; Relay may still hold a finalizer-assembled response.diff --git a/tests/agent/test_codex_request_transport_diagnostics.py b/tests/agent/test_codex_request_transport_diagnostics.pyindex 0a65155baf5..48cbd79c840 100644--- a/tests/agent/test_codex_request_transport_diagnostics.py+++ b/tests/agent/test_codex_request_transport_diagnostics.py@@ -2,7 +2,10 @@from __future__ import annotations+import jsonimport logging+import re+from pathlib import Pathfrom types import SimpleNamespaceimport httpx@@ -61,3 +64,77 @@ def test_transport_failure_logs_exact_request_bytes_and_class_chain(caplog):assert "payload" not in messageassert request_content.decode() not in messageassert "example.invalid" not in message+++def _zero_event_then_completed_client(seen_inputs: list):+ """``responses.create`` that dies before any stream event on the first call and completes on+ the second; records the ``input`` list each physical attempt was given."""+ from tests.agent.test_run_agent_codex_responses import _FakeCreateStream++ events = [+ SimpleNamespace(type="response.output_item.done", item=SimpleNamespace(+ type="message", status="completed", content=[SimpleNamespace(type="output_text", text="ok")])),+ SimpleNamespace(type="response.completed", response=SimpleNamespace(+ status="completed", usage=SimpleNamespace(input_tokens=1, output_tokens=1, total_tokens=2), id="r1")),+ ]++ def _create(**kwargs):+ seen_inputs.append(kwargs.get("input") or (kwargs.get("extra_body") or {}).get("input"))+ if len(seen_inputs) == 1:+ raise httpx.ConnectError("no first byte")+ return _FakeCreateStream(events)++ return SimpleNamespace(responses=SimpleNamespace(create=_create))+++def _oversized_codex_kwargs(size: int) -> dict:+ return {"model": "gpt-5-codex", "instructions": "You are Hermes.", "store": False, "tools": None,+ "input": [{"role": "user", "content": "look"},+ {"type": "function_call", "call_id": "call_browser", "name": "browser_exec", "arguments": "{}"},+ {"type": "function_call_output", "call_id": "call_browser", "output": "x" * size},+ {"role": "user", "content": "continue"}]}+++def test_zero_event_retry_prunes_oversized_tool_output_and_logs_size_delta(monkeypatch, tmp_path, caplog):+ """#95429 criterion 3: a reconnect after a zero-event attempt must not resend the same oversized+ payload unchanged -- the inline tool output is spilled and the size delta is logged."""+ from tests.agent.test_run_agent_codex_responses import _build_agent+ from tools.tool_result_storage import PERSISTED_OUTPUT_TAG++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path, raising=False)+ agent = _build_agent(monkeypatch)+ seen: list = []+ agent.client = _zero_event_then_completed_client(seen)++ with caplog.at_level(logging.INFO, logger="agent.codex_runtime"):+ response = agent._run_codex_stream(_oversized_codex_kwargs(760_396))++ assert response.status == "completed" and len(seen) == 2+ first, second = (len(json.dumps(i)) for i in seen)+ assert second < first // 10+ retried_output = seen[1][2]["output"]+ assert PERSISTED_OUTPUT_TAG in retried_output and len(retried_output) < 10_000+ assert Path(tmp_path, "cache", "spillover", "call_browser.txt").read_text() == "x" * 760_396+ assert seen[0][2]["output"] == "x" * 760_396 # the caller's kwargs are not mutated+ prune_logs = [r.message for r in caplog.records if "zero-event" in r.message]+ assert len(prune_logs) == 1 and "attempt 1/2" in prune_logs[0]+ assert re.search(r"serialized_input_bytes=\d+ -> \d+", prune_logs[0])+++def test_zero_event_retry_without_prunable_output_logs_unchanged_resend(monkeypatch, caplog):+ from tests.agent.test_run_agent_codex_responses import _build_agent++ agent = _build_agent(monkeypatch)+ seen: list = []+ agent.client = _zero_event_then_completed_client(seen)+ kwargs = _oversized_codex_kwargs(300_000)+ kwargs["input"][2]["output"] = ["not-a-string"] # nothing prunable+ kwargs["input"][0]["content"] = "u" * 300_000 # still a large payload++ with caplog.at_level(logging.INFO, logger="agent.codex_runtime"):+ response = agent._run_codex_stream(kwargs)++ assert response.status == "completed" and seen[0] == seen[1]+ (log,) = [r.message for r in caplog.records if "zero-event" in r.message]+ assert "unchanged" in log and "attempt 1/2" in log and re.search(r"serialized_input_bytes=\d+", log)