Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions native/codex/tests/test_gateway_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Agent,
EngineError,
RunError,
RunResult,
RunRetrying,
function_tool,
testing as harness,
Expand All @@ -18,6 +19,81 @@
from openai_agents.codex.testing import MockModel


@pytest.mark.parametrize(
("code", "status", "expected"),
[
("http_connection_failed", 408, True),
("http_connection_failed", 429, True),
("response_too_many_failed_attempts", 500, True),
("http_connection_failed", 502, True),
("response_stream_disconnected", 503, True),
("http_connection_failed", 504, True),
("http_connection_failed", 400, False),
("http_connection_failed", 401, False),
("http_connection_failed", 403, False),
("http_connection_failed", 404, False),
("http_connection_failed", 422, False),
("rate_limit_exceeded", None, True),
("server_overloaded", None, True),
("internal_server_error", None, True),
("invalid_input", None, False),
("invalid_prompt", None, False),
("bad_request", None, False),
("unauthorized", None, False),
("invalid_prompt", 503, None),
("server_overloaded", 401, None),
("server_overloaded", 503, True),
("unauthorized", 401, False),
("future_code", 503, True),
("future_code", None, None),
("other", 200, None),
("other", 409, None),
("other", 501, None),
("http_connection_failed", None, None),
("response_stream_disconnected", None, None),
("response_too_many_failed_attempts", None, None),
("turn_aborted", None, None),
("tool_error", None, None),
],
)
def test_shared_retryability_advice(code: str, status: int | None, expected: bool | None) -> None:
details = {"http_status_code": status}
error = RunError("Synthetic failure", code=code, details=details)
event = _parse_event(
"turn/retrying",
{"message": "Synthetic failure", "codex_error_info": {code: details}},
)
assert isinstance(event, RunRetrying)
for failure in (error, event):
assert failure.retryable is expected
assert failure.code == code
assert failure.details == details
with pytest.raises(AttributeError):
failure.retryable = True # type: ignore[misc]


@pytest.mark.parametrize(
"details",
[
{},
{"http_status_code": None},
{"http_status_code": "503"},
{"http_status_code": 503.0},
{"http_status_code": True},
{"nested": {"http_status_code": 503}},
],
)
def test_retryability_ignores_prose_and_unstructured_status(details: dict[str, Any]) -> None:
message = "503 server overloaded; retry this request"
error = RunError(message, code="other", details=details)
event = RunRetrying(message=message, code="other", additional_details=message, details=details)
assert error.retryable is None
assert event.retryable is None
assert str(error) == message
assert event.additional_details == message
assert error.details == event.details == details


