codex: simplify deferred goal retry handling (#31176)

This commit is contained in:
Eric Traut
2026-07-08 21:48:23 -07:00
parent 7a0b03d642
commit cf5851b5a6
10 changed files with 133 additions and 233 deletions
-3
View File
@@ -46,9 +46,6 @@ impl Session {
self: &Arc<Self>,
input: Vec<ResponseItem>,
) -> Result<(), TryStartTurnIfIdleError> {
if input.is_empty() {
return Ok(());
}
if self.input_queue.has_trigger_turn_mailbox_items().await {
return Err(TryStartTurnIfIdleError::new(
TryStartTurnIfIdleRejectionReason::PendingTriggerTurn,
+13 -6
View File
@@ -54,12 +54,12 @@ impl InputQueue {
Option<InputQueueActivity>,
) {
let activity_rx = self.activity_tx.subscribe();
let has_pending_turn_input = if let Some(turn_state) = turn_state {
!turn_state.lock().await.pending_input.items.is_empty()
let has_pending_steer = if let Some(turn_state) = turn_state {
turn_state.lock().await.pending_input.has_user_input()
} else {
false
};
let pending_activity = if has_pending_turn_input {
let pending_activity = if has_pending_steer {
Some(InputQueueActivity::Steer)
} else if self.has_pending_mailbox_items().await {
Some(InputQueueActivity::Mailbox)
@@ -181,7 +181,6 @@ impl InputQueue {
input: Vec<TurnInput>,
) {
turn_state.lock().await.pending_input.items.extend(input);
self.activity_tx.send_replace(InputQueueActivity::Steer);
}
pub(crate) async fn take_pending_input_for_turn_state(
@@ -253,6 +252,14 @@ impl InputQueue {
}
}
impl TurnInputQueue {
fn has_user_input(&self) -> bool {
self.items
.iter()
.any(|input| matches!(input, TurnInput::UserInput { .. }))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -306,7 +313,7 @@ mod tests {
}
#[tokio::test]
async fn input_queue_notifies_turn_input_subscribers() {
async fn input_queue_notifies_steer_subscribers() {
let input_queue = InputQueue::new();
let turn_state = Mutex::new(TurnState::default());
let (mut activity_rx, pending_activity) =
@@ -314,7 +321,7 @@ mod tests {
assert_eq!(pending_activity, None);
input_queue
.extend_pending_input_for_turn_state(
.extend_pending_input_and_accept_mailbox_delivery_for_turn_state(
&turn_state,
vec![TurnInput::UserInput {
content: vec![UserInput::Text {
+19 -82
View File
@@ -102,7 +102,6 @@ use codex_protocol::protocol::PlanDeltaEvent;
use codex_protocol::protocol::ReasoningContentDeltaEvent;
use codex_protocol::protocol::ReasoningRawContentDeltaEvent;
use codex_protocol::protocol::SafetyBufferingEvent;
use codex_protocol::protocol::StreamErrorEvent;
use codex_protocol::protocol::TurnDiffEvent;
use codex_protocol::protocol::WarningEvent;
use codex_protocol::user_input::UserInput;
@@ -159,7 +158,7 @@ pub(crate) async fn run_turn(
return Err(err);
}
let error = err.to_codex_protocol_error();
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
sess.emit_compaction_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
error!("Failed to run pre-sampling compact");
return Ok(None);
@@ -223,7 +222,6 @@ pub(crate) async fn run_turn(
// 2. After auto-compact, when model/tool continuation needs to resume before any steer.
let mut next_step_context = Some(first_step_context);
let mut retrying_sampling_without_input = false;
loop {
// Note that pending_input would be something like a message the user
// submitted through the UI while the model was running. Though the UI
@@ -251,23 +249,18 @@ pub(crate) async fn run_turn(
Some(step_context) => step_context,
None => sess.capture_step_context(Arc::clone(&turn_context)).await,
};
let capacity_only_retry = std::mem::take(&mut retrying_sampling_without_input);
let sampling_request_result: CodexResult<_> = async {
// A capacity-only retry should not grow model context or invalidate its cache.
if !capacity_only_retry {
super::time_reminder::maybe_record_current_time_reminder(
sess.as_ref(),
turn_context.as_ref(),
&window_id,
)
.await?;
}
super::time_reminder::maybe_record_current_time_reminder(
sess.as_ref(),
turn_context.as_ref(),
&window_id,
)
.await?;
if !capacity_only_retry
&& turn_context
.config
.features
.enabled(Feature::DeferredExecutor)
if turn_context
.config
.features
.enabled(Feature::DeferredExecutor)
{
world_state = sess
.record_step_world_state_if_changed(&world_state, step_context.as_ref())
@@ -368,8 +361,11 @@ pub(crate) async fn run_turn(
return Err(err);
}
let error = err.to_codex_protocol_error();
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
sess.emit_compaction_turn_error_lifecycle(
turn_context.as_ref(),
error.clone(),
)
.await;
return Ok(None);
}
can_drain_pending_input = !model_needs_follow_up;
@@ -452,70 +448,11 @@ pub(crate) async fn run_turn(
Err(e) => {
info!("Turn error: {e:#}");
let error = e.to_codex_protocol_error();
let retry_delay = sess
.retry_delay_for_turn_error(turn_context.as_ref(), error.clone())
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error.clone())
.await;
let error_event = e.to_error_event(/*message_prefix*/ None);
if let Some(delay) = retry_delay {
sess.send_event(
&turn_context,
EventMsg::StreamError(StreamErrorEvent {
message: error_event.message.clone(),
codex_error_info: error_event.codex_error_info.clone(),
additional_details: None,
}),
)
.await;
// Keep this turn alive so its recorded input is not appended again.
// Let deliverable input interrupt the backoff instead of parking the turn.
let turn_state = sess
.input_queue
.turn_state_for_sub_id(&sess.active_turn, &turn_context.sub_id)
.await;
let (mut activity_rx, _) = sess
.input_queue
.subscribe_activity(turn_state.as_deref())
.await;
let retry_interrupted = if sess
.input_queue
.has_pending_input(&sess.active_turn)
.await
{
true
} else {
tokio::select! {
_ = cancellation_token.cancelled() => {
return Err(CodexErr::TurnAborted);
}
result = tokio::time::timeout(delay, async {
while activity_rx.changed().await.is_ok() {
// Ignore mailbox activity deferred to the next turn.
if sess.input_queue.has_pending_input(&sess.active_turn).await {
return true;
}
}
false
}) => {
result.unwrap_or(false)
}
}
};
if retry_interrupted
|| sess
.retry_delay_for_turn_error(turn_context.as_ref(), error.clone())
.await
.is_some()
{
retrying_sampling_without_input = !retry_interrupted;
can_drain_pending_input = true;
continue;
}
}
sess.track_turn_codex_error(turn_context.as_ref(), &e);
sess.emit_turn_error_lifecycle(turn_context.as_ref(), error)
.await;
sess.send_event(&turn_context, EventMsg::Error(error_event))
.await;
let event = EventMsg::Error(e.to_error_event(/*message_prefix*/ None));
sess.send_event(&turn_context, event).await;
// let the user continue the conversation
break;
}
+20 -24
View File
@@ -1,5 +1,3 @@
use std::time::Duration;
use codex_extension_api::ExtensionData;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::TokenUsage;
@@ -74,38 +72,36 @@ impl Session {
}
}
pub(crate) async fn retry_delay_for_turn_error(
&self,
turn_context: &TurnContext,
error: CodexErrorInfo,
) -> Option<Duration> {
for contributor in self.services.extensions.turn_lifecycle_contributors() {
if let Some(delay) = contributor
.retry_delay_for_turn_error(codex_extension_api::TurnErrorInput {
turn_id: turn_context.sub_id.as_str(),
error: error.clone(),
session_store: &self.services.session_extension_data,
thread_store: &self.services.thread_extension_data,
turn_store: turn_context.extension_data.as_ref(),
})
.await
{
return Some(delay);
}
}
None
}
pub(crate) async fn emit_turn_error_lifecycle(
&self,
turn_context: &TurnContext,
error: CodexErrorInfo,
) {
self.emit_turn_error_lifecycle_for(turn_context, error, /*is_compaction*/ false)
.await;
}
pub(crate) async fn emit_compaction_turn_error_lifecycle(
&self,
turn_context: &TurnContext,
error: CodexErrorInfo,
) {
self.emit_turn_error_lifecycle_for(turn_context, error, /*is_compaction*/ true)
.await;
}
async fn emit_turn_error_lifecycle_for(
&self,
turn_context: &TurnContext,
error: CodexErrorInfo,
is_compaction: bool,
) {
for contributor in self.services.extensions.turn_lifecycle_contributors() {
contributor
.on_turn_error(codex_extension_api::TurnErrorInput {
turn_id: turn_context.sub_id.as_str(),
error: error.clone(),
is_compaction,
session_store: &self.services.session_extension_data,
thread_store: &self.services.thread_extension_data,
turn_store: turn_context.extension_data.as_ref(),
@@ -3,8 +3,6 @@ use std::sync::Arc;
use codex_core::CodexThread;
use codex_core::config::CurrentTimeReminderConfig;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::TurnLifecycleContributor;
use codex_features::Feature;
use codex_protocol::AgentPath;
use codex_protocol::items::SleepItem;
@@ -42,17 +40,6 @@ use serde_json::from_slice;
use serde_json::json;
use tokio::sync::oneshot;
struct RetryTurnErrors;
impl TurnLifecycleContributor for RetryTurnErrors {
fn retry_delay_for_turn_error<'a>(
&'a self,
_input: codex_extension_api::TurnErrorInput<'a>,
) -> codex_extension_api::ExtensionFuture<'a, Option<std::time::Duration>> {
Box::pin(async { Some(std::time::Duration::from_secs(60)) })
}
}
fn ev_message_item_done(id: &str, text: &str) -> Value {
serde_json::json!({
"type": "response.output_item.done",
@@ -300,55 +287,6 @@ async fn wait_for_sleep_item_completed(codex: &CodexThread, call_id: &str, durat
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn sampling_error_retries_in_place_and_steer_interrupts_delay() {
const INITIAL: &str = "INITIAL_PROMPT";
const STEER: &str = "USER_STEER";
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse_failed(
"overloaded",
"server_is_overloaded",
"Selected model is at capacity. Please try a different model.",
),
responses::sse_completed("response-2"),
],
)
.await;
let mut extensions = ExtensionRegistryBuilder::new();
extensions.turn_lifecycle_contributor(Arc::new(RetryTurnErrors));
let test = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| config.model_provider.stream_max_retries = Some(0))
.build(&server)
.await
.expect("build Codex test session");
submit_user_input(&test.codex, INITIAL).await;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::StreamError(_))
})
.await;
steer_user_input(&test.codex, STEER).await;
wait_for_turn_complete(&test.codex).await;
let requests = response_mock.requests();
let [_, second] = requests.as_slice() else {
panic!("expected two requests, got {}", requests.len());
};
assert!(second.body_contains_text(STEER));
assert_eq!(
1,
second
.message_input_texts("user")
.iter()
.filter(|text| text.as_str() == INITIAL)
.count()
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn steer_interrupts_wait_agent_and_is_sent_in_follow_up_request() {
const WAIT_CALL_ID: &str = "wait-call";
+1 -15
View File
@@ -1,7 +1,6 @@
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use codex_context_fragments::ContextualUserFragment;
use codex_protocol::items::TurnItem;
@@ -185,20 +184,7 @@ pub trait TurnLifecycleContributor: Send + Sync {
})
}
/// Returns how long the host should wait before retrying a failed sampling
/// request. Returning `None` leaves the error terminal.
fn retry_delay_for_turn_error<'a>(
&'a self,
input: TurnErrorInput<'a>,
) -> ExtensionFuture<'a, Option<Duration>> {
Box::pin(async move {
let _self = self;
let _input = input;
None
})
}
/// Called when the host observes a terminal error for a running turn.
/// Called when the host observes an error for a running turn.
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let _self = self;
@@ -49,6 +49,8 @@ pub struct TurnErrorInput<'a> {
pub turn_id: &'a str,
/// Error surfaced by the host for this turn.
pub error: CodexErrorInfo,
/// Whether the error came from compaction rather than model sampling.
pub is_compaction: bool,
/// Store scoped to the host session runtime.
pub session_store: &'a ExtensionData,
/// Store scoped to this thread runtime.
+13 -25
View File
@@ -32,7 +32,6 @@ use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::TokenUsageInfo;
use rand::Rng;
use crate::accounting::BudgetLimitedGoalDisposition;
use crate::accounting::GoalAccountingState;
@@ -298,36 +297,25 @@ where
})
}
fn retry_delay_for_turn_error<'a>(
&'a self,
input: TurnErrorInput<'a>,
) -> ExtensionFuture<'a, Option<Duration>> {
Box::pin(async move {
let runtime = goal_runtime_handle(input.thread_store)?;
if input.error == CodexErrorInfo::ServerOverloaded
&& runtime.tools_visible()
&& runtime
.accounting_state()
.turn_is_current_active_goal(input.turn_id)
{
// Capacity failures do not consume tokens. Jitter around five minutes
// prevents clients that hit capacity together from retrying in lockstep.
return Some(Duration::from_secs(
rand::rng().random_range(4 * 60..=6 * 60),
));
}
None
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let Some(runtime) = goal_runtime_handle(input.thread_store) else {
return;
};
let reason = match input.error {
// Capacity failures do not consume user tokens. Jittering the
// delay prevents clients that fail together from retrying in lockstep.
CodexErrorInfo::ServerOverloaded
if !input.is_compaction
&& runtime.tools_visible()
&& runtime
.accounting_state()
.turn_is_current_active_goal(input.turn_id) =>
{
runtime.defer_retry(Duration::from_secs(rand::random_range(4 * 60..=6 * 60)));
return;
}
CodexErrorInfo::UsageLimitExceeded => ActiveGoalStopReason::UsageLimit,
// The turn has ended because the error was non-retryable or its
// retries were exhausted. Block the goal to prevent automatic
+45 -2
View File
@@ -2,6 +2,7 @@ use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_core::ThreadManager;
use codex_protocol::ThreadId;
@@ -45,6 +46,7 @@ struct GoalRuntimeInner {
thread_manager: Weak<ThreadManager>,
accounting_state: Arc<GoalAccountingState>,
enabled: AtomicBool,
retry_pending: AtomicBool,
tools_available_for_thread: bool,
goal_state_lock: Semaphore,
}
@@ -97,6 +99,7 @@ impl GoalRuntimeHandle {
thread_manager,
accounting_state,
enabled: AtomicBool::new(config.enabled),
retry_pending: AtomicBool::new(false),
tools_available_for_thread: config.tools_available_for_thread,
goal_state_lock: Semaphore::new(/*permits*/ 1),
}),
@@ -115,6 +118,32 @@ impl GoalRuntimeHandle {
self.is_enabled() && self.inner.tools_available_for_thread
}
/// Suppresses ordinary idle continuation while a retry timer is pending,
/// then starts a new turn from the existing conversation history. The weak
/// reference ensures the timer neither keeps an unloaded runtime alive nor
/// survives a thread lifecycle.
pub(crate) fn defer_retry(&self, delay: Duration) {
if self.inner.retry_pending.swap(true, Ordering::Relaxed) {
return;
}
let runtime = Arc::downgrade(&self.inner);
drop(tokio::spawn(async move {
tokio::time::sleep(delay).await;
let Some(inner) = runtime.upgrade() else {
return;
};
inner.retry_pending.store(false, Ordering::Relaxed);
let runtime = GoalRuntimeHandle { inner };
if let Err(err) = runtime.retry_if_idle().await {
tracing::warn!(
"failed to retry active goal for idle thread {}: {err}",
runtime.thread_id()
);
}
}));
}
pub(crate) fn thread_id(&self) -> ThreadId {
self.inner.thread_id
}
@@ -357,6 +386,21 @@ impl GoalRuntimeHandle {
}
pub(crate) async fn continue_if_idle(&self) -> Result<(), String> {
if self.inner.retry_pending.load(Ordering::Relaxed) {
return Ok(());
}
self.start_if_idle(|goal| vec![continuation_steering_item(&protocol_goal_from_state(goal))])
.await
}
async fn retry_if_idle(&self) -> Result<(), String> {
self.start_if_idle(|_| Vec::new()).await
}
async fn start_if_idle(
&self,
input_for_goal: impl FnOnce(codex_state::ThreadGoal) -> Vec<ResponseItem>,
) -> Result<(), String> {
if !self.tools_visible() {
self.inner.accounting_state.clear_active_goal();
return Ok(());
@@ -389,9 +433,8 @@ impl GoalRuntimeHandle {
self.inner.accounting_state.clear_active_goal();
return Ok(());
}
let item = continuation_steering_item(&protocol_goal_from_state(goal));
if let Err(err) = thread.try_start_turn_if_idle(vec![item]).await {
if let Err(err) = thread.try_start_turn_if_idle(input_for_goal(goal)).await {
let reason = err.reason();
tracing::debug!(
?reason,
@@ -520,7 +520,11 @@ async fn turn_error_usage_limit_accounts_progress_and_clears_accounting() -> any
)
.await;
harness
.notify_turn_error("turn-1", CodexErrorInfo::UsageLimitExceeded)
.notify_turn_error(
"turn-1",
CodexErrorInfo::UsageLimitExceeded,
/*is_compaction*/ false,
)
.await;
let goal = runtime
@@ -574,7 +578,7 @@ async fn turn_error_usage_limit_accounts_progress_and_clears_accounting() -> any
}
#[tokio::test]
async fn retryable_error_keeps_goal_active_and_terminal_error_blocks_it() -> anyhow::Result<()> {
async fn capacity_error_retries_sampling_but_not_compaction() -> anyhow::Result<()> {
let runtime = test_runtime().await?;
let thread_id = test_thread_id()?;
seed_thread_metadata(runtime.as_ref(), thread_id).await?;
@@ -590,17 +594,14 @@ async fn retryable_error_keeps_goal_active_and_terminal_error_blocks_it() -> any
))
.await?;
let turn_store = ExtensionData::new("turn-1");
let retry_delay = harness.registry.turn_lifecycle_contributors()[0]
.retry_delay_for_turn_error(TurnErrorInput {
turn_id: "turn-1",
error: CodexErrorInfo::ServerOverloaded,
session_store: &harness.session_store,
thread_store: &harness.thread_store,
turn_store: &turn_store,
})
harness
.notify_turn_error(
"turn-1",
CodexErrorInfo::ServerOverloaded,
/*is_compaction*/ false,
)
.await;
assert!(retry_delay.is_some());
let goal = runtime
.thread_goals()
.get_thread_goal(thread_id)
@@ -609,7 +610,11 @@ async fn retryable_error_keeps_goal_active_and_terminal_error_blocks_it() -> any
assert_eq!(codex_state::ThreadGoalStatus::Active, goal.status);
harness
.notify_turn_error("turn-1", CodexErrorInfo::Other)
.notify_turn_error(
"turn-1",
CodexErrorInfo::ServerOverloaded,
/*is_compaction*/ true,
)
.await;
let goal = runtime
@@ -1323,13 +1328,14 @@ impl GoalExtensionHarness {
}
}
async fn notify_turn_error(&self, turn_id: &str, error: CodexErrorInfo) {
async fn notify_turn_error(&self, turn_id: &str, error: CodexErrorInfo, is_compaction: bool) {
let turn_store = ExtensionData::new(turn_id);
for contributor in self.registry.turn_lifecycle_contributors() {
contributor
.on_turn_error(TurnErrorInput {
turn_id,
error: error.clone(),
is_compaction,
session_store: &self.session_store,
thread_store: &self.thread_store,
turn_store: &turn_store,