Using Codex to Automatically Fix a Real Bug and Verify It by Running Tests

Using codex exec to fix real issue #239 in the open-source library humanize: write a failing test first, then let Codex find the root cause. It finished in 246 seconds, and the source change matches upstream PR #240. Includes config, prompts, a usage breakdown, and the pitfalls I hit.

5 分钟阅读
Using Codex to Automatically Fix a Real Bug and Verify It by Running Tests

Here are the results up front. We took real issue python-humanize/humanize from the open-source library #239 as our experiment and ran it once non-interactively with codex exec:

ItemResult
Before fix (full test suite)2 failed, 599 passed, 24 skipped
After fix (full test suite)601 passed, 24 skipped
Codex changes1 file, 1 line. The source change matches upstream PR #240 (upstream also added 6 tests; this article adds only 2)
Time246 seconds
Modelgpt-5.6-sol (accessed through AI Code With)
Token19 model requests in total, 517,604 cumulative input tokens (484,608 of them cache hits), and 4,572 output tokens (987 of them reasoning)

I hit three pitfalls along the way. Each one is described below with its symptoms and the fix.

Who this is for

  • Developers who already use Codex CLI and want to hand "fix the bug + run the tests" to it, but aren't sure how well it works;
  • People who want to use codex exec for unattended fixes in CI or scripts;
  • People who want to know how many tokens a real fix costs.

Prerequisites

Step 1: Pick a real bug

The problem described in issue #239: in humanize 4.11.0, naturalsize(1.123456789) returns 1 Bytes, but after upgrading to 4.12.0 it became 1.123456789 Bytes.

Check out the commit from before the fix was merged, which is the parent of the PR #240 merge commit:

bash
git clone https://github.com/python-humanize/humanize.git
cd humanize
git checkout a0602c70bb6e11322107b51114333bab7adab021
python3 -m venv ../venv && . ../venv/bin/activate
pip install -e . pytest freezegun pytest-cov
Pitfall 1: if you install only pytest and not pytest-cov, pytest fails right away with PytestConfigWarning: Failed to import filter module 'coverage' and the tests never start. The cause is that this project's pytest config references coverage. Just install pytest-cov as well.

Step 2: Write the failing test first

In tests/test_filesize.py, add two rows to the test_naturalsize parameter table:

python
        ([1.123456789], "1 Bytes"),
        ([1.123456789, False, True], "1B"),

Run the full test suite:

text
$ python -m pytest -q
FAILED tests/test_filesize.py::test_naturalsize[test_args62-1 Bytes] - AssertionError: assert '1.123456789 Bytes' == '1 Bytes'
FAILED tests/test_filesize.py::test_naturalsize[test_args63-1B] - AssertionError: assert '1.123456789B' == '1B'
2 failed, 599 passed, 24 skipped in 0.92s

Commit the tests first so you can look at Codex's diff on its own later:git commit -am "test: reproduce #239".

This whole approach only works if you make the tests go red first, and only then let the AI change the code.

Step 3: Configure Codex to use AI Code With

To connect Codex to a third-party provider, put the config in the global config file ~/.codex/config.toml. Write the Key directly with experimental_bearer_token in [model_providers.<id>], so you don't need to set an environment variable:

toml
# ~/.codex/config.toml
model_provider = "aicodewith"
model = "gpt-5.6-sol"

[model_providers.aicodewith]
name = "aicodewith"
base_url = "https://api.aicodewith.ai/chatgpt/v1"
wire_api = "responses"
experimental_bearer_token = "sk-你的Key"
Back up your original config before changing it:cp ~/.codex/config.toml ~/.codex/config.toml.bak. If the original config has a line for env_key, remember to delete it. Don't use it together with experimental_bearer_token. In this experiment I passed the Key through an environment variable, and after moving it into the global config the endpoint and model are the same.

