Skip to content

trace: keep a Codex session's usage across a context-window overflow - #386

Open
Lanre Shittu (Shizoqua) wants to merge 1 commit into
microsoft:mainfrom
Shizoqua:fix-trace-codex-context-window-reset
Open

Lanre Shittu (Shizoqua) wants to merge 1 commit into
microsoft:mainfrom
Shizoqua:fix-trace-codex-context-window-reset

Conversation

@Shizoqua

Copy link
Copy Markdown
Contributor

codex_session_usage read a Codex session's usage off its last cumulative token_count total. When a turn fails with "context window exceeded", Codex sets that running total to the window's size and every count to 0 (TokenUsageInfo::fill_to_context_window, through set_total_tokens_full), writes it as a token_count event, which the rollout keeps, and adds later calls to it. So everything spent before the overflow was lost from the ledger, a session that ended on one was priced at nothing, and the reset was counted as a request.

Fix: a total whose counts (input, cached, cache-write, output, reasoning) go down is read as that reset: the total before it is kept and added to what follows, across any number of resets. total_tokens is not compared, since the reset sets it to the window's size. A total whose counts are all 0 is not counted as a request, as no model call made it. A session without an overflow reads as before, a re-sent total included.

Tests, in a new tests/test_trace_codex_context_window_reset.py:

  • a session that ended on an overflow keeps what it spent before it, reasoning included, and counts no request for the reset (fails on main);
  • calls after the overflow are added to what came before, and every overflow of a session is carried (fail on main);
  • an overflow on the first call is no request (fails on main);
  • a session without an overflow reads as before, a re-sent total being no request;
  • the ledger prices what was spent before the overflow (fails on main).
python -m pytest tests -n 4 --dist worksteal -rfEs --tb=line
1918 passed, 41 skipped

The skips need Windows, a real agent CLI (Codex, Hermes, opencode) or aider, or a non-root user.

Fixes #385

When a turn fails with "context window exceeded", Codex sets the session's running totals to
the window's size and every count to 0 (TokenUsageInfo::fill_to_context_window), writes that as
a token_count event, and adds later calls to it. codex_session_usage read a session's usage off
its last running total, so all that was spent before the overflow was lost, and a session that
ended on one was priced at nothing. A total whose counts go down is now read as that reset: the
total before it is kept and added to what follows, and the reset is not counted as a request.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

trace: a Codex session that overflows its context window loses the usage it had

1 participant