From 0e45dc6aafa152539462ceb8c9b09b46f883e82a Mon Sep 17 00:00:00 2001 From: vogt-agent Date: Wed, 18 Nov 2026 20:51:17 +0000 Subject: [PATCH] fix(core): stop auto-compaction looping when compaction cannot get below the limit (WI-2832) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-applied onto fork/main (5c4381bb4) instead of merging PR #36's 2026-10-19 base, which produced 4678 changed files of drift. The real change is 6 files. The guard flag is set inside the `Ok(true)` arm of the compaction match, before the `continue` that restarts the loop; setting it after that `continue` (as the first re-apply did) meant it was never observed and the loop still recursed. Two existing fixtures asserted the old loop (two consecutive over-limit prompts each compacting). Under the new contract the turn stops after the first ineffective compaction, so each fixture now runs an under-limit continuation before the next over-limit step: the same number of compactions still happens, and every hook still runs. - `mid_turn_auto_compact_session_start_hooks_run_before_each_continuation`: one under-limit continuation before the second over-limit step. - `multiple_auto_compact_per_task_runs_after_token_limit_hit`: the fixture's work steps report 270_000 tokens, which is still above this model's 244_800 auto-compact limit, so the new guard correctly stopped the turn. An under-limit (100_000) continuation is inserted after the first and second compactions; the third compaction and the final response are unchanged, so the test still proves legitimate repeated compactions run. The guard's stop path is covered separately by `auto_compact_stops_when_compaction_cannot_get_below_limit`. Verification (CI runs tests with RUST_MIN_STACK=8388608; without it the debug-build futures overflow the 2 MiB tokio worker stack, which is why the repo sets it in every test job): - cargo fmt --all -- --check: clean - cargo clippy -p codex-core --all-targets -- -D warnings: clean - cargo test -p codex-core --lib turn: 359 passed, 0 failed - cargo test -p codex-core --test all suite::compact::: 89 passed, 0 failed, 1 ignored - cargo test -p codex-core --test all suite::hooks::: 87 passed, 6 failed — the identical six names fail on unmodified fork/main 5c4381bb4 - cargo test -p codex-core --test all (whole binary): 2540 passed, 665 failed, 8 ignored; unmodified fork/main on the same host: 2538 passed, 666 failed. The unique failing-name set on this branch (636) is a strict subset of fork/main's (637) — zero branch-only failures. The residual failures are sandbox/harness/environment failures that also fail on the baseline. - the previously red test passes: suite::compact::multiple_auto_compact_per_task_runs_after_token_limit_hit --- .github/workflows/fork-ci.yml | 16 + FORK.md | 1 + codex-rs/core/src/session/turn.rs | 107 ++- codex-rs/core/src/session/turn_tests.rs | 62 ++ codex-rs/core/tests/suite/compact.rs | 861 +++++++++++++++--------- codex-rs/core/tests/suite/hooks.rs | 27 +- 6 files changed, 745 insertions(+), 329 deletions(-) diff --git a/.github/workflows/fork-ci.yml b/.github/workflows/fork-ci.yml index e51bd76c1e27..6ea9958cc87f 100644 --- a/.github/workflows/fork-ci.yml +++ b/.github/workflows/fork-ci.yml @@ -142,6 +142,22 @@ jobs: working-directory: ${{ github.workspace }} run: sudo apt-get update && sudo apt-get install -y libcap-dev pkg-config libasound2-dev bubblewrap + # The `rust-heavy` label is also served by container runners (for example + # nodef-gha-public-docker) that lack the baked packages, so codex-bwrap's + # build.rs fails on "libcap not available via pkg-config". Those runners + # may run as root with no sudo. Skip when libcap is already present (the + # baked rust-heavy image, whose jobs have no sudo). + - name: Install build libraries on self-hosted runners + if: runner.environment == 'self-hosted' + working-directory: ${{ github.workspace }} + run: | + if command -v pkg-config >/dev/null && pkg-config --exists libcap; then + echo "libcap already available via pkg-config" + exit 0 + fi + SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO=sudo + $SUDO apt-get update && $SUDO apt-get install -y libcap-dev pkg-config + # Ubuntu 24.04's AppArmor user-namespace restriction blocks bwrap, so # every sandbox test fails without this. Copied from # .github/actions/setup-ci/action.yml, which upstream's Linux nextest diff --git a/FORK.md b/FORK.md index 5ef5e0ad8bb0..dbf54e060b1e 100644 --- a/FORK.md +++ b/FORK.md @@ -80,6 +80,7 @@ passing on its own is enough: a cherry-pick does not move the base. | — | `agent-state` terminal title item (`codex: ready\|working\|awaiting approval`), written only on change, with the user's title pushed (`CSI 22;0t`) at the first title write and popped (`CSI 23;0t`) on exit. Idle with `animations = false` schedules no refresh. Landed on `fork/wi-1127-agent-state` at `b5f9b014`. | fork-only; Klaudia contract from vogt `internal/tui/idle.go` | | — | `wire_api = "chat"`: Chat Completions client restored for providers whose Responses path drops tool calls (grok via theclawbay/LiteLLM, WI-1139). New files only, plus one dispatch arm: `core/src/chat_request.rs` (request conversion; namespaced tools flattened to `ns__name`, freeform tools such as apply_patch exposed as a function taking one `input` string, calls restored by `ChatToolMap`), `codex-api/src/{endpoint,sse}/chat.rs` (client and SSE parser, fixture tests in `sse/chat_tests.rs`). Reasoning, web search and tool search are not sent over chat. Branch `fork/wi-1286-chat-wire`. | fork-only; upstream removed the chat client | | — | Headless MCP startup (issue #26, WI-1514): `codex exec` defaults `mcp_optional_startup_grace_ms` to 0 unless set, so every enabled server's startup is awaited (each bounded by its `startup_timeout_sec`) before the first request; a failed or timed-out server is printed as a warning and the run continues. Tool dispatch resolves un-namespaced `mcp____` names and bare names unique across MCP servers, and answers a call to a server still handshaking with "MCP server `x` is still starting" instead of "unsupported call". `exec/src/lib.rs`, `core/src/tools/registry.rs`, `codex-mcp` `pending_startup_servers`. Branch `fix/issue-26-mcp-startup`. | fork-only | +| — | Auto-compaction loop guard (WI-2832): after a context-limit compaction (pre-turn or mid-turn), if the first request's prompt alone is still at or over `model_auto_compact_token_limit` (body after prefix for that scope) or the usable window, the turn ends with a warning and a `ContextWindowExceeded` error instead of compacting again. Before this, a fixed prefix (tool specs) over the limit looped compaction -> one tool call -> compaction (235 compactions in one turn). `core/src/session/turn.rs`; tests `turn_tests.rs` `prompt_over_limit_*`, `suite::compact::auto_compact_stops_when_compaction_cannot_get_below_limit`. Branch `wi-2832-compaction-thrash-guard`. | fork-only; upstream has the same loop | ## External adapters diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index d775099466fd..dfcbf5345e1f 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -258,8 +258,8 @@ pub(crate) async fn run_turn( // new user message are recorded. Estimate pending incoming items (context // diffs/full reinjection + user input) and trigger compaction preemptively // when they would push the thread over the compaction threshold. - if auto_compaction_enabled - && let Err(err) = preserve_initial_input_during( + let pre_sampling_compact = if auto_compaction_enabled { + preserve_initial_input_during( &sess, &turn_context, &mut input, @@ -271,7 +271,13 @@ pub(crate) async fn run_turn( ), ) .await? - { + } else { + Ok(false) + }; + // Set when a context-limit compaction ran and the next sampling request has not been + // checked against the limit yet (see `compaction_left_prompt_over_limit`). + let mut context_limit_compaction_pending_check = matches!(pre_sampling_compact, Ok(true)); + if let Err(err) = pre_sampling_compact { // Compaction runs before the new input is recorded, so preserve it on every failure. let _ = run_hooks_and_record_inputs( &sess, @@ -758,7 +764,56 @@ pub(crate) async fn run_turn( .await; } - // as long as compaction works well in getting us way below the token limit, we shouldn't worry about being in an infinite loop. + // Compacting again cannot help when the first request after a compaction was + // already over the limit: the part compaction cannot shrink (tool specs, + // instructions, retained context) fills the window by itself. End the turn with + // an error instead of looping compaction -> one step -> compaction. + let compaction_pending_check = + std::mem::take(&mut context_limit_compaction_pending_check); + if should_roll_over + && token_limit_reached + && compaction_pending_check + && let Some(prompt_tokens) = compaction_left_prompt_over_limit( + sess.as_ref(), + turn_context.config.model_auto_compact_token_limit_scope, + &token_status, + ) + .await + { + let limit = token_status + .auto_compact_scope_limit + .or(token_status.full_context_window_limit) + .unwrap_or_default(); + warn!( + turn_id = %turn_context.sub_id, + prompt_tokens, + limit, + "auto-compaction left the prompt over the limit; not compacting again" + ); + sess.send_event( + &turn_context, + EventMsg::Warning(WarningEvent { + message: format!( + "Auto-compaction could not bring the context below the limit: the first request after compaction used {prompt_tokens} prompt tokens against a limit of {limit}. What compaction cannot shrink (tool definitions, instructions, retained context) is too large for this limit, so Codex stopped instead of compacting again. Reduce the enabled MCP servers or tools, or raise model_auto_compact_token_limit." + ), + }), + ) + .await; + let err = CodexErr::ContextWindowExceeded; + sess.emit_turn_error_lifecycle( + turn_context.as_ref(), + err.to_codex_protocol_error(), + err.details(), + ) + .await; + sess.send_event( + turn_context.as_ref(), + EventMsg::Error(err.to_error_event(/*message_prefix*/ None)), + ) + .await; + return Ok(None); + } + if should_roll_over { let compacted = run_auto_compact( &sess, @@ -783,6 +838,10 @@ pub(crate) async fn run_turn( .preempt .as_ref() .is_some_and(CancellationToken::is_cancelled); + // The next request is the first after this context-limit compaction; + // check it before deciding to compact again. Must be set before the + // `continue`, which restarts the loop. + context_limit_compaction_pending_check = token_limit_reached; continue; } Ok(false) => {} @@ -1550,7 +1609,7 @@ async fn run_pre_sampling_compact( turn_context: &Arc, client_session: &mut ModelClientSession, cancellation_token: &CancellationToken, -) -> CodexResult<()> { +) -> CodexResult { maybe_run_previous_model_inline_compact(sess, turn_context, client_session, cancellation_token) .await?; let token_status = @@ -1573,8 +1632,44 @@ async fn run_pre_sampling_compact( candidate, ) .await?; + return Ok(true); } - Ok(()) + Ok(false) +} + +/// Returns the prompt size of the last sampling request when that prompt alone already +/// reached the auto-compaction limit (or the usable context window). +/// +/// Called for the first request after a context-limit compaction: if its prompt is still +/// over the limit, another compaction would produce the same prompt again. +async fn compaction_left_prompt_over_limit( + sess: &Session, + scope: AutoCompactTokenLimitScope, + token_status: &super::context_window::ContextWindowTokenStatus, +) -> Option { + let prompt_tokens = sess.token_usage_info().await?.last_token_usage.input_tokens; + prompt_over_limit(scope, prompt_tokens, token_status).then_some(prompt_tokens) +} + +fn prompt_over_limit( + scope: AutoCompactTokenLimitScope, + prompt_tokens: i64, + token_status: &super::context_window::ContextWindowTokenStatus, +) -> bool { + let scope_prompt_tokens = match scope { + AutoCompactTokenLimitScope::Total => Some(prompt_tokens), + // The prefix does not count against this scope; compare only the body after it. + AutoCompactTokenLimitScope::BodyAfterPrefix => token_status + .auto_compact_window_prefill_tokens + .map(|prefill| prompt_tokens.saturating_sub(prefill)), + }; + let over_scope_limit = scope_prompt_tokens + .zip(token_status.auto_compact_scope_limit) + .is_some_and(|(tokens, limit)| tokens >= limit); + let over_context_window = token_status + .full_context_window_limit + .is_some_and(|limit| prompt_tokens >= limit); + over_scope_limit || over_context_window } /// Returns true only when both turns declare compaction compatibility hashes and they differ. diff --git a/codex-rs/core/src/session/turn_tests.rs b/codex-rs/core/src/session/turn_tests.rs index d201607c5645..b7ff83319f89 100644 --- a/codex-rs/core/src/session/turn_tests.rs +++ b/codex-rs/core/src/session/turn_tests.rs @@ -116,3 +116,65 @@ fn realtime_user_verification_notice_excludes_request_payload() { )), ); } + +fn token_status_for_prompt_check( + scope_limit: Option, + prefill: Option, + context_window: Option, +) -> super::super::context_window::ContextWindowTokenStatus { + super::super::context_window::ContextWindowTokenStatus { + active_context_tokens: 0, + auto_compact_scope_tokens: 0, + auto_compact_scope_limit: scope_limit, + full_context_window_limit: context_window, + base_window_tokens_remaining: None, + auto_compact_window_prefill_tokens: prefill, + full_context_window_limit_reached: false, + token_limit_reached: true, + turn_end_compaction_threshold_reached: false, + } +} + +#[test] +fn prompt_over_limit_detects_a_prefix_that_compaction_cannot_shrink() { + // WI-2832: a 130.5k-token prompt after compaction against a 128k limit. + let status = token_status_for_prompt_check(Some(128_000), None, Some(258_400)); + assert!(prompt_over_limit( + AutoCompactTokenLimitScope::Total, + 130_516, + &status + )); + // A normal post-compaction prompt leaves room for the turn to make progress. + assert!(!prompt_over_limit( + AutoCompactTokenLimitScope::Total, + 43_000, + &status + )); +} + +#[test] +fn prompt_over_limit_ignores_the_prefix_for_body_after_prefix_scope() { + let status = token_status_for_prompt_check(Some(20_000), Some(110_000), Some(258_400)); + assert!(!prompt_over_limit( + AutoCompactTokenLimitScope::BodyAfterPrefix, + 125_000, + &status + )); + assert!(prompt_over_limit( + AutoCompactTokenLimitScope::BodyAfterPrefix, + 130_000, + &status + )); + // Without a recorded prefix the body cannot be measured; only the hard window applies. + let status = token_status_for_prompt_check(Some(20_000), None, Some(100_000)); + assert!(!prompt_over_limit( + AutoCompactTokenLimitScope::BodyAfterPrefix, + 90_000, + &status + )); + assert!(prompt_over_limit( + AutoCompactTokenLimitScope::BodyAfterPrefix, + 100_000, + &status + )); +} diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 4b78fd25189c..50ebd1111bbf 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -33,6 +33,7 @@ use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ItemStartedEvent; use codex_protocol::protocol::Op; use codex_protocol::protocol::ThreadSettingsOverrides; +use codex_protocol::protocol::WarningEvent; use codex_protocol::request_user_input::RequestUserInputAnswer; use codex_protocol::request_user_input::RequestUserInputResponse; use codex_protocol::user_input::UserInput; @@ -1760,6 +1761,10 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { let token_count_used = 270_000; // token used count after compaction let token_count_used_after_compaction = 80000; + // a continuation that runs after a compaction reports a prompt that is + // genuinely under the limit: the compaction did shrink the context, and the + // guard must let the turn continue. + let token_count_after_continuation = 100_000; // mock responses from the model @@ -1817,6 +1822,29 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { ev_completed_with_tokens("r7", token_count_used_after_compaction), ]); + // Continuations that run immediately after a compaction. Each reports a prompt + // below `model_auto_compact_token_limit` (244_800 for this model), so the + // ineffective-compaction guard does not fire and the turn keeps going. + let reasoning_cont_1 = ev_reasoning_item("m2b", &["I will inspect the react app"], &[]); + let encrypted_content_cont_1 = reasoning_cont_1["item"]["encrypted_content"] + .as_str() + .unwrap(); + let continuation_1_sse = sse(vec![ + reasoning_cont_1.clone(), + ev_exec_command_call("r2-shell", "echo inspect-react"), + ev_completed_with_tokens("r2", token_count_after_continuation), + ]); + + let reasoning_cont_2 = ev_reasoning_item("m4b", &["I will inspect the node app"], &[]); + let encrypted_content_cont_2 = reasoning_cont_2["item"]["encrypted_content"] + .as_str() + .unwrap(); + let continuation_2_sse = sse(vec![ + reasoning_cont_2.clone(), + ev_exec_command_call("r5-shell", "echo inspect-node"), + ev_completed_with_tokens("r5", token_count_after_continuation), + ]); + // final response let model_final_response_sse = sse(vec![ ev_assistant_message( @@ -1830,8 +1858,10 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { let bodies = vec![ model_reasoning_response_1_sse, model_compact_response_1_sse, + continuation_1_sse, model_reasoning_response_2_sse, model_compact_response_2_sse, + continuation_2_sse, model_reasoning_response_3_sse, model_compact_response_3_sse, model_final_response_sse, @@ -1909,7 +1939,7 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { let environment_message = initial_input[0]["content"][0]["text"].as_str().unwrap(); // test 1: after compaction, we should have one environment message, one user message, and one user message with summary prefix - let compaction_indices = [2, 4, 6]; + let compaction_indices = [2, 5, 8]; let expected_summaries = [ prefixed_first_summary.as_str(), prefixed_second_summary.as_str(), @@ -1933,320 +1963,434 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { // test 2: the expected requests inputs should be as follows: let expected_requests_inputs = json!([ - [ - // 0: first request of the user message. - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - [ - // 1: first automatic compaction request. - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": null, - "encrypted_content": encrypted_content_1, - "summary": [ - { - "text": "I will create a react app", - "type": "summary_text" - } - ], - "type": "reasoning" - }, - { - "arguments": "{\"cmd\":\"echo make-react\"}", - "call_id": "r1-shell", - "name": "exec_command", - "type": "function_call" - }, - { - "call_id": "r1-shell", - "output": "execution error: Io(Os { code: 2, kind: NotFound, message: \"No such file or directory\" })", - "type": "function_call_output" - }, - { - "content": [ - { - "text": SUMMARIZATION_PROMPT, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - [ - // 2: request after first automatic compaction. - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": prefixed_first_summary.clone(), - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - [ - // 3: request for second automatic compaction. - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": prefixed_first_summary.clone(), - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": null, - "encrypted_content": encrypted_content_2, - "summary": [ - { - "text": "I will create a node app", - "type": "summary_text" - } - ], - "type": "reasoning" - }, - { - "arguments": "{\"cmd\":\"echo make-node\"}", - "call_id": "r3-shell", - "name": "exec_command", - "type": "function_call" - }, - { - "call_id": "r3-shell", - "output": "execution error: Io(Os { code: 2, kind: NotFound, message: \"No such file or directory\" })", - "type": "function_call_output" - }, - { - "content": [ - { - "text": SUMMARIZATION_PROMPT, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - // 4: request after second automatic compaction. - [ - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": prefixed_second_summary.clone(), - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - [ - // 5: request for third automatic compaction. - { - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": prefixed_second_summary.clone(), - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": null, - "encrypted_content": encrypted_content_3, - "summary": [ - { - "text": "I will create a python app", - "type": "summary_text" - } - ], - "type": "reasoning" - }, - { - "arguments": "{\"cmd\":\"echo make-python\"}", - "call_id": "r6-shell", - "name": "exec_command", - "type": "function_call" - }, - { - "call_id": "r6-shell", - "output": "execution error: Io(Os { code: 2, kind: NotFound, message: \"No such file or directory\" })", - "type": "function_call_output" - }, - { - "content": [ - { - "text": SUMMARIZATION_PROMPT, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } - ] - , - [ - { - // 6: request after third automatic compaction. - "content": [ - { - "text": environment_message, - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": "create an app", - "type": "input_text" - } - ], - "role": "user", - "type": "message" - }, - { - "content": [ - { - "text": prefixed_third_summary.clone(), - "type": "input_text" - } - ], - "role": "user", - "type": "message" - } + // 0: initial turn. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 1: first automatic compaction request. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": null, + "encrypted_content": encrypted_content_1, + "summary": [ + { + "text": "I will create a react app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo make-react\"}", + "call_id": "r1-shell", + "name": "exec_command", + "type": "function_call" + }, + { + "content": [ + { + "text": SUMMARIZATION_PROMPT, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 2: request after the first automatic compaction (under-limit continuation). + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_first_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 3: second chunk of work. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_first_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": null, + "encrypted_content": encrypted_content_cont_1, + "summary": [ + { + "text": "I will inspect the react app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo inspect-react\"}", + "call_id": "r2-shell", + "name": "exec_command", + "type": "function_call" + } + ], + // 4: second automatic compaction request. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_first_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": null, + "encrypted_content": encrypted_content_cont_1, + "summary": [ + { + "text": "I will inspect the react app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo inspect-react\"}", + "call_id": "r2-shell", + "name": "exec_command", + "type": "function_call" + }, + { + "content": null, + "encrypted_content": encrypted_content_2, + "summary": [ + { + "text": "I will create a node app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo make-node\"}", + "call_id": "r3-shell", + "name": "exec_command", + "type": "function_call" + }, + { + "content": [ + { + "text": SUMMARIZATION_PROMPT, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 5: request after the second automatic compaction (under-limit continuation). + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_second_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 6: third chunk of work. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_second_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": null, + "encrypted_content": encrypted_content_cont_2, + "summary": [ + { + "text": "I will inspect the node app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo inspect-node\"}", + "call_id": "r5-shell", + "name": "exec_command", + "type": "function_call" + } + ], + // 7: third automatic compaction request. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_second_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": null, + "encrypted_content": encrypted_content_cont_2, + "summary": [ + { + "text": "I will inspect the node app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo inspect-node\"}", + "call_id": "r5-shell", + "name": "exec_command", + "type": "function_call" + }, + { + "content": null, + "encrypted_content": encrypted_content_3, + "summary": [ + { + "text": "I will create a python app", + "type": "summary_text" + } + ], + "type": "reasoning" + }, + { + "arguments": "{\"cmd\":\"echo make-python\"}", + "call_id": "r6-shell", + "name": "exec_command", + "type": "function_call" + }, + { + "content": [ + { + "text": SUMMARIZATION_PROMPT, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ], + // 8: final request, after the third automatic compaction. + [ + { + "content": [ + { + "text": environment_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": user_message, + "type": "input_text" + } + ], + "role": "user", + "type": "message" + }, + { + "content": [ + { + "text": prefixed_third_summary.clone(), + "type": "input_text" + } + ], + "role": "user", + "type": "message" + } + ] ] - ]); + ); for (i, request) in requests_payloads.iter().enumerate() { let body = request.body_json(); @@ -2255,8 +2399,8 @@ async fn multiple_auto_compact_per_task_runs_after_token_limit_hit() { assert_eq!(normalize_inputs(input), normalize_inputs(expected_input)); } - // test 3: the number of requests should be 7 - assert_eq!(requests_payloads.len(), 7); + // test 3: the number of requests should be 9 + assert_eq!(requests_payloads.len(), 9); } // Windows CI only: bump to 4 workers to prevent SSE/event starvation and test timeouts. @@ -5019,6 +5163,91 @@ async fn auto_compact_allows_multiple_attempts_when_interleaved_with_other_turn_ ); } +/// WI-2832: when the part of the prompt that compaction cannot shrink (tool specs, +/// instructions) is already over `model_auto_compact_token_limit`, every request after a +/// compaction is over the limit again. Codex used to loop compaction -> one tool call -> +/// compaction until the session was stopped (235 compactions in one turn). The turn must +/// stop after the first ineffective compaction instead. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn auto_compact_stops_when_compaction_cannot_get_below_limit() { + skip_if_no_network!(); + + let server = start_mock_server().await; + + let over_limit_step = || { + sse(vec![ + ev_function_call(DUMMY_CALL_ID, DUMMY_FUNCTION_NAME, "{}"), + ev_completed_with_tokens("over-limit", /*total_tokens*/ 400), + ]) + }; + let summary_step = || { + sse(vec![ + ev_assistant_message("summary", &auto_summary(AUTO_SUMMARY_TEXT)), + ev_completed_with_tokens("summary", /*total_tokens*/ 50), + ]) + }; + // One step, one compaction, one step. The old loop compacted again here; the sequence + // has no fourth response, so a further request fails the turn with a different error. + let request_log = mount_sse_sequence( + &server, + vec![over_limit_step(), summary_step(), over_limit_step()], + ) + .await; + + let model_provider = non_openai_model_provider(&server); + let codex = test_codex() + .with_config(move |config| { + config.model_provider = model_provider; + set_test_compact_prompt(config); + config.model_auto_compact_token_limit = Some(300); + }) + .build(&server) + .await + .unwrap() + .codex; + + codex + .start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text { + text: FUNCTION_CALL_LIMIT_MSG.into(), + text_elements: Vec::new(), + }])) + .await + .unwrap(); + + let mut warnings = Vec::new(); + let mut errors = Vec::new(); + let turn_error = loop { + match wait_for_event(&codex, |_| true).await { + EventMsg::Warning(WarningEvent { message }) => warnings.push(message), + EventMsg::Error(error) => errors.push(error.codex_error_info), + EventMsg::TurnComplete(event) => { + break event.error.and_then(|error| error.codex_error_info); + } + _ => {} + } + }; + + assert_eq!(turn_error, Some(CodexErrorInfo::ContextWindowExceeded)); + assert_eq!(errors, vec![Some(CodexErrorInfo::ContextWindowExceeded)]); + assert!( + warnings.iter().any(|message| message + .contains("Auto-compaction could not bring the context below the limit") + && message.contains("400 prompt tokens against a limit of 300")), + "expected an ineffective-compaction warning, got {warnings:?}" + ); + + let requests = request_log.requests(); + assert_eq!( + requests.len(), + 3, + "expected one step, one compaction and one step, then a stop" + ); + assert!(body_contains_text( + &requests[1].body_json().to_string(), + SUMMARIZATION_PROMPT + )); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn paginated_compaction_cold_resume_from_bounded_suffix() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs index 7add9d09f69b..cb1ba5f126ba 100644 --- a/codex-rs/core/tests/suite/hooks.rs +++ b/codex-rs/core/tests/suite/hooks.rs @@ -2282,39 +2282,52 @@ async fn mid_turn_auto_compact_session_start_hooks_run_before_each_continuation( ]), ) .await; + // WI-2832: the first request after a compaction must not itself be over the + // limit, or the turn stops instead of compacting again. This continuation is + // under the limit, so it runs and the next over-limit step can compact a + // second time. let first_continuation = mount_sse_once( &server, sse(vec![ ev_response_created("resp-3"), ev_function_call("call-2", "test_tool", "{}"), - ev_completed_with_tokens("resp-3", over_limit_tokens), + ev_completed_with_tokens("resp-3", limit / 2), ]), ) .await; - let _second_compact = mount_sse_once( + let _over_limit_again = mount_sse_once( &server, sse(vec![ ev_response_created("resp-4"), + ev_function_call("call-3", "test_tool", "{}"), + ev_completed_with_tokens("resp-4", over_limit_tokens), + ]), + ) + .await; + let _second_compact = mount_sse_once( + &server, + sse(vec![ + ev_response_created("resp-5"), ev_assistant_message("summary-2", "second compact summary"), - ev_completed_with_tokens("resp-4", compacted_tokens), + ev_completed_with_tokens("resp-5", compacted_tokens), ]), ) .await; let second_continuation = mount_sse_once( &server, sse(vec![ - ev_response_created("resp-5"), + ev_response_created("resp-6"), ev_assistant_message("final", "finished after compaction"), - ev_completed_with_tokens("resp-5", compacted_tokens), + ev_completed_with_tokens("resp-6", compacted_tokens), ]), ) .await; let next_turn = mount_sse_once( &server, sse(vec![ - ev_response_created("resp-6"), + ev_response_created("resp-7"), ev_assistant_message("next", "finished next turn"), - ev_completed_with_tokens("resp-6", compacted_tokens), + ev_completed_with_tokens("resp-7", compacted_tokens), ]), ) .await;