Repository navigation
Description
What version of Codex CLI is running?
codex-cli 0.117.0
What subscription do you have?
Pro
Which model were you using?
gpt-5.3-codex
What platform is your computer?
macOS Darwin 25.3.0 (Apple Silicon)
What terminal emulator and version are you using (if applicable)?
Headless mode via codex exec (spawned programmatically)
What issue are you seeing?
Auto-compaction never fires when running Codex in headless exec mode. The session accumulates tool outputs until it hits the context window limit, then crashes with "Codex ran out of room in the model's context window." The watcher retries, each retry adds to the session, and it enters a permanent crash loop.
Config:
model_context_window = 400000
model_auto_compact_token_limit = 350000Evidence from Codex session file:
- 86 shell commands executed, producing ~242K tokens of tool output
token_countevents in session file all show emptyinput_tokens_used— token tracking appears broken in exec mode- Zero
compactevents in the session — compaction never triggered - Session crashes at context limit without any compaction attempt
Evidence from traces:
turn_contextevents appear (which I believe are compaction triggers) but they are followed immediately bytask_completewithlast_agent_message: null— suggesting compaction was attempted but failed silently- After first crash, every retry fails within 4-5 seconds with the same context overflow error
Codex session ID: 019d30b8-c263-7190-9072-14650024a1ae
This is blocking automated workflows where agents need to read large codebases. The agent reads files incrementally (200-300 line chunks via sed), but after ~86 commands the accumulated context exceeds the window. In interactive mode, compaction would presumably trigger and summarize earlier context. In exec mode, it never fires.
What steps can reproduce the bug?
- Set
model_auto_compact_token_limit = 350000andmodel_context_window = 400000in config.toml - Run codex in headless exec mode:
codex exec --resume <session-id> "Read a large codebase by running sed on many files" - The agent will read files until it accumulates ~350K+ tokens
- Expected: auto-compact triggers at 350K, summarizes context, continues
- Actual: no compaction, crashes at 400K, permanent crash loop on retry
What is the expected behavior?
model_auto_compact_token_limit should trigger auto-compaction in exec mode the same way it does in interactive mode. Token counting should work (currently reports empty values in exec mode).
Additional information
Related issues: #14860, #14913, #13279 (compaction death spiral)
This may be the same underlying issue as #14860 (TCP timeout on compaction endpoint), but the symptom is different — in our case compaction never even attempts to fire, rather than timing out mid-compact.
Activity
github-actions commentedon Mar 27, 2026
Potential duplicates detected. Please review them and close your issue if it is a duplicate.
Powered by Codex Action
brandomagnani commentedon Mar 27, 2026
Update: confirmed this persists after completely nuking
~/.codex/, fresh installing 0.117.0, and re-authenticating (Pro subscription). No old threads or sessions carried over.Error on every retry:
Running via
codex execwith--resume. Config:model_context_window = 400000,model_auto_compact_token_limit = 300000.brandomagnani commentedon Mar 27, 2026
Root cause found in source code (
codex-rs/core/src/codex.rs):Auto-compaction only checks token count between turns, not between tool calls within a turn.
Pre-sampling compact check (line 6080) runs once at turn start. But within a single turn, the agent can make 80+ tool calls that accumulate 240K+ tokens of output. No compaction check runs between tool calls — the token counter only updates from API response headers after the model responds.
So the sequence is:
get_total_token_usage()returns 0 (fresh session, no prior API response) → skip compactContextWindowExceededThere is a TODO in the code acknowledging this (line 5584-5586):
The fix would be checking accumulated token count after each tool output (or periodically mid-turn), not just between turns.
brandomagnani commentedon Mar 27, 2026
Additional finding: compaction also fails to trigger in interactive mode (not just exec), suggesting this is not exec-specific.
Also noting that #16042 confirms a regression in >=0.115 where compaction fires but the model stops afterward with a "Handoff" summary instead of continuing. That reporter confirms 0.114.0 works correctly with no issues in multi-day runs. We will test downgrading to 0.114.0.
Our session traces show token_count events with real values climbing from 17K → 302K → 1.3M with model_context_window=380000 and auto_compact_token_limit derived as 342K (90% of 380K), yet zero compaction events fire. The compaction condition at codex.rs:5895 (
token_limit_reached && needs_follow_up) is never satisfied despite both conditions appearing to be independently true at different points in the turn.[-]Auto-compaction never triggers in headless exec mode (codex exec), context overflow crash loop[/-][+]Auto-compaction never triggers[/+]brandomagnani commentedon Mar 27, 2026
Important update: the issue does not reproduce when
model_context_windowandmodel_auto_compact_token_limitare NOT set in config.toml. With defaults (256K context window), compaction works correctly and agents run for 10+ minutes with zero failures on the same workload.The bug only triggers when these variables are explicitly set in config.toml (e.g.
model_context_window = 400000,model_auto_compact_token_limit = 300000). Removing both lines and letting Codex use the default 256K window resolves the issue completely.EvolveAegis commentedon Aug 1, 2026
Looking into this, I found an accounting mutation on the
ContextWindowExceededrecovery path that looks relevant. It overwrites the cumulative token usage in a way that conflicts with how the same value is read back for the limit-reached check.Where.
codex-rs/protocol/src/protocol.rs,TokenUsageInfo::fill_to_context_window(L2100 atf57467275cb0; unchanged on currentmain, now ~L2115):Two things happen here:
total_token_usageis replaced wholesale — the accumulated input/output/cache breakdown is zeroed andtotal_tokensis set to the full window.last_token_usage.total_tokensbecomesmax(0, context_window - previous_total).previous_totalis cumulative across turns, so once it crosses the window this is0.The recovery path reaches this on overflow:
core/src/session/turn.rs:1185callsset_total_tokens_full(&turn_context)onErr(ContextWindowExceeded), which routes intofill_to_context_window(core/src/compact.rs:295does the same).Downstream,
core/src/context_manager/history.rs:328(get_total_token_usage) readsinfo.last_token_usage.total_tokensas the active context size, andcore/src/session/context_window.rs:23(context_window_token_status) uses that return value to computetoken_limit_reached/full_context_window_limit_reached(L75-79). In the common case where cumulative usage already exceeds the window, the fill leaveslast_token_usage.total_tokensat0, so the next reached-check would read as not-reached.Observed behavior (synthetic turn sizes, in-crate test). I drove the real function with fabricated usage:
fill_to_context_window(200_000):total.{input,output,cached}all0,total.total = 200_000,last.total = 168_500— a turn nobody made.last.total = 0, and the 217_000 lifetime spend gets reported down to 200_000.Reproduce (needs only a Rust toolchain):
Save this as
codex-rs/protocol/tests/zz_fill_usage.rs:Scope. This is a crate-level test of the accounting function — it shows the mutation and the arithmetic, not an end-to-end run that observes the next compaction decision after an overflow. So I'd treat it as a candidate contributor to the symptoms in this issue rather than a confirmed root cause. If it checks out, the fix looks like:
last_token_usageshould carry the actual current request size (notwindow - cumulative), and the cumulativetotal_token_usageshouldn't be overwritten — the fabricated baseline belongs in a separate field.Dordor333 commentedon Aug 29, 2026
Is this issue fixed or this is still a problem?
lywaterman commentedon Oct 20, 2026
Still reproducible on
rust-v0.162.0and onmainat8196bcdc18(2026-10-20). We hit it with a custom Responses provider: once a request returnedresponse.failedwithcontext_length_exceeded, the next turn never compacted, and every later turn of that thread failed the same way.Root cause (confirms the analysis above). After
ContextWindowExceeded,Session::set_total_tokens_fullcallsTokenUsageInfo::fill_to_context_window, which sets:total_token_usageis cumulative (append_last_usageadds every request), but the pre-sampling check reads the active context fromlast_token_usage(ContextManager::get_total_token_usage). Once a thread's cumulative usage passes the window, which takes only a few requests,deltais 0. The "full" marker then reads back as an empty context, sotoken_limit_reachedstays false.Repro (mock server,
core/tests/suite/compact.rs):model_context_window = 1000andmodel_auto_compact_token_limit = 900. Three turns report 400 tokens each (1,200 cumulative), then the fourth request fails withcontext_length_exceeded. The fifth turn should start with a compaction request, but it goes straight to the normal request.Fix we are now carrying (one line, plus the test above, which fails before the fix and passes after):
Commit with the test: claymorelab@7be6b45 (based on
rust-v0.162.0, applies tomainunchanged).With this change, the next turn compacts. Compaction then trims the oldest items while the request is still too large (
compact.rs), and the compacted history drops images, so the thread recovers. That matters for image-heavy threads: images are cheap in tokens but large in bytes, so a request-size limit can be hit long before the token limit.Chuncheng95 commentedon Nov 1, 2026
Adding the image/413-specific angle to the accounting analysis above, since it changes what a complete fix has to cover.
The
fill_to_context_windowbehaviour described here is real and reproducible, but for image-heavy threads it is the second of two independent layers, and the first layer prevents it from even being reached.Layer 1 — a plain HTTP 413 never reaches
fill_to_context_windowat all.Only
context_length_exceededinside a streamedresponse.failedevent is mapped toContextWindowExceeded(codex-api/src/sse/responses_error.rs). A transport-level 413 is handled as an ordinary failure, soSession::set_total_tokens_fullis never called, no "full" marker is recorded, and compaction never runs. Correcting the accounting alone does not change this outcome, because the accounting function is never invoked on that path.Layer 2 — even with the correct error, the marker reads back as zero. As described above,
last_token_usagebecomesmax(0, window − cumulative), which is 0 once a thread has made a few requests, so the nexttoken_limit_reachedcheck reads as not-reached.The part that seems missing from the current framing: token accounting is structurally blind to byte-bound failures.
This asymmetry is structural rather than incidental. An image costs comparatively little in tokens and a great deal in bytes, so the token accounting that decides whether a thread is "full" can sit well inside its own threshold while the serialized request body is already past a transport limit. In that state token-based compaction has no reason to fire, and does not — the constraint that is actually binding is not the one being measured. Several reports in #30441 describe exactly this shape of failure, from different providers.
This has a concrete implication.
fill_to_context_windowmarks "full" in token space. For a thread stuck because its request body is too large, a correct token-space marker is not sufficient — there needs to be a byte-space counterpart (serialized request bytes against a transport budget), and the "should we compact" decision needs to consult both. Otherwise a byte-bound thread stays stuck even after the one-line fix below is applied.On the fix itself and its cost. The one-line change (
last_token_usage.total_tokens = context_window) is enough to make the next turn compact, as reported above in this thread. The recovery path is still expensive for image threads, though:compact.rsdrops the oldest items one at a time while the compaction request remains too large, so compaction only succeeds after one full-size upload per removed item. A byte-aware preflight would avoid that retry storm rather than merely surviving it. @ChenxuBucm also reported in #30441 that the native compaction request itself failed with 413, so this path can be blocked before it starts.One caveat on the workaround path. Making a gateway answer an oversized streaming request with HTTP 200 and an SSE
response.failedcarryingerror.code = "context_length_exceeded"is what allows the recovery path to engage — but that translation is only semantically honest for a token-based limit. When the rejection is caused by a byte-size limit, mapping it tocontext_length_exceededdescribes a condition that did not occur. It is an effective bridge, but it should not be mistaken for the real fix.Questions I would like input on:
fill_to_context_windowaccounting, so this can be linked rather than duplicated?What I verified myself, and what I would want from an official fix, is in #30441.
No private conversation identifiers, paths, images or raw logs are included here.
agent-context-window: research and deferral (owner 2026-11-07)
bplattenburg commentedon Nov 9, 2026
Interactive reproduction without overrides
Reproduced on unmodified Codex CLI 0.164.0–0.166.0 in interactive sessions, with neither
model_context_windownormodel_auto_compact_token_limitset. AfterContextWindowExceeded, later turns skip auto-compaction and overflow again.Why later turns skip compaction
Once cumulative usage exceeds the context window,
fill_to_context_windowcomputesmax(0, context_window - total_token_usage.total_tokens)and writes zero tolast_token_usage.total_tokens. The next check reads the full context as empty.Required accounting correction
In
fill_to_context_window, setlast_token_usage.total_tokens = context_windowinstead of the computed delta. Also leavetotal_token_usageunchanged so its cumulative input/output/cache breakdown is not erased.Merge pull request #1 from ivishnevs/conversation-model-and-codex-com…