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
+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;
};