Preserve initial turn input when suspension races with startup (#64002)

## Why

Suspension can detach the active task just as startup tries to save
unrecorded input before reading the host roster. If detachment wins,
cleanup can miss the initial submission when saving the turn for recovery.

## What changed

Store pending initial input in the shared `TurnContext` during host
admission and startup steps that can wait on the host roster. Save the
input before checking whether the task is still active, so suspension
and abort cleanup can retrieve it after the task exits. Reclaim it under
the active-turn lock when startup completes so only one path records
the submission.

GitOrigin-RevId: 2f180fc372daaa8f2d8e0ebcb4787a1b2cfd61fa
This commit is contained in:
jif
2026-11-25 22:47:01 +00:00
committed by copyberry
parent f39c3c78d7
commit 44d359767f
6 changed files with 47 additions and 36 deletions
+20 -16
View File
@@ -169,15 +169,16 @@ pub(crate) struct McpStartupRequirements {
required_plugins: HashSet<String>,
}
/// Keep the initial input recoverable while startup can block on a host roster read.
/// Keep the initial input recoverable while a startup step can block.
async fn preserve_initial_input_during<T>(
sess: &Session,
turn_context: &Arc<TurnContext>,
input: &mut Vec<TurnInput>,
can_block: bool,
prepare: impl Future<Output = T>,
) -> CodexResult<T> {
// A context-only submission still needs Some([]) so suspension records its context.
if sess.host_roster_reader(turn_context).is_none()
if !can_block
|| (input.is_empty()
&& turn_context
.extension_data
@@ -187,25 +188,25 @@ async fn preserve_initial_input_during<T>(
return Ok(prepare.await);
}
let exchange_input = async |replacement| {
let mut active = sess.active_turn.lock().await;
let task = active
.as_mut()
.and_then(|turn| turn.task.as_mut())
// Suspension can detach the task before we acquire the lock. Park the input
// first: cleanup reads this same context after joining the task.
turn_context.park_initial_input(std::mem::take(input));
let lock_active_turn = async || {
let active = sess.active_turn.lock().await;
active
.as_ref()
.and_then(|turn| turn.task.as_ref())
.filter(|task| Arc::ptr_eq(&task.turn_context, turn_context))
.ok_or_else(|| CodexErr::new(CodexErrorDetails::TurnAborted))?;
Ok::<_, CodexErr>(std::mem::replace(
&mut task.pending_initial_input,
replacement,
))
Ok::<_, CodexErr>(active)
};
let previous = exchange_input(Some(std::mem::take(input))).await?;
debug_assert!(previous.is_none());
drop(lock_active_turn().await?);
let result = prepare.await;
// If suspension took the task, its cleanup owns the input.
*input = exchange_input(/* replacement */ None)
.await?
// Reclaim under the same lock as suspension. Only the winner records the input.
let _active = lock_active_turn().await?;
*input = turn_context
.take_initial_input()
.ok_or_else(|| CodexErr::Fatal("initial input missing after turn preparation".into()))?;
Ok(result)
}
@@ -265,6 +266,7 @@ pub(crate) async fn run_turn(
let mut client_session =
prewarmed_client_session.unwrap_or_else(|| sess.services.model_client.new_session());
let reads_host_roster = sess.host_roster_reader(&turn_context).is_some();
// TODO(ccunningham): Pre-turn compaction runs before context updates and the
// new user message are recorded. Estimate pending incoming items (context
// diffs/full reinjection + user input) and trigger compaction preemptively
@@ -274,6 +276,7 @@ pub(crate) async fn run_turn(
&sess,
&turn_context,
&mut input,
reads_host_roster,
run_pre_sampling_compact(
&sess,
&turn_context,
@@ -380,6 +383,7 @@ pub(crate) async fn run_turn(
&sess,
&turn_context,
&mut input,
reads_host_roster,
sess.record_context_updates_and_set_reference_context_item(first_step_context.as_ref()),
)
.await??;
+15
View File
@@ -368,6 +368,10 @@ pub(crate) struct NewTurnContextOptions {
pub(crate) goal_daybreak: Option<crate::GoalDaybreakSnapshot>,
}
/// Unrecorded input shared with cleanup, even after the active task is detached.
#[derive(Clone)]
struct PendingInitialInput(Vec<TurnInput>);
/// The context needed for a single turn of the thread.
#[derive(Debug)]
pub struct TurnContext {
@@ -453,6 +457,17 @@ enum TurnContextBuildMode {
}
impl TurnContext {
pub(crate) fn park_initial_input(&self, input: Vec<TurnInput>) {
let previous = self.extension_data.insert(PendingInitialInput(input));
debug_assert!(previous.is_none());
}
pub(crate) fn take_initial_input(&self) -> Option<Vec<TurnInput>> {
self.extension_data
.remove::<PendingInitialInput>()
.map(|input| Arc::unwrap_or_clone(input).0)
}
/// Returns the resolved causal root for this admitted turn.
pub(crate) fn root_turn_id(&self) -> String {
self.turn_metadata_state
@@ -89,7 +89,6 @@ pub(super) async fn suspend_turn_and_shutdown(
.record_pending_initial_input(
&task.turn_context,
&turn.turn_state,
task.pending_initial_input,
/*abort_reason*/ None,
)
.await;
-3
View File
@@ -23,7 +23,6 @@ use super::TurnTokenUsage;
use crate::agent::types::AgentExecutionGuard;
use crate::session::PendingUserInput;
use crate::session::SamplingInterrupt;
use crate::session::TurnInput;
use crate::session::TurnInputQueue;
use crate::session::step_context::StepContext;
use crate::session::turn_context::TurnContext;
@@ -100,8 +99,6 @@ pub(crate) struct RunningTask {
pub(crate) _agent_execution_guard: Option<AgentExecutionGuard>,
/// Follows the task into whichever finalizer claims its terminal event.
pub(crate) outcome_handoff: Option<TaskTrackerToken>,
/// Unrecorded input retained during host admission or preparation that can wait on the roster.
pub(crate) pending_initial_input: Option<Vec<TurnInput>>,
pub(crate) _diagnostics_guard: GaugeGuard,
// Timer recorded when the task drops to capture the full turn duration.
pub(crate) _timer: Option<codex_otel::Timer>,
+3 -4
View File
@@ -1,5 +1,5 @@
//! Acquires host execution capacity without blocking the submission dispatcher.
//! Input stays with the registered task until admission succeeds, so abort owns cleanup.
//! Input stays on the turn context until admission succeeds, so abort owns cleanup.
use std::sync::Arc;
@@ -66,7 +66,7 @@ pub(super) async fn admit(
.filter(|task| Arc::ptr_eq(&task.turn_context, context))
.filter(|_| !cancellation.is_cancelled())
.ok_or_else(|| CodexErr::new(CodexErrorDetails::TurnAborted))?;
let input = task.pending_initial_input.take().ok_or_else(|| {
let input = context.take_initial_input().ok_or_else(|| {
CodexErr::Fatal("initial input missing from the task awaiting host admission".into())
})?;
task._agent_execution_guard = Some(guard);
@@ -89,10 +89,9 @@ impl Session {
self: &Arc<Self>,
context: &Arc<TurnContext>,
turn_state: &Mutex<TurnState>,
input: Option<Vec<TurnInput>>,
abort_reason: Option<&TurnAbortReason>,
) -> Result<()> {
let Some(input) = input else {
let Some(input) = context.take_initial_input() else {
return Ok(());
};
let pending_input = self
+9 -12
View File
@@ -412,15 +412,17 @@ impl Session {
self.bind_realtime_handoffs_to_turn(&input, &turn_context.sub_id)
.await;
let host_admission = self.host_turn_admission();
let (agent_execution_guard, task_input, pending_initial_input) = match &host_admission {
Some(_) => (None, Vec::new(), Some(input)),
let (agent_execution_guard, task_input) = match &host_admission {
Some(_) => {
turn_context.park_initial_input(input);
(None, Vec::new())
}
None => (
self.services.agent_control.admit_turn(
turn_context.multi_agent_version,
&turn_context.session_source,
),
input,
None,
),
};
// Native admission is synchronous, including unrestricted turns that have no guard.
@@ -546,7 +548,6 @@ impl Session {
turn_context: Arc::clone(&turn_context),
_agent_execution_guard: agent_execution_guard,
outcome_handoff,
pending_initial_input,
_diagnostics_guard: ACTIVE_TURNS.track(),
_timer: timer,
};
@@ -818,11 +819,12 @@ impl Session {
let task = active_turn.task.take()?;
task.handle.detach();
active_turn.finishing = Some(finishing);
let initial_input = turn_context.take_initial_input();
(
Arc::clone(&active_turn.turn_state),
(task._agent_execution_guard.is_none() && task.pending_initial_input.is_some())
(task._agent_execution_guard.is_none() && initial_input.is_some())
.then_some(task.task),
task.pending_initial_input,
initial_input,
task.outcome_handoff,
sampling_interrupted,
)
@@ -1241,12 +1243,7 @@ impl Session {
}
if let Err(error) = self
.record_pending_initial_input(
&task.turn_context,
turn_state,
task.pending_initial_input,
Some(&reason),
)
.record_pending_initial_input(&task.turn_context, turn_state, Some(&reason))
.await
{
self.send_event(