Keep plan item IDs unique after completion (#61186)

## Why

Plan items used a single ID derived from the turn ID, so multiple completed plans within one turn shared an ID across retries or tool continuations.

## What changed

Generate UUIDv7 plan item IDs and carry an unfinished plan's ID across model requests within a turn. Once a plan completes, assign a fresh ID to the next plan.

## Testing

Add unit and integration coverage for unfinished retries, retries after plan completion, and tool continuations, including matching streamed events to saved completions. Update the app-server test to check plan IDs against the start notification.

GitOrigin-RevId: 87b4b3e6bd74224ea96f4308f739bcd2efb62299
This commit is contained in:
neerajrj-oai
2026-11-12 21:40:33 +00:00
committed by copyberry
parent d4242793f7
commit d0221bc947
4 changed files with 277 additions and 14 deletions
+20 -9
View File
@@ -156,6 +156,7 @@ use tracing::instrument;
use tracing::trace;
use tracing::trace_span;
use tracing::warn;
use uuid::Uuid;
const POST_SAMPLING_TOKEN_ESTIMATE_TARGET: &str = "codex_core::post_sampling_token_estimate";
@@ -540,6 +541,7 @@ pub(crate) async fn run_turn(
let mut next_step_context = Some(first_step_context);
let mut guardian_budget_compacted = false;
let mut unfinished_plan_id = None;
loop {
// Note that pending_input would be something like a message the user
// submitted through the UI while the model was running. Though the UI
@@ -651,6 +653,7 @@ pub(crate) async fn run_turn(
Arc::clone(&turn_diff_tracker),
&mut client_session,
sampling_request_input,
&mut unfinished_plan_id,
cancellation_token.child_token(),
)
.await
@@ -1895,6 +1898,7 @@ async fn run_sampling_request(
turn_diff_tracker: SharedTurnDiffTracker,
client_session: &mut ModelClientSession,
input: crate::context_manager::ContextManager,
unfinished_plan_id: &mut Option<String>,
cancellation_token: CancellationToken,
) -> CodexResult<(SamplingRequestResult, Vec<String>)> {
let turn_context = Arc::clone(&step_context.turn);
@@ -2016,6 +2020,7 @@ async fn run_sampling_request(
prompt,
pending_audio,
input_item_count,
unfinished_plan_id,
cancellation_token.child_token(),
&mut draining_for_mailbox,
)
@@ -2259,12 +2264,16 @@ struct PlanModeStreamState {
}
impl PlanModeStreamState {
fn new(turn_id: &str) -> Self {
fn new(unfinished_plan_id: Option<String>) -> Self {
Self {
pending_agent_message_items: HashMap::new(),
started_agent_message_items: HashSet::new(),
leading_whitespace_by_item: HashMap::new(),
plan_item_state: ProposedPlanItemState::new(turn_id),
plan_item_state: ProposedPlanItemState {
item_id: unfinished_plan_id.unwrap_or_else(|| Uuid::now_v7().to_string()),
started: false,
completed: false,
},
}
}
}
@@ -2320,12 +2329,9 @@ impl AssistantMessageStreamParsers {
}
impl ProposedPlanItemState {
fn new(turn_id: &str) -> Self {
Self {
item_id: format!("{turn_id}-plan"),
started: false,
completed: false,
}
/// Keep the ID across model requests until a completion claims it.
fn unfinished_id(self) -> Option<String> {
(!self.completed).then_some(self.item_id)
}
async fn start(&mut self, sess: &Session, turn_context: &TurnContext) {
@@ -2898,6 +2904,7 @@ async fn try_run_sampling_request(
prompt: Prompt,
mut pending_audio: Option<codex_history::AcceptedFileAudio>,
input_item_count: usize,
unfinished_plan_id: &mut Option<String>,
cancellation_token: CancellationToken,
draining_for_mailbox: &mut bool,
) -> CodexResult<SamplingRequestResult> {
@@ -3058,7 +3065,8 @@ async fn try_run_sampling_request(
.unwrap_or_else(|| "default".to_string());
let plan_mode = turn_context.mode() == ModeKind::Plan;
let mut assistant_message_stream_parsers = AssistantMessageStreamParsers::new(plan_mode);
let mut plan_mode_state = plan_mode.then(|| PlanModeStreamState::new(&turn_context.sub_id));
let mut plan_mode_state =
plan_mode.then(|| PlanModeStreamState::new(unfinished_plan_id.clone()));
let defer_streamed_turn_items_for_contributors =
!sess.services.extensions.turn_item_contributors().is_empty();
let mut active_item_is_streaming_to_client = false;
@@ -3791,6 +3799,9 @@ async fn try_run_sampling_request(
&mut assistant_message_stream_parsers,
)
.await;
if let Some(state) = plan_mode_state {
*unfinished_plan_id = state.plan_item_state.unfinished_id();
}
if !in_flight.is_empty() {
let _tool_blocking_timing_guard = turn_context
+65 -1
View File
@@ -3,6 +3,8 @@ use codex_extension_api::ExtensionData;
use codex_extension_api::TurnItemContributor;
use codex_protocol::ResponseItemId;
use codex_protocol::items::AgentMessageContent;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ItemStartedEvent;
use pretty_assertions::assert_eq;
use std::sync::Arc;
use tracing_subscriber::prelude::*;
@@ -71,7 +73,7 @@ async fn plan_mode_uses_contributed_turn_item_for_last_agent_message() {
builder.turn_item_contributor(Arc::new(RewriteAgentMessageContributor));
session.services.extensions = Arc::new(builder.build());
let turn_store = ExtensionData::new(turn_context.sub_id.clone());
let mut state = PlanModeStreamState::new(&turn_context.sub_id);
let mut state = PlanModeStreamState::new(/*unfinished_plan_id*/ None);
let mut last_agent_message = None;
let item = assistant_output_text("original assistant text");
@@ -95,6 +97,68 @@ async fn plan_mode_uses_contributed_turn_item_for_last_agent_message() {
);
}
/// A model retry can reuse an unfinished plan. A later completion must use its own ID.
#[tokio::test]
async fn plan_attempts_only_reuse_unfinished_item_ids() {
let (session, turn, events) = crate::session::tests::make_session_and_context_with_rx().await;
let mut first = PlanModeStreamState::new(/*unfinished_plan_id*/ None).plan_item_state;
let first_id = first.item_id.clone();
first.start(&session, &turn).await;
first.push_delta(&session, &turn, "Partial").await;
let mut retry = PlanModeStreamState::new(first.unfinished_id()).plan_item_state;
retry.start(&session, &turn).await;
retry.push_delta(&session, &turn, "Plan A").await;
retry
.complete_with_text(&session, &turn, "Plan A".into())
.await;
retry
.complete_with_text(&session, &turn, "Repeated A".into())
.await;
let mut next = PlanModeStreamState::new(retry.unfinished_id()).plan_item_state;
next.start(&session, &turn).await;
next.push_delta(&session, &turn, "Plan B").await;
next.complete_with_text(&session, &turn, "Plan B".into())
.await;
let mut observed = Vec::new();
while let Ok(event) = events.try_recv() {
match event.msg {
EventMsg::ItemStarted(ItemStartedEvent {
item: TurnItem::Plan(plan),
..
}) => {
observed.push(("start", plan.id, plan.text));
}
EventMsg::PlanDelta(event) => observed.push(("delta", event.item_id, event.delta)),
EventMsg::ItemCompleted(ItemCompletedEvent {
item: TurnItem::Plan(plan),
..
}) => {
observed.push(("complete", plan.id, plan.text));
}
_ => {}
}
}
let next_id = next.item_id;
assert_eq!(Uuid::parse_str(&first_id).unwrap().get_version_num(), 7);
assert_ne!(first_id, next_id);
assert_eq!(
observed,
vec![
("start", first_id.clone(), String::new()),
("delta", first_id.clone(), "Partial".into()),
("start", first_id.clone(), String::new()),
("delta", first_id.clone(), "Plan A".into()),
("complete", first_id, "Plan A".into()),
("start", next_id.clone(), String::new()),
("delta", next_id.clone(), "Plan B".into()),
("complete", next_id, "Plan B".into()),
],
);
}
#[test]
fn realtime_user_verification_notice_excludes_request_payload() {
let event = EventMsg::ElicitationRequest(codex_protocol::approvals::ElicitationRequestEvent {