An alternative setup: AI Code With's integration docsuse ~/.codex/auth.json (written to OPENAI_API_KEY), and then set requires_openai_auth = true in the provider, which suits everyday interactive use. Pick either approach, but don't mix them.

For more on the fields, see Codex config.toml Explained.

Step 4: Fix it non-interactively with codex exec

The prompt, verbatim:

text
tests/test_filesize.py 里有 2 个失败用例,对应 issue #239:naturalsize(1.123456789) 在 4.12.0 返回 "1.123456789 Bytes",期望 "1 Bytes"(gnu=True 时期望 "1B")。请找到根因,做最小修改修复 src/ 下的代码,不要修改测试。修复后运行 python -m pytest -q 确认全部通过,最后用中文简述根因和改动。

The command:

bash
codex exec --sandbox workspace-write --skip-git-repo-check --json "$(cat prompt.txt)" \
  < /dev/null > codex-run.jsonl
Pitfall 2: the first run didn't include < /dev/null. In a script or background environment, Codex printed Reading additional input from stdin... and then just hung, with no output for 10 minutes, and I had to kill it manually. When running non-interactively, remember to point stdin at /dev/null.

Step 5: What Codex did

From the --json log, it did the following, in order:

  1. Read src/humanize/filesize.py and the test file;
  2. Used git blame and git log -p to dig through history, and found that the old implementation formatted with %d, and that the rounding semantics were lost when it was later changed to an f-string. This change came from upstream commit fb61d5a ("Update pre-commit (#226)", 2025-01-07);
  3. Made a minimal change:
diff
     if abs_bytes < base:
-        return f"{bytes_}B" if gnu else f"{bytes_} Bytes"
+        return f"{int(bytes_)}B" if gnu else f"{int(bytes_)} Bytes"

This source change matches the one the upstream maintainer made in PR #240.

Pitfall 3: when Codex ran python -m pytest in the sandbox, it reported command not found (exit 127). Its shell is a bash -lc login shell that doesn't inherit the venv I had activated, and the workspace-write sandbox blocks network access by default, so it couldn't install pytest. Its workaround was to parse the test parameter table with the standard library and assert each case one by one (128 passed), and it honestly noted in its summary that the full pytest run didn't complete.
The fix: write the absolute path of the test command into the prompt, for example ../venv/bin/python -m pytest -q. Either way, run the tests yourself once more before merging.

Step 6: Verify it yourself

text
$ python -m pytest -q
601 passed, 24 skipped in 0.92s

How many tokens it used

turn.completed event reports the following usage:

text
{"input_tokens":517604,"cached_input_tokens":484608,"cache_write_input_tokens":0,"output_tokens":4572,"reasoning_output_tokens":987}

A few notes:

  • The 510,000 input tokens are the sum of 19 model requests, with a single-request maximum of about 34,000;
  • Cache writes are 0;
  • 94% of input tokens hit the cache. Codex resends the context with every model request, so most of the input for this kind of task can hit the cache.

Common errors

SymptomCauseFix
Reading additional input from stdin... hangsstdin isn't closed in a non-interactive environmentAdd this to the end of the command: < /dev/null
In the sandbox, python: command not found or pytest is missingThe sandbox shell doesn't inherit the venv and blocks network access by defaultPut the venv's absolute path in the prompt
Failed to import filter module 'coverage'The project's pytest config depends on coveragepip install pytest-cov
401 UnauthorizedWrong Key, or the Key in ~/.codex/config.toml is incorrectSee Troubleshooting Codex 401 Errors
No response for a long time, or a timeoutNetwork or upstream timeoutSee Four Kinds of Codex Timeouts and How to Troubleshoot Them

Takeaways

  • Write a red test first, so Codex has a clear goal and acceptance criteria;
  • State "make the minimal change, don't modify the tests" clearly in the prompt. Codex followed that this time;
  • Don't take its claim that "the tests pass" at face value.--json log records every command, exit code, and token count. Read the log, then rerun the tests yourself.

Related tutorials