Add critical-path snapshots for turn milestones (#64935)

## Why

The completed turn profile describes the whole turn. A host measuring latency
to an intermediate event needs the elapsed time and critical path at that event.

## What changed

Expose `turn_milestones` through `codex-core-api` and bind host-provided watches
when a regular turn starts. Add helpers to match published assistant text to
the sampled response and capture a one-shot observation with its source,
elapsed time, and critical path at the cutoff.

## Testing

Add tests that verify a cutoff during a second sampling round includes earlier
sampling and joined tool work, stale or cancelled candidates leave the watch
available, and elapsed time is recorded even when critical-path capture is
disabled.

GitOrigin-RevId: 507b7aaf8819b5cedf608ea66807c632bcb59c82
This commit is contained in:
akak-oai
2026-12-01 06:25:16 +00:00
committed by copyberry
parent 1ba4c7b4fb
commit 936ac6dbe6
10 changed files with 481 additions and 3 deletions
+1
View File
@@ -3166,6 +3166,7 @@ dependencies = [
"codex-thread-store",
"codex-tool-call-id",
"codex-tools",
"codex-turn-milestones",
"codex-user-input",
"codex-utils-absolute-path",
"codex-utils-audio",
+1
View File
@@ -323,6 +323,7 @@ codex-tool-call-id = { path = "tool-call-id" }
codex-tools = { path = "tools" }
codex-tcp-tunnel = { path = "tcp-tunnel" }
codex-tui = { path = "tui" }
codex-turn-milestones = { path = "turn-milestones" }
codex-uds = { path = "uds" }
codex-utils-absolute-path = { path = "utils/absolute-path" }
codex-utils-approval-presets = { path = "utils/approval-presets" }
+1
View File
@@ -90,6 +90,7 @@ pub use codex_core::init_state_db;
pub use codex_core::local_agent_graph_store_from_state_db;
pub use codex_core::passthrough_image_store;
pub use codex_core::resolve_installation_id;
pub use codex_core::turn_milestones;
pub use codex_exec_server::EnvironmentManager;
pub use codex_exec_server::EnvironmentRegistryConnectRequest;
pub use codex_exec_server::EnvironmentRegistryConnectResponse;
+1
View File
@@ -76,6 +76,7 @@ codex-terminal-detection = { workspace = true }
codex-thread-store = { workspace = true }
codex-tool-call-id = { workspace = true }
codex-tools = { workspace = true }
codex-turn-milestones = { workspace = true }
codex-user-input = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-audio = { workspace = true }
+1
View File
@@ -39,6 +39,7 @@ pub use thread_input::InputWaitOutcome;
mod turn_extension_data;
pub use agent::helper_daybreak::goal::GoalDaybreakSnapshot;
pub use turn_extension_data::WithTurnExtensionData;
pub use turn_timing::milestones as turn_milestones;
mod compact_model_fallback;
mod compact_pending_input;
mod compact_remote_history;
+8
View File
@@ -45,6 +45,7 @@ use crate::state::ActiveTurn;
use crate::state::RunningTask;
use crate::state::TaskKind;
use crate::turn_diff_tracker::TurnDiffTracker;
use crate::turn_milestones::TurnMilestoneWatches;
use codex_analytics::IncompleteReason;
use codex_analytics::TurnProfileFact;
use codex_analytics::TurnTokenUsageFact;
@@ -410,6 +411,13 @@ impl Session {
.await;
self.bind_realtime_handoffs_to_turn(&input, &turn_context.sub_id)
.await;
if task_kind == TaskKind::Regular
&& let Some(watches) = turn_context.extension_data.get::<TurnMilestoneWatches>()
{
turn_context
.turn_timing_state
.bind_milestone_watches(&watches);
}
let host_admission = self.host_turn_admission();
let (agent_execution_guard, task_input) = match &host_admission {
Some(_) => {
+8 -1
View File
@@ -94,6 +94,7 @@ pub(crate) struct TurnTimingState {
state: Mutex<TurnTimingStateInner>,
profile: StdMutex<TurnProfileState>,
critical_path_metrics: std::sync::OnceLock<()>,
milestone_watches: std::sync::OnceLock<Box<milestones::BoundMilestoneWatches>>,
}
#[derive(Debug, Default)]
@@ -115,6 +116,7 @@ struct TurnProfileState {
tool_dependency: Option<CriticalPath>,
started_at: Option<Instant>,
last_transition_at: Option<Instant>,
last_milestone_at: Option<Instant>,
active_phase: Option<TurnProfilePhase>,
seen_sampling: bool,
before_first_sampling: Duration,
@@ -485,7 +487,7 @@ impl TurnProfileState {
};
let mut profile = TurnProfile {
critical_path: report::completed_critical_path(self, now),
critical_path: report::critical_path(self, self.path.as_ref(), now),
before_first_sampling_ms: duration_to_u64_ms(self.before_first_sampling),
sampling_ms: duration_to_u64_ms(self.sampling),
compaction_ms: duration_to_u64_ms(self.compaction),
@@ -610,6 +612,11 @@ fn response_item_records_turn_ttft(item: &ResponseItem) -> bool {
}
}
#[allow(
dead_code,
reason = "Publication wiring lands in the next PR in the stack."
)]
pub mod milestones;
mod report;
pub(crate) mod review_execution;
+279
View File
@@ -0,0 +1,279 @@
//! Freezes the live Core turn path for a host-selected milestone. Claims are
//! serialized with phase transitions, while predicates and delivery run outside
//! the timing lock.
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::time::Instant;
use codex_protocol::ThreadId;
use codex_protocol::items::AgentMessageContent;
use codex_protocol::items::TurnItem;
use codex_protocol::protocol::EventMsg;
use codex_turn_milestones::Watch;
use codex_utils_critical_path::CriticalPath;
use tokio_util::sync::CancellationToken;
use super::TurnProfileState;
use super::TurnTimingState;
use super::report;
pub use codex_analytics::TurnCriticalPath;
pub use codex_analytics::TurnCriticalPathDurations;
pub use codex_turn_milestones::AssistantText;
pub use codex_turn_milestones::AssistantTextCandidate;
pub use codex_turn_milestones::DirectAppsToolStart;
pub use codex_turn_milestones::MilestoneSourceId;
pub use codex_turn_milestones::MilestoneWatches;
pub type TurnMilestoneWatches = codex_turn_milestones::TurnMilestoneWatches<TurnCriticalPath>;
pub type MilestoneObservation = codex_turn_milestones::MilestoneObservation<TurnCriticalPath>;
pub(super) type ActiveMilestoneWatches =
codex_turn_milestones::ActiveMilestoneWatches<TurnCriticalPath>;
impl TurnTimingState {
pub(crate) fn bind_milestone_watches(&self, registration: &TurnMilestoneWatches) {
if let Some(watches) = registration.take() {
let _ = self.milestone_watches.set(Box::new(BoundMilestoneWatches {
watches: *watches,
sampled_text: Mutex::new(None),
}));
}
}
}
struct MilestoneCapture<'a> {
timing: &'a TurnTimingState,
watches: &'a ActiveMilestoneWatches,
thread_id: ThreadId,
turn_id: &'a str,
cancellation: &'a CancellationToken,
}
impl<'a> MilestoneCapture<'a> {
fn new(
timing: &'a TurnTimingState,
thread_id: ThreadId,
turn_id: &'a str,
cancellation: &'a CancellationToken,
) -> Option<Self> {
Some(Self {
timing,
watches: &timing.milestone_watches.get()?.watches,
thread_id,
turn_id,
cancellation,
})
}
fn capture<P>(
&self,
watch: &Watch<P>,
clock: impl FnOnce() -> Instant,
path_at: impl FnOnce(&TurnProfileState, Instant) -> Option<CriticalPath>,
source: impl FnOnce() -> MilestoneSourceId,
) -> Option<MilestoneObservation> {
let mut state = self.timing.profile_state();
let cutoff = clock();
let elapsed = cutoff.checked_duration_since(state.started_at?)?;
if state.completed_profile.is_some()
|| state.last_transition_at.is_some_and(|at| cutoff < at)
|| state.last_milestone_at.is_some_and(|at| cutoff < at)
|| self.cancellation.is_cancelled()
|| !watch.try_claim()
{
return None;
}
state.last_milestone_at = Some(cutoff);
let path = path_at(&state, cutoff);
let critical_path = report::critical_path(&state, path.as_ref(), cutoff);
drop(state);
Some(MilestoneObservation {
thread_id: self.thread_id,
turn_id: self.turn_id.to_owned(),
source: source(),
cutoff,
elapsed,
critical_path,
})
}
}
#[derive(Debug)]
pub(super) struct BoundMilestoneWatches {
watches: ActiveMilestoneWatches,
sampled_text: Mutex<Option<SampledTextResponse>>,
}
impl BoundMilestoneWatches {
fn sampled_text(&self) -> MutexGuard<'_, Option<SampledTextResponse>> {
self.sampled_text
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
#[derive(Clone, Debug)]
struct ResponseOrigin {
response_id: Option<Arc<str>>,
cancellation: CancellationToken,
}
#[derive(Debug)]
struct SampledTextResponse {
origin: ResponseOrigin,
items: HashSet<String>,
}
/// The sampling loop drains its publications before another response takes ownership.
pub(crate) struct SampledTextScope<'a>(&'a BoundMilestoneWatches);
impl SampledTextScope<'_> {
pub(crate) fn set_response_id(&self, response_id: Option<&str>) {
if let Some(response) = self.0.sampled_text().as_mut() {
response.origin.response_id = response_id.map(Arc::from);
}
}
pub(crate) fn fill_response_id(&self, response_id: &str) {
if let Some(response) = self.0.sampled_text().as_mut() {
response
.origin
.response_id
.get_or_insert_with(|| Arc::from(response_id));
}
}
pub(crate) fn reset_for_retry(&self) {
if let Some(response) = self.0.sampled_text().as_mut() {
response.origin.response_id = None;
response.items.clear();
}
}
}
impl Drop for SampledTextScope<'_> {
fn drop(&mut self) {
self.0.sampled_text().take();
}
}
impl TurnTimingState {
pub(crate) fn track_sampled_text(
&self,
cancellation: &CancellationToken,
) -> Option<SampledTextScope<'_>> {
let bound = self.milestone_watches.get()?;
bound.watches.assistant_text()?;
let mut sampled_text = bound.sampled_text();
debug_assert!(
sampled_text.is_none(),
"sampled text responses must publish in order"
);
*sampled_text = Some(SampledTextResponse {
origin: ResponseOrigin {
response_id: None,
cancellation: cancellation.clone(),
},
items: HashSet::new(),
});
Some(SampledTextScope(bound))
}
/// Called when the sampler has the canonical item ID, including final-only items.
pub(crate) fn remember_sampled_assistant_item(&self, item: &TurnItem) {
if let TurnItem::AgentMessage(message) = item
&& let Some(bound) = self.milestone_watches.get()
&& bound.watches.assistant_text().is_some()
&& let Some(response) = bound.sampled_text().as_mut()
&& !response.items.contains(message.id.as_str())
{
response.items.insert(message.id.clone());
}
}
pub(crate) fn match_published_assistant_text<'a>(
&'a self,
turn_id: &str,
msg: &'a EventMsg,
) -> Option<MatchedAssistantText<'a>> {
let bound = self.milestone_watches.get()?;
let watch = bound.watches.assistant_text()?;
let matches = |item_id: &'a str, text: &str| {
if text.is_empty() {
return None;
}
let origin = {
let sampled_text = bound.sampled_text();
let response = sampled_text.as_ref()?;
if !response.items.contains(item_id) || response.origin.cancellation.is_cancelled()
{
return None;
}
response.origin.clone()
};
watch
.matches(AssistantTextCandidate {
text,
response_id: origin.response_id.as_deref(),
item_id,
})
.then_some(MatchedAssistantText {
bound,
origin,
item_id,
})
};
let item = match msg {
EventMsg::AgentMessageContentDelta(delta) if delta.turn_id == turn_id => {
return matches(&delta.item_id, &delta.delta);
}
EventMsg::ItemStarted(event) if event.turn_id == turn_id => &event.item,
EventMsg::ItemCompleted(event) if event.turn_id == turn_id => &event.item,
_ => return None,
};
let TurnItem::AgentMessage(message) = item else {
return None;
};
message
.content
.iter()
.find_map(|AgentMessageContent::Text { text }| matches(&message.id, text))
}
}
pub(crate) struct MatchedAssistantText<'a> {
bound: &'a BoundMilestoneWatches,
origin: ResponseOrigin,
item_id: &'a str,
}
impl MatchedAssistantText<'_> {
pub(crate) fn capture(
&self,
timing: &TurnTimingState,
thread_id: ThreadId,
turn_id: &str,
) -> Option<MilestoneObservation> {
let capture = MilestoneCapture::new(timing, thread_id, turn_id, &self.origin.cancellation)?;
let watch = capture.watches.assistant_text()?;
capture.capture(watch, Instant::now, TurnProfileState::path_at, || {
MilestoneSourceId::AssistantText {
response_id: self.origin.response_id.as_deref().map(str::to_owned),
item_id: self.item_id.to_owned(),
}
})
}
pub(crate) fn deliver(self, observation: MilestoneObservation) {
self.bound.sampled_text().take();
self.bound.watches.deliver(observation);
}
}
#[cfg(test)]
#[path = "milestones_tests.rs"]
mod tests;
@@ -0,0 +1,174 @@
#![cfg(test)]
use super::*;
use crate::turn_timing::TurnProfilePhase;
use codex_analytics::IncompleteReason;
use codex_utils_critical_path::WorkKind;
use pretty_assertions::assert_eq;
use std::time::Duration;
fn bind_watches<'a>(
timing: &'a TurnTimingState,
cancellation: &'a CancellationToken,
) -> MilestoneCapture<'a> {
timing.bind_milestone_watches(&TurnMilestoneWatches::new(
MilestoneWatches {
assistant_text: Some(AssistantText::new(|_| true)),
direct_apps_tool_start: Some(DirectAppsToolStart::new(|_| true)),
},
|_| {},
));
MilestoneCapture::new(timing, ThreadId::new(), "turn", cancellation).unwrap()
}
fn text() -> MilestoneSourceId {
MilestoneSourceId::AssistantText {
response_id: Some("response-b".to_owned()),
item_id: "message".to_owned(),
}
}
fn breakdown(sampling_ms: u64, tools_ms: u64) -> TurnCriticalPath {
TurnCriticalPath::Complete(TurnCriticalPathDurations {
duration_ms: sampling_ms + tools_ms,
inference_ms: sampling_ms,
sampling_ms,
compaction_ms: 0,
auto_review_ms: 0,
auto_review_overhead_ms: Some(0),
user_wait_ms: 0,
tools_ms,
overhead_ms: 0,
unknown_ms: 0,
})
}
#[test]
fn round_b_cutoff_includes_round_a_and_joined_tool_work() {
let timing = TurnTimingState::default();
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
timing.enable_critical_path();
{
let mut state = timing.profile_state();
state.start(start);
assert!(state.begin_sampling(start).is_some());
state.end_phase(at(40), TurnProfilePhase::Sampling);
assert!(state.begin_tool_blocking(at(40)));
state.tool_dependency = state
.path_at(at(40))
.map(|prefix| prefix.work(at(40), at(70), WorkKind::Tools));
state.end_phase(at(70), TurnProfilePhase::ToolBlocking);
assert!(state.begin_sampling(at(70)).is_some());
}
let cancellation = CancellationToken::new();
let capture = bind_watches(&timing, &cancellation);
let watch = capture.watches.assistant_text().unwrap();
let captured = capture
.capture(watch, || at(90), TurnProfileState::path_at, text)
.unwrap();
{
let mut state = timing.profile_state();
state.end_phase(at(130), TurnProfilePhase::Sampling);
assert_eq!(
state.complete(at(130)).critical_path,
breakdown(/*sampling_ms*/ 100, /*tools_ms*/ 30)
);
}
assert_eq!(
captured,
MilestoneObservation {
thread_id: capture.thread_id,
turn_id: "turn".to_owned(),
source: text(),
cutoff: at(90),
elapsed: Duration::from_millis(90),
critical_path: breakdown(/*sampling_ms*/ 60, /*tools_ms*/ 30),
}
);
}
#[test]
fn stale_and_cancelled_candidates_leave_the_second_source_available() {
let timing = TurnTimingState::default();
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
timing.enable_critical_path();
timing.profile_state().start(start);
assert!(timing.profile_state().begin_sampling(start).is_some());
let cancellation = CancellationToken::new();
let capture = bind_watches(&timing, &cancellation);
let watch = capture.watches.direct_apps_tool_start().unwrap();
let tool = || MilestoneSourceId::DirectToolStart {
call_id: "call".to_owned(),
resource_uri: "app://send".to_owned(),
response_attempt_id: Some(3),
};
let first = capture
.capture(watch, || at(20), TurnProfileState::path_at, tool)
.unwrap();
assert!(
capture
.capture(watch, || at(25), TurnProfileState::path_at, tool)
.is_none()
);
let watch = capture.watches.assistant_text().unwrap();
assert!(
capture
.capture(watch, || at(10), TurnProfileState::path_at, text)
.is_none()
);
let cancelled = CancellationToken::new();
cancelled.cancel();
let rejected = MilestoneCapture {
cancellation: &cancelled,
..capture
};
assert!(
rejected
.capture(watch, || at(26), TurnProfileState::path_at, text)
.is_none()
);
timing.invalidate_critical_path(&[IncompleteReason::UnsupportedOperation]);
assert_eq!(
capture.capture(watch, || at(30), TurnProfileState::path_at, text),
Some(MilestoneObservation {
thread_id: capture.thread_id,
turn_id: "turn".to_owned(),
source: text(),
cutoff: at(30),
elapsed: Duration::from_millis(30),
critical_path: TurnCriticalPath::Incomplete(vec![
IncompleteReason::UnsupportedOperation
]),
})
);
assert_eq!(
first.critical_path,
breakdown(/*sampling_ms*/ 20, /*tools_ms*/ 0)
);
}
#[test]
fn capture_disabled_still_records_elapsed_time() {
let timing = TurnTimingState::default();
let start = Instant::now();
timing.profile_state().start(start);
let cancellation = CancellationToken::new();
let capture = bind_watches(&timing, &cancellation);
let watch = capture.watches.assistant_text().unwrap();
let cutoff = start + Duration::from_millis(10);
assert_eq!(
capture.capture(watch, || cutoff, TurnProfileState::path_at, text),
Some(MilestoneObservation {
thread_id: capture.thread_id,
turn_id: "turn".to_owned(),
source: text(),
cutoff,
elapsed: Duration::from_millis(10),
critical_path: TurnCriticalPath::Disabled,
})
);
}
+7 -2
View File
@@ -8,13 +8,18 @@ use codex_analytics::TurnCriticalPathDurations;
use codex_otel::TURN_CRITICAL_PATH_CAPTURE_METRIC;
use codex_otel::TURN_CRITICAL_PATH_COMPONENT_METRIC;
use codex_otel::TURN_CRITICAL_PATH_DURATION_METRIC;
use codex_utils_critical_path::CriticalPath;
use std::time::Instant;
pub(super) fn completed_critical_path(state: &TurnProfileState, end: Instant) -> TurnCriticalPath {
pub(super) fn critical_path(
state: &TurnProfileState,
path: Option<&CriticalPath>,
end: Instant,
) -> TurnCriticalPath {
if !state.capture_enabled {
return TurnCriticalPath::Disabled;
}
let (Some(path), Some(start)) = (&state.path, state.started_at) else {
let (Some(path), Some(start)) = (path, state.started_at) else {
let mut reasons = state.incomplete_reasons.clone();
if state.started_at.is_none() && !reasons.contains(&IncompleteReason::MissingTurnStart) {
reasons.push(IncompleteReason::MissingTurnStart);