8. Compaction and the Token Budget

A thread can outlive any context window, so Codex watches an estimate of the tokens in play and, near the limit, replaces history with a smaller checkpoint: recent user messages, a summary, and a fresh copy of the initial context. Three strategies produce the checkpoint (a server-side summary for OpenAI and Azure, a local summarization turn for other providers, and an experimental reset with no summary), but all three share one trigger and one installation step.

Chapters 6 and 7 showed a request that only grows: every turn appends items, and nothing already sent is edited. Left alone, that request would hit the model’s context limit, and the provider would reject it. Compaction is the harness’s answer. It is also the one moment when Codex deliberately breaks the cached prefix, because a new window must start from a smaller, freshly rendered context.

This chapter covers how Codex counts tokens, the exact conditions that trigger compaction, the three ways it builds a checkpoint, the optional background mode, and how a checkpoint is written to the rollout so that a resumed thread starts from the same place. The formulas use constants read from code; the worked example uses a real catalog window of 272,000 tokens.

The picture

After each sampling request the turn loop reaches a checkpoint; under the limit it continues the window, and at the limit it compacts by remote v2 for OpenAI and Azure, by a local summary turn for other providers, or by a token-budget reset when that flag is on; every path installs fresh history and starts the next window, a background request can prepare a candidate from 65 percent of the window, and a local summary that still does not fit ends the turn with an error.

The main path runs along the top. A window fills up; at each checkpoint the turn loop compares its token estimate with the limits. Under the limit, the dashed loop returns to normal work. At the limit, run_auto_compact picks a strategy: remote compaction v2 on the top row, or one of the two branches below it. All three converge on one installation step, Session::replace_compacted_history, which writes a Compacted record and starts the next numbered window. The waiting state on the left is async compaction, which can prepare a checkpoint early in the background. The red exit is the one failure the diagram shows: a local summary request that still exceeds the window when only one item is left.

Counting tokens

What the server reports

Each response.completed event carries a TokenUsage from codex-rs/protocol/src/protocol.rs, with input_tokens, cached_input_tokens, cache_write_input_tokens, output_tokens, reasoning_output_tokens, and total_tokens. Session::record_token_usage_info folds it into a TokenUsageInfo that holds a running total_token_usage, the last_token_usage, and model_context_window. The turn loop sends a TokenCount event to clients once the request’s tool calls have resolved.

The last report goes stale as soon as the turn appends anything, such as a tool output. ContextManager::get_total_token_usage in codex-rs/core/src/context_manager/history.rs therefore estimates the active context:

where is the active context in tokens, is total_tokens from the last server report, is an estimate for items appended since that report, is an estimate for encrypted reasoning items before the last user turn, and is 0 when the last report already includes reasoning (the model is a Responses Lite model, or the server sent x-reasoning-included) and 1 otherwise. Estimates divide model-visible bytes by 4 and round up (APPROX_BYTES_PER_TOKEN).

What the user sees

The terminal UI shows the share of the window left. TokenUsage::percent_of_context_window_remaining subtracts a fixed baseline from both sides, so a new thread starts at 100 percent:

where is the percentage shown, is the usable window defined in equation (8.3), and 12,000 is BASELINE_TOKENS. The doc comment says the baseline should capture “tokens that are always present in the context (e.g., system prompt and fixed tool instructions).” The function returns 0 when is at most 12,000. The UI passes last_token_usage, so ignores the tail estimate in equation (8.1).

When compaction fires

The limits

ModelInfo in codex-rs/protocol/src/openai_models.rs derives two limits from the catalog window:

where is context_window (or max_context_window when the first is absent), is effective_context_window_percent (default 95), is usable_context_window, is the model’s or the user’s model_auto_compact_token_limit, and is auto_compact_token_limit. A configured model_context_window replaces but is clamped to max_context_window. A test in the same file pins the arithmetic: max_context_window 400,000 with no context_window gives a usable window of 380,000 and a limit of 360,000.