@pytest.mark.parametrize("status", [None, 503])
def test_retry_event_preserves_structured_status(status: int | None) -> None:
event = _parse_event(
Expand Down Expand Up @@ -116,6 +192,12 @@ async def run(model: MockModel) -> None:
assert error.code in ("http_connection_failed", "response_too_many_failed_attempts")
assert error.details == {"http_status_code": status}
assert error.http_status_code == status
request_count = len(model.requests)
expected = None if status is None else status != 401
assert error.retryable is expected
assert error.retryable is expected
assert all(retry.retryable is expected for retry in retries)
assert len(model.requests) == request_count
assert error.turn_id
assert error.new_items
assert error.usage.turn is None
Expand Down Expand Up @@ -166,6 +248,7 @@ async def run() -> None:
assert str(error) == "Synthetic refusal"
assert error.details == {}
assert error.http_status_code is None
assert error.retryable is False
assert error.turn_id
assert len(error.usage.responses) == 1
assert error.usage.responses[0].response_id == "resp_1"
Expand All @@ -180,6 +263,48 @@ async def run() -> None:
assert len(mock_model.requests) == 2


def test_response_failure_advice_preserves_native_retry_and_tool_count(
mock_model: MockModel,
) -> None:
calls: list[str] = []

@function_tool
def record(value: str) -> str:
calls.append(value)
return value

mock_model.call("record", {"value": "once"})
mock_model.events(
{
"type": "response.failed",
"response": {
"id": "resp_overloaded",
"error": {"code": "server_overloaded", "message": "Synthetic overload"},
},
}
)
mock_model.reply("Continued")

async def run() -> None:
retries: list[RunRetrying] = []
output: str | None = None
async with Agent(model="offline-test", tools=[record]).session() as session:
async for event in session.stream("Record once"):
if isinstance(event, RunRetrying):
retries.append(event)
assert event.code == "response_stream_disconnected"
assert event.http_status_code is None
assert event.retryable is None
if isinstance(event, RunResult):
output = event.final_output
assert retries
assert output == "Continued"

asyncio.run(run())
assert calls == ["once"]
assert len(mock_model.requests) == 3


def test_requested_interruption_supplies_state_and_preserves_live_session(
mock_model: MockModel,
) -> None:
Expand Down Expand Up @@ -209,6 +334,7 @@ async def wait() -> str:
error = raised.value
assert error.code == "turn_aborted"
assert error.http_status_code is None
assert error.retryable is None
assert error.state is not None
assert error.state == session.snapshot()
assert error.turn_id
Expand Down
29 changes: 29 additions & 0 deletions src/openai_agents/codex/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,17 @@ def http_status_code(self) -> int | None:
status = self.details.get("http_status_code")
return status if type(status) is int else None

@property
def retryable(self) -> bool | None:
"""Get retryability advice from the error code and HTTP status.

True indicates a recognized transient failure. False indicates a recognized
client or request failure. None indicates insufficient or conflicting evidence.
Reading this property starts no retry. The application must decide whether
replaying the turn or tool call is safe, even when the value is True.
"""
return _retryable(self.code, self.http_status_code)


class ToolError(RunError):
"""A Python handler failed. The original exception is available as __cause__."""
Expand All @@ -38,6 +49,24 @@ def __init__(self, message: str, *, tool_name: str, call_id: str) -> None:
self.call_id = call_id


def _retryable(code: str, status: int | None) -> bool | None:
code_advice = None
if code in {"rate_limit_exceeded", "server_overloaded", "internal_server_error"}:
code_advice = True
elif code in {"invalid_input", "invalid_prompt", "bad_request", "unauthorized"}:
code_advice = False

status_advice = None
if status in {408, 429, 500, 502, 503, 504}:
status_advice = True
elif status in {400, 401, 403, 404, 422}:
status_advice = False

if code_advice is not None and status_advice is not None and code_advice != status_advice:
return None
return code_advice if code_advice is not None else status_advice


def _error_info(info: str | dict[str, Any] | None) -> tuple[str, dict[str, Any]]:
# Codex serializes variants carrying fields as {code: {fields}}.
if isinstance(info, dict) and info:
Expand Down
13 changes: 12 additions & 1 deletion src/openai_agents/codex/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from dataclasses import dataclass, field
from typing import Any, ClassVar, Literal, TypeAlias

from openai_agents.codex.errors import EngineError, _error_info
from openai_agents.codex.errors import EngineError, _error_info, _retryable
from openai_agents.codex.items import RunItem, _parse_item
from openai_agents.codex.result import RunResult
from openai_agents.codex.usage import ResponseUsage, TokenUsage
Expand Down Expand Up @@ -92,6 +92,17 @@ def http_status_code(self) -> int | None:
status = self.details.get("http_status_code")
return status if type(status) is int else None

@property
def retryable(self) -> bool | None:
"""Get retryability advice from the retry event's code and HTTP status.

True indicates a recognized transient failure. False indicates a recognized
client or request failure. None indicates insufficient or conflicting evidence,
including when a retry is already underway. This advice leaves automatic
retries unchanged. The application owns decisions about safe replay.
"""
return _retryable(self.code, self.http_status_code)


@dataclass(frozen=True, kw_only=True)
class HookStarted:
Expand Down
Loading