Preserve queued agent messages when a parent turn is interrupted (#62348)

## Why

A parent turn can acknowledge a child agent's final reply while a model
request is in flight. If the parent is interrupted before consuming the
queued reply, turn cleanup can discard it.

## What changed

Record queued agent messages in conversation history during interruption
and flush the rollout before emitting `TurnAborted`, even when the
interruption marker is disabled.

## Testing

Add a regression test that interrupts a parent while a child's final
reply is queued. The test checks that the reply is persisted when
`TurnAborted` arrives and appears exactly once in the next model request.

GitOrigin-RevId: 5bd828c4101942fa4fe7ba5040355a8244f02018
This commit is contained in:
jif
2026-11-18 19:39:41 +00:00
committed by copyberry
parent 0e011c0092
commit 9d8ca1df71
3 changed files with 152 additions and 11 deletions
+40 -11
View File
@@ -1176,24 +1176,23 @@ impl Session {
turn_context: &TurnContext,
cause: Option<&CodexErrorInfo>,
) {
let Some(marker) = interrupted_turn_history_marker(
if let Some(marker) = interrupted_turn_history_marker(
InterruptedTurnHistoryMarker::from_config_and_version(
turn_context.config.as_ref(),
turn_context.multi_agent_version,
),
cause,
) else {
return;
};
self.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&marker),
)
.await;
) {
self.record_conversation_items(
turn_context,
turn_context.model_info(),
std::slice::from_ref(&marker),
)
.await;
}
// Clients may re-read the rollout as soon as they receive the terminal event.
if let Err(err) = self.flush_rollout().await {
warn!("failed to flush interrupted-turn marker before terminal event: {err}");
warn!("failed to flush interrupted-turn history before terminal event: {err}");
}
}
@@ -1270,6 +1269,36 @@ impl Session {
.await;
if reason == TurnAbortReason::Interrupted {
// Injection acknowledges queueing. Preserve accepted agent mail before
// teardown discards pending input and the host observes TurnAborted.
let mut pending_mail = Vec::new();
let mut remaining_input = Vec::new();
for input in self
.input_queue
.take_pending_input_for_turn_state(turn_state)
.await
{
match input {
TurnInput::ResponseItem(item)
if matches!(item.item, ResponseItem::AgentMessage { .. }) =>
{
pending_mail.push(item);
}
input => remaining_input.push(input),
}
}
// Existing cleanup requeues native terminal results from this input.
self.input_queue
.extend_pending_input_for_turn_state(turn_state, remaining_input)
.await;
if !pending_mail.is_empty() {
self.record_annotated_conversation_items(
&task.turn_context,
&task.turn_context.capture_current_model_info(),
pending_mail,
)
.await;
}
self.record_interrupted_turn_history(
&task.turn_context,
error
@@ -346,6 +346,93 @@ async fn interrupt_before_admission_skips_submit_hook_and_uninspected_prompt() -
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;
let sampling = Arc::new(Notify::new());
let sampled = Arc::clone(&sampling);
let model = responses::mount_response_handler(&server, move |request| {
let response = responses::sse_response(responses::sse_completed("done"));
if request
.message_input_texts("user")
.iter()
.any(|text| text == "Continue work.")
{
response
} else {
sampled.notify_one();
response.set_delay(Duration::from_secs(60))
}
})
.await;
let builder = test_codex().with_config(|config| {
config
.features
.disable(Feature::InstantInterrupt)
.expect("keep mail queued during sampling");
// Mail must be durable even when no interruption marker is written.
config.agent_interrupt_message_enabled = false;
});
let (test, mut attempts) =
root_with_admission(&server, builder, /*session_reader*/ None).await?;
let (_, grant) = start(&test, &mut attempts, "Start work.").await?;
assert!(grant.send(Ok(AgentExecutionGuard::new(()))).is_ok());
sampling.notified().await;
let message: ResponseItem = serde_json::from_value(json!({
"type": "agent_message", "id": "agent_child-final", "author": "/root/worker", "recipient": "/root",
"content": [{"type": "input_text", "text": "Message Type: FINAL_ANSWER\nTask name: /root\nSender: /root/worker\nPayload:\nThe worker finished."}]
}))?;
// Injection has acknowledged the final, but the blocked sample has not consumed it.
test.codex
.inject_response_items(vec![message.clone()])
.await?;
test.codex.submit(Op::Interrupt).await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnAborted(_))
})
.await;
let history = test
.thread_store
.load_latest_model_context(LoadThreadHistoryParams {
thread_id: test.session_configured.thread_id,
include_archived: false,
})
.await?;
let persisted = history
.items
.into_iter()
.filter_map(|item| match item {
RolloutItem::ResponseItem(envelope)
if matches!(envelope.item, ResponseItem::AgentMessage { .. }) =>
{
Some(responses::strip_metadata(envelope.item))
}
_ => None,
})
.collect::<Vec<_>>();
assert_eq!(persisted, vec![message.clone()]);
let (_, grant) = start(&test, &mut attempts, "Continue work.").await?;
assert!(grant.send(Ok(AgentExecutionGuard::new(()))).is_ok());
wait_for_successful_turn(&test.codex).await;
let mail = model
.requests()
.iter()
.map(|request| request.inputs_of_type("agent_message"))
.collect::<Vec<_>>();
assert_eq!(
responses::strip_metadata_from_json(json!(mail)),
json!([[], [message]])
);
insta::assert_snapshot!(context_snapshot::format_request_history_snapshot(
"An acknowledged child final queued during parent sampling survives interruption and appears once in the next request.",
&responses::received_responses_requests(&server).await,
&ContextSnapshotOptions::default().rewrite_known_segments(),
));
test.codex.shutdown_and_wait().await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn suspending_root_during_admission_preserves_the_recoverable_prompt() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -0,0 +1,25 @@
---
source: core/tests/suite/host_turn_admission.rs
assertion_line: 397
expression: "context_snapshot::format_request_history_snapshot(\"An acknowledged child final queued during parent sampling survives interruption and appears once in the next request.\",\n&responses::received_responses_requests(&server).await,\n&ContextSnapshotOptions::default().rewrite_known_segments(),)"
---
Scenario: An acknowledged child final queued during parent sampling survives interruption and appears once in the next request.
## Window 1
-- request 1 (turn) --
00:message/developer:
<MODEL_INSTRUCTIONS>
01:message/developer[2]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <tools>
Deferred tool namespaces:
- multi_agent_v1: Tools for spawning and managing sub-agents.
</tools>
02:message/user:
<ENVIRONMENT_CONTEXT>
03:message/user:
Start work.
-- request 2 (turn) --
04:agent_message
05:message/user:
Continue work.