The trigger

context_window_token_status in codex-rs/core/src/session/context_window.rs turns those limits into two booleans:

where is the tokens counted for the configured model_auto_compact_token_limit_scope, is the window’s prefill baseline, is a fallback buffer that is 0 unless the token-budget feature configures a fallback prompt, and is model_post_turn_compact_threshold_percent (default 0, which disables post-turn compaction; values above 100 are rejected). The first boolean is token_limit_reached; the second is turn_end_compaction_threshold_reached. The second clause of the limit makes the usable window a hard cap that no setting can raise. In the body_after_prefix scope, the code compares with the configured limit directly when one is set, without the 90 percent clamp.

The checkpoints

The turn loop in codex-rs/core/src/session/turn.rs checks these conditions at three points. The table lists them.

Checkpoint Compacts when Code
Pre-turn A model switch requires it, the limit is reached, or a background candidate is ready run_pre_sampling_compact
Mid-turn A follow-up is needed and the limit is reached or a candidate is ready should_roll_over in run_turn
Post-turn With : post is true or a candidate is ready, with no pending input after the final answer

A model switch compacts with the previous model when both models declare a comp_hash and the hashes differ, or when the new model’s window is smaller and the current context already exceeds the new model’s limits. Pre-turn compaction runs before the new user message is recorded; a TODO in the code notes that it does not yet estimate the incoming items.

If a sampling request fails with ContextWindowExceeded anyway, the turn loop calls set_total_tokens_full and ends the turn. Chapter 6 showed why: that error’s retry policy is Never.

The strategy switch

run_auto_compact chooses the strategy in a fixed order. With the token_budget feature on, it runs a token-budget reset. Otherwise it matches on the provider capability remote_compaction: V2 runs remote compaction, and Unsupported runs local compaction. ProviderCapabilities::from_config in codex-rs/model-provider/src/capabilities.rs sets V2 by default for the OpenAI provider and Azure Responses providers, and Unsupported for every other provider unless its config overrides the capability. This is the strategy pattern with a capability check as the selector.

A worked example

Take gpt-5.6-terra from the bundled catalog, with and default settings. Equation (8.3) gives and ; with scope total and , compaction fires at 244,800 active tokens, before the hard cap. The book computed these numbers from the constants.

  1. A sampling request completes with total_tokens 231,000, and the server sends x-reasoning-included. The model called a shell tool.
  2. The call and its output add 52,000 model-visible bytes. Equation (8.1) gives , just under . The turn samples again.
  3. That request completes with total_tokens 247,500 and another tool call whose items add 8,000 bytes. Now .
  4. A follow-up is needed, so should_roll_over is true and mid-turn compaction runs before the next request.

At step 3, equation (8.2) shows percent left. With async compaction on, a background request could have started much earlier, at tokens.

Local compaction

Local compaction asks the current model to write a handoff summary. compact::run_inline_auto_compact_task uses the config value compact_prompt if set, else SUMMARIZATION_PROMPT, the template in codex-rs/prompts/templates/compact/prompt.md. It opens: “You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.” It then asks for progress and decisions, constraints and preferences, next steps, and critical data.

The summarization request is ordinary history plus the prompt as one more user message, so it reuses the cached prefix. A manual-compaction snapshot test shows request 2 as items 00 to 03 of request 1, then the assistant reply, then <SUMMARIZATION_PROMPT>. If even this request exceeds the window, run_compact_task_inner_impl removes the oldest history item and tries again; the comment says it trims “from the beginning to preserve cache (prefix-based) and keep recent messages intact.” With one item left it gives up and returns the error.

The summary becomes SUMMARY_PREFIX plus a newline plus the model’s last assistant message. The prefix tells the next model that “Another language model started to solve this problem and produced a summary of its thinking process.” Because the prefix is always there, the live path never passes an empty summary; the fallback text “(no summary available)” appears only when build_compacted_history gets an empty one, as when resume replays a legacy Compacted record that has no replacement history and an empty message.

