litellm/tests/e2e/codex/harness.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

253 lines
8.7 KiB
Python

from __future__ import annotations
import json
import subprocess
import tempfile
from collections.abc import Generator, Mapping
from contextlib import contextmanager
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
from types import MappingProxyType
from typing import Final, Literal
from cli_harness.lockdown import isolated_home, locked_down_env
from cli_harness.rate_limiter import RateBucket, RateLimiter
from codex.rollout import Compaction, Subagent, rollout_compactions, rollout_parent_thread, rollout_subagent
from codex.run import CodexRun, codex_run
from e2e_metadata import step
from pydantic import BaseModel, ConfigDict
CODEX_CLI: Final = "codex"
EXEC_TIMEOUT_SECONDS: Final = 600.0
_API_KEY_ENV: Final = "LITELLM_API_KEY"
_PROVIDER: Final = "litellm"
_CONFIG_TOML: Final = """\
model_provider = "{provider}"
approval_policy = "never"
sandbox_mode = "workspace-write"
check_for_update_on_startup = false
[analytics]
enabled = false
[model_providers.{provider}]
name = "LiteLLM"
base_url = "{gateway}/v1"
env_key = "{api_key_env}"
wire_api = "responses"
model_catalog_url = "{gateway}/v1/models"
"""
type CodexCatalog = Literal["gateway", "openai", "amazon-bedrock", "amazon-bedrock-runtime"]
class _CatalogTier(BaseModel):
model_config = ConfigDict(frozen=True)
id: str
class _CatalogModel(BaseModel):
model_config = ConfigDict(frozen=True)
slug: str
service_tiers: tuple[_CatalogTier, ...] = ()
tool_mode: str | None = None
class _Catalog(BaseModel):
model_config = ConfigDict(frozen=True)
models: tuple[_CatalogModel, ...]
@dataclass(frozen=True, slots=True)
class McpServer:
command: str
args: tuple[str, ...]
env: Mapping[str, str]
@dataclass(frozen=True, slots=True)
class CodexHarness:
home: Path
api_key: str = field(repr=False)
rate_bucket: RateBucket
limiter: RateLimiter
cli: str = CODEX_CLI
timeout_seconds: float = EXEC_TIMEOUT_SECONDS
@property
def codex_home(self) -> Path:
return self.home / ".codex"
@step('Run Codex on {model} through the proxy with the flags {flags} and the prompt "{prompt}"')
def exec_with_flags(self, prompt: str, *, model: str, cwd: Path, flags: tuple[str, ...]) -> CodexRun:
return self._run(("exec",), (*flags, "--model", model, "--", prompt), cwd)
@step("Create a workspace folder holding the test's files")
def new_workspace(self, files: Mapping[str, str]) -> Path:
workspace: Final = Path(tempfile.mkdtemp(prefix="workspace-", dir=self.home)).resolve()
for name, content in files.items():
_ = (workspace / name).write_text(content)
return workspace
@step("Give Codex the {name} MCP server")
def add_mcp_server(self, name: str, server: McpServer) -> None:
with (self.codex_home / "config.toml").open("a") as config:
_ = config.write(_mcp_server_table(name, server))
@step('Run Codex on {model} through the proxy with the prompt "{prompt}"')
def exec(
self,
prompt: str,
*,
model: str,
cwd: Path,
compact_after_tokens: int | None = None,
enable: tuple[str, ...] = (),
disable: tuple[str, ...] = (),
fast: bool = False,
) -> CodexRun:
return self._run(
("exec",),
(
*_compaction_flags(compact_after_tokens),
*_feature_flags(enable=enable, disable=disable),
*_fast_mode_flags(fast),
"--model",
model,
"--",
prompt,
),
cwd,
)
@step('Resume Codex thread {thread_id} on {model} through the proxy with the prompt "{prompt}"')
def resume(
self, thread_id: str, prompt: str, *, model: str, cwd: Path, compact_after_tokens: int | None = None
) -> CodexRun:
return self._run(
("exec", "resume"),
(*_compaction_flags(compact_after_tokens), "--model", model, "--", thread_id, prompt),
cwd,
)
def compactions(self, thread_id: str) -> tuple[Compaction, ...]:
rollouts: Final = sorted(self.codex_home.glob(f"sessions/**/rollout-*-{thread_id}.jsonl"))
return tuple(chain.from_iterable(rollout_compactions(rollout.read_text()) for rollout in rollouts))
def subagents(self, thread_id: str) -> tuple[Subagent, ...]:
rollouts: Final = tuple(
path.read_text() for path in sorted(self.codex_home.glob("sessions/**/rollout-*.jsonl"))
)
return tuple(rollout_subagent(rollout) for rollout in rollouts if rollout_parent_thread(rollout) == thread_id)
@step("Read the service tiers Codex's catalog from the gateway offers each model")
def service_tiers(self) -> Mapping[str, frozenset[str]]:
return MappingProxyType(
{
model.slug: frozenset(tier.id for tier in model.service_tiers)
for model in self._catalog("gateway").models
}
)
@step("Read the tool mode the {source} catalog gives each model in Codex")
def tool_modes(self, source: CodexCatalog = "gateway") -> Mapping[str, str | None]:
return MappingProxyType({model.slug: model.tool_mode for model in self._catalog(source).models})
def _catalog(self, source: CodexCatalog) -> _Catalog:
completed: Final = subprocess.run(
(self.cli, *_catalog_args(source)),
cwd=self.home,
env=self._env(),
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=self.timeout_seconds,
check=True,
)
return _Catalog.model_validate_json(completed.stdout)
def _env(self) -> Mapping[str, str]:
return locked_down_env(
home=self.home, overrides={"CODEX_HOME": str(self.codex_home), _API_KEY_ENV: self.api_key}
)
def _run(self, subcommand: tuple[str, ...], args: tuple[str, ...], cwd: Path) -> CodexRun:
_ = self.limiter.acquire(self.rate_bucket)
completed: Final = subprocess.run(
(self.cli, *subcommand, "--json", "--skip-git-repo-check", *args),
cwd=cwd,
env=self._env(),
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=self.timeout_seconds,
check=False,
)
return codex_run(exit_code=completed.returncode, stdout=completed.stdout, stderr=completed.stderr)
def _mcp_server_table(name: str, server: McpServer) -> str:
env: Final = ", ".join(f"{json.dumps(key)} = {json.dumps(value)}" for key, value in server.env.items())
return (
f"\n[mcp_servers.{json.dumps(name)}]\n"
f"command = {json.dumps(server.command)}\n"
f"args = {json.dumps(server.args)}\n"
f"env = {{ {env} }}\n"
'default_tools_approval_mode = "approve"\n'
"required = true\n"
)
def _feature_flags(*, enable: tuple[str, ...], disable: tuple[str, ...]) -> tuple[str, ...]:
return (
*chain.from_iterable(("--enable", feature) for feature in enable),
*chain.from_iterable(("--disable", feature) for feature in disable),
)
def _catalog_args(catalog: CodexCatalog) -> tuple[str, ...]:
match catalog:
case "gateway":
return ("debug", "models")
case "openai":
return ("debug", "models", "--bundled")
case "amazon-bedrock" | "amazon-bedrock-runtime":
return ("--config", f'model_provider="{catalog}"', "debug", "models")
def _compaction_flags(after_tokens: int | None) -> tuple[str, ...]:
match after_tokens:
case None:
return ()
case int():
return (
"--config",
f'model_providers.{_PROVIDER}.capabilities.remote_compaction="v2"',
"--config",
'model_auto_compact_token_limit_scope="body_after_prefix"',
"--config",
f"model_auto_compact_token_limit={after_tokens}",
)
def _fast_mode_flags(fast: bool) -> tuple[str, ...]:
return ("--config", 'service_tier="priority"') if fast else ()
@step("Give Codex a fresh empty home whose config sends every request to the proxy")
@contextmanager
def codex_harness(
*, gateway: str, api_key: str, rate_bucket: RateBucket, limiter: RateLimiter
) -> Generator[CodexHarness]:
with isolated_home("codex-cli-home-") as home:
harness: Final = CodexHarness(home=home, api_key=api_key, rate_bucket=rate_bucket, limiter=limiter)
harness.codex_home.mkdir()
_ = (harness.codex_home / "config.toml").write_text(
_CONFIG_TOML.format(provider=_PROVIDER, gateway=gateway, api_key_env=_API_KEY_ENV)
)
yield harness