mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Wake sleeping hosted roots on injected agent mail (#64680)
## Why With native tools disabled, injected agent mail could be persisted without waking a hosted root in durable sleep. ## What changed Schedule a mailbox wake for sleeping hosted roots after injected plaintext mail is durably recorded. Keep the interrupted turn active through `TurnAborted` so mail arriving during the interruption can start a turn only after the abort event is published. ## Testing Add regression coverage for queue-only mail waking a hosted root with its previous turn context and for mail injected during the sleep interruption starting a turn after `TurnAborted`. GitOrigin-RevId: 939db5ffca9af1273e4fb4c8d0dfb6bb7a95ea09
This commit is contained in:
@@ -1313,8 +1313,8 @@ impl CodexThread {
|
||||
self.inject_response_items_with_retention(items).await
|
||||
}
|
||||
|
||||
/// Inject Responses items with persisted retention policies. Ordinary native-root
|
||||
/// agent mail can wake through the mailbox scheduler after the durable checkpoint.
|
||||
/// Inject Responses items with persisted retention policies. After the durable checkpoint,
|
||||
/// plaintext mail can wake native roots and hosted roots parked in durable sleep.
|
||||
pub async fn inject_response_items_with_retention(
|
||||
&self,
|
||||
items: Vec<impl Into<InjectedResponseItem>>,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use super::session::Session;
|
||||
use crate::codex_thread::CodexThread;
|
||||
use crate::state::ActiveTurn;
|
||||
use codex_extension_api::ThreadIdleCause;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
@@ -13,6 +14,7 @@ use codex_protocol::protocol::TurnAbortReason;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::oneshot::error::TryRecvError;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::Instrument;
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -66,7 +68,7 @@ impl Session {
|
||||
) {
|
||||
let active_turn = {
|
||||
let mut active = self.active_turn.lock().await;
|
||||
let Some(turn) = active.as_ref().filter(|turn| {
|
||||
let Some(turn) = active.as_mut().filter(|turn| {
|
||||
turn.task
|
||||
.as_ref()
|
||||
.is_some_and(|task| task.turn_context.sub_id == turn_id)
|
||||
@@ -82,7 +84,17 @@ impl Session {
|
||||
return;
|
||||
}
|
||||
self.mark_interrupted();
|
||||
active.take()
|
||||
// Keep the slot occupied so injected mail can wake only after TurnAborted.
|
||||
turn.finishing = Some(CancellationToken::new());
|
||||
let finishing_turn = ActiveTurn {
|
||||
turn_id: turn.turn_id.clone(),
|
||||
admitted: turn.admitted,
|
||||
task: None,
|
||||
sampling_interrupt: None,
|
||||
turn_state: Arc::clone(&turn.turn_state),
|
||||
finishing: turn.finishing.clone(),
|
||||
};
|
||||
active.replace(finishing_turn)
|
||||
};
|
||||
// The caller may be inside the task that cancellation must join.
|
||||
let _ = reply.send(active_turn.is_some());
|
||||
|
||||
@@ -4,9 +4,11 @@ use super::RealtimeRecord;
|
||||
use super::TurnInput as PendingTurnInput;
|
||||
use super::session::Session;
|
||||
use super::turn_context::TurnContext;
|
||||
use crate::agent::host::AgentRuntimeServices;
|
||||
use codex_features::Feature;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result as CodexResult;
|
||||
use codex_protocol::models::AgentMessageInputContent;
|
||||
@@ -71,10 +73,18 @@ impl Session {
|
||||
) -> std::io::Result<()> {
|
||||
self.try_ensure_rollout_materialized(PersistContext::ThreadPreparation)
|
||||
.await?;
|
||||
if let Some(recorded_through) = recorded_mail.filter(|sequence| *sequence > 0)
|
||||
&& self.multi_agent_version() == Some(MultiAgentVersion::V2)
|
||||
&& !self.get_config().await.multi_agent_v2.disable_native_tools
|
||||
{
|
||||
if let Some(recorded_through) = recorded_mail.filter(|sequence| *sequence > 0) {
|
||||
let eligible = if self.get_config().await.multi_agent_v2.disable_native_tools {
|
||||
// Hosted children share the root's session ID without native lineage.
|
||||
matches!(&self.agent_runtime, AgentRuntimeServices::Host(_))
|
||||
&& self.session_id() == SessionId::from(self.thread_id())
|
||||
&& self.has_outstanding_durable_sleep()
|
||||
} else {
|
||||
self.multi_agent_version() == Some(MultiAgentVersion::V2)
|
||||
};
|
||||
if !eligible {
|
||||
return Ok(());
|
||||
}
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
if state
|
||||
|
||||
@@ -712,7 +712,7 @@ async fn start_if_idle(
|
||||
};
|
||||
|
||||
if session.input_queue.has_trigger_turn_mailbox_items().await {
|
||||
session.clear_reserved_idle_turn(&turn_state).await;
|
||||
session.clear_taskless_turn(&turn_state).await;
|
||||
session.maybe_start_turn_for_pending_work().await;
|
||||
return Ok(TurnInputSubmission::NotSubmitted {
|
||||
reason: NotSubmittedReason::PendingTriggerTurn,
|
||||
@@ -731,7 +731,7 @@ async fn start_if_idle(
|
||||
{
|
||||
Ok(settings) => settings,
|
||||
Err(error) => {
|
||||
session.clear_reserved_idle_turn(&turn_state).await;
|
||||
session.clear_taskless_turn(&turn_state).await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
@@ -742,13 +742,13 @@ async fn start_if_idle(
|
||||
{
|
||||
Ok(Some(turn_context)) => turn_context,
|
||||
Ok(None) => {
|
||||
session.clear_reserved_idle_turn(&turn_state).await;
|
||||
session.clear_taskless_turn(&turn_state).await;
|
||||
return Ok(TurnInputSubmission::NotSubmitted {
|
||||
reason: NotSubmittedReason::PlanMode,
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
session.clear_reserved_idle_turn(&turn_state).await;
|
||||
session.clear_taskless_turn(&turn_state).await;
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
@@ -1040,13 +1040,19 @@ impl Session {
|
||||
&& TurnStartKind::Automatic.permits_mode(config.step_settings.collaboration_mode.mode)
|
||||
}
|
||||
|
||||
async fn clear_reserved_idle_turn(&self, turn_state: &Arc<tokio::sync::Mutex<TurnState>>) {
|
||||
pub(crate) async fn clear_taskless_turn(
|
||||
&self,
|
||||
turn_state: &Arc<tokio::sync::Mutex<TurnState>>,
|
||||
) -> bool {
|
||||
let mut active_turn_guard = self.active_turn.lock().await;
|
||||
if let Some(active_turn) = active_turn_guard.as_ref()
|
||||
&& active_turn.task.is_none()
|
||||
&& Arc::ptr_eq(&active_turn.turn_state, turn_state)
|
||||
{
|
||||
*active_turn_guard = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -44,7 +44,6 @@ use crate::session::turn_context::TurnContext;
|
||||
use crate::state::ActiveTurn;
|
||||
use crate::state::RunningTask;
|
||||
use crate::state::TaskKind;
|
||||
use crate::state::TurnState;
|
||||
use crate::turn_diff_tracker::TurnDiffTracker;
|
||||
use codex_analytics::IncompleteReason;
|
||||
use codex_analytics::TurnProfileFact;
|
||||
@@ -697,7 +696,7 @@ impl Session {
|
||||
self.handle_task_abort(
|
||||
task,
|
||||
reason.clone(),
|
||||
&active_turn.turn_state,
|
||||
&active_turn,
|
||||
/*error*/ None,
|
||||
std::future::ready(()),
|
||||
)
|
||||
@@ -776,14 +775,8 @@ impl Session {
|
||||
) {
|
||||
let task = active_turn.task.take();
|
||||
if let Some(task) = task {
|
||||
self.handle_task_abort(
|
||||
task,
|
||||
reason.clone(),
|
||||
&active_turn.turn_state,
|
||||
error,
|
||||
publication,
|
||||
)
|
||||
.await;
|
||||
self.handle_task_abort(task, reason.clone(), &active_turn, error, publication)
|
||||
.await;
|
||||
} else {
|
||||
publication.await;
|
||||
}
|
||||
@@ -791,6 +784,9 @@ impl Session {
|
||||
// in-flight approval wait can surface as a model-visible rejection before TurnAborted.
|
||||
self.input_queue.clear_pending(&active_turn).await;
|
||||
|
||||
if active_turn.finishing.is_some() {
|
||||
self.clear_taskless_turn(&active_turn.turn_state).await;
|
||||
}
|
||||
if reason == TurnAbortReason::Interrupted {
|
||||
self.maybe_start_turn_for_pending_work().await;
|
||||
}
|
||||
@@ -1105,18 +1101,7 @@ impl Session {
|
||||
self.send_event(turn_context.as_ref(), event.clone()).await;
|
||||
}
|
||||
|
||||
let cleared_active_turn = {
|
||||
let mut active = self.active_turn.lock().await;
|
||||
if let Some(active_turn) = active.as_ref()
|
||||
&& active_turn.task.is_none()
|
||||
&& Arc::ptr_eq(&active_turn.turn_state, &turn_state)
|
||||
{
|
||||
*active = None;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
};
|
||||
let cleared_active_turn = self.clear_taskless_turn(&turn_state).await;
|
||||
if saved_guardian_completion {
|
||||
// The parent can request another review as soon as it receives this event.
|
||||
self.send_event(turn_context.as_ref(), event).await;
|
||||
@@ -1216,12 +1201,18 @@ impl Session {
|
||||
self: &Arc<Self>,
|
||||
task: RunningTask,
|
||||
reason: TurnAbortReason,
|
||||
turn_state: &Mutex<TurnState>,
|
||||
active_turn: &ActiveTurn,
|
||||
error: Option<ErrorEvent>,
|
||||
publication: impl Future<Output = ()>,
|
||||
) {
|
||||
let turn_state = active_turn.turn_state.as_ref();
|
||||
let finish_recording = active_turn
|
||||
.finishing
|
||||
.clone()
|
||||
.map(CancellationToken::drop_guard);
|
||||
let sub_id = task.turn_context.sub_id.clone();
|
||||
if task.cancellation_token.is_cancelled() {
|
||||
drop(finish_recording);
|
||||
publication.await;
|
||||
self.emit_turn_abort_lifecycle(reason, task.turn_context.extension_data.as_ref())
|
||||
.await;
|
||||
@@ -1336,6 +1327,7 @@ impl Session {
|
||||
.and_then(|error| error.codex_error_info.as_ref()),
|
||||
)
|
||||
.await;
|
||||
drop(finish_recording);
|
||||
run_turn_interrupt_hooks(self, &task.turn_context, turn_state).await;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Verifies abort callbacks finish exactly once before the terminal event is published.
|
||||
//! Verifies abort callbacks finish exactly once and the terminal event precedes a mail wake.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
@@ -10,9 +10,12 @@ use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::TurnAbortInput;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_items::sleep::SleepItem;
|
||||
use codex_protocol::AgentPath;
|
||||
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::InterAgentCommunication;
|
||||
use codex_protocol::protocol::Op;
|
||||
use codex_protocol::protocol::TurnAbortReason;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
@@ -47,11 +50,13 @@ impl TurnLifecycleContributor for AbortGate {
|
||||
enum AbortOperation {
|
||||
Interrupt,
|
||||
ConditionalInterrupt,
|
||||
HostedSleep,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
#[test_case(AbortOperation::Interrupt; "interrupt")]
|
||||
#[test_case(AbortOperation::ConditionalInterrupt; "conditional_interrupt")]
|
||||
#[test_case(AbortOperation::HostedSleep; "hosted_mail_during_clock_abort")]
|
||||
#[test_case(AbortOperation::Shutdown; "shutdown")]
|
||||
#[tokio::test]
|
||||
async fn abort_lifecycle_finishes_before_terminal_event(
|
||||
@@ -70,7 +75,13 @@ async fn abort_lifecycle_finishes_before_terminal_event(
|
||||
let gate = Arc::new(AbortGate::default());
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
extensions.turn_lifecycle_contributor(gate.clone());
|
||||
let mut builder = test_codex().with_extensions(Arc::new(extensions.build()));
|
||||
let hosted_sleep = matches!(operation, AbortOperation::HostedSleep);
|
||||
let mut builder = test_codex();
|
||||
if hosted_sleep {
|
||||
extensions.thread_lifecycle_contributor(Arc::new(super::agent_control::HostRuntime));
|
||||
builder = builder.with_config(|config| config.multi_agent_v2.disable_native_tools = true);
|
||||
}
|
||||
builder = builder.with_extensions(Arc::new(extensions.build()));
|
||||
let test = builder.build_with_auto_env(&server).await?;
|
||||
let thread = test
|
||||
.thread_manager
|
||||
@@ -105,21 +116,37 @@ async fn abort_lifecycle_finishes_before_terminal_event(
|
||||
AbortOperation::Interrupt => {
|
||||
thread.submit(Op::Interrupt).await?;
|
||||
}
|
||||
AbortOperation::ConditionalInterrupt => {
|
||||
let (reply, received) = tokio::sync::oneshot::channel();
|
||||
thread
|
||||
.submit(Op::InterruptIfNoPendingInput {
|
||||
turn_id: call.turn_id.clone(),
|
||||
reply,
|
||||
})
|
||||
.await?;
|
||||
assert!(received.await?);
|
||||
AbortOperation::ConditionalInterrupt | AbortOperation::HostedSleep => {
|
||||
if hosted_sleep {
|
||||
thread.thread_extension_data().insert(SleepItem {
|
||||
id: call.call_id.clone(),
|
||||
duration_ms: 60_000,
|
||||
});
|
||||
}
|
||||
assert!(thread.interrupt_if_no_pending_input(&call.turn_id).await?);
|
||||
}
|
||||
AbortOperation::Shutdown => {
|
||||
thread.submit(Op::Shutdown).await?;
|
||||
}
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(10), gate.entered.notified()).await?;
|
||||
let wake = if hosted_sleep {
|
||||
let wake = responses::mount_sse_once(&server, responses::sse_completed("wake")).await;
|
||||
let mail = InterAgentCommunication::new(
|
||||
AgentPath::try_from("/root/worker").expect("worker path"),
|
||||
AgentPath::root(),
|
||||
Vec::new(),
|
||||
"worker completed".to_string(),
|
||||
/*trigger_turn*/ false,
|
||||
);
|
||||
thread
|
||||
.inject_response_items(vec![mail.to_model_input_item()])
|
||||
.await?;
|
||||
assert_eq!(thread.current_turn_id().await, Some(call.turn_id.clone()));
|
||||
Some(wake)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// Keep the callback suspended: scheduling alone must not hide an early event.
|
||||
let early_event = tokio::time::timeout(
|
||||
Duration::from_millis(100),
|
||||
@@ -138,6 +165,14 @@ async fn abort_lifecycle_finishes_before_terminal_event(
|
||||
};
|
||||
assert_eq!(aborted.turn_id, Some(call.turn_id.clone()));
|
||||
assert_eq!(aborted.reason, TurnAbortReason::Interrupted);
|
||||
if let Some(wake) = wake {
|
||||
wait_for_event(&thread, |event| matches!(event, EventMsg::TurnStarted(_))).await;
|
||||
wait_for_event(&thread, |event| matches!(event, EventMsg::TurnComplete(_))).await;
|
||||
assert_eq!(
|
||||
wake.single_request().inputs_of_type("agent_message").len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
if !matches!(operation, AbortOperation::Shutdown) {
|
||||
thread.submit(Op::Shutdown).await?;
|
||||
}
|
||||
|
||||
@@ -520,6 +520,7 @@ impl codex_extension_api::ThreadLifecycleContributor<codex_core::config::Config>
|
||||
enum MailDelivery {
|
||||
Native,
|
||||
Injected,
|
||||
HostedInjected,
|
||||
Persisted,
|
||||
}
|
||||
|
||||
@@ -529,6 +530,7 @@ enum MailDelivery {
|
||||
#[test_case(true, None, None, false, MailDelivery::Native; "reloaded_unknown")]
|
||||
#[test_case(false, Some("automation"), Some("original-parent"), true, MailDelivery::Native; "settings_while_asleep")]
|
||||
#[test_case(false, Some("automation"), None, false, MailDelivery::Injected; "injected_live_root")]
|
||||
#[test_case(false, Some("automation"), None, false, MailDelivery::HostedInjected; "hosted_injected_live_root")]
|
||||
#[test_case(true, Some("automation"), Some("original-parent"), false, MailDelivery::Injected; "injected_reloaded_root")]
|
||||
#[test_case(true, Some("automation"), Some("original-parent"), false, MailDelivery::Persisted; "persisted_reloaded_root")]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
@@ -554,15 +556,20 @@ async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
|
||||
let mut extensions =
|
||||
codex_extension_api::ExtensionRegistryBuilder::<codex_core::config::Config>::new();
|
||||
extensions.thread_lifecycle_contributor(Arc::new(SleepingRootExtension));
|
||||
let hosted = matches!(delivery, MailDelivery::HostedInjected);
|
||||
if hosted {
|
||||
extensions.thread_lifecycle_contributor(Arc::new(super::agent_control::HostRuntime));
|
||||
}
|
||||
let mut builder = test_codex()
|
||||
.with_model("gpt-5.4")
|
||||
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
|
||||
.with_config(move |config| {
|
||||
if matches!(delivery, MailDelivery::Injected | MailDelivery::Persisted) {
|
||||
if !matches!(delivery, MailDelivery::Native) {
|
||||
config.multi_agent_v2.disable_native_tools = hosted;
|
||||
config
|
||||
.features
|
||||
.enable(Feature::MultiAgentV2)
|
||||
.expect("enable native mail");
|
||||
.expect("enable multi-agent V2");
|
||||
config
|
||||
.features
|
||||
.disable(Feature::WakeOnAgentMessages)
|
||||
@@ -618,7 +625,7 @@ async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
if matches!(delivery, MailDelivery::Injected | MailDelivery::Persisted) {
|
||||
if !matches!(delivery, MailDelivery::Native) {
|
||||
let items = vec![
|
||||
InterAgentCommunication::new(
|
||||
AgentPath::try_from("/root/worker").expect("worker path"),
|
||||
@@ -630,7 +637,9 @@ async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
|
||||
.to_model_input_item(),
|
||||
];
|
||||
match delivery {
|
||||
MailDelivery::Injected => test.codex.inject_response_items(items).await?,
|
||||
MailDelivery::Injected | MailDelivery::HostedInjected => {
|
||||
test.codex.inject_response_items(items).await?
|
||||
}
|
||||
MailDelivery::Persisted => {
|
||||
test.codex
|
||||
.inject_response_items_with_retention(items)
|
||||
|
||||
Reference in New Issue
Block a user