The replacement history

build_compacted_history builds the new window’s body. It walks real user messages newest first and keeps them verbatim while they fit in COMPACT_USER_MESSAGE_MAX_TOKENS, 20,000 tokens; it truncates the message that crosses the budget and stops. Earlier summaries are recognized by their prefix and are not kept. The summary message goes last. insert_initial_context_before_last_real_user_or_summary then renders a fresh full context from world state and places it just before the last real user message, and any window prefix items go at the front. The same snapshot test shows the window after a second compaction:

00:message/developer:
    <MODEL_INSTRUCTIONS>
01:message/user:
    first manual turn
02:message/developer[2]: <PERMISSIONS_INSTRUCTIONS> <tools>...
03:message/user:
    <ENVIRONMENT_CONTEXT>
04:message/user:
    second manual turn
05:message/user:
    <COMPACTION_SUMMARY>
    SECOND_MANUAL_SUMMARY
06:message/user:
    post compact follow-up

Placing the context before the last user message keeps the model’s attention order intact: older requests, current rules, the latest request, then the summary of what has been done about it. The first summary, FIRST_MANUAL_SUMMARY, is gone; it was replaced, not stacked.

Remote compaction v2

Remote compaction lets the server produce the checkpoint. compact_remote_v2_attempt.rs sends a normal streamed Responses request whose input ends with a request-only item, ResponseItem::CompactionTrigger {}, which serializes as {"type":"compaction_trigger"}. The trigger is popped before the input becomes checkpoint history. The response must contain exactly one Compaction output item, which carries encrypted_content; collect_compaction_output treats any other count as a fatal error.

Foreground retries are capped at the smaller of stream_max_retries and 2, because, in the code’s words, “compact attempts can run much longer than normal turns.” build_v2_compacted_history then keeps items from the request input within RETAINED_MESSAGE_TOKEN_BUDGET, 64,000 tokens, spent newest first and restored to source order. It retains real user messages and hook prompts, plus inter-agent messages of at most 10,000 tokens that are neither a descendant’s progress reports nor FINAL_ANSWER completions. Client items marked retain_across_windows follow their mark; otherwise retained tool outputs survive under retain_client_tool_outputs. The server’s Compaction item becomes the checkpoint, and installation uses the same context-insertion rule as local compaction.

The trade-off is visibility. A local summary is text you can read in the rollout. A remote checkpoint is opaque to the client, but the server produces it in one request and it keeps more of the user’s words: 64,000 tokens of retained messages against 20,000.

Background compaction

Async compaction prepares a remote checkpoint before it is needed. async_compaction::enabled in codex-rs/core/src/session/async_compaction.rs requires the async_compaction feature, the token_budget feature off, remote v2 support, and, under async_compaction_root_only, a root session. maybe_start launches a background request when

where is model_async_compact_threshold_percent (default 65, DEFAULT_ASYNC_COMPACTION_THRESHOLD_PERCENT) and is the resolved window, not . At the post-turn checkpoint it also requires post from equation (8.4) to be false. At the pre-turn checkpoint, maybe_start launches nothing unless the foreground client session already holds a turn-state routing token. Attempts are deduplicated by history version, model slug, compaction hash, and auth owner.

The background request always uses HTTP and replays the foreground routing token without changing it. At the next checkpoint, take_ready adopts the result only if it still matches the current history version. The module comment names the cost of this speculation: “Discarded requests still charge completed usage.”

The token-budget feature

The token_budget feature replaces summarization with a reset. compact_token_budget::run_inline_auto_compact_task calls start_new_context_window, which installs a fresh window without a model request. The doc comment on run_inline_auto_compact_task says the reset is “still modeled as compaction so compact hooks and ContextCompaction turn items observe the same lifecycle.” With the feature on, the initial context also carries a TokenBudgetContext item with window IDs and hints, the model can call a new_context tool described as “Start a new context window,” and the config can set reminder thresholds and a fallback prompt. What the model keeps across such a reset depends on retention rules and notes extensions that this chapter does not trace.

