26. Observing, Testing, and Shipping

Codex watches itself through three channels with different audiences: OpenTelemetry for operators, a local log ring and trace bundles for debugging one bad session, and a doctor command for the machine. Testing and shipping follow the same discipline. A fake model server makes the agent loop testable end to end, and one tag push builds, signs, and publishes binaries for six platforms.

An agent fails in ways that a stack trace does not explain. The model may have asked for the wrong tool, the sandbox may have refused a write, or a proxy may have rewritten a response. To diagnose those failures, you need the request ID the server saw, the sequence of events the engine produced, and the state of the machine at the time. Codex collects each of these in a different place, and each one has a different privacy and retention trade-off.

This chapter covers the observability stack first: the codex-otel crate, product analytics, /feedback, rollout traces, response debug context, and codex doctor. It then turns to how the maintainers test the engine and how the workspace builds under Cargo and Bazel. After that come the continuous integration (CI) workflows that guard the main branch and the path a release takes to npm, GitHub, and the install scripts. It ends with a short, measured history of the repository.

The picture

A timeline from April 2025 to May 2026 with three lanes: the runtime lane shows the initial commit, the Rust import, removal of the TypeScript code, the app server, and the extension API; the harness lane shows unified exec, the agent controller, and code mode on V8; the state and operations lane shows rollout files, ChatGPT login, Bazel, SQLite state, and the ThreadStore interface.

Each marker is the first commit that added a path, found with git log --diff-filter=A at the pinned commit. The runtime lane shows the project’s largest turn: the Rust implementation arrived eight days after the initial commit, and the TypeScript code left on 2025-08-08. The harness lane shows the agent’s capabilities growing after that, from one exec tool to many agents and a JavaScript runtime. The state and operations lane shows the work this part of the book describes: rollouts first, then Bazel, SQLite, and a storage-neutral thread store. The last section of this chapter gives the numbers behind the picture.

Observing a running agent

OpenTelemetry: logs, traces, metrics

The codex-otel crate wires three OpenTelemetry (OTel) signals. Log events are tracing events with names such as codex.conversation_starts, codex.api_request, codex.sse_event, codex.user_prompt, codex.tool_decision, codex.turn_ttft, and codex.turn_cost, emitted by SessionTelemetry. Traces come from tracing spans through tracing_opentelemetry. Metrics go through a MetricsClient, and codex-rs/otel/src/metrics/names.rs defines 84 codex.* metric names, such as codex.tool.call and codex.tool.call.duration_ms. Export filters drop spans from h2 and tokio because, as the source comment explains, the exporter’s own network spans “would generate further OTLP exports.”

Some metrics are designed for correct aggregation across export batches. The doc comment on codex.exec_command.duration_total_ms says to pair it with codex.exec_command.calls:

where is the total-milliseconds counter increment in export batch , is the call counter increment in the same batch, and is the mean exec-command latency in milliseconds. Summing both counters before dividing avoids averaging per-batch means, which would weight a quiet batch the same as a busy one.

Each signal has its own exporter setting under [otel]: exporter for logs, trace_exporter for traces, and metrics_exporter for metrics. OtelExporter in codex-rs/otel/src/config.rs has four variants: None, Statsig, OtlpGrpc, and OtlpHttp. The defaults send nothing for logs and traces and use statsig for metrics. resolve_exporter turns Statsig into an OTLP HTTP JSON exporter aimed at https://ab.chatgpt.com/otlp/v1/metrics in release builds, and into None in debug builds, so local development and tests emit no traffic. A configuration that sends logs to your own collector looks like this, in the shape used by codex-rs/core/src/config/config_tests.rs:

[otel]
environment = "staging"
log_user_prompt = false
exporter = { otlp-http = { endpoint = "https://otel.example.com/v1/logs", protocol = "binary" } }
metrics_exporter = "none"

Three defaults protect content. log_user_prompt is false, and log_agent_responses and log_guardian_assessments are opt-in and capped at 64 KiB. A headers_helper command can supply auth headers for an explicit OTLP HTTP exporter instead of writing them into the file. The project denylist from Chapter 25 includes otel, so a repository cannot redirect your telemetry.

Product analytics

Analytics is a separate channel from OTel. codex-rs/analytics/src/client.rs posts product events to {base_url}/codex/analytics-events/events. Setting [analytics] enabled = false turns this off, and because the default statsig metrics exporter “follows analytics.enabled,” it turns that off too. A custom OTLP metrics exporter is independent of the switch; the doc comment says to set otel.metrics_exporter = "none" to stop it.

