Wake idle root threads on persisted agent messages (#63312)

## Why

Plaintext agent messages injected through `thread/inject_items` could
be saved to root-thread history without waking the thread, even when
agent-message wakes were enabled.

## What changed

After persisting a batch of plaintext agent messages with unspecified
retention, let the native multi-agent v2 root thread's mailbox scheduler
apply its usual wake and turn-admission rules. Use the recorded history
sequence to skip a wake if another turn already read the messages and
to deliver the mail directly from history without re-enqueueing it.

## Testing

Cover app-server injection with wakes enabled and disabled, wake a
reloaded sleeping root with its previous turn context, and verify that
a paused turn-admission gate defers the wake and the eventual model
request contains the message once.

GitOrigin-RevId: 5fde8062a179fd7a7919d240373592f2dbb4a389
This commit is contained in:
jif
2026-11-23 11:16:31 +00:00
committed by copyberry
parent a1604a8c05
commit ca891cecdc
9 changed files with 237 additions and 101 deletions
@@ -45,11 +45,13 @@ use tokio::time::timeout;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
#[test_case(ThreadHistoryMode::Legacy; "legacy")]
#[test_case(ThreadHistoryMode::Paginated; "paginated")]
#[test_case(ThreadHistoryMode::Legacy, false; "legacy")]
#[test_case(ThreadHistoryMode::Paginated, false; "paginated")]
#[test_case(ThreadHistoryMode::Paginated, true; "paginated_wake")]
#[tokio::test]
async fn thread_inject_items_adds_raw_response_items_to_thread_history(
history_mode: ThreadHistoryMode,
wake_on_agent_messages: bool,
) -> Result<()> {
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
@@ -57,16 +59,21 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
responses::ev_assistant_message("msg-1", "Done"),
responses::ev_completed("resp-1"),
]);
let response_mock = responses::mount_sse_once(&server, body).await;
let expected_requests = if wake_on_agent_messages { 2 } else { 1 };
let response_mock = responses::mount_sse_sequence(&server, vec![body; expected_requests]).await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
let config = MockResponsesConfig::new(&server.uri())
.enable_feature(Feature::Sqlite)
.enable_feature(Feature::MultiAgentV2)
.disable_feature(Feature::WakeOnAgentMessages)
.enable_feature(Feature::RetainClientDeveloperMessages)
.with_extra_config("[memories]\ndisable_on_external_context = true")
.write(codex_home.path())?;
.with_extra_config("[memories]\ndisable_on_external_context = true");
if wake_on_agent_messages {
config.enable_feature(Feature::WakeOnAgentMessages)
} else {
config.disable_feature(Feature::WakeOnAgentMessages)
}
.write(codex_home.path())?;
let state_db = StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"mock_provider".into(),
@@ -137,6 +144,7 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
.await?;
let _response: ThreadInjectItemsResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(inject_req)).await??;
assert!(response_mock.requests().is_empty());
// A standalone plaintext batch must retain the root's persisted injection path.
let agent_mail: ResponseItem = serde_json::from_value(json!({
"type": "agent_message",
@@ -152,7 +160,24 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
.await?;
let _: ThreadInjectItemsResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(inject_req)).await??;
assert!(response_mock.requests().is_empty());
if wake_on_agent_messages {
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
assert_eq!(
response_mock
.single_request()
.inputs_of_type("agent_message")
.into_iter()
.map(strip_response_item_ids_from_json)
.collect::<Vec<_>>(),
vec![serde_json::to_value(&agent_mail)?],
);
} else {
assert!(response_mock.requests().is_empty());
}
assert_eq!(
state_db
@@ -307,8 +332,11 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
);
let injected_value = serde_json::to_value(&injected_item)?;
let model_input: Vec<Value> = response_mock
.single_request()
let requests = response_mock.requests();
assert_eq!(requests.len(), expected_requests);
let model_input: Vec<Value> = requests
.last()
.context("resumed request missing")?
.input()
.into_iter()
.map(strip_response_item_ids_from_json)
@@ -426,7 +454,7 @@ async fn thread_inject_items_adds_raw_response_items_to_thread_history(
.await?;
let ThreadResumeResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_req)).await??;
assert_eq!(thread.turns.len(), 2);
assert_eq!(thread.turns.len(), expected_requests + 1);
assert!(thread.turns.iter().any(|turn| {
turn.id == turn_started.turn.id
&& turn.status == TurnStatus::Completed
+18 -40
View File
@@ -9,6 +9,7 @@ use crate::session::SessionIo;
use crate::session::SessionSettingsUpdate;
use crate::session::Submission;
use crate::session::emit_subagent_session_started;
use crate::session::inject::plaintext_agent_messages;
use crate::session::inject::validate_injected_response_item;
use crate::session::new_submission_id;
use crate::session::session::AppServerClientMetadata;
@@ -28,7 +29,6 @@ use codex_history::RolloutItem;
use codex_models_manager::ModelsManagerConfig;
use codex_otel::SessionTelemetry;
use codex_otel::current_span_w3c_trace_context;
use codex_protocol::AgentPath;
use codex_protocol::RequestCountry;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ApprovalsReviewer;
@@ -41,7 +41,6 @@ use codex_protocol::error::Result as CodexResult;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::models::ActivePermissionProfile;
use codex_protocol::models::AgentMessageInputContent;
use codex_protocol::models::PermissionProfile;
use codex_protocol::models::ProfileWorkspaceRoot;
use codex_protocol::models::ResponseItem;
@@ -52,7 +51,6 @@ use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EnvironmentConfig;
use codex_protocol::protocol::EnvironmentConfigState;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SandboxPolicy;
@@ -1181,35 +1179,7 @@ impl CodexThread {
// mixed history and multipart/encrypted items on the raw injection path.
if !config.multi_agent_v2.disable_native_tools
&& !items.is_empty()
&& let Some(messages) = items
.iter()
.map(|item| {
let ResponseItem::AgentMessage {
id,
author,
recipient,
content,
internal_chat_message_metadata_passthrough,
} = item
else {
return None;
};
let [AgentMessageInputContent::InputText { text }] = content.as_slice() else {
return None;
};
Some(InterAgentCommunication {
id: id.clone(),
author: AgentPath::try_from(author.as_str()).ok()?,
recipient: AgentPath::try_from(recipient.as_str()).ok()?,
other_recipients: Vec::new(),
content: text.clone(),
encrypted_content: None,
internal_chat_message_metadata_passthrough:
internal_chat_message_metadata_passthrough.clone(),
trigger_turn: false,
})
})
.collect::<Option<Vec<_>>>()
&& let Some(messages) = plaintext_agent_messages(&items)
&& match self.multi_agent_version() {
Some(version) => version,
None => self.session.resolve_multi_agent_version_for_model(
@@ -1238,13 +1208,21 @@ impl CodexThread {
self.inject_response_items_with_retention(items).await
}
/// Inject Responses items with explicit, persisted retention policies.
/// Inject Responses items with persisted retention policies. Ordinary native-root
/// agent mail can wake through the mailbox scheduler after the durable checkpoint.
pub async fn inject_response_items_with_retention(
&self,
items: Vec<impl Into<InjectedResponseItem>>,
) -> CodexResult<()> {
self.record_injected_items(items).await?;
self.checkpoint_preparation().await?;
let items: Vec<InjectedResponseItem> = items.into_iter().map(Into::into).collect();
let agent_mail = items
.iter()
.all(|item| item.retention == ItemRetention::Unspecified)
&& plaintext_agent_messages(items.iter().map(|item| &item.item)).is_some();
let recorded_through = self.record_injected_items(items).await?;
self.session
.checkpoint_client_injection(agent_mail.then_some(recorded_through))
.await?;
Ok(())
}
@@ -1270,13 +1248,13 @@ impl CodexThread {
&self,
items: Vec<ResponseItem>,
) -> CodexResult<()> {
self.record_injected_items(items).await
self.record_injected_items(items).await.map(|_| ())
}
async fn record_injected_items(
&self,
items: Vec<impl Into<InjectedResponseItem>>,
) -> CodexResult<()> {
) -> CodexResult<u64> {
if items.is_empty() {
return Err(CodexErr::InvalidRequest(
"items must not be empty".to_string(),
@@ -1309,10 +1287,10 @@ impl CodexThread {
}
let turn_context = self.session.history_injection_context().await?;
self.session
Ok(self
.session
.inject_client_response_items(items, &turn_context)
.await;
Ok(())
.await)
}
pub fn rollout_path(&self) -> Option<PathBuf> {
+76 -5
View File
@@ -1,17 +1,58 @@
//! Records client injections and preserves their existing active-turn delivery.
use super::RealtimeRecord;
use super::TurnInput as PendingTurnInput;
use super::session::Session;
use super::turn_context::TurnContext;
use codex_features::Feature;
use codex_history::ResponseItemEnvelope;
use codex_protocol::AgentPath;
use codex_protocol::error::CodexErr;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::AgentMessageInputContent;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::MultiAgentVersion;
use codex_thread_store::PersistContext;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
/// Native queue-only delivery accepts only ordinary plaintext agent messages.
pub(crate) fn plaintext_agent_messages<'a>(
items: impl IntoIterator<Item = &'a ResponseItem>,
) -> Option<Vec<InterAgentCommunication>> {
items
.into_iter()
.map(|item| {
let ResponseItem::AgentMessage {
id,
author,
recipient,
content,
internal_chat_message_metadata_passthrough,
} = item
else {
return None;
};
let [AgentMessageInputContent::InputText { text }] = content.as_slice() else {
return None;
};
Some(InterAgentCommunication {
id: id.clone(),
author: AgentPath::try_from(author.as_str()).ok()?,
recipient: AgentPath::try_from(recipient.as_str()).ok()?,
other_recipients: Vec::new(),
content: text.clone(),
encrypted_content: None,
internal_chat_message_metadata_passthrough:
internal_chat_message_metadata_passthrough.clone(),
trigger_turn: false,
})
})
.collect()
}
/// Uploaded files need the admission checks on typed turn input before entering history.
pub(crate) fn validate_injected_response_item(item: &ResponseItem) -> CodexResult<()> {
if item.file_audio_ids().next().is_some() {
@@ -23,6 +64,34 @@ pub(crate) fn validate_injected_response_item(item: &ResponseItem) -> CodexResul
}
impl Session {
/// Seal idle input before exposing its wake to the ordinary mailbox scheduler.
pub(crate) async fn checkpoint_client_injection(
self: &Arc<Self>,
recorded_mail: Option<u64>,
) -> 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
{
{
let mut state = self.state.lock().await;
if state
.session_configuration
.session_source
.is_non_root_agent()
{
return Ok(());
}
state.pending_recorded_mail_sequence =
state.pending_recorded_mail_sequence.max(recorded_through);
}
self.maybe_start_turn_for_pending_work().await;
}
Ok(())
}
/// History injection can precede the first turn. Capture full initial context
/// only when the thread has no reference context, including after compaction.
pub(crate) async fn history_injection_context(
@@ -120,6 +189,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.
#[expect(
clippy::await_holding_invalid_type,
reason = "active turn checks and turn state updates must remain atomic"
@@ -128,7 +198,7 @@ impl Session {
&self,
items: Vec<impl Into<ResponseItemEnvelope>>,
turn_context: &TurnContext,
) {
) -> u64 {
let items = items
.into_iter()
.map(Into::into)
@@ -145,7 +215,7 @@ impl Session {
.collect(),
)
.await;
return;
return 0;
}
let finishing = active.as_ref().and_then(|turn| turn.finishing.clone());
drop(active);
@@ -153,7 +223,7 @@ impl Session {
finishing.cancelled().await;
}
self.record_annotated_conversation_items(turn_context, turn_context.model_info(), items)
.await;
.await
}
pub(crate) fn annotate_client_response_item(
@@ -183,7 +253,7 @@ impl Session {
turn_context: &TurnContext,
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
) {
) -> u64 {
let (annotated_items, image_preparations) = self
.prepare_conversation_items_for_history(turn_context, model_info, items)
.await;
@@ -193,7 +263,7 @@ impl Session {
annotated_items,
image_preparations,
)
.await;
.await
}
pub(crate) async fn record_realtime_session_chunk(
@@ -214,6 +284,7 @@ impl Session {
Some(RealtimeRecord::Chunk),
)
.await
.map(|_| ())
}
/// Injects items into active work, or records them without starting a turn.
+17 -12
View File
@@ -4099,17 +4099,17 @@ impl Session {
model_info: &ModelInfo,
items: Vec<ResponseItemEnvelope>,
image_preparations: Vec<ImagePreparationMetadata>,
) {
) -> u64 {
// Ordinary history persistence retains its existing best-effort behavior.
let _ = self
.record_prepared_items(
turn_context,
model_info,
items,
image_preparations,
/*realtime*/ None,
)
.await;
self.record_prepared_items(
turn_context,
model_info,
items,
image_preparations,
/*realtime*/ None,
)
.await
.unwrap_or_default()
}
#[expect(
@@ -4123,7 +4123,7 @@ impl Session {
mut items: Vec<ResponseItemEnvelope>,
image_preparations: Vec<ImagePreparationMetadata>,
realtime: Option<RealtimeRecord<'_>>,
) -> std::io::Result<()> {
) -> std::io::Result<u64> {
// Save the originating history budget for replay.
// Preserve any existing tool-specific override.
let policy: codex_utils_output_truncation::TruncationPolicy =
@@ -4254,6 +4254,11 @@ impl Session {
.current_time_reminder
.note_recorded_items(&response_items);
}
let recorded_through = items
.iter()
.filter_map(|item| item.metadata.as_ref()?.history_sequence)
.max()
.unwrap_or_default();
for image in image_preparations {
self.services
.analytics_events_client
@@ -4297,7 +4302,7 @@ impl Session {
}
self.send_raw_response_items(turn_context, &response_items)
.await;
Ok(())
Ok(recorded_through)
}
pub(crate) async fn record_step_world_state_if_changed(
+12
View File
@@ -900,6 +900,7 @@ impl Session {
let mut state = self.state.lock().await;
state.last_started_turn_id = Some(turn_id.to_owned());
if let Some(attribution) = attribution {
state.pending_recorded_mail_sequence = 0;
state.turn_attribution = Some(attribution);
}
}
@@ -913,6 +914,17 @@ impl Session {
if active_turn.is_some() || self.turn_starts_closed() {
return None;
}
if !self.input_queue.has_pending_mailbox_items().await {
let mut state = self.state.lock().await;
// An intervening turn may already have sampled the durable injection.
if state.pending_recorded_mail_sequence == 0
|| state.pending_recorded_mail_sequence
<= crate::context_manager::sampled_through(state.history.annotated_items())
{
state.pending_recorded_mail_sequence = 0;
return None;
}
}
let has_trigger_turn = self.input_queue.has_trigger_turn_mailbox_items().await;
if !has_trigger_turn
&& !self.has_outstanding_durable_sleep()
+4
View File
@@ -88,6 +88,8 @@ pub(crate) struct SessionState {
/// Persisted origin of the session base instructions, when known.
pub(crate) base_instructions_provenance: Option<BaseInstructionsProvenance>,
pub(crate) history: ContextManager,
/// Durable injected mail awaiting an ordinary mailbox wake; never re-enqueued as input.
pub(crate) pending_recorded_mail_sequence: u64,
/// Newly recorded files awaiting best-effort lookup after the input batch is durable.
pub(crate) pending_audio_duration_ids: BTreeSet<String>,
/// Cancels work bound to discarded history or a superseded Guardian evidence policy.
@@ -153,6 +155,7 @@ impl SessionState {
base_instructions_provenance: None,
history,
pending_audio_duration_ids: BTreeSet::new(),
pending_recorded_mail_sequence: 0,
history_reset: CancellationToken::new(),
latest_rate_limits: None,
latest_token_usage_record: None,
@@ -241,6 +244,7 @@ impl SessionState {
HistoryReplacement::Reset => {
self.turn_attribution = None;
self.restored_turn_routing = None;
self.pending_recorded_mail_sequence = 0;
self.history.replace_annotated(items);
true
}
-4
View File
@@ -589,10 +589,6 @@ impl Session {
self: &Arc<Self>,
sub_id: String,
) {
if !self.input_queue.has_pending_mailbox_items().await {
return;
}
let Some(reservation) = self.reserve_pending_work_turn().await else {
return;
};
+31 -14
View File
@@ -520,6 +520,7 @@ impl codex_extension_api::ThreadLifecycleContributor<codex_core::config::Config>
enum MailDelivery {
Native,
Injected,
Persisted,
}
#[test_case(false, Some("automation"), None, false, MailDelivery::Native; "live_root")]
@@ -529,6 +530,7 @@ enum MailDelivery {
#[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(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)]
async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
reload: bool,
@@ -556,7 +558,7 @@ async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
.with_model("gpt-5.4")
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(move |config| {
if matches!(delivery, MailDelivery::Injected) {
if matches!(delivery, MailDelivery::Injected | MailDelivery::Persisted) {
config
.features
.enable(Feature::MultiAgentV2)
@@ -616,25 +618,40 @@ async fn queue_only_agent_mail_wakes_sleeping_root_with_previous_turn_context(
)
.await?;
}
if matches!(delivery, MailDelivery::Injected) {
test.codex
.inject_response_items(vec![
InterAgentCommunication::new(
AgentPath::try_from("/root/worker").expect("worker path"),
AgentPath::root(),
Vec::new(),
CHILD_MESSAGE.to_owned(),
/*trigger_turn*/ false,
)
.to_model_input_item(),
])
.await?;
if matches!(delivery, MailDelivery::Injected | MailDelivery::Persisted) {
let items = vec![
InterAgentCommunication::new(
AgentPath::try_from("/root/worker").expect("worker path"),
AgentPath::root(),
Vec::new(),
CHILD_MESSAGE.to_owned(),
/*trigger_turn*/ false,
)
.to_model_input_item(),
];
match delivery {
MailDelivery::Injected => test.codex.inject_response_items(items).await?,
MailDelivery::Persisted => {
test.codex
.inject_response_items_with_retention(items)
.await?
}
MailDelivery::Native => unreachable!("native mail is enqueued below"),
}
} else {
enqueue_queue_only_agent_mail(&test.codex, CHILD_MESSAGE).await;
}
wait_for_turn_complete(&test.codex).await;
let captured = requests.requests();
assert_eq!(
captured
.last()
.expect("wake request")
.inputs_of_type("agent_message")
.len(),
1
);
let metadata = captured
.iter()
.skip(1)
@@ -264,8 +264,12 @@ impl TurnStartAdmission for TestAdmission {
}
}
#[test_case(false; "queued_mail")]
#[test_case(true; "persisted_root_mail")]
#[tokio::test]
async fn host_drain_rejects_turn_start_paths_without_recording_input() -> anyhow::Result<()> {
async fn host_drain_rejects_turn_start_paths_without_recording_input(
persisted_root_mail: bool,
) -> anyhow::Result<()> {
let server = responses::start_mock_server().await;
let response = responses::mount_sse_sequence(
&server,
@@ -283,13 +287,20 @@ async fn host_drain_rejects_turn_start_paths_without_recording_input() -> anyhow
extensions.turn_start_admission(admission.clone());
extensions.thread_lifecycle_contributor(Arc::new(ThreadIdle));
let test = test_codex()
.with_model("gpt-5.4")
.with_model_info_override("gpt-5.4", |model| {
model.multi_agent_version = Some(codex_protocol::protocol::MultiAgentVersion::V2);
})
.with_extensions(Arc::new(extensions.build()))
.with_config(|config| {
config.features.enable(Feature::MultiAgentV2).unwrap();
config
.features
.disable(Feature::MultiAgentV2)
.expect("select multi-agent version from model metadata");
config
.features
.enable(Feature::WakeOnAgentMessages)
.unwrap();
.expect("enable agent-message wakes");
})
.build_with_auto_env(&server)
.await?;
@@ -316,18 +327,25 @@ async fn host_drain_rejects_turn_start_paths_without_recording_input() -> anyhow
);
}
assert!(response.requests().is_empty());
test.codex
.submit(Op::InterAgentCommunication {
communication: InterAgentCommunication::new(
AgentPath::root().join("worker").unwrap(),
AgentPath::root(),
Vec::new(),
"mail received while admission is paused".to_owned(),
/*trigger_turn*/ false,
),
start_options: TurnStartOptions::default(),
})
.await?;
let communication = InterAgentCommunication::new(
AgentPath::root().join("worker").expect("valid worker path"),
AgentPath::root(),
Vec::new(),
"mail received while admission is paused".to_owned(),
/*trigger_turn*/ false,
);
if persisted_root_mail {
test.codex
.inject_response_items_with_retention(vec![communication.to_model_input_item()])
.await?;
} else {
test.codex
.submit(Op::InterAgentCommunication {
communication,
start_options: TurnStartOptions::default(),
})
.await?;
}
// Fence the mailbox dispatch so the first wake has already been rejected.
test.codex
.update_thread_settings(ThreadSettingsOverrides::default())
@@ -347,6 +365,13 @@ async fn host_drain_rejects_turn_start_paths_without_recording_input() -> anyhow
.single_request()
.body_contains_text("mail received while admission is paused")
);
assert_eq!(
response
.single_request()
.inputs_of_type("agent_message")
.len(),
1
);
test.codex
.start_turn_if_idle(user_message_request("allowed input"))