Isolate app-server turn metadata by turn ID (#61817)

## Why

A turn can complete after the next turn has started. Sharing one turn summary lets late completion events consume the next turn's metadata and clear its command tracking.

## What changed

Track turn summaries and command start times by turn ID so errors, timestamps, final agent messages, and command lifecycle notifications stay associated with the correct turn. Read and remove only the completing turn's state, and clear tracked state when listeners are replaced or removed.

Initialize summaries for inline reviews that can finish before their delegate emits `TurnStarted`.

## Testing

Extend regression coverage to check that overlapping turns retain their own errors, completed turns include start timestamps, and the next turn's approved command emits one start and one completion notification despite a late completion from the previous turn.

GitOrigin-RevId: 91f022d885c67c7d8982091c72325f1d701569a6
This commit is contained in:
jif
2026-11-16 14:08:16 +00:00
committed by copyberry
parent 662a634e88
commit 2309bae1ae
4 changed files with 152 additions and 96 deletions
@@ -5,7 +5,6 @@ use crate::request_processors::thread_settings_from_config_snapshot;
use crate::server_request_error::is_turn_transition_server_request_error;
use crate::thread_state::PendingNetworkApproval;
use crate::thread_state::ThreadState;
use crate::thread_state::TurnSummary;
use crate::thread_state::resolve_server_request_on_thread_listener;
use crate::thread_status::ThreadWatchActiveGuard;
use crate::thread_status::ThreadWatchManager;
@@ -202,7 +201,12 @@ pub(crate) async fn apply_bespoke_event_handling(
EventMsg::TurnComplete(turn_complete_event) => {
respond_to_pending_interrupts(&thread_state, &outgoing).await;
if finishes_latest_turn {
let turn_failed = thread_state.lock().await.turn_summary.last_error.is_some();
let turn_failed = thread_state
.lock()
.await
.turn_summaries
.get(&event_turn_id)
.is_some_and(|summary| summary.last_error.is_some());
thread_watch_manager
.note_turn_completed(&conversation_id.to_string(), turn_failed)
.await;
@@ -1124,8 +1128,7 @@ pub(crate) async fn apply_bespoke_event_handling(
CoreTurnItem::CommandExecution(item) => thread_state
.lock()
.await
.turn_summary
.record_command_start(item.id.clone(), event.started_at_ms),
.record_command_start(&event_turn_id, item.id.clone(), event.started_at_ms),
_ => true,
};
let dynamic_tool_call_params = match &event.item {
@@ -1165,6 +1168,7 @@ pub(crate) async fn apply_bespoke_event_handling(
&thread_manager,
&thread_watch_manager,
&thread_state,
&event_turn_id,
&mut event,
)
.await;
@@ -1445,6 +1449,7 @@ async fn apply_canonical_item_completed_side_effects(
thread_manager: &Arc<ThreadManager>,
thread_watch_manager: &ThreadWatchManager,
thread_state: &Arc<Mutex<ThreadState>>,
event_turn_id: &str,
event: &mut codex_protocol::protocol::ItemCompletedEvent,
) {
match &event.item {
@@ -1452,9 +1457,7 @@ async fn apply_canonical_item_completed_side_effects(
let observed_start = thread_state
.lock()
.await
.turn_summary
.command_start_times
.remove(&item.id);
.take_command_start(event_turn_id, &item.id);
// A client can already be displaying the command's approval-time start.
event.started_at_ms = observed_start.or(event.started_at_ms);
}
@@ -1498,11 +1501,11 @@ async fn start_command_execution_item(
outgoing: &ThreadScopedOutgoingMessageSender,
thread_state: &Arc<Mutex<ThreadState>>,
) -> bool {
let first_start = thread_state
.lock()
.await
.turn_summary
.record_command_start(item_id.clone(), started_at_ms);
let first_start =
thread_state
.lock()
.await
.record_command_start(&turn_id, item_id.clone(), started_at_ms);
if first_start {
let notification = ItemStartedNotification::new(
conversation_id.to_string(),
@@ -1546,9 +1549,7 @@ async fn complete_command_execution_item(
let Some(started_at_ms) = thread_state
.lock()
.await
.turn_summary
.command_start_times
.remove(&item_id)
.take_command_start(&turn_id, &item_id)
else {
return;
};
@@ -1582,14 +1583,6 @@ async fn complete_command_execution_item(
.await;
}
async fn find_and_remove_turn_summary(
_conversation_id: ThreadId,
thread_state: &Arc<Mutex<ThreadState>>,
) -> TurnSummary {
let mut state = thread_state.lock().await;
std::mem::take(&mut state.turn_summary)
}
async fn handle_turn_complete(
conversation_id: ThreadId,
event_turn_id: String,
@@ -1597,7 +1590,7 @@ async fn handle_turn_complete(
outgoing: &ThreadScopedOutgoingMessageSender,
thread_state: &Arc<Mutex<ThreadState>>,
) {
let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await;
let turn_summary = thread_state.lock().await.take_turn_summary(&event_turn_id);
let (status, error, last_agent_message) = match turn_summary.last_error {
Some(error) => (TurnStatus::Failed, Some(error), None),
@@ -1628,7 +1621,7 @@ async fn handle_turn_interrupted(
outgoing: &ThreadScopedOutgoingMessageSender,
thread_state: &Arc<Mutex<ThreadState>>,
) {
let turn_summary = find_and_remove_turn_summary(conversation_id, thread_state).await;
let turn_summary = thread_state.lock().await.take_turn_summary(&event_turn_id);
emit_turn_completed_with_status(
conversation_id,
@@ -1696,13 +1689,10 @@ async fn handle_token_count_event(
}
}
async fn handle_error(
_conversation_id: ThreadId,
error: TurnError,
thread_state: &Arc<Mutex<ThreadState>>,
) {
let mut state = thread_state.lock().await;
state.turn_summary.last_error = Some(error);
async fn handle_error(turn_id: &str, error: TurnError, thread_state: &Arc<Mutex<ThreadState>>) {
if let Some(summary) = thread_state.lock().await.turn_summaries.get_mut(turn_id) {
summary.last_error = Some(error);
}
}
async fn handle_error_notification(
@@ -1712,7 +1702,7 @@ async fn handle_error_notification(
outgoing: &ThreadScopedOutgoingMessageSender,
thread_state: &Arc<Mutex<ThreadState>>,
) {
handle_error(conversation_id, error.clone(), thread_state).await;
handle_error(event_turn_id, error.clone(), thread_state).await;
outgoing
.send_server_notification(ServerNotification::Error(ErrorNotification {
error,
@@ -2179,9 +2169,9 @@ async fn on_command_execution_request_approval_response(
if approval_id.is_some() {
let state = thread_state.lock().await;
state
.turn_summary
.command_start_times
.contains_key(&item_id)
.get(&event_turn_id)
.is_some_and(|starts| starts.contains_key(&item_id))
} else {
false
}
@@ -3149,11 +3139,15 @@ mod tests {
#[tokio::test]
async fn test_handle_error_records_message() -> Result<()> {
let conversation_id = ThreadId::new();
let event_turn_id = "turn-1";
let thread_state = new_thread_state();
thread_state
.lock()
.await
.note_turn_started(event_turn_id, /*started_at*/ None);
handle_error(
conversation_id,
event_turn_id,
TurnError {
misalignment: None,
message: "boom".to_string(),
@@ -3164,7 +3158,7 @@ mod tests {
)
.await;
let turn_summary = find_and_remove_turn_summary(conversation_id, &thread_state).await;
let turn_summary = thread_state.lock().await.take_turn_summary(event_turn_id);
assert_eq!(
turn_summary.last_error,
Some(TurnError {
@@ -3511,7 +3505,7 @@ mod tests {
);
let thread_state = new_thread_state();
handle_error(
conversation_id,
&event_turn_id,
TurnError {
misalignment: None,
message: "conversation is not running".to_string(),
@@ -3622,8 +3616,12 @@ mod tests {
let conversation_id = ThreadId::new();
let event_turn_id = "interrupt1".to_string();
let thread_state = new_thread_state();
thread_state
.lock()
.await
.note_turn_started(&event_turn_id, /*started_at*/ None);
handle_error(
conversation_id,
&event_turn_id,
TurnError {
misalignment: None,
message: "oops".to_string(),
@@ -3690,7 +3688,7 @@ mod tests {
}),
);
handle_error(
conversation_id,
&event_turn_id,
TurnError {
misalignment: None,
message: "bad".to_string(),
@@ -3922,9 +3920,7 @@ mod tests {
#[tokio::test]
async fn test_handle_turn_complete_emits_error_multiple_turns() -> Result<()> {
// Conversation A will have two turns; Conversation B will have one turn.
let conversation_a = ThreadId::new();
let conversation_b = ThreadId::new();
let conversation_id = ThreadId::new();
let thread_state = new_thread_state();
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
@@ -3938,10 +3934,13 @@ mod tests {
ThreadId::new(),
);
// Turn 1 on conversation A
let a_turn1 = "a_turn1".to_string();
let first = "first".to_string();
thread_state
.lock()
.await
.note_turn_started(&first, /*started_at*/ None);
handle_error(
conversation_a,
&first,
TurnError {
misalignment: None,
message: "a1".to_string(),
@@ -3951,19 +3950,14 @@ mod tests {
&thread_state,
)
.await;
handle_turn_complete(
conversation_a,
a_turn1.clone(),
turn_complete_event(&a_turn1),
&outgoing,
&thread_state,
)
.await;
// Turn 1 on conversation B
let b_turn1 = "b_turn1".to_string();
// The second turn reports its error before the first one completes.
let second = "second".to_string();
thread_state
.lock()
.await
.note_turn_started(&second, /*started_at*/ None);
handle_error(
conversation_b,
&second,
TurnError {
misalignment: None,
message: "b1".to_string(),
@@ -3974,30 +3968,37 @@ mod tests {
)
.await;
handle_turn_complete(
conversation_b,
b_turn1.clone(),
turn_complete_event(&b_turn1),
conversation_id,
first.clone(),
turn_complete_event(&first),
&outgoing,
&thread_state,
)
.await;
// Turn 2 on conversation A
let a_turn2 = "a_turn2".to_string();
handle_turn_complete(
conversation_a,
a_turn2.clone(),
turn_complete_event(&a_turn2),
conversation_id,
second.clone(),
turn_complete_event(&second),
&outgoing,
&thread_state,
)
.await;
let third = "third".to_string();
handle_turn_complete(
conversation_id,
third.clone(),
turn_complete_event(&third),
&outgoing,
&thread_state,
)
.await;
// Verify: A turn 1
let msg = recv_broadcast_notification(&mut rx).await?;
match msg {
ServerNotification::TurnCompleted(n) => {
assert_eq!(n.turn.id, a_turn1);
assert_eq!(n.turn.id, first);
assert_eq!(n.turn.status, TurnStatus::Failed);
assert_eq!(
n.turn.error,
@@ -4012,11 +4013,10 @@ mod tests {
other => bail!("unexpected message: {other:?}"),
}
// Verify: B turn 1
let msg = recv_broadcast_notification(&mut rx).await?;
match msg {
ServerNotification::TurnCompleted(n) => {
assert_eq!(n.turn.id, b_turn1);
assert_eq!(n.turn.id, second);
assert_eq!(n.turn.status, TurnStatus::Failed);
assert_eq!(
n.turn.error,
@@ -4031,11 +4031,10 @@ mod tests {
other => bail!("unexpected message: {other:?}"),
}
// Verify: A turn 2
let msg = recv_broadcast_notification(&mut rx).await?;
match msg {
ServerNotification::TurnCompleted(n) => {
assert_eq!(n.turn.id, a_turn2);
assert_eq!(n.turn.id, third);
assert_eq!(n.turn.status, TurnStatus::Completed);
assert_eq!(n.turn.error, None);
}
@@ -554,7 +554,7 @@ async fn start_listener(
let mut thread_state = thread_state.lock().await;
thread_state.track_current_turn_event(&event.id, &event.msg);
let terminal = matches!(event.msg, EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_))
.then(|| thread_state.turn_summary.clone());
.then(|| thread_state.turn_summaries.get(&event.id).cloned().unwrap_or_default());
(thread_state.experimental_raw_events, terminal)
};
if matches!(
@@ -1319,6 +1319,7 @@ mod thread_processor_behavior_tests {
.await
.expect("A must reach its stop hook");
let second = start("second").await?;
let mut command_events = Vec::new();
let mut next_message = async |stage: &str| loop {
if let OutgoingEnvelope::ToConnection { message, .. } =
tokio::time::timeout(std::time::Duration::from_secs(20), rx.recv())
@@ -1326,6 +1327,21 @@ mod thread_processor_behavior_tests {
.expect(stage)
.expect("listener closed")
{
if let OutgoingMessage::AppServerNotification(envelope) = &message {
match &envelope.notification {
ServerNotification::ItemStarted(n)
if n.turn_id == second && n.item.id() == "command" =>
{
command_events.push("started");
}
ServerNotification::ItemCompleted(n)
if n.turn_id == second && n.item.id() == "command" =>
{
command_events.push("completed");
}
_ => {}
}
}
break message;
}
};
@@ -1355,6 +1371,7 @@ mod thread_processor_behavior_tests {
&& let ServerNotification::TurnCompleted(completed) = envelope.notification
{
assert_eq!(completed.turn.id, expected);
assert!(completed.turn.started_at.is_some());
break;
}
}
@@ -1378,6 +1395,7 @@ mod thread_processor_behavior_tests {
.notify_client_response(connection_id, approval_id, json!({"decision": "accept"}))
.await;
wait_for_completion(&second).await;
assert_eq!(command_events, ["started", "completed"]);
let output = model
.function_call_output_text("command")
.expect("command output");
+61 -22
View File
@@ -100,34 +100,22 @@ pub(crate) struct PendingNetworkApproval {
pub(crate) permission_guard: crate::thread_status::ThreadWatchActiveGuard,
}
/// Per-conversation accumulation of the latest states e.g. error message while a turn runs.
/// Metadata accumulated for one turn until its terminal notification.
#[derive(Default, Clone)]
pub(crate) struct TurnSummary {
pub(crate) started_at: Option<i64>,
pub(crate) command_start_times: HashMap<String, i64>,
pub(crate) last_error: Option<TurnError>,
pub(crate) last_agent_message: Option<ThreadItem>,
}
impl TurnSummary {
pub(crate) fn record_command_start(&mut self, item_id: String, started_at_ms: i64) -> bool {
if let std::collections::hash_map::Entry::Vacant(entry) =
self.command_start_times.entry(item_id)
{
entry.insert(started_at_ms);
true
} else {
false
}
}
}
#[derive(Default)]
pub(crate) struct ThreadState {
goal_resume_lock: Arc<Mutex<()>>,
pub(crate) pending_interrupts: PendingInterruptQueue,
pub(crate) network_approvals: HashMap<String, PendingNetworkApproval>,
pub(crate) turn_summary: TurnSummary,
pub(crate) turn_summaries: HashMap<String, TurnSummary>,
// A background command can emit events even after its originating turn finishes.
pub(crate) command_start_times: HashMap<String, HashMap<String, i64>>,
/// A terminal event can arrive after the listener has already started the next turn.
pub(crate) last_started_turn_id: Option<String>,
pub(crate) last_terminal_turn_id: Option<String>,
@@ -180,6 +168,8 @@ impl ThreadState {
if let Some(previous) = self.cancel_tx.replace(cancel_tx) {
let _ = previous.send(());
}
self.turn_summaries.clear();
self.command_start_times.clear();
self.shutdown_drain = Some(shutdown_drain);
self.listener_generation = self.listener_generation.wrapping_add(1);
self.last_thread_settings = Some(thread_settings_baseline);
@@ -201,6 +191,8 @@ impl ThreadState {
self.listener_command_tx = None;
self.current_turn_history.reset();
self.last_started_turn_id = None;
self.turn_summaries.clear();
self.command_start_times.clear();
self.listener_thread = None;
self.watch_registration = WatchRegistration::default();
}
@@ -236,13 +228,59 @@ impl ThreadState {
self.current_turn_history.active_turn_metadata_snapshot()
}
pub(crate) fn record_command_start(
&mut self,
turn_id: &str,
item_id: String,
started_at_ms: i64,
) -> bool {
let starts = self
.command_start_times
.entry(turn_id.to_owned())
.or_default();
if let Entry::Vacant(entry) = starts.entry(item_id) {
entry.insert(started_at_ms);
true
} else {
false
}
}
pub(crate) fn take_command_start(&mut self, turn_id: &str, item_id: &str) -> Option<i64> {
let starts = self.command_start_times.get_mut(turn_id)?;
let started_at = starts.remove(item_id);
if starts.is_empty() {
self.command_start_times.remove(turn_id);
}
started_at
}
pub(crate) fn take_turn_summary(&mut self, turn_id: &str) -> TurnSummary {
self.command_start_times.remove(turn_id);
self.turn_summaries.remove(turn_id).unwrap_or_default()
}
pub(crate) fn note_turn_started(&mut self, turn_id: &str, started_at: Option<i64>) {
self.last_started_turn_id = Some(turn_id.to_owned());
self.turn_summaries.insert(
turn_id.to_owned(),
TurnSummary {
started_at,
..Default::default()
},
);
}
pub(crate) fn track_current_turn_event(&mut self, event_turn_id: &str, event: &EventMsg) {
if let EventMsg::TurnStarted(payload) = event {
self.last_started_turn_id = Some(event_turn_id.to_owned());
self.turn_summary = TurnSummary {
started_at: payload.started_at,
..Default::default()
};
self.note_turn_started(event_turn_id, payload.started_at);
} else if let EventMsg::ItemStarted(payload) = event
&& matches!(payload.item, CoreTurnItem::EnteredReviewMode(_))
{
// Inline reviews can finish before their delegate emits TurnStarted.
self.turn_summaries
.entry(event_turn_id.to_owned())
.or_default();
}
if let EventMsg::ItemCompleted(payload) = event
&& let CoreTurnItem::AgentMessage(item) = &payload.item
@@ -250,8 +288,9 @@ impl ThreadState {
&& item.content.iter().any(|content| {
matches!(content, CoreAgentMessageContent::Text { text } if !text.trim().is_empty())
})
&& let Some(summary) = self.turn_summaries.get_mut(event_turn_id)
{
self.turn_summary.last_agent_message = Some(ThreadItem::from(payload));
summary.last_agent_message = Some(ThreadItem::from(payload));
}
if self.evict_superseded_agent_text {
self.current_turn_history.handle_live_paginated_event(event);