litellm/tests/e2e/codex/run.py
izzybn 0a72066fa8
test(e2e): add a Codex compatibility table, a Vertex AI column and five rows to tests/e2e/codex (#54065)
* test(e2e): add a Codex compatibility matrix suite

Add tests/e2e/client_apps, a compatibility matrix for coding-agent CLIs
other than Claude Code, starting with Codex 0.164.0 pinned through npm.
Each of the 36 cells drives the real codex exec against the proxy for one
feature and provider column, records a pass or fail per model, and the
typed matrix builder turns the results into a matrix and flags cells that
went from green to red. The harness parts are covered in
tests/e2e_harness/client_apps

* test(e2e): mark known proxy gaps in the Codex matrix as strict xfails

The codex manifest gets a known_gaps list of feature, provider and reason. The
client_apps conftest marks each listed cell xfail(strict=True) at collection,
so the shared e2e lane stays green while a known gap lasts and goes red when
the cell starts passing. The results file still records what the cell did,
including crashes under the xfail and a passing strict XPASS. An entry naming a
feature or provider the manifest lacks, or a cell listed twice, fails loudly.

Web search is listed for all four columns with the proxy behavior behind each
failure.

* test(e2e): let a Codex known gap be non-strict for intermittent cells

A known_gaps entry can now set strict: false (a real bool, default true). That
entry marks its cell xfail(strict=False), so the e2e lane stays green whether
the cell passes or fails, while the results file still records what happened.

Vertex structured output gets a non-strict entry, since gemini-3.8-flash
sometimes loops on shell calls or stalls under an output schema and times out.

* test(e2e): drop gemini-3.8-flash from the Codex Vertex column and fail vision on shell reads

Flash timed out at random on structured output and file edit, and once named the vision color by reading the PNG with PIL. Vertex now runs gemini-4-argon alone, so the non-strict known gap option goes away, and the vision cell fails when the model ran any shell command.

* test(e2e): settle the Codex claude_bedrock caching and reasoning cells and skip Mantle web search without the IAM grant

* test(e2e): tighten codex known gaps and effort checks, rerun cells once, record the Codex version

The reasoning effort row now checks that every logged request asked for high effort and every logged response echoes it or nothing. Known gaps expect only an AssertionError, so a setup error, crash or timeout still fails. Each codex cell reruns once on an AssertionError, and the table keeps the last attempt. The table builder takes --codex-version, refuses a missing table, reports a dropped pass cell as missing, and keeps acronyms in row names

* test(e2e): wait for the codex MCP server, turn off pytest-retry, and give codex harness tests unique names

Codex sent a turn's first request before the local MCP server was up, so
on a resumed turn the model called the vault tool before Codex registered
it and the MCP row failed on Claude, Gemini and OpenAI. The harness now
marks the server required, so Codex waits for it.

pytest-retry, a ci-group plugin, reads the same flaky marker as
pytest-rerunfailures and retried crashes too, so tests/e2e/pytest.ini
turns it off and the rerun test runs with the real pytest.ini.

The new codex harness test files collided with the claude_code ones of
the same name at collection, so they take the folder's test_codex_ prefix.

* test(e2e): turn off pytest-retry in the codex harness test instead of tests/e2e/pytest.ini

A change to tests/e2e/pytest.ini makes CI's e2e picker run every e2e suite on this PR, and the e2e runners do not install pytest-retry, so the line only mattered locally. The codex conftest harness test now passes -p no:pytest-retry itself, and AGENTS.md tells a local run to do the same

* test(e2e): expect only a missing feature in codex known gaps and match whole color names in the vision row

A strict xfail on a codex setup now expects MissingFeature, which a row raises
through require_feature on the check of the feature itself, so a setup error,
a Codex crash or any other failed assertion in a known-gap cell still fails.
The vision row matches whole color names, so "colored" no longer reads as red.

* test(e2e): record the failed first attempt on a codex cell that passed on its rerun

The OpenAI and Azure web search xfail reason now names Codex's bundled entry as the cause, served by LiteLLM's model list.

* test(e2e): keep a codex known gap's failed first attempt and document the Claude and Gemini real-name check

A known gap after a failed attempt now carries first_attempt_error like a pass does. The docs say the real-name row checks that the gateway adds no tool mode for models no Codex catalog lists, the run.py docstring names the lockfile pin, and pytest.ini drops a duplicate meta marker

---------

Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-24 01:14:11 -08:00

224 lines
6.4 KiB
Python

"""What one `codex exec --json` run did, read from the JSONL events it printed.
The event shapes are Codex's own (`codex-rs/exec/src/exec_events.rs`). `package-lock.json` pins the Codex release,
and a bump can add events, so an event or item type this module does not model is skipped, while one it does model
is validated strictly and fails loudly when Codex changes it.
"""
from __future__ import annotations
import re
from collections.abc import Callable, Iterator, Mapping
from dataclasses import dataclass
from itertools import chain
from pathlib import Path
from typing import Annotated, Final, Literal, cast
from pydantic import BaseModel, ConfigDict, Discriminator, Tag, TypeAdapter
_HTTP_STATUS: Final = re.compile(r"\bstatus:? (\d{3})\b")
class _Frozen(BaseModel):
model_config = ConfigDict(frozen=True)
class TokenUsage(_Frozen):
input_tokens: int
cached_input_tokens: int
cache_write_input_tokens: int = 0
output_tokens: int
reasoning_output_tokens: int
class _AgentMessage(_Frozen):
type: Literal["agent_message"]
text: str
class _CommandExecution(_Frozen):
type: Literal["command_execution"]
command: str
aggregated_output: str
exit_code: int | None
class _FileUpdate(_Frozen):
path: str
kind: Literal["add", "delete", "update"]
class _FileChange(_Frozen):
type: Literal["file_change"]
changes: tuple[_FileUpdate, ...]
status: Literal["in_progress", "completed", "failed"]
class _McpContentBlock(_Frozen):
text: str | None = None
class _McpResult(_Frozen):
content: tuple[_McpContentBlock, ...]
class _McpToolCall(_Frozen):
type: Literal["mcp_tool_call"]
server: str
tool: str
result: _McpResult | None
status: Literal["in_progress", "completed", "failed"]
class _ErrorItem(_Frozen):
type: Literal["error"]
message: str
class _Unmodelled(_Frozen):
type: str
class _Message(_Frozen):
message: str
def _known_or_unmodelled(known: frozenset[str]) -> Callable[[object], str]:
def tag(raw: object) -> str:
kind: Final = cast("Mapping[str, object]", raw).get("type") if isinstance(raw, Mapping) else None
return kind if isinstance(kind, str) and kind in known else "unmodelled"
return tag
_Item = Annotated[
Annotated[_AgentMessage, Tag("agent_message")]
| Annotated[_CommandExecution, Tag("command_execution")]
| Annotated[_FileChange, Tag("file_change")]
| Annotated[_McpToolCall, Tag("mcp_tool_call")]
| Annotated[_ErrorItem, Tag("error")]
| Annotated[_Unmodelled, Tag("unmodelled")],
Discriminator(
_known_or_unmodelled(frozenset({"agent_message", "command_execution", "file_change", "mcp_tool_call", "error"}))
),
]
class _ThreadStarted(_Frozen):
type: Literal["thread.started"]
thread_id: str
class _ItemCompleted(_Frozen):
type: Literal["item.completed"]
item: _Item
class _TurnCompleted(_Frozen):
type: Literal["turn.completed"]
usage: TokenUsage
class _TurnFailed(_Frozen):
type: Literal["turn.failed"]
error: _Message
class _StreamError(_Frozen):
type: Literal["error"]
message: str
_Event = Annotated[
Annotated[_ThreadStarted, Tag("thread.started")]
| Annotated[_ItemCompleted, Tag("item.completed")]
| Annotated[_TurnCompleted, Tag("turn.completed")]
| Annotated[_TurnFailed, Tag("turn.failed")]
| Annotated[_StreamError, Tag("error")]
| Annotated[_Unmodelled, Tag("unmodelled")],
Discriminator(
_known_or_unmodelled(frozenset({"thread.started", "item.completed", "turn.completed", "turn.failed", "error"}))
),
]
_EVENT: Final = TypeAdapter[_Event](_Event)
@dataclass(frozen=True, slots=True)
class Command:
command: str
output: str
exit_code: int | None
@dataclass(frozen=True, slots=True)
class McpCall:
server: str
tool: str
output: str
@dataclass(frozen=True, slots=True)
class CodexError:
message: str
status_code: int | None
@dataclass(frozen=True, slots=True)
class CodexRun:
exit_code: int
thread_id: str | None
commands: tuple[Command, ...]
patched_files: tuple[Path, ...]
mcp_calls: tuple[McpCall, ...]
answer: str
usage: TokenUsage | None
errors: tuple[CodexError, ...]
stderr: str
web_searches: int
def codex_run(*, exit_code: int, stdout: str, stderr: str) -> CodexRun:
events: Final = tuple(_EVENT.validate_json(line) for line in stdout.splitlines() if line.strip())
items: Final = tuple(event.item for event in events if isinstance(event, _ItemCompleted))
patches: Final = tuple(item for item in items if isinstance(item, _FileChange) and item.status == "completed")
answers: Final = tuple(item.text for item in items if isinstance(item, _AgentMessage))
usages: Final = tuple(event.usage for event in events if isinstance(event, _TurnCompleted))
return CodexRun(
exit_code=exit_code,
thread_id=next((event.thread_id for event in events if isinstance(event, _ThreadStarted)), None),
commands=tuple(
Command(command=item.command, output=item.aggregated_output, exit_code=item.exit_code)
for item in items
if isinstance(item, _CommandExecution)
),
patched_files=tuple(Path(change.path) for change in chain.from_iterable(patch.changes for patch in patches)),
mcp_calls=tuple(
_mcp_call(item) for item in items if isinstance(item, _McpToolCall) and item.status == "completed"
),
answer=answers[-1] if answers else "",
usage=usages[-1] if usages else None,
errors=tuple(_errors(events)),
stderr=stderr,
web_searches=sum(1 for item in items if item.type == "web_search"),
)
def _mcp_call(item: _McpToolCall) -> McpCall:
blocks: Final = item.result.content if item.result else ()
return McpCall(server=item.server, tool=item.tool, output="".join(block.text or "" for block in blocks))
def _errors(events: tuple[_Event, ...]) -> Iterator[CodexError]:
for event in events:
match event:
case _TurnFailed(error=_Message(message=message)) | _StreamError(message=message):
yield _codex_error(message)
case _ItemCompleted(item=_ErrorItem(message=message)):
yield _codex_error(message)
case _:
pass
def _codex_error(message: str) -> CodexError:
status: Final = _HTTP_STATUS.search(message)
return CodexError(message=message, status_code=int(status.group(1)) if status else None)