Record pre-sampling overhead in turn telemetry (#64799)

## What changed

Record `codex.turn.pre_sampling.duration_ms` when a sampling phase starts. Use the `is_first_sampling_request` label to distinguish overhead before the first request from overhead accumulated since the preceding request. The timing excludes tool blocking and compaction.

## Testing

Extend turn timing tests to verify the first-request duration, per-request overhead across subsequent requests, and the exclusion of tool blocking and compaction.

GitOrigin-RevId: 068be5cb4d1345dc064fa8f1df2469dfa0f3071f
This commit is contained in:
bkotsopoulos
2026-11-30 19:56:54 +00:00
committed by copyberry
parent e251a64500
commit 9b64b43207
5 changed files with 66 additions and 20 deletions
@@ -46,7 +46,10 @@ async fn interrupt_with_warning_exports_turn_profile_under_caller_span() -> anyh
turn.turn_timing_state
.mark_turn_started(std::time::Instant::now())
.await;
drop(turn.turn_timing_state.begin_sampling());
drop(
turn.turn_timing_state
.begin_sampling(&turn.session_telemetry),
);
turn.turn_timing_state.record_sampling_retry();
// Guardian uses this detached abort path rather than submitting Op::Interrupt.
session
+3 -1
View File
@@ -3194,7 +3194,9 @@ async fn try_run_sampling_request(
let effort = sess
.reasoning_effort_for_request(&step_context.settings, super::RequestEffortUsage::Sampling)
.await;
let sampling_timing_guard = turn_context.turn_timing_state.begin_sampling();
let sampling_timing_guard = turn_context
.turn_timing_state
.begin_sampling(&step_context.session_telemetry);
let mut response_id_for_assessment = None;
let mut answer_moderation: Option<codex_protocol::protocol::TargetedAnswerModeration> = None;
let mut pending_assessment: Option<codex_api::GuardianAssessment> = None;
+31 -9
View File
@@ -9,6 +9,8 @@ use std::time::UNIX_EPOCH;
use codex_analytics::IncompleteReason;
use codex_analytics::TurnProfile;
use codex_direct_tool_timing::DirectToolTimings;
use codex_otel::SessionTelemetry;
use codex_otel::TURN_PRE_SAMPLING_DURATION_METRIC;
use codex_otel::TURN_TTFM_DURATION_METRIC;
use codex_protocol::ThreadId;
use codex_protocol::items::TurnItem;
@@ -243,12 +245,27 @@ impl TurnTimingState {
.map(|duration| i64::try_from(duration.as_millis()).unwrap_or(i64::MAX))
}
pub(crate) fn begin_sampling(self: &Arc<Self>) -> TurnProfileTimingGuard {
let active = self.profile_state().begin_sampling(Instant::now());
pub(crate) fn begin_sampling(
self: &Arc<Self>,
telemetry: &SessionTelemetry,
) -> TurnProfileTimingGuard {
let pre_sampling = self.profile_state().begin_sampling(Instant::now());
if let Some((is_first_sampling_request, duration)) = pre_sampling {
let label_value = if is_first_sampling_request {
"true"
} else {
"false"
};
telemetry.record_duration(
TURN_PRE_SAMPLING_DURATION_METRIC,
duration,
&[("is_first_sampling_request", label_value)],
);
}
TurnProfileTimingGuard {
timing: Arc::clone(self),
phase: TurnProfilePhase::Sampling,
active,
active: pre_sampling.is_some(),
tool_batch: None,
}
}
@@ -356,21 +373,26 @@ impl TurnProfileState {
};
}
fn begin_sampling(&mut self, now: Instant) -> bool {
fn begin_sampling(&mut self, now: Instant) -> Option<(bool, Duration)> {
if self.completed_profile.is_some()
|| self.started_at.is_none()
|| self.active_phase.is_some()
{
return false;
return None;
}
self.advance(now);
if self.seen_sampling {
self.between_sampling_overhead += std::mem::take(&mut self.pending_idle_after_sampling);
}
let is_first_sampling_request = !self.seen_sampling;
let pre_sampling = if is_first_sampling_request {
self.before_first_sampling
} else {
let overhead = std::mem::take(&mut self.pending_idle_after_sampling);
self.between_sampling_overhead += overhead;
overhead
};
self.seen_sampling = true;
self.active_phase = Some(TurnProfilePhase::Sampling);
self.sampling_request_count = self.sampling_request_count.saturating_add(1);
true
Some((is_first_sampling_request, pre_sampling))
}
fn record_sampling_retry(&mut self) {
+27 -9
View File
@@ -236,7 +236,10 @@ fn turn_profile_breaks_down_sampling_blocking_and_retry_overhead() {
let mut state = TurnProfileState::default();
state.start(started_at);
let _ = state.begin_sampling(started_at + Duration::from_millis(100));
assert_eq!(
state.begin_sampling(started_at + Duration::from_millis(100)),
Some((true, Duration::from_millis(100)))
);
state.end_phase(
started_at + Duration::from_millis(600),
TurnProfilePhase::Sampling,
@@ -247,23 +250,35 @@ fn turn_profile_breaks_down_sampling_blocking_and_retry_overhead() {
TurnProfilePhase::ToolBlocking,
);
state.record_sampling_retry();
let _ = state.begin_sampling(started_at + Duration::from_millis(1_000));
assert_eq!(
state.begin_sampling(started_at + Duration::from_millis(1_000)),
Some((false, Duration::from_millis(100)))
);
state.end_phase(
started_at + Duration::from_millis(1_200),
TurnProfilePhase::Sampling,
);
assert_eq!(
state.complete(started_at + Duration::from_millis(1_300)),
state.begin_sampling(started_at + Duration::from_millis(1_250)),
Some((false, Duration::from_millis(50)))
);
state.end_phase(
started_at + Duration::from_millis(1_300),
TurnProfilePhase::Sampling,
);
assert_eq!(
state.complete(started_at + Duration::from_millis(1_400)),
TurnProfile {
critical_path: codex_analytics::TurnCriticalPath::Disabled,
before_first_sampling_ms: 100,
sampling_ms: 700,
sampling_ms: 750,
compaction_ms: 0,
between_sampling_overhead_ms: 100,
between_sampling_overhead_ms: 150,
tool_blocking_ms: 300,
after_last_sampling_ms: 100,
sampling_request_count: 2,
sampling_request_count: 3,
sampling_retry_count: 1,
tools_change_count: 0,
}
@@ -285,7 +300,10 @@ fn turn_profile_counts_compaction_as_an_exclusive_phase() {
started_at + Duration::from_millis(300),
TurnProfilePhase::Compaction,
);
let _ = state.begin_sampling(started_at + Duration::from_millis(400));
assert_eq!(
state.begin_sampling(started_at + Duration::from_millis(400)),
Some((true, Duration::from_millis(200)))
);
state.end_phase(
started_at + Duration::from_millis(700),
TurnProfilePhase::Sampling,
@@ -379,7 +397,7 @@ fn capture_preserves_phases_and_freezes_missing_dependencies() {
assert!(state.path_at(time_after_turn_start(10)).is_none());
state.capture_enabled = true;
state.path = Some(CriticalPath::default());
assert!(state.begin_sampling(time_after_turn_start(10)));
assert!(state.begin_sampling(time_after_turn_start(10)).is_some());
state.end_phase(time_after_turn_start(20), TurnProfilePhase::Sampling);
assert!(state.begin_tool_blocking(time_after_turn_start(20)));
state.end_phase(time_after_turn_start(50), TurnProfilePhase::ToolBlocking);
@@ -521,7 +539,7 @@ fn critical_path_report_retains_fractional_millisecond_rounding_and_compaction()
..Default::default()
};
state.start(start);
state.begin_sampling(start);
let _ = state.begin_sampling(start);
let compact_at = start + Duration::from_nanos(999_999);
state.end_phase(compact_at, TurnProfilePhase::Sampling);
state.begin_compaction(compact_at);
+1
View File
@@ -56,6 +56,7 @@ pub const REASONING_ITEMS_REMOVED_METRIC: &str = "codex.responses.reasoning_item
pub const TURN_E2E_DURATION_METRIC: &str = "codex.turn.e2e_duration_ms";
pub const TURN_TTFT_DURATION_METRIC: &str = "codex.turn.ttft.duration_ms";
pub const TURN_TTFM_DURATION_METRIC: &str = "codex.turn.ttfm.duration_ms";
pub const TURN_PRE_SAMPLING_DURATION_METRIC: &str = "codex.turn.pre_sampling.duration_ms";
pub const TURN_CRITICAL_PATH_CAPTURE_METRIC: &str = "codex.turn.critical_path.capture";
pub const TURN_CRITICAL_PATH_DURATION_METRIC: &str = "codex.turn.critical_path.duration_ms";
pub const TURN_CRITICAL_PATH_COMPONENT_METRIC: &str = "codex.turn.critical_path.component_ms";