Files
codex/codex-rs/core/src/thread_rollout_truncation.rs
T
jif ae78265f08 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
2026-11-30 09:40:54 +00:00

265 lines
9.2 KiB
Rust

//! 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;
use codex_history::RolloutItem;
use codex_protocol::error::CodexErr;
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)
}
fn rollout_item_is_user_turn_boundary(item: &RolloutItem) -> bool {
match item {
RolloutItem::ResponseItem(item) => is_instruction_turn_boundary(item),
RolloutItem::Compacted(checkpoint) => checkpoint
.replacement_history
.iter()
.flatten()
.any(is_instruction_turn_boundary),
RolloutItem::InterAgentCommunication(_) => true,
_ => false,
}
}
/// Return the indices of user message boundaries in a rollout.
///
/// A user message boundary is a `RolloutItem::ResponseItem(ResponseItem::Message { .. })`
/// whose parsed turn item is `TurnItem::UserMessage`.
///
/// 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.
fn user_message_positions_in_rollout(items: &[RolloutItem]) -> Vec<usize> {
let mut user_positions = Vec::new();
for (idx, item) in items.iter().enumerate() {
match item {
RolloutItem::ResponseItem(item)
if !item
.metadata
.as_ref()
.is_some_and(|metadata| metadata.realtime_session_end_input)
&& matches!(&item.item, ResponseItem::Message { .. })
&& matches!(
event_mapping::parse_turn_item(&item.item),
Some(TurnItem::UserMessage(_))
) =>
{
user_positions.push(idx);
}
RolloutItem::EventMsg {
event: EventMsg::ThreadRolledBack(rollback),
..
} => {
let num_turns = usize::try_from(rollback.num_turns).unwrap_or(usize::MAX);
let new_len = user_positions.len().saturating_sub(num_turns);
user_positions.truncate(new_len);
}
_ => {}
}
}
user_positions
}
/// 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<String>,
root_turn_id: Option<String>,
started_at: Option<i64>,
}
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<RolloutItem>, 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<UnfinishedTurn> {
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,
});
}
// 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;
}
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.
///
/// The turn must still be present in the effective post-rollback history and
/// must have an explicit persisted TurnStarted boundary. Synthetic IDs
/// generated while projecting legacy rollouts are intentionally unsupported
/// because they do not provide a stable raw rollout boundary for a fork.
pub fn truncate_rollout_after_turn_id(
mut items: Vec<RolloutItem>,
last_turn_id: &str,
) -> CodexResult<Vec<RolloutItem>> {
let turns = build_turns_from_rollout_items(&items);
let turn = turns
.iter()
.find(|turn| turn.id == last_turn_id)
.ok_or_else(|| {
CodexErr::InvalidRequest(format!(
"lastTurnId '{last_turn_id}' was not found in the source thread"
))
})?;
let target_start_index = items
.iter()
.position(|item| {
matches!(
item,
RolloutItem::EventMsg { event: EventMsg::TurnStarted(event), .. }
if event.turn_id == last_turn_id
)
})
.ok_or_else(|| {
CodexErr::InvalidRequest(format!(
"lastTurnId '{last_turn_id}' is not a persisted canonical turn in the source thread"
))
})?;
if matches!(turn.status, TurnStatus::InProgress) {
return Err(CodexErr::InvalidRequest(format!(
"lastTurnId '{last_turn_id}' identifies an in-progress turn"
)));
}
let cut_index = items
.iter()
.enumerate()
.skip(target_start_index.saturating_add(1))
.find_map(|(index, item)| {
matches!(
item,
RolloutItem::EventMsg {
event: EventMsg::TurnStarted(_),
..
}
)
.then_some(index)
})
.unwrap_or(items.len());
items.truncate(cut_index);
Ok(items)
}
/// Return a rollout prefix ending immediately before the requested persisted turn.
pub fn truncate_rollout_before_turn_id(
mut items: Vec<RolloutItem>,
before_turn_id: &str,
) -> CodexResult<Vec<RolloutItem>> {
let cut_index = items.iter().position(|item| {
matches!(
item,
RolloutItem::EventMsg { event: EventMsg::TurnStarted(event), .. }
if event.turn_id == before_turn_id
)
});
let Some(cut_index) = cut_index else {
// Older rollouts can expose generated turn IDs without a TurnStarted item to fork at.
if build_turns_from_rollout_items(&items)
.iter()
.any(|turn| turn.id == before_turn_id)
{
return Err(CodexErr::InvalidRequest(format!(
"beforeTurnId '{before_turn_id}' is not a persisted canonical turn in the source thread"
)));
}
return Err(CodexErr::InvalidRequest(format!(
"beforeTurnId '{before_turn_id}' was not found in the source thread"
)));
};
// A persisted turn boundary proves the turn exists unless a later rollback removes it.
if items[cut_index + 1..].iter().any(|item| {
matches!(
item,
RolloutItem::EventMsg {
event: EventMsg::ThreadRolledBack(_),
..
}
)
}) && !build_turns_from_rollout_items(&items)
.iter()
.any(|turn| turn.id == before_turn_id)
{
return Err(CodexErr::InvalidRequest(format!(
"beforeTurnId '{before_turn_id}' was not found in the source thread"
)));
}
items.truncate(cut_index);
Ok(items)
}
#[cfg(test)]
#[path = "thread_rollout_truncation_tests.rs"]
mod tests;