/feedback

The /feedback command in the TUI sends logs to the maintainers or saves a ZIP. Its data comes from CodexFeedback in codex-rs/feedback/src/lib.rs, which installs a tracing_subscriber layer that writes formatted log lines into an in-memory ring buffer. The buffer keeps only the newest bytes:

where is the buffered size before a write, is the size of the new chunk, MiB is DEFAULT_MAX_BYTES, and is the size after the write. When the sum exceeds , the oldest bytes fall off the front; a single chunk larger than keeps only its own trailing bytes. Nothing reaches disk until you ask. An upload goes to Sentry with a 300-second timeout, and the report path can attach files up to 64 MiB each and 126 MiB in total, including codex-doctor-report.json. When a model stream fails, the client tags the feedback with the upstream request ID, which ties a report to a server-side log line.

Rollout traces

A rollout (Chapter 24) records what the thread remembers. A rollout trace records what the engine did, for one debugging session. Tracing turns on only when CODEX_ROLLOUT_TRACE_ROOT is set, and spawned child threads share their root’s bundle. A bundle in codex-rs/rollout-trace/src/bundle.rs holds manifest.json, a raw trace.jsonl event log, a payloads directory, and a reduced state.json; the manifest schema is version 3 and the reduced schema version 4. The crate’s AGENTS.md states the rule that keeps this cheap to maintain: “Only the exact Codex binary that wrote a diagnostic trace bundle runs its reducer. There is no cross-binary replay compatibility, even between builds with identical version numbers.” Writers and reducers change together, with no migrations, while state.json is the consumer API, versioned by REDUCED_TRACE_SCHEMA_VERSION; the file says breaking changes are allowed.

Response debug context and codex doctor

When a model request fails over HTTP, extract_response_debug_context in codex-rs/response-debug-context/src/lib.rs pulls four fields from the response headers: request_id, cf_ray, auth_error, and auth_error_code, the last decoded from a Base64 JSON header. core/src/client.rs records the request ID on the failed inference attempt in the rollout trace and in the feedback tags.

codex doctor checks the machine. Its modules under codex-rs/cli/src/doctor/ cover disk, filesystem paths, Git, network, runtime, sandbox, security, system, thread inventory, and updates. Flags shape the output. --json emits a redacted machine-readable report, and --network-only runs only the config, network, provider HTTP, and WebSocket checks. --summary shows grouped rows, and --all, --no-color, and --ascii adjust the human view.

Testing the agent

A fake Responses server

The engine’s main loop talks to a model over Server-Sent Events (SSE), so the integration tests replace the model with a local HTTP server. The helper crate core_test_support lives in codex-rs/core/tests/common, and core/tests/suite holds 311 Rust files compiled into one test binary. start_mock_server in responses.rs starts a wiremock server and mounts an empty /models response “so tests remain hermetic.” mount_sse_once answers the next Responses request with a scripted stream, and sse() renders a list of JSON events as event: and data: frames.

This test from codex-rs/core/tests/suite/client.rs checks that a model’s default verbosity reaches the wire. The #[tokio::test] attribute and the final assertion are trimmed:

async fn includes_default_verbosity_in_request() -> anyhow::Result<()> {
    skip_if_no_network!(Ok(()));
    let server = MockServer::start().await;

    let resp_mock = mount_sse_once(
        &server,
        sse(vec![ev_response_created("resp1"), ev_completed("resp1")]),
    )
    .await;
    let TestCodex { codex, .. } = test_codex().with_model("gpt-5.5").build(&server).await?;

    codex
        .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
            text: "hello".into(),
            text_elements: Vec::new(),
        }]))
        .await
        .unwrap();

    wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;

    let request = resp_mock.single_request();
    let request_body = request.body_json();
    // ... asserts that request_body["text"]["verbosity"] is "low"
}

The pattern exercises the real path: config, session, context assembly, the HTTP client, SSE parsing, and the event stream. Only the network peer is fake. The cost is that SSE fixtures must track the real API, so the helpers centralize event builders such as ev_completed and ev_function_call instead of letting each test hand-write frames.

Snapshot tests in the TUI

