Keep hosted agent corrections behind pending follow-up tasks (#64785)

## Why

An injected `send_message` correction could reach a hosted worker before
the `followup_task` it refers to because turn-local input drains before
the mailbox. An interrupt during a history checkpoint could also drop
corrections from a batch that had already left the queue.

## What changed

Queue plain-text agent messages behind pending follow-up tasks and
deliver them in mailbox order, even across turn boundaries. Record
accepted follow-ups and corrections before waiting on their checkpoint,
and save deferred injections to session history on shutdown.

## Testing

Add regression coverage for native and hosted delivery order, hosted
corrections sent between turns, interruption during a checkpoint, and
correction persistence across shutdown and resume.

GitOrigin-RevId: 3acffd175d3bb2d7e1a9f704fe6c6d6ce38e798d
This commit is contained in:
jif
2026-11-30 18:37:59 +00:00
committed by copyberry
parent 10a8d4ff15
commit 89a5bb31f4
6 changed files with 451 additions and 14 deletions
+8
View File
@@ -436,6 +436,14 @@ pub(super) async fn shutdown_session_runtime(sess: &Arc<Session>) {
if let Some(reporting) = &sess.outcome_reporting {
reporting.handoffs.wait().await;
}
// No next turn will consume injections deferred behind a follow-up. Save
// them before draining native mail or closing the rollout writer.
let injected = sess.input_queue.take_injected_mail().await;
if !injected.is_empty() {
let context = sess.new_inject_items_context().await;
sess.record_annotated_conversation_items(&context, context.model_info(), injected)
.await;
}
if runtime.suspension_root().is_some() {
let pending: Vec<_> = sess
.input_queue
+10 -2
View File
@@ -200,7 +200,7 @@ impl Session {
}
/// Applies client developer-message retention before queueing or recording items.
/// Returns the recorded history sequence, or zero for input queued into an active turn.
/// Returns the recorded history sequence, or zero for queued input.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
@@ -210,12 +210,20 @@ impl Session {
items: Vec<impl Into<ResponseItemEnvelope>>,
turn_context: &TurnContext,
) -> u64 {
let items = items
let mut items = items
.into_iter()
.map(Into::into)
.map(|item| self.annotate_client_response_item(item))
.collect::<Vec<_>>();
let mut active = self.active_turn.lock().await;
if turn_context.config.multi_agent_v2.disable_native_tools
&& self
.input_queue
.try_enqueue_after_followup(&mut items)
.await
{
return 0;
}
if let Some(active_turn) = active.as_mut().filter(|turn| turn.finishing.is_none()) {
self.input_queue
.extend_pending_input_and_notify_for_turn_state(
+53 -12
View File
@@ -170,9 +170,21 @@ pub(crate) struct InputQueue {
pub(crate) struct PendingMailboxCommunication {
pub(crate) communication: crate::PendingAgentMessage,
start_options: TurnStartOptions,
injected_after: Vec<ResponseItemEnvelope>,
_diagnostics_guard: GaugeGuard,
}
impl PendingMailboxCommunication {
fn new(communication: crate::PendingAgentMessage, start_options: TurnStartOptions) -> Self {
Self {
communication,
start_options,
injected_after: Vec::new(),
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
}
}
}
impl InputQueue {
pub(crate) fn new() -> Self {
let (activity_tx, _) = watch::channel(InputQueueActivity::Mailbox);
@@ -208,10 +220,8 @@ impl InputQueue {
control
.take_mailbox(*thread_id)
.into_iter()
.map(|communication| PendingMailboxCommunication {
communication,
start_options: TurnStartOptions::default(),
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
.map(|communication| {
PendingMailboxCommunication::new(communication, TurnStartOptions::default())
}),
);
}
@@ -248,14 +258,43 @@ impl InputQueue {
let mut pending = self.mailbox_pending_mails.lock().await;
// Mail retained while unloaded precedes new submissions to the loaded session.
self.read_mailbox(&mut pending);
pending.push_back(PendingMailboxCommunication {
pending.push_back(PendingMailboxCommunication::new(
communication,
start_options,
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
});
));
self.activity_tx.send_replace(InputQueueActivity::Mailbox);
}
/// Turn-local input drains before the mailbox. Keep queue-only mail behind a
/// pending task, even if that task has to wait for the next turn.
pub(super) async fn try_enqueue_after_followup(
&self,
items: &mut Vec<ResponseItemEnvelope>,
) -> bool {
let mut pending = self.mailbox_pending_mails.lock().await;
if pending.iter().any(|mail| mail.communication.trigger_turn)
&& items.iter().all(|item| item.metadata.is_none())
&& super::inject::plaintext_agent_messages(items.iter().map(|item| &item.item))
.is_some()
&& let Some(tail) = pending.back_mut()
{
// Keep these as injected items so interruption and shutdown can save them.
tail.injected_after.append(items);
self.notify_mailbox();
return true;
}
false
}
pub(super) async fn take_injected_mail(&self) -> Vec<ResponseItemEnvelope> {
self.mailbox_pending_mails
.lock()
.await
.iter_mut()
.flat_map(|mail| std::mem::take(&mut mail.injected_after))
.collect()
}
pub(crate) async fn has_pending_mailbox_items(&self) -> bool {
!self.mailbox_pending_mails.lock().await.is_empty()
|| self
@@ -356,7 +395,10 @@ impl InputQueue {
let start_options = Self::trigger_turn_options(&pending_mails).unwrap_or_default();
let items = pending_mails
.drain(..)
.map(|mail| TurnInput::InterAgentCommunication(mail.communication))
.flat_map(|mail| {
std::iter::once(TurnInput::InterAgentCommunication(mail.communication))
.chain(mail.injected_after.into_iter().map(TurnInput::ResponseItem))
})
.collect();
(items, start_options)
}
@@ -422,11 +464,10 @@ impl InputQueue {
if !results.is_empty() {
let mut pending = self.mailbox_pending_mails.lock().await;
for communication in results.into_iter().rev() {
pending.push_front(PendingMailboxCommunication {
pending.push_front(PendingMailboxCommunication::new(
communication,
start_options: TurnStartOptions::default(),
_diagnostics_guard: PENDING_MAILBOX_MESSAGES.track(),
});
TurnStartOptions::default(),
));
}
}
}
+22
View File
@@ -1205,6 +1205,15 @@ pub(crate) async fn run_hooks_and_record_input_entries(
record_delivered_additional_context(sess, turn_context, model_info, context).await;
}
let initial_input = initial_input.unwrap_or_default();
// A forced interrupt can drop the drained batch while a checkpoint is waiting.
// Record hosted follow-ups and their injected corrections before that wait.
let batch_hosted_mail = persist_context == PersistContext::SteeredUserInput
&& turn_context.config.multi_agent_v2.disable_native_tools
&& pending_input.iter().any(|entry| matches!(
&entry.input,
TurnInput::ResponseItem(item) if matches!(item.item, ResponseItem::AgentMessage { .. })
));
let mut checkpoint_agent_mail = false;
let mut blocked_input = false;
let mut accepted_user_input = false;
let mut input_error = None;
@@ -1231,6 +1240,16 @@ pub(crate) async fn run_hooks_and_record_input_entries(
if let Some(context) = additional_context {
record_delivered_additional_context(sess, turn_context, model_info, context).await;
}
if batch_hosted_mail
&& let TurnInput::InterAgentCommunication(mail) = input_item.as_ref()
{
sess.record_inter_agent_communication(turn_context, model_info, mail.clone())
.await;
record_additional_contexts(sess, turn_context, hook_outcome.additional_contexts)
.await;
checkpoint_agent_mail = true;
continue;
}
// Tool outputs retain their durability barrier, including in mixed input batches.
let input_persist_context = if persist_context == PersistContext::SteeredUserInput
&& matches!(input_item.as_ref(), TurnInput::FunctionCallOutput(_))
@@ -1257,6 +1276,9 @@ pub(crate) async fn run_hooks_and_record_input_entries(
}
}
}
if checkpoint_agent_mail {
sess.ensure_rollout_materialized(persist_context).await;
}
// The batch has left the input queue. Persist every accepted item before the
// optional lookup can suspend this task long enough for an interrupt to abort it.
if !initial_input.is_empty() || !pending_input.is_empty() {
@@ -4,17 +4,21 @@ use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;
use crate::suite::agent_control::HostRuntime;
use anyhow::Context;
use anyhow::Result;
use codex_core::AgentExecutionGuard;
use codex_core::AgentRef;
use codex_core::AgentRuntimeOwnership;
use codex_core::AgentSessionReader;
use codex_core::AgentTurnAdmission;
use codex_core::AgentTurnAdmissionRequest;
use codex_core::CodexThread;
use codex_core::InheritedSessionId;
use codex_core::SteerSubmission;
use codex_core::SuspendTurnOutcome;
use codex_core::TurnAdmissionState;
use codex_core::TurnInput;
use codex_core::TurnInputRequest;
use codex_core::TurnInputSubmission;
use codex_extension_api::ExtensionData;
@@ -24,6 +28,8 @@ use codex_extension_api::TurnStartInput;
use codex_extension_api::TurnStartPhase;
use codex_features::Feature;
use codex_history::RolloutItem;
use codex_protocol::AgentPath;
use codex_protocol::ResponseItemId;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
use codex_protocol::dynamic_tools::DynamicToolResponse;
use codex_protocol::dynamic_tools::DynamicToolSpec;
@@ -36,10 +42,14 @@ use codex_protocol::models::input_text;
use codex_protocol::protocol::AdditionalContextEntry;
use codex_protocol::protocol::AdditionalContextKind;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewRequest;
use codex_protocol::protocol::ReviewTarget;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::user_input::UserInput;
use codex_thread_store::LoadThreadHistoryParams;
use core_test_support::ThreadIdle;
@@ -56,6 +66,7 @@ use core_test_support::wait_for_successful_turn;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use serde_json::json;
use test_case::test_case;
use tokio::sync::Notify;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
@@ -478,6 +489,217 @@ async fn interrupt_before_admission_skips_submit_hook_and_uninspected_prompt() -
Ok(())
}
#[test_case(false; "native")]
#[test_case(true; "hosted")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn followup_task_then_send_message_reaches_worker_in_order(hosted: bool) -> Result<()> {
let server = responses::start_mock_server().await;
let mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("work"),
responses::ev_function_call("hold", "hold_turn", "{}"),
responses::ev_completed("work"),
]),
responses::sse_completed("done"),
],
)
.await;
let test = test_codex()
.with_model("gpt-5.4")
.build_with_auto_env(&server)
.await?;
let worker = AgentPath::try_from("/root/worker").expect("valid path");
let mut options = test.start_thread_options().await;
options.config.features.enable(Feature::MultiAgentV2)?;
options.config.multi_agent_v2.disable_native_tools = hosted;
options.thread_source = Some(ThreadSource::Subagent);
options.session_source = Some(if hosted {
options
.thread_extension_init
.insert(AgentRuntimeOwnership::Host);
options
.thread_extension_init
.insert(Arc::new(HostRuntime) as Arc<dyn AgentTurnAdmission>);
options
.thread_extension_init
.insert(InheritedSessionId(test.session_configured.session_id));
SessionSource::Custom("host".into())
} else {
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: test.session_configured.thread_id,
depth: 1,
agent_path: Some(worker.clone()),
agent_nickname: None,
agent_role: None,
})
});
options.dynamic_tools = vec![hold_tool()];
let child = test.thread_manager.start_thread(options).await?.thread;
submit(&child, "Work").await?;
wait_for_event(
&child,
|event| matches!(event, EventMsg::DynamicToolCallRequest(call) if call.call_id == "hold"),
)
.await;
// Native delivery sends both through the mailbox. Hosts submit followup_task as
// typed turn input and inject send_message as an already formatted Responses item.
let task = InterAgentCommunication::new(
AgentPath::root(),
worker.clone(),
vec![],
"Check main".into(),
/*trigger_turn*/ true,
);
assert_eq!(
child
.start_or_steer_turn(TurnInputRequest::new(TurnInput::InterAgentCommunication(
task
)))
.await?,
TurnInputSubmission::Accepted
);
let mut correction = InterAgentCommunication::new(
AgentPath::root(),
worker,
vec![],
"Message Type: MESSAGE\nTask name: /root/worker\nSender: /root\nPayload:\nUse release instead".into(),
/*trigger_turn*/ false,
);
correction.id = Some(ResponseItemId::with_suffix("amsg", "correction"));
child
.inject_response_items(vec![correction.to_model_input_item()])
.await?;
child
.submit(Op::DynamicToolResponse {
id: "hold".into(),
response: DynamicToolResponse {
content_items: vec![],
success: true,
},
})
.await?;
wait_for_successful_turn(&child).await;
child.shutdown_and_wait().await?;
let requests = mock.requests();
assert_eq!(requests.len(), 2);
let mail = requests[1].inputs_of_type("agent_message");
let order: Vec<_> = mail
.iter()
.map(|item| {
item["content"][0]["text"]
.as_str()
.expect("plaintext agent message")
})
.collect();
assert_eq!(
order,
[
"Message Type: NEW_TASK\nTask name: /root/worker\nSender: /root\nPayload:\nCheck main",
correction.content.as_str(),
]
);
assert_eq!(mail[1]["id"], "amsg_correction");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hosted_correction_survives_worker_shutdown_and_resume() -> Result<()> {
let server = responses::start_mock_server().await;
let model = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("work"),
responses::ev_function_call("hold", "hold_turn", "{}"),
responses::ev_completed("work"),
]),
responses::sse_completed("continued"),
],
)
.await;
let test = test_codex()
.with_model("gpt-5.4")
.build_with_auto_env(&server)
.await?;
let worker_options = async || {
let mut options = test.start_thread_options().await;
options
.config
.features
.enable(Feature::MultiAgentV2)
.expect("enable multi-agent");
options.config.multi_agent_v2.disable_native_tools = true;
options.thread_source = Some(ThreadSource::Subagent);
options.session_source = Some(SessionSource::Custom("host".into()));
options
.thread_extension_init
.insert(AgentRuntimeOwnership::Host);
options
.thread_extension_init
.insert(Arc::new(HostRuntime) as Arc<dyn AgentTurnAdmission>);
options.dynamic_tools = vec![hold_tool()];
options
};
let mut options = worker_options().await;
options
.thread_extension_init
.insert(InheritedSessionId(test.session_configured.session_id));
let worker = test.thread_manager.start_thread(options).await?;
let task = |text: &str| {
TurnInputRequest::new(TurnInput::InterAgentCommunication(
InterAgentCommunication::new(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("worker path"),
vec![],
text.to_owned(),
/*trigger_turn*/ true,
),
))
};
worker.thread.start_or_steer_turn(task("Work")).await?;
wait_for_event(
&worker.thread,
|event| matches!(event, EventMsg::DynamicToolCallRequest(call) if call.call_id == "hold"),
)
.await;
assert_eq!(
worker
.thread
.start_or_steer_turn(task("Check main"))
.await?,
TurnInputSubmission::Accepted
);
let correction = json!({
"type": "agent_message", "id": "amsg_correction", "author": "/root", "recipient": "/root/worker",
"content": [{"type": "input_text", "text": "Use release instead"}]
});
worker
.thread
.inject_response_items(vec![serde_json::from_value(correction.clone())?])
.await?;
// Stop before the tool can return, then load the worker from durable history.
worker.thread.shutdown_and_wait().await?;
let path = worker.thread.rollout_path().expect("worker rollout");
test.thread_manager.remove_thread(&worker.thread_id).await;
let mut options = worker_options().await;
options.initial_history = codex_rollout::RolloutRecorder::get_rollout_history(&path).await?;
let resumed = test.thread_manager.start_thread(options).await?.thread;
resumed.start_or_steer_turn(task("Continue")).await?;
wait_for_successful_turn(&resumed).await;
resumed.shutdown_and_wait().await?;
let corrections: Vec<_> = model.requests()[1]
.inputs_of_type("agent_message")
.into_iter()
.filter(|item| item["id"] == "amsg_correction")
.map(responses::strip_metadata_from_json)
.collect();
assert_eq!(corrections, [correction]);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn injected_child_final_survives_parent_interrupt() -> Result<()> {
let server = responses::start_mock_server().await;
@@ -6,6 +6,10 @@ use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use crate::suite::agent_control::HostRuntime;
use codex_core::AgentRuntimeOwnership;
use codex_core::AgentTurnAdmission;
use codex_core::InheritedSessionId;
use codex_core::TurnInput;
use codex_core::TurnInputRequest;
use codex_core::TurnInputSubmission;
@@ -21,8 +25,10 @@ use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::protocol::ThreadSource;
use codex_protocol::protocol::TurnSettingsUpdate;
use codex_protocol::protocol::TurnSettingsUpdateOutcome;
use codex_protocol::user_input::UserInput;
@@ -52,6 +58,7 @@ use core_test_support::streaming_sse::StreamingSseChunk;
use core_test_support::streaming_sse::start_streaming_sse_server;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_successful_turn;
use pretty_assertions::assert_eq;
use serde_json::json;
use test_case::test_case;
@@ -373,6 +380,135 @@ async fn steered_input_checkpoint_controls_next_request(
Ok(())
}
#[test_case(InferenceCompletion::Response; "next_turn")]
#[test_case(InferenceCompletion::Interrupt; "interrupt_during_task_checkpoint")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn hosted_corrections_stay_in_order_between_turns(
completion: InferenceCompletion,
) -> anyhow::Result<()> {
let server = responses::start_mock_server().await;
let mut answer = responses::ev_assistant_message("answer", "Done.");
answer["item"]["phase"] = json!("final_answer");
let model = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("first"),
answer,
responses::ev_completed("first"),
]),
responses::sse_completed("second"),
],
)
.await;
let (checkpoints, mut checkpoint_requests) = mpsc::unbounded_channel();
let store = Arc::new(GatedCheckpointStore {
inner: InMemoryThreadStore::default(),
policy: CheckpointPolicy::Synchronous,
armed: AtomicBool::new(false),
arm_on: None,
checkpoint_context: Some(PersistContext::SteeredUserInput),
checkpoints,
next_flush: Mutex::default(),
});
let test = test_codex()
.with_model("gpt-5.4")
.with_thread_store(store.clone())
.build_with_auto_env(&server)
.await?;
let mut options = test.start_thread_options().await;
options.config.features.enable(Feature::MultiAgentV2)?;
options.config.multi_agent_v2.disable_native_tools = true;
options.thread_source = Some(ThreadSource::Subagent);
options.session_source = Some(SessionSource::Custom("host".into()));
options
.thread_extension_init
.insert(AgentRuntimeOwnership::Host);
options
.thread_extension_init
.insert(Arc::new(HostRuntime) as Arc<dyn AgentTurnAdmission>);
options
.thread_extension_init
.insert(InheritedSessionId(test.session_configured.session_id));
let worker = test.thread_manager.start_thread(options).await?.thread;
let flush = Arc::new(Barrier::new(/*n*/ 2));
*store.next_flush.lock().await = Some(flush.clone());
worker
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "Work".into(),
text_elements: vec![],
}]))
.await?;
// The first flush follows the final answer while the turn is still active.
flush.wait().await;
assert!(worker.has_active_turn().await);
let mail = |text: &str| {
InterAgentCommunication::new(
AgentPath::root(),
AgentPath::try_from("/root/worker").expect("worker path"),
vec![],
text.into(),
/*trigger_turn*/ false,
)
};
let task = TurnInputRequest::new(TurnInput::InterAgentCommunication(mail("Check main")));
assert_eq!(
worker.start_or_steer_turn(task).await?,
TurnInputSubmission::Accepted
);
worker
.inject_response_items(vec![mail("Use release").to_model_input_item()])
.await?;
// Hold the terminal flush after the active turn clears, before the task starts.
*store.next_flush.lock().await = Some(flush.clone());
flush.wait().await;
flush.wait().await;
assert!(!worker.has_active_turn().await);
worker
.inject_response_items(vec![mail("Use stable").to_model_input_item()])
.await?;
store.armed.store(true, Ordering::SeqCst);
flush.wait().await;
wait_for_successful_turn(&worker).await;
let checkpoint = checkpoint_requests
.recv()
.await
.expect("follow-up checkpoint");
match completion {
InferenceCompletion::Response => checkpoint.complete.send(()).expect("release checkpoint"),
InferenceCompletion::Interrupt => {
// Hold the write past task cancellation, after the mailbox has drained.
worker.submit(Op::Interrupt).await?;
wait_for_event(&worker, |event| matches!(event, EventMsg::TurnAborted(_))).await;
drop(checkpoint);
worker
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "Continue".into(),
text_elements: vec![],
}]))
.await?;
}
}
wait_for_successful_turn(&worker).await;
worker.shutdown_and_wait().await?;
let requests = model.requests();
assert_eq!(requests.len(), 2);
let items = requests[1].inputs_of_type("agent_message");
let messages: Vec<_> = items
.iter()
.map(|item| item["content"][0]["text"].as_str().expect("message text"))
.collect();
assert_eq!(
messages,
[
"Message Type: NEW_TASK\nTask name: /root/worker\nSender: /root\nPayload:\nCheck main",
"Use release",
"Use stable",
]
);
Ok(())
}
#[test_case(false; "read_only_steer")]
#[test_case(true; "steer_with_patch")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]