Status at commit 081295be9d. Local and remote v2 compaction: IMPLEMENTED; remote v2 is the default only for OpenAI and Azure Responses providers. token_budget: UNDER DEVELOPMENT, off. async_compaction: UNDER DEVELOPMENT, off. async_compaction_root_only: UNDER DEVELOPMENT, off. retain_client_tool_outputs: STABLE, on. retain_client_developer_messages: UNDER DEVELOPMENT, off. Post-turn compaction: off unless model_post_turn_compact_threshold_percent is above 0. Read in code and snapshot tests, not run.

Recording compaction in the rollout

Session::replace_compacted_history in codex-rs/core/src/session/mod.rs installs the new history and persists four rollout items in one write: RolloutItem::Compacted, a full WorldState baseline, the frozen TurnContext, and a settings event. It stamps the model’s comp_hash on the last Compaction or ContextCompaction item, if the new history has one, and holds the settings persistence lock while it writes. AutoCompactWindow::advance increments the window number, moves the current window ID to previous_window_id, and clears per-window reminders.

CompactedItem in codex-rs/history/src/lib.rs is the checkpoint. A rollout line for a local compaction looks like this, reconstructed from the wire types and trimmed:

{"timestamp": "2026-12-03T06:00:00.000Z", "type": "compacted",
 "payload": {"message": "Another language model started ...\nProgress: ...",
             "replacement_history": [ ... ],
             "window_number": 2,
             "compaction_response_id": "resp_...",
             "latest_token_usage_record": { ... }}}

The message holds the summary text for local compaction and is empty for remote v2. replacement_history is the complete new history, so resume does not replay anything before it; this is event sourcing with snapshots. latest_token_usage_record lets thread/resume restore token totals “without scanning arbitrarily far past the compaction,” in its doc comment’s words. Chapter 24 covers the rollout format and resume in full.

What breaks

Symptom Cause Check
Turn ends with a context-window error Request crossed the window before a checkpoint Pre-turn TODO; lower model_auto_compact_token_limit
“Context window exceeded while compacting” in logs Summary request too large; oldest items dropped Count of remove_first_item retries
Error “expected exactly one compaction output item” Remote v2 returned zero or several Provider support; remote_compaction capability
Custom provider never compacts remotely Default capability is Unsupported Provider capabilities override
Model forgets early requests after compaction 20,000-token cap on retained user text (local) Retained items in replacement_history
UI shows 0 percent before compaction Equation (8.2) floors at the usable window last_token_usage against

Code map

What it is Source Identifier
Trigger math codex:codex-rs/core/src/session/context_window.rs context_window_token_status
Window limits codex:codex-rs/protocol/src/openai_models.rs auto_compact_token_limit
Strategy switch codex:codex-rs/core/src/session/turn.rs run_auto_compact
Local compaction codex:codex-rs/core/src/compact.rs build_compacted_history
Remote v2 retention codex:codex-rs/core/src/compact_remote_v2.rs RETAINED_MESSAGE_TOKEN_BUDGET
Background compaction codex:codex-rs/core/src/session/async_compaction.rs maybe_start
Token-budget reset codex:codex-rs/core/src/compact_token_budget.rs start_new_context_window
Rollout checkpoint codex:codex-rs/history/src/lib.rs CompactedItem

Recall check

At how many tokens does a 272,000-token window compact by default?
244,800, which is 90 percent of the window; the hard cap is the usable window of 258,400.

What decides between remote and local compaction?
The provider capability remote_compaction: V2 for OpenAI and Azure by default, Unsupported for others.

What does local compaction keep verbatim?
Up to 20,000 tokens of the most recent real user messages, followed by the summary message.

Where does the fresh initial context go in the replacement history?
Just before the last real user message, so the summary stays last.

Why does a compaction rollout record carry the whole replacement history?
So resume can start from the checkpoint without replaying the items before it.