Terminal rendering is easier to review as text than as assertions. The TUI uses insta: a test renders a widget to a string and calls assert_snapshot!, and insta compares it with a stored .snap file. At this commit codex-rs/tui has 1,562 assert_snapshot! call sites and 1,597 .snap files, and the repository has 1,884 .snap files in total. A change that alters the screen shows up in review as a text diff of the snapshot.

Test binaries that act like codex

Codex dispatches on argv[0]: the same binary acts as apply_patch or codex-linux-sandbox when invoked under those names (see Chapter 14). Tests need that too. configure_test_binary_dispatch in codex-rs/test-binary-support/lib.rs runs before any test through a #[ctor] static in core/tests/suite/mod.rs. It classifies the current invocation, then either dispatches as the helper, skips, or installs aliases, and its TestBinaryDispatchGuard keeps a temporary CODEX_HOME and the alias directory alive for the test run.

Building

The Cargo workspace

codex-rs/Cargo.toml lists 175 workspace members, all at version 0.0.0 with edition 2024. rust-toolchain.toml pins Rust 1.99.1 with clippy, rustfmt, and rust-src. [workspace.lints.clippy] sets 36 lints to deny, including unwrap_used, expect_used, and await_holding_lock. clippy.toml adds disallowed methods: ratatui RGB and indexed colors, because ANSI colors “work better in various terminal themes,” and direct sqlx pool or connection creation outside the codex-state shim. rustfmt.toml sets imports_granularity = "Item", so every imported item gets its own use line. The release profile uses thin link-time optimization, 4 codegen units, and line-table debug info.

Bazel

Bazel builds the same code hermetically. codex-rs/docs/bazel.md states that “Cargo remains the source of truth for crates and features” and that the setup is “still experimental” as of 6/1/2026. MODULE.bazel imports third-party crates through rules_rs 0.2.3, which reads Cargo.toml and Cargo.lock, and registers a hermetic LLVM toolchain. defs.bzl defines codex_rust_crate, which wraps rust_library, rust_binary, and rust_test; the repository has 207 BUILD.bazel files. rbe.bzl defines a Linux remote-execution platform, and .bazelrc has a remote config for “callers that provide an approved remote executor,” but the checked-in files define no remote endpoints. Local builds run locally.

just recipes

The root justfile runs every recipe through a Python shell shim, scripts/just-shell.py, with a separate Windows shell setting. It defines 33 recipe names, 39 definitions counting per-platform variants. just test runs cargo nextest run --no-fail-fast with an 8 MiB RUST_MIN_STACK. just bazel-test and just bazel-clippy are the Bazel entry points, just bazel-lock-check verifies MODULE.bazel.lock, just write-config-schema regenerates the config schema from Chapter 25, and just build-for-release builds //codex-rs/cli:release_binaries with Bazel.

Continuous integration

The .github/workflows directory holds 28 workflow files. The workflow README explains the split: pull requests get “fast, review-friendly signal while main still gets the full cross-platform verification pass.” The table lists the ones that matter most.

Workflow Trigger What it runs
blocking-ci.yml Pull request, push to main Calls the checks below; required gates merge on all but Bazel, which bazel-result reports
bazel.yml Called by blocking-ci Bazel test and clippy, the main pre-merge Rust path
rust-ci.yml Called by blocking-ci cargo fmt --check, cargo shear, argument-comment lint
cargo-deny.yml, codespell.yml, repo-checks.yml Called by blocking-ci Licenses, spelling, repository rules
postmerge-ci.yml Push to main rust-ci-full.yml: full clippy and nextest matrix
rust-release.yml Tag rust-v*.*.* Build, sign, package, publish
issue-labeler.yml and siblings Issues Triage automation

Two details show care. In blocking-ci.yml, the required job runs with if: always(). Its comment explains that without it “a required check can appear successful instead of reporting the failure.” The workflow README adds that required checks run against GitHub’s synthetic merge commit, so a pull request is tested with the changes already on main.

Releasing

A release starts with a pushed tag such as rust-v0.153.4. rust-release.yml checks that the tag matches the Cargo version and builds a matrix of Linux musl, macOS, and Windows targets. It signs macOS binaries and DMGs through a protected environment and signs Linux artifacts with cosign. Later jobs stage npm packages, create the GitHub release with install.sh and install.ps1 attached, publish assets to an R2 bucket and DotSlash manifests, publish to npm, and open a winget pull request. Versions of the form X.Y.Z publish to npm’s default tag, X.Y.Z-alpha.N and alpha hotfixes X.Y.Z-alpha.N.M publish under alpha, and anything else is not published.

On npm, @openai/codex is a thin wrapper. codex-cli/package.json points bin at bin/codex.js and requires Node 16 or newer. The wrapper maps the host’s target triple to one of six platform packages, @openai/codex-linux-x64, -linux-arm64, -darwin-x64, -darwin-arm64, -win32-x64, and -win32-arm64, and spawns the native binary from it. scripts/install/install.sh installs the release named by CODEX_RELEASE, default latest, from https://releases.openai.com/codex, and falls back to GitHub Releases when that host is unavailable. The repository has 984 tags matching rust-v*; the newest stable is rust-v0.153.4 and the newest prerelease rust-v0.175.0-alpha.16.

A short history in numbers

These figures are computed from git log on the pinned checkout, read only. The first commit, “Initial commit,” is dated 2025-04-16. The Rust implementation arrived on 2025-04-24 in pull request #629, and the commit that removed the TypeScript code is dated 2025-08-08 (#2048). The history holds 14,582 commits: 2,601 dated 2025 and 11,981 dated 2026 through 2026-12-03. The busiest month was September 2026, with 1,617 commits. The commits carry 762 distinct author names; that count does not merge people who used several names, so it is an upper-bound estimate of contributors, not a head count.

The timeline in the picture marks when each subsystem first appeared. Read it with one caveat: “first added path” dates a directory or file, and earlier work under other paths may exist. Read as a sequence, the dates suggest an order of work. The project shipped a terminal agent, made it durable with rollouts and login, and replaced its runtime language. It then opened the engine to other clients through the app server, and only later built the heavier state and extension machinery that Parts V to VII describe.

Status at commit 081295be9d. OTel logs, traces, and metrics exporters: IMPLEMENTED; Statsig metrics default is off in debug builds. Rollout traces: IMPLEMENTED, enabled only by CODEX_ROLLOUT_TRACE_ROOT, no cross-binary replay. Bazel build: IMPLEMENTED; its own documentation calls it experimental. Remote execution: platform defined, no endpoints checked in. Windows install script install.ps1: PLATFORM-SPECIFIC. History figures: computed from git, author names not deduplicated. Read in code, not run.

What breaks

Symptom Cause Check
No metrics from a local build Statsig exporter resolves to None in debug builds resolve_exporter
Metrics continue after [analytics] enabled = false A custom OTLP metrics exporter is configured otel.metrics_exporter
A trace bundle will not reduce A different binary wrote it rollout-trace/AGENTS.md
/feedback logs miss early startup The ring kept only the newest 4 MiB DEFAULT_MAX_BYTES
An integration test hangs waiting for a turn No SSE response mounted for a request mount_sse_once, single_request
Bazel CI fails after a dependency bump MODULE.bazel.lock is stale just bazel-lock-check
A prerelease tag never reaches npm The version does not match X.Y.Z-alpha.N rust-release.yml publish settings

Code map

What it is Where it lives Identifier
Exporter resolution codex:codex-rs/otel/src/config.rs resolve_exporter
Metric names codex:codex-rs/otel/src/metrics/names.rs TOOL_CALL_COUNT_METRIC
Feedback log ring codex:codex-rs/feedback/src/lib.rs DEFAULT_MAX_BYTES
Trace bundle layout codex:codex-rs/rollout-trace/src/bundle.rs REDUCED_TRACE_SCHEMA_VERSION
Doctor command codex:codex-rs/cli/src/doctor.rs DoctorCommand
Mock Responses server codex:codex-rs/core/tests/common/responses.rs start_mock_server
Bazel crate macro codex:defs.bzl codex_rust_crate
npm platform packages codex:codex-cli/scripts/build_npm_package.py CODEX_PLATFORM_PACKAGES

Recall check

Why does a debug build send no metrics by default?
resolve_exporter maps the default Statsig exporter to None when debug_assertions is on.

Where do /feedback logs come from, and how much is kept?
A tracing layer writes them into an in-memory ring that keeps the newest 4 MiB.

What does the mock Responses server replace in an integration test?
Only the model endpoint; config, session, client, SSE parsing, and events all run for real.

Which build system is the source of truth for crates and features?
Cargo; Bazel imports crates from Cargo.toml and Cargo.lock through rules_rs.

What decides whether a tagged release is published to npm?
The version string: X.Y.Z publishes to the default tag, X.Y.Z-alpha.N (or X.Y.Z-alpha.N.M) to alpha, others are skipped.