mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
core: continue compact fallback until tool call
This commit is contained in:
@@ -17,7 +17,8 @@ use crate::session::turn::run_sampling_request;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
|
||||
/// Runs the optional, extension-configured turn immediately before an automatic compaction
|
||||
/// rollover. Tool follow-up inference is ignored.
|
||||
/// rollover. Non-tool responses may continue sampling, but the first response containing a tool
|
||||
/// call is terminal for the fallback after its tool output is recorded.
|
||||
///
|
||||
/// The returned step refreshes request-scoped world state after any fallback tool side effects while
|
||||
/// retaining the model that successfully performed compaction.
|
||||
@@ -67,10 +68,6 @@ pub(crate) async fn run_auto_compact_fallback(
|
||||
window_id,
|
||||
CodexResponsesRequestKind::AutoCompactFallback,
|
||||
);
|
||||
let input = sess
|
||||
.clone_history()
|
||||
.await
|
||||
.for_prompt(&restricted_turn.model_info.input_modalities);
|
||||
let turn_diff_tracker = Arc::new(Mutex::new(TurnDiffTracker::new()));
|
||||
let cancellation_token = sess
|
||||
.active_turn_context_and_cancellation_token()
|
||||
@@ -79,18 +76,28 @@ pub(crate) async fn run_auto_compact_fallback(
|
||||
.unwrap_or_else(CancellationToken::new);
|
||||
|
||||
let _elicitation_guard = McpElicitationAutoDenyGuard::new(restricted_step.mcp.manager_arc());
|
||||
run_sampling_request(
|
||||
Arc::clone(sess),
|
||||
restricted_step,
|
||||
Arc::clone(&restricted_turn.extension_data),
|
||||
turn_diff_tracker,
|
||||
client_session,
|
||||
&responses_metadata,
|
||||
input,
|
||||
SamplingRequestOptions::auto_compact_fallback(),
|
||||
cancellation_token,
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
let input = sess
|
||||
.clone_history()
|
||||
.await
|
||||
.for_prompt(&restricted_turn.model_info.input_modalities);
|
||||
let (result, _) = run_sampling_request(
|
||||
Arc::clone(sess),
|
||||
Arc::clone(&restricted_step),
|
||||
Arc::clone(&restricted_turn.extension_data),
|
||||
Arc::clone(&turn_diff_tracker),
|
||||
client_session,
|
||||
&responses_metadata,
|
||||
input,
|
||||
SamplingRequestOptions::auto_compact_fallback(),
|
||||
cancellation_token.child_token(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
if result.tool_call_emitted || !result.needs_follow_up {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Some(
|
||||
sess.capture_step_context(Arc::clone(turn_context)).await,
|
||||
|
||||
@@ -301,6 +301,7 @@ pub(crate) async fn run_turn(
|
||||
let SamplingRequestResult {
|
||||
needs_follow_up: model_needs_follow_up,
|
||||
last_agent_message: sampling_request_last_agent_message,
|
||||
tool_call_emitted: _,
|
||||
} = sampling_request_output;
|
||||
can_drain_pending_input = true;
|
||||
let (has_pending_input, token_status, estimated_token_count) = async {
|
||||
@@ -1398,8 +1399,9 @@ pub(crate) async fn built_tools(
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct SamplingRequestResult {
|
||||
needs_follow_up: bool,
|
||||
pub(crate) needs_follow_up: bool,
|
||||
last_agent_message: Option<String>,
|
||||
pub(crate) tool_call_emitted: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
@@ -2036,6 +2038,7 @@ async fn try_run_sampling_request(
|
||||
let mut in_flight: FuturesOrdered<BoxFuture<'static, CodexResult<ResponseInputItem>>> =
|
||||
FuturesOrdered::new();
|
||||
let mut needs_follow_up = false;
|
||||
let mut tool_call_emitted = false;
|
||||
let mut last_agent_message: Option<String> = None;
|
||||
let mut active_item: Option<TurnItem> = None;
|
||||
let mut active_tool_argument_diff_consumer: Option<(
|
||||
@@ -2181,11 +2184,13 @@ async fn try_run_sampling_request(
|
||||
last_agent_message = Some(agent_message);
|
||||
}
|
||||
needs_follow_up |= output_result.needs_follow_up;
|
||||
tool_call_emitted |= output_result.tool_call_emitted;
|
||||
// todo: remove before stabilizing multi-agent v2
|
||||
if preempt_for_mailbox_mail && sess.input_queue.has_pending_mailbox_items().await {
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up: true,
|
||||
last_agent_message,
|
||||
tool_call_emitted,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2345,6 +2350,7 @@ async fn try_run_sampling_request(
|
||||
break Ok(SamplingRequestResult {
|
||||
needs_follow_up,
|
||||
last_agent_message,
|
||||
tool_call_emitted,
|
||||
});
|
||||
}
|
||||
ResponseEvent::OutputTextDelta(delta) => {
|
||||
|
||||
@@ -310,6 +310,7 @@ pub(crate) type InFlightFuture<'f> =
|
||||
pub(crate) struct OutputItemResult {
|
||||
pub last_agent_message: Option<String>,
|
||||
pub needs_follow_up: bool,
|
||||
pub tool_call_emitted: bool,
|
||||
pub tool_future: Option<InFlightFuture<'static>>,
|
||||
}
|
||||
|
||||
@@ -409,8 +410,10 @@ pub(crate) async fn handle_output_item_done(
|
||||
) -> Result<OutputItemResult> {
|
||||
let mut output = OutputItemResult::default();
|
||||
let plan_mode = ctx.turn_context.collaboration_mode.mode == ModeKind::Plan;
|
||||
let tool_call = ToolRouter::build_tool_call(item.clone());
|
||||
output.tool_call_emitted = !matches!(&tool_call, Ok(None));
|
||||
|
||||
match ToolRouter::build_tool_call(item.clone()) {
|
||||
match tool_call {
|
||||
// The model emitted a tool call; log it, persist the item immediately, and queue the tool execution.
|
||||
Ok(Some(call)) => {
|
||||
ctx.sess
|
||||
|
||||
@@ -1961,10 +1961,13 @@ async fn auto_compact_fallback_is_gated_by_feature_flag() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
async fn auto_compact_fallback_allows_reasoning_before_one_tool_call() {
|
||||
skip_if_no_network!();
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let mut fallback_reasoning_completed =
|
||||
ev_completed_with_tokens("fallback-reasoning-response", /*total_tokens*/ 10);
|
||||
fallback_reasoning_completed["response"]["end_turn"] = json!(false);
|
||||
let request_log = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
@@ -1976,6 +1979,14 @@ async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
ev_assistant_message("compact-message", AUTO_SUMMARY_TEXT),
|
||||
ev_completed_with_tokens("compact-response", /*total_tokens*/ 10),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_reasoning_item(
|
||||
"fallback-reasoning",
|
||||
&["I should record fallback state before rollover."],
|
||||
&[],
|
||||
),
|
||||
fallback_reasoning_completed,
|
||||
]),
|
||||
// Deliberately violate `parallel_tool_calls: false`: the fallback
|
||||
// runtime must still execute no more than one tool call.
|
||||
sse(vec![
|
||||
@@ -2024,8 +2035,8 @@ async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
let requests = request_log.requests();
|
||||
assert_eq!(
|
||||
requests.len(),
|
||||
4,
|
||||
"expected initial, compact, one fallback sample, and post-rollover requests"
|
||||
5,
|
||||
"expected initial, compact, reasoning fallback, tool fallback, and post-rollover requests"
|
||||
);
|
||||
assert!(
|
||||
requests[1].body_contains_text(SUMMARIZATION_PROMPT),
|
||||
@@ -2045,6 +2056,16 @@ async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
Some(&Value::Bool(false)),
|
||||
"fallback sampling must disable parallel tool calls"
|
||||
);
|
||||
let tool_fallback_request = &requests[3];
|
||||
assert!(
|
||||
tool_fallback_request.body_contains_text("I should record fallback state before rollover."),
|
||||
"the tool-call fallback request should include the preceding reasoning item"
|
||||
);
|
||||
assert_eq!(
|
||||
tool_fallback_request.body_json().get("parallel_tool_calls"),
|
||||
Some(&Value::Bool(false)),
|
||||
"every fallback sampling request must disable parallel tool calls"
|
||||
);
|
||||
assert_eq!(prompt_calls.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
tool_calls.load(Ordering::SeqCst),
|
||||
@@ -2052,7 +2073,7 @@ async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
"fallback runtime should execute at most one tool call"
|
||||
);
|
||||
|
||||
let post_rollover_request = &requests[3];
|
||||
let post_rollover_request = &requests[4];
|
||||
let post_rollover_body = post_rollover_request.body_json().to_string();
|
||||
assert!(
|
||||
post_rollover_body.contains("continue after compaction"),
|
||||
@@ -2064,6 +2085,7 @@ async fn auto_compact_fallback_runs_one_tool_once_before_rollover() {
|
||||
);
|
||||
assert!(
|
||||
!post_rollover_body.contains(AUTO_COMPACT_FALLBACK_PROMPT)
|
||||
&& !post_rollover_body.contains("I should record fallback state before rollover.")
|
||||
&& !post_rollover_body.contains("fallback-call-1")
|
||||
&& !post_rollover_body.contains("fallback-call-2"),
|
||||
"fallback-only prompt and tool artifacts should stay in the old window"
|
||||
|
||||
@@ -41,6 +41,7 @@ use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_completed_with_tokens;
|
||||
use core_test_support::responses::ev_function_call;
|
||||
use core_test_support::responses::ev_reasoning_item;
|
||||
use core_test_support::responses::ev_response_created;
|
||||
use core_test_support::responses::mount_compact_json_once;
|
||||
use core_test_support::responses::mount_sse_sequence;
|
||||
@@ -954,13 +955,16 @@ async fn token_budget_mid_turn_auto_compaction_resets_before_active_follow_up()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn token_budget_auto_compact_fallback_runs_in_old_window_before_reset() -> Result<()> {
|
||||
async fn token_budget_auto_compact_fallback_allows_reasoning_before_one_tool_call() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let trigger_call_id = "token-budget-trigger-call";
|
||||
let first_fallback_call_id = "token-budget-fallback-call-1";
|
||||
let second_fallback_call_id = "token-budget-fallback-call-2";
|
||||
let mut fallback_reasoning_completed =
|
||||
ev_completed_with_tokens("fallback-reasoning", /*total_tokens*/ 10);
|
||||
fallback_reasoning_completed["response"]["end_turn"] = json!(false);
|
||||
let responses = mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
@@ -969,6 +973,14 @@ async fn token_budget_auto_compact_fallback_runs_in_old_window_before_reset() ->
|
||||
ev_function_call(trigger_call_id, "get_context_remaining", "{}"),
|
||||
ev_completed_with_tokens("resp-1", /*total_tokens*/ 9_500),
|
||||
]),
|
||||
sse(vec![
|
||||
ev_reasoning_item(
|
||||
"fallback-reasoning-item",
|
||||
&["I should persist token-budget fallback state."],
|
||||
&[],
|
||||
),
|
||||
fallback_reasoning_completed,
|
||||
]),
|
||||
// Deliberately return two calls even though the request disables parallel tool calls.
|
||||
// The fallback runtime must execute only the first one.
|
||||
sse(vec![
|
||||
@@ -1021,8 +1033,8 @@ async fn token_budget_auto_compact_fallback_runs_in_old_window_before_reset() ->
|
||||
let requests = responses.requests();
|
||||
assert_eq!(
|
||||
requests.len(),
|
||||
3,
|
||||
"expected initial, fallback, and post-rollover sampling requests"
|
||||
4,
|
||||
"expected initial, reasoning fallback, tool fallback, and post-rollover sampling requests"
|
||||
);
|
||||
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
@@ -1048,13 +1060,27 @@ async fn token_budget_auto_compact_fallback_runs_in_old_window_before_reset() ->
|
||||
fallback_request.body_json().get("parallel_tool_calls"),
|
||||
Some(&Value::Bool(false))
|
||||
);
|
||||
let tool_fallback_request = &requests[2];
|
||||
assert_eq!(
|
||||
token_budget_contexts(tool_fallback_request),
|
||||
initial_context,
|
||||
"tool fallback sampling should remain in the old context window"
|
||||
);
|
||||
assert!(
|
||||
tool_fallback_request.body_contains_text("I should persist token-budget fallback state."),
|
||||
"the tool-call request should include the preceding reasoning item"
|
||||
);
|
||||
assert_eq!(
|
||||
tool_fallback_request.body_json().get("parallel_tool_calls"),
|
||||
Some(&Value::Bool(false))
|
||||
);
|
||||
assert_eq!(
|
||||
tool_calls.load(Ordering::SeqCst),
|
||||
1,
|
||||
"only one extension tool call may execute during fallback"
|
||||
);
|
||||
|
||||
let post_rollover_request = &requests[2];
|
||||
let post_rollover_request = &requests[3];
|
||||
let post_rollover_context = token_budget_contexts(post_rollover_request);
|
||||
assert_eq!(post_rollover_context.len(), 1);
|
||||
let (new_first_window_id, previous_window_id, new_window_id) =
|
||||
@@ -1064,6 +1090,7 @@ async fn token_budget_auto_compact_fallback_runs_in_old_window_before_reset() ->
|
||||
assert_ne!(new_window_id, old_window_id);
|
||||
for fallback_artifact in [
|
||||
TOKEN_BUDGET_FALLBACK_PROMPT,
|
||||
"I should persist token-budget fallback state.",
|
||||
first_fallback_call_id,
|
||||
second_fallback_call_id,
|
||||
"first-fallback-state",
|
||||
|
||||
Reference in New Issue
Block a user