From ae78265f08244e7543e783f217a8b07102653208 Mon Sep 17 00:00:00 2001 From: jif Date: Mon, 30 Nov 2026 09:28:58 +0000 Subject: [PATCH] Streamline rollout history handling for thread forks (#64704) ## Why Forking before a known user message only needs its rollout position. The previous path replayed turn history even when that position was available. ## What changed Compute the fork boundary on the borrowed rollout before taking ownership of its records. Use rollback-aware user message positions for in-range requests and inspect the unfinished turn only for out-of-range requests. Share unfinished-turn detection and closure between interrupted thread forks and subagent forks that preserve the parent prefix. Read turn metadata without materializing the active turn's items. ## Testing Cover empty fork histories and verify that an interrupted fork persists the original turn ID, root turn ID, and start time in its abort event. GitOrigin-RevId: 8d732f9f9c5fcc9aa4be27c3e48b68e43531e938 --- codex-rs/core/src/agent/history.rs | 15 +- codex-rs/core/src/thread_manager.rs | 209 ++--------- codex-rs/core/src/thread_manager_tests.rs | 342 ++++-------------- .../core/src/thread_rollout_truncation.rs | 100 +++-- .../src/thread_rollout_truncation_tests.rs | 64 +--- 5 files changed, 186 insertions(+), 544 deletions(-) diff --git a/codex-rs/core/src/agent/history.rs b/codex-rs/core/src/agent/history.rs index fb191c9c12..c3fb7bfe23 100644 --- a/codex-rs/core/src/agent/history.rs +++ b/codex-rs/core/src/agent/history.rs @@ -17,11 +17,10 @@ use crate::context::MultiAgentRoleInstructions; use crate::context::MultiAgentUsageHint; use crate::context::world_state::IncrementalToolsUpdate; use crate::context::world_state::PersistentModeState; +use crate::rollout::truncation::unfinished_turn; use crate::session::multi_agents::resolve_usage_hints; use crate::tasks::InterruptedTurnHistoryMarker; -use crate::thread_manager::ForkSnapshot; use crate::thread_manager::ThreadManagerState; -use crate::thread_manager::fork_history_from_snapshot; use codex_context_fragments::set_annotated_content; use codex_context_fragments::to_annotated_content; use codex_history::CodexHarnessMetadata; @@ -448,15 +447,11 @@ pub(super) async fn prepare_forked_history( let preserve_fork_prefix = multi_agent_version == MultiAgentVersion::V2 && config.multi_agent_v2.preserve_fork_prefix && preserve_context_baselines; - if preserve_fork_prefix { - let InitialHistory::Forked(items) = fork_history_from_snapshot( - ForkSnapshot::Interrupted, - InitialHistory::Forked(forked_rollout_items), + if preserve_fork_prefix && let Some(turn) = unfinished_turn(&forked_rollout_items) { + turn.close( + &mut forked_rollout_items, InterruptedTurnHistoryMarker::Disabled, - ) else { - unreachable!("a forked snapshot remains forked"); - }; - forked_rollout_items = items; + ); } let retain_forked_item = |envelope: &mut ResponseItemEnvelope, replaced: &mut bool| { let response_item = &mut envelope.item; diff --git a/codex-rs/core/src/thread_manager.rs b/codex-rs/core/src/thread_manager.rs index 5780a91052..12e466e146 100644 --- a/codex-rs/core/src/thread_manager.rs +++ b/codex-rs/core/src/thread_manager.rs @@ -46,13 +46,10 @@ use crate::session::session::Session; use crate::session::startup::SessionStartup; use crate::session::startup::SessionStartupGuard; use crate::tasks::InterruptedTurnHistoryMarker; -use crate::tasks::interrupted_turn_history_marker; use crate::thread_startup_metadata::ThreadStartupMetadata; use codex_agent_graph_store::AgentGraphStore; use codex_agent_graph_store::LocalAgentGraphStore; use codex_analytics::AnalyticsEventsClient; -use codex_app_server_protocol::ThreadHistoryBuilder; -use codex_app_server_protocol::TurnStatus; use codex_attachment_store::AttachmentStore; use codex_attachment_store::InlineAttachmentStore; use codex_code_mode::CodeModeSessionProvider; @@ -103,8 +100,6 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadHistoryMode; use codex_protocol::protocol::ThreadSource; -use codex_protocol::protocol::TurnAbortReason; -use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::TurnEnvironmentRequest; use codex_protocol::protocol::TurnEnvironmentSelection; use codex_protocol::protocol::W3cTraceContext; @@ -3394,200 +3389,42 @@ fn thread_store_metadata_update_error(thread_id: ThreadId, err: ThreadStoreError } } -/// Return a fork snapshot cut strictly before the nth user message (0-based). -/// -/// Out-of-range values keep the full committed history at a turn boundary, but -/// when the source thread is currently mid-turn they fall back to cutting -/// before the active turn's opening boundary so the fork omits the unfinished -/// suffix entirely. -fn truncate_before_nth_user_message( - history: InitialHistory, - n: usize, - snapshot_state: &SnapshotTurnState, -) -> InitialHistory { - let mut items = match history { - InitialHistory::New | InitialHistory::Cleared => Vec::new(), - InitialHistory::Resumed(resumed) => Arc::unwrap_or_clone(resumed.history), - InitialHistory::Forked(items) => items, - }; - let user_positions = truncation::user_message_positions_in_rollout(&items); - let rolled = if snapshot_state.ends_mid_turn && n >= user_positions.len() { - if let Some(cut_idx) = snapshot_state - .active_turn_start_index - .or_else(|| user_positions.last().copied()) - { - items.truncate(cut_idx); - items - } else { - items - } - } else { - truncation::truncate_rollout_before_nth_user_message_from_start(items, n) - }; - - if rolled.is_empty() { - InitialHistory::New - } else { - InitialHistory::Forked(rolled) - } -} - -#[derive(Debug, Eq, PartialEq)] -struct SnapshotTurnState { - ends_mid_turn: bool, - active_turn_id: Option, - active_turn_started_at: Option, - active_turn_root_id: Option, - active_turn_start_index: Option, -} - -fn snapshot_turn_state(history: &InitialHistory) -> SnapshotTurnState { - let rollout_items = history.get_rollout_items(); - let mut builder = ThreadHistoryBuilder::new(); - for item in rollout_items { - builder.handle_rollout_item(item); - } - let active_turn_id = builder.active_turn_id_if_explicit(); - if builder.has_active_turn() && active_turn_id.is_some() { - let active_turn_snapshot = builder.active_turn_snapshot(); - if active_turn_snapshot - .as_ref() - .is_some_and(|turn| turn.status != TurnStatus::InProgress) - { - return SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }; - } - - return SnapshotTurnState { - ends_mid_turn: true, - active_turn_id, - active_turn_started_at: active_turn_snapshot - .as_ref() - .and_then(|turn| turn.started_at), - active_turn_root_id: active_turn_snapshot.and_then(|turn| turn.root_turn_id), - active_turn_start_index: builder.active_turn_start_index(), - }; - } - - let Some(last_user_position) = truncation::user_message_positions_in_rollout(rollout_items) - .last() - .copied() - else { - return SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }; - }; - - // Synthetic fork/resume histories can contain user/assistant response items - // without explicit turn lifecycle events. If the persisted snapshot has no - // terminating boundary after its last user message, treat it as mid-turn. - SnapshotTurnState { - ends_mid_turn: !rollout_items[last_user_position + 1..].iter().any(|item| { - matches!( - item.event_msg(), - Some(EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_)) - ) - }), - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - } -} - -pub(crate) fn fork_history_from_snapshot( +fn fork_history_from_snapshot( snapshot: ForkSnapshot, history: InitialHistory, interrupted_marker: InterruptedTurnHistoryMarker, ) -> InitialHistory { - let snapshot_state = snapshot_turn_state(&history); + // Finish replay on the borrowed source before cloning any shared rollout records. + let source = history.get_rollout_items(); match snapshot { - ForkSnapshot::TruncateBeforeNthUserMessage(nth_user_message) => { - truncate_before_nth_user_message(history, nth_user_message, &snapshot_state) + ForkSnapshot::TruncateBeforeNthUserMessage(n) => { + let len = truncation::fork_prefix_len(source, n); + if len == 0 { + return InitialHistory::New; + } + let mut items = into_fork_items(history); + items.truncate(len); + InitialHistory::Forked(items) } ForkSnapshot::Interrupted => { - let history = match history { - InitialHistory::New => InitialHistory::New, - InitialHistory::Cleared => InitialHistory::Cleared, - InitialHistory::Forked(history) => InitialHistory::Forked(history), - InitialHistory::Resumed(resumed) => { - InitialHistory::Forked(Arc::unwrap_or_clone(resumed.history)) - } - }; - if snapshot_state.ends_mid_turn { - append_interrupted_boundary( - history, - snapshot_state.active_turn_id, - snapshot_state.active_turn_root_id, - snapshot_state.active_turn_started_at, - interrupted_marker, - ) - } else { - history + if matches!(history, InitialHistory::New | InitialHistory::Cleared) { + return history; } + let turn = truncation::unfinished_turn(source); + let mut items = into_fork_items(history); + if let Some(turn) = turn { + turn.close(&mut items, interrupted_marker); + } + InitialHistory::Forked(items) } } } -/// Append the same persisted interrupt boundary used by the live interrupt path -/// to an existing fork snapshot after the source thread has been confirmed to -/// be mid-turn. -fn append_interrupted_boundary( - history: InitialHistory, - turn_id: Option, - root_turn_id: Option, - started_at: Option, - interrupted_marker: InterruptedTurnHistoryMarker, -) -> InitialHistory { - let aborted_event = RolloutItem::EventMsg(EventMsg::TurnAborted(TurnAbortedEvent { - root_turn_id, - turn_id, - reason: TurnAbortReason::Interrupted, - error: None, - started_at, - completed_at: None, - duration_ms: None, - })); - +fn into_fork_items(history: InitialHistory) -> Vec { match history { - InitialHistory::New | InitialHistory::Cleared => { - let mut history = Vec::new(); - if let Some(marker) = - interrupted_turn_history_marker(interrupted_marker, /*cause*/ None) - { - history.push(RolloutItem::ResponseItem(marker.into())); - } - history.push(aborted_event); - InitialHistory::Forked(history) - } - InitialHistory::Forked(mut history) => { - if let Some(marker) = - interrupted_turn_history_marker(interrupted_marker, /*cause*/ None) - { - history.push(RolloutItem::ResponseItem(marker.into())); - } - history.push(aborted_event); - InitialHistory::Forked(history) - } - InitialHistory::Resumed(resumed) => { - let mut history = Arc::unwrap_or_clone(resumed.history); - if let Some(marker) = - interrupted_turn_history_marker(interrupted_marker, /*cause*/ None) - { - history.push(RolloutItem::ResponseItem(marker.into())); - } - history.push(aborted_event); - InitialHistory::Forked(history) - } + InitialHistory::New | InitialHistory::Cleared => Vec::new(), + InitialHistory::Resumed(resumed) => Arc::unwrap_or_clone(resumed.history), + InitialHistory::Forked(items) => items, } } diff --git a/codex-rs/core/src/thread_manager_tests.rs b/codex-rs/core/src/thread_manager_tests.rs index 16e66bf55b..83ed5ac764 100644 --- a/codex-rs/core/src/thread_manager_tests.rs +++ b/codex-rs/core/src/thread_manager_tests.rs @@ -16,7 +16,6 @@ use crate::rollout::RolloutRecorder; use crate::session::session::SessionSettingsUpdate; use crate::session::step_context::StepContext; use crate::session::tests::build_world_state_from_turn_context; -use crate::session::tests::make_session_and_context; use crate::tasks::InterruptedTurnHistoryMarker; use crate::tasks::interrupted_turn_history_marker; use crate::windows_sandbox::WindowsSandboxLevelExt; @@ -36,7 +35,6 @@ use codex_history::InitialHistory; use codex_history::ResumedHistory; use codex_models_manager::manager::ModelCatalogSettings; use codex_models_manager::manager::RefreshStrategy; -use codex_protocol::ResponseItemId; use codex_protocol::approvals::ExecPolicyAmendment; use codex_protocol::capabilities::CapabilityRootLocation; use codex_protocol::capabilities::SelectedCapabilityRoot; @@ -50,7 +48,6 @@ use codex_protocol::models::ContentItem; use codex_protocol::models::ContentItemKind; use codex_protocol::models::ContentItemMetadata; use codex_protocol::models::InternalChatMessageMetadataPassthrough; -use codex_protocol::models::ReasoningItemReasoningSummary; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelsResponse; use codex_protocol::protocol::AgentMessageEvent; @@ -62,6 +59,8 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnAbortedEvent; use codex_protocol::protocol::TurnStartedEvent; use codex_protocol::protocol::UserMessageEvent; use codex_thread_store::InMemoryThreadStore; @@ -1229,83 +1228,14 @@ fn effective_originator_prefers_thread_scoped_sources_before_env_originator() { } #[test] -fn truncates_before_requested_user_message() { - let items = [ - user_msg("u1"), - assistant_msg("a1"), - assistant_msg("a2"), - user_msg("u2"), - assistant_msg("a3"), - ResponseItem::Reasoning { - id: Some(ResponseItemId::with_suffix("rs", "1")), - summary: vec![ReasoningItemReasoningSummary::SummaryText { - text: "s".to_string(), - }], - content: None, - encrypted_content: None, - internal_chat_message_metadata_passthrough: None, - }, - ResponseItem::FunctionCall { - status: None, - encrypted_content: None, - id: None, - call_id: "c1".to_string(), - name: "tool".to_string(), - namespace: None, - arguments: "{}".to_string(), - encrypted_function_args: None, - internal_chat_message_metadata_passthrough: None, - }, - assistant_msg("a4"), - ]; - - let initial: Vec = items - .iter() - .cloned() - .map(|item| RolloutItem::ResponseItem(item.into())) - .collect(); - let truncated = truncate_before_nth_user_message( - InitialHistory::Forked(initial), - /*n*/ 1, - &SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, - ); - let got_items = truncated.get_rollout_items(); - let expected_items = vec![ - RolloutItem::ResponseItem(items[0].clone().into()), - RolloutItem::ResponseItem(items[1].clone().into()), - RolloutItem::ResponseItem(items[2].clone().into()), - ]; - assert_eq!( - serde_json::to_value(got_items).unwrap(), - serde_json::to_value(&expected_items).unwrap() - ); - - let initial2: Vec = items - .iter() - .cloned() - .map(|item| RolloutItem::ResponseItem(item.into())) - .collect(); - let truncated2 = truncate_before_nth_user_message( - InitialHistory::Forked(initial2.clone()), - /*n*/ 2, - &SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, - ); - assert_eq!( - serde_json::to_value(truncated2.get_rollout_items()).unwrap(), - serde_json::to_value(initial2).unwrap() +fn fork_before_first_user_message_with_empty_prefix_starts_new_history() { + let history = InitialHistory::Forked(vec![RolloutItem::ResponseItem(user_msg("hello").into())]); + let fork = fork_history_from_snapshot( + ForkSnapshot::TruncateBeforeNthUserMessage(0), + history, + InterruptedTurnHistoryMarker::Disabled, ); + assert!(matches!(fork, InitialHistory::New), "{fork:?}"); } #[test] @@ -1317,16 +1247,10 @@ fn out_of_range_truncation_drops_only_unfinished_suffix_mid_turn() { RolloutItem::ResponseItem(assistant_msg("partial").into()), ]; - let truncated = truncate_before_nth_user_message( + let truncated = fork_history_from_snapshot( + ForkSnapshot::TruncateBeforeNthUserMessage(usize::MAX), InitialHistory::Forked(items.clone()), - usize::MAX, - &SnapshotTurnState { - ends_mid_turn: true, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, + InterruptedTurnHistoryMarker::Disabled, ); assert_eq!( @@ -1367,22 +1291,10 @@ fn out_of_range_truncation_drops_pre_user_active_turn_prefix() { RolloutItem::ResponseItem(assistant_msg("partial").into()), ]; - let snapshot_state = snapshot_turn_state(&InitialHistory::Forked(items.clone())); - assert_eq!( - snapshot_state, - SnapshotTurnState { - ends_mid_turn: true, - active_turn_id: Some("turn-2".to_string()), - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: Some(2), - }, - ); - - let truncated = truncate_before_nth_user_message( + let truncated = fork_history_from_snapshot( + ForkSnapshot::TruncateBeforeNthUserMessage(usize::MAX), InitialHistory::Forked(items.clone()), - usize::MAX, - &snapshot_state, + InterruptedTurnHistoryMarker::Disabled, ); assert_eq!( @@ -1391,54 +1303,6 @@ fn out_of_range_truncation_drops_pre_user_active_turn_prefix() { ); } -#[tokio::test] -async fn ignores_session_prefix_messages_when_truncating() { - let (session, turn_context) = make_session_and_context().await; - let turn_context = Arc::new(turn_context); - let world_state = build_world_state_from_turn_context(&session, &turn_context).await; - let step_context = StepContext::for_test(turn_context); - let updates = session - .build_initial_context_with_world_state(&step_context, &world_state) - .await - .0; - let mut items = crate::context_manager::updates::merge_world_state_updates(updates); - items.push(user_msg("feature request")); - items.push(assistant_msg("ack")); - items.push(user_msg("second question")); - items.push(assistant_msg("answer")); - - let rollout_items: Vec = items - .iter() - .cloned() - .map(|item| RolloutItem::ResponseItem(item.into())) - .collect(); - - let truncated = truncate_before_nth_user_message( - InitialHistory::Forked(rollout_items), - /*n*/ 1, - &SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, - ); - let got_items = truncated.get_rollout_items(); - - let expected: Vec = vec![ - RolloutItem::ResponseItem(items[0].clone().into()), - RolloutItem::ResponseItem(items[1].clone().into()), - RolloutItem::ResponseItem(items[2].clone().into()), - RolloutItem::ResponseItem(items[3].clone().into()), - ]; - - assert_eq!( - serde_json::to_value(got_items).unwrap(), - serde_json::to_value(&expected).unwrap() - ); -} - #[tokio::test] async fn shutdown_all_threads_bounded_submits_shutdown_to_every_thread() { let temp_dir = tempdir().expect("tempdir"); @@ -3839,11 +3703,9 @@ fn interrupted_fork_snapshot_appends_interrupt_boundary() { assert_eq!( serde_json::to_value( - append_interrupted_boundary( + fork_history_from_snapshot( + ForkSnapshot::Interrupted, committed_history, - /*turn_id*/ None, - /*root_turn_id*/ None, - /*started_at*/ None, InterruptedTurnHistoryMarker::ContextualUser, ) .get_rollout_items() @@ -3864,32 +3726,6 @@ fn interrupted_fork_snapshot_appends_interrupt_boundary() { ]) .expect("serialize expected interrupted fork history"), ); - assert_eq!( - serde_json::to_value( - append_interrupted_boundary( - InitialHistory::New, - /*turn_id*/ None, - /*root_turn_id*/ None, - /*started_at*/ None, - InterruptedTurnHistoryMarker::ContextualUser, - ) - .get_rollout_items() - ) - .expect("serialize interrupted empty fork history"), - serde_json::to_value(vec![ - RolloutItem::ResponseItem(contextual_user_interrupted_marker().into()), - RolloutItem::EventMsg(EventMsg::TurnAborted(TurnAbortedEvent { - root_turn_id: None, - turn_id: None, - started_at: None, - reason: TurnAbortReason::Interrupted, - error: None, - completed_at: None, - duration_ms: None, - })), - ]) - .expect("serialize expected interrupted empty history"), - ); } #[test] @@ -3899,11 +3735,9 @@ fn disabled_interrupted_fork_snapshot_appends_only_interrupt_event() { assert_eq!( serde_json::to_value( - append_interrupted_boundary( + fork_history_from_snapshot( + ForkSnapshot::Interrupted, committed_history, - /*turn_id*/ None, - /*root_turn_id*/ None, - /*started_at*/ None, InterruptedTurnHistoryMarker::Disabled, ) .get_rollout_items() @@ -3923,31 +3757,25 @@ fn disabled_interrupted_fork_snapshot_appends_only_interrupt_event() { ]) .expect("serialize expected disabled interrupted fork history"), ); - assert_eq!( - serde_json::to_value( - append_interrupted_boundary( - InitialHistory::New, - /*turn_id*/ None, - /*root_turn_id*/ None, - /*started_at*/ None, - InterruptedTurnHistoryMarker::Disabled, - ) - .get_rollout_items() - ) - .expect("serialize disabled interrupted empty fork history"), - serde_json::to_value(vec![RolloutItem::EventMsg(EventMsg::TurnAborted( - TurnAbortedEvent { - root_turn_id: None, - turn_id: None, - started_at: None, - reason: TurnAbortReason::Interrupted, - error: None, - completed_at: None, - duration_ms: None, - }, - ))]) - .expect("serialize expected disabled interrupted empty fork history"), - ); +} + +#[test] +fn interrupted_fork_preserves_empty_history_variants() { + for history in [ + InitialHistory::New, + InitialHistory::Cleared, + InitialHistory::Forked(Vec::new()), + ] { + let fork = fork_history_from_snapshot( + ForkSnapshot::Interrupted, + history.clone(), + InterruptedTurnHistoryMarker::ContextualUser, + ); + assert_eq!( + serde_json::to_value(fork).unwrap(), + serde_json::to_value(history).unwrap() + ); + } } #[test] @@ -3967,15 +3795,14 @@ fn interrupted_snapshot_is_not_mid_turn() { })), ]); + let fork = fork_history_from_snapshot( + ForkSnapshot::Interrupted, + interrupted_history.clone(), + InterruptedTurnHistoryMarker::ContextualUser, + ); assert_eq!( - snapshot_turn_state(&interrupted_history), - SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, + serde_json::to_value(fork).unwrap(), + serde_json::to_value(interrupted_history).unwrap() ); } @@ -4029,15 +3856,14 @@ fn completed_legacy_event_history_is_not_mid_turn() { })), ]); + let fork = fork_history_from_snapshot( + ForkSnapshot::Interrupted, + completed_history.clone(), + InterruptedTurnHistoryMarker::ContextualUser, + ); assert_eq!( - snapshot_turn_state(&completed_history), - SnapshotTurnState { - ends_mid_turn: false, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, + serde_json::to_value(fork).unwrap(), + serde_json::to_value(completed_history).unwrap() ); } @@ -4055,16 +3881,21 @@ fn mixed_response_and_legacy_user_event_history_is_mid_turn() { })), ]); - assert_eq!( - snapshot_turn_state(&mixed_history), - SnapshotTurnState { - ends_mid_turn: true, - active_turn_id: None, - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: None, - }, + let fork = fork_history_from_snapshot( + ForkSnapshot::Interrupted, + mixed_history, + InterruptedTurnHistoryMarker::Disabled, ); + assert!(matches!( + fork.get_rollout_items() + .last() + .and_then(RolloutItem::event_msg), + Some(EventMsg::TurnAborted(TurnAbortedEvent { + turn_id: None, + reason: TurnAbortReason::Interrupted, + .. + })) + )); } #[tokio::test] @@ -4114,13 +3945,6 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor .thread .rollout_path() .expect("source rollout path should exist"); - let source_history = RolloutRecorder::get_rollout_history(&source_path) - .await - .expect("read source rollout history"); - let source_snapshot_state = snapshot_turn_state(&source_history); - assert!(source_snapshot_state.ends_mid_turn); - let expected_turn_id = source_snapshot_state.active_turn_id.clone(); - assert_eq!(expected_turn_id, None); let forked = manager .fork_legacy_thread( @@ -4137,7 +3961,6 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor let history = RolloutRecorder::get_rollout_history(&forked_path) .await .expect("read forked rollout history"); - assert!(!snapshot_turn_state(&history).ends_mid_turn); let rollout_items: Vec<_> = history .get_rollout_items() .iter() @@ -4150,7 +3973,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor let interrupted_abort_json = serde_json::to_value(RolloutItem::EventMsg( EventMsg::TurnAborted(TurnAbortedEvent { root_turn_id: None, - turn_id: expected_turn_id, + turn_id: None, started_at: None, reason: TurnAbortReason::Interrupted, error: None, @@ -4183,7 +4006,7 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor } #[tokio::test] -async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { +async fn interrupted_fork_snapshot_preserves_explicit_turn_metadata() { let temp_dir = tempdir().expect("tempdir"); let mut config = test_config().await; config.codex_home = temp_dir.path().join("codex-home").abs(); @@ -4221,9 +4044,9 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { turn_attribution: None, turn_id: "turn-explicit".to_string(), - root_turn_id: None, + root_turn_id: Some("root-turn".to_string()), trace_id: None, - started_at: None, + started_at: Some(100), model_context_window: None, collaboration_mode_kind: Default::default(), })), @@ -4238,20 +4061,6 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { .thread .rollout_path() .expect("source rollout path should exist"); - let source_history = RolloutRecorder::get_rollout_history(&source_path) - .await - .expect("read source rollout history"); - let source_snapshot_state = snapshot_turn_state(&source_history); - assert_eq!( - source_snapshot_state, - SnapshotTurnState { - ends_mid_turn: true, - active_turn_id: Some("turn-explicit".to_string()), - active_turn_started_at: None, - active_turn_root_id: None, - active_turn_start_index: Some(1), - }, - ); let forked = manager .fork_legacy_thread( @@ -4278,14 +4087,14 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() { matches!( item, RolloutItem::EventMsg { event: EventMsg::TurnAborted(TurnAbortedEvent { - root_turn_id: None, + root_turn_id: Some(root_turn_id), turn_id: Some(turn_id), - started_at: None, + started_at: Some(100), reason: TurnAbortReason::Interrupted, error: None, completed_at: None, duration_ms: None, - }), .. } if turn_id == "turn-explicit" + }), .. } if turn_id == "turn-explicit" && root_turn_id == "root-turn" ) })); } @@ -4337,10 +4146,6 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ .thread .rollout_path() .expect("source rollout path should exist"); - let source_history = RolloutRecorder::get_rollout_history(&source_path) - .await - .expect("read source rollout history"); - assert!(snapshot_turn_state(&source_history).ends_mid_turn); manager.remove_thread(&source.thread_id).await; let forked = manager @@ -4358,7 +4163,6 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_ let history = RolloutRecorder::get_rollout_history(&forked_path) .await .expect("read forked rollout history"); - assert!(!snapshot_turn_state(&history).ends_mid_turn); let forked_rollout_items: Vec<_> = history .get_rollout_items() diff --git a/codex-rs/core/src/thread_rollout_truncation.rs b/codex-rs/core/src/thread_rollout_truncation.rs index b365b406c2..84d7e4c5d5 100644 --- a/codex-rs/core/src/thread_rollout_truncation.rs +++ b/codex-rs/core/src/thread_rollout_truncation.rs @@ -1,10 +1,13 @@ -//! Helpers for truncating rollouts based on "user turn" boundaries. +//! Selects rollout prefixes and closes unfinished turns in forked history. //! //! In core, "user turns" are detected by scanning `ResponseItem::Message` items and //! interpreting them via `event_mapping::parse_turn_item(...)`. use crate::context_manager::is_instruction_turn_boundary; use crate::event_mapping; +use crate::tasks::InterruptedTurnHistoryMarker; +use crate::tasks::interrupted_turn_history_marker; +use codex_app_server_protocol::ThreadHistoryBuilder; use codex_app_server_protocol::TurnStatus; use codex_app_server_protocol::build_turns_from_rollout_items; use codex_history::InitialHistory; @@ -14,6 +17,8 @@ use codex_protocol::error::Result as CodexResult; use codex_protocol::items::TurnItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::EventMsg; +use codex_protocol::protocol::TurnAbortReason; +use codex_protocol::protocol::TurnAbortedEvent; pub(crate) fn initial_history_has_prior_user_turns(conversation_history: &InitialHistory) -> bool { conversation_history.scan_rollout_items(rollout_item_is_user_turn_boundary) @@ -40,7 +45,7 @@ fn rollout_item_is_user_turn_boundary(item: &RolloutItem) -> bool { /// Rollouts can contain `ThreadRolledBack` markers. Those markers indicate that the /// last N user turns were removed from the effective thread history; we apply them here so /// indexing uses the post-rollback history rather than the raw stream. -pub(crate) fn user_message_positions_in_rollout(items: &[RolloutItem]) -> Vec { +fn user_message_positions_in_rollout(items: &[RolloutItem]) -> Vec { let mut user_positions = Vec::new(); for (idx, item) in items.iter().enumerate() { match item { @@ -71,33 +76,76 @@ pub(crate) fn user_message_positions_in_rollout(items: &[RolloutItem]) -> Vec, - n_from_start: usize, -) -> Vec { - if n_from_start == usize::MAX { - return items; +/// Cut before user message `n`. If it is out of range, omit only the unfinished turn. +pub(crate) fn fork_prefix_len(items: &[RolloutItem], n: usize) -> usize { + user_message_positions_in_rollout(items) + .get(n) + .copied() + .or_else(|| unfinished_turn(items).map(|turn| turn.start_index)) + .unwrap_or(items.len()) +} + +pub(crate) struct UnfinishedTurn { + start_index: usize, + turn_id: Option, + root_turn_id: Option, + started_at: Option, +} + +impl UnfinishedTurn { + /// Close this turn in the fork's copy, writing the optional model-visible marker first. + pub(crate) fn close(self, items: &mut Vec, marker: InterruptedTurnHistoryMarker) { + if let Some(marker) = interrupted_turn_history_marker(marker, /*cause*/ None) { + items.push(RolloutItem::ResponseItem(marker.into())); + } + items.push(RolloutItem::EventMsg(EventMsg::TurnAborted( + TurnAbortedEvent { + root_turn_id: self.root_turn_id, + turn_id: self.turn_id, + reason: TurnAbortReason::Interrupted, + error: None, + started_at: self.started_at, + completed_at: None, + duration_ms: None, + }, + ))); + } +} + +pub(crate) fn unfinished_turn(items: &[RolloutItem]) -> Option { + let mut builder = ThreadHistoryBuilder::new(); + for item in items { + builder.handle_rollout_item(item); + } + if let Some(turn_id) = builder.active_turn_id_if_explicit() { + let metadata = builder.active_turn_metadata_snapshot()?; + if metadata.status != TurnStatus::InProgress { + return None; + } + return Some(UnfinishedTurn { + start_index: builder.active_turn_start_index()?, + turn_id: Some(turn_id), + root_turn_id: metadata.root_turn_id, + started_at: metadata.started_at, + }); } - let user_positions = user_message_positions_in_rollout(&items); - - // If fewer than or equal to n user messages exist, keep the full rollout. - if user_positions.len() <= n_from_start { - return items; + // Legacy histories can start with a user message and have no persisted turn ID. + let start_index = user_message_positions_in_rollout(items).last().copied()?; + if items[start_index + 1..].iter().any(|item| { + matches!( + item.event_msg(), + Some(EventMsg::TurnComplete(_) | EventMsg::TurnAborted(_)) + ) + }) { + return None; } - - // Cut strictly before the nth user message (do not keep the nth itself). - let cut_idx = user_positions[n_from_start]; - items.truncate(cut_idx); - items + Some(UnfinishedTurn { + start_index, + turn_id: None, + root_turn_id: None, + started_at: None, + }) } /// Return a rollout prefix ending after the requested persisted terminal turn. diff --git a/codex-rs/core/src/thread_rollout_truncation_tests.rs b/codex-rs/core/src/thread_rollout_truncation_tests.rs index a6ee1d1296..aeb5908adc 100644 --- a/codex-rs/core/src/thread_rollout_truncation_tests.rs +++ b/codex-rs/core/src/thread_rollout_truncation_tests.rs @@ -266,47 +266,24 @@ fn truncates_rollout_from_start_before_nth_user_only() { assistant_msg("a4"), ]; - let rollout: Vec = items.iter().cloned().map(response_item).collect(); + let mut rollout: Vec = items.into_iter().map(response_item).collect(); - let truncated = truncate_rollout_before_nth_user_message_from_start( - rollout.clone(), - /*n_from_start*/ 1, - ); - let expected = vec![ - response_item(items[0].clone()), - response_item(items[1].clone()), - response_item(items[2].clone()), - ]; - assert_eq!( - serde_json::to_value(&truncated).unwrap(), - serde_json::to_value(&expected).unwrap() - ); + assert_eq!(fork_prefix_len(&rollout, /*n*/ 1), 3); - let truncated2 = truncate_rollout_before_nth_user_message_from_start( - rollout.clone(), - /*n_from_start*/ 2, - ); - assert_eq!( - serde_json::to_value(&truncated2).unwrap(), - serde_json::to_value(&rollout).unwrap() - ); + rollout.push(turn_completed("turn-2")); + assert_eq!(fork_prefix_len(&rollout, /*n*/ 2), rollout.len()); } #[test] -fn truncation_max_keeps_full_rollout() { +fn truncation_max_keeps_completed_rollout() { let rollout = vec![ response_item(user_msg("u1")), response_item(assistant_msg("a1")), response_item(user_msg("u2")), + turn_completed("turn-2"), ]; - let truncated = - truncate_rollout_before_nth_user_message_from_start(rollout.clone(), usize::MAX); - - assert_eq!( - serde_json::to_value(&truncated).unwrap(), - serde_json::to_value(&rollout).unwrap() - ); + assert_eq!(fork_prefix_len(&rollout, usize::MAX), rollout.len()); } #[test] @@ -327,15 +304,7 @@ fn truncates_rollout_from_start_applies_thread_rollback_markers() { // Effective user history after applying rollback(1) is: u1, u3, u4. // So n_from_start=2 should cut before u4 (not u3). - let truncated = truncate_rollout_before_nth_user_message_from_start( - rollout_items.clone(), - /*n_from_start*/ 2, - ); - let expected = rollout_items[..7].to_vec(); - assert_eq!( - serde_json::to_value(&truncated).unwrap(), - serde_json::to_value(&expected).unwrap() - ); + assert_eq!(fork_prefix_len(&rollout_items, /*n*/ 2), 7); } #[tokio::test] @@ -351,22 +320,11 @@ async fn ignores_session_prefix_messages_when_truncating_rollout_from_start() { let mut items = crate::context_manager::updates::merge_world_state_updates(updates); items.push(user_msg("feature request")); items.push(assistant_msg("ack")); + let second_user_index = items.len(); items.push(user_msg("second question")); items.push(assistant_msg("answer")); - let rollout_items: Vec = items.iter().cloned().map(response_item).collect(); + let rollout_items: Vec = items.into_iter().map(response_item).collect(); - let truncated = - truncate_rollout_before_nth_user_message_from_start(rollout_items, /*n_from_start*/ 1); - let expected: Vec = vec![ - response_item(items[0].clone()), - response_item(items[1].clone()), - response_item(items[2].clone()), - response_item(items[3].clone()), - ]; - - assert_eq!( - serde_json::to_value(&truncated).unwrap(), - serde_json::to_value(&expected).unwrap() - ); + assert_eq!(fork_prefix_len(&rollout_items, /*n*/ 1), second_user_index); }