diff --git a/codex-rs/analytics/src/analytics_client_tests.rs b/codex-rs/analytics/src/analytics_client_tests.rs index e94d69ed5b..6a8e4b911a 100644 --- a/codex-rs/analytics/src/analytics_client_tests.rs +++ b/codex-rs/analytics/src/analytics_client_tests.rs @@ -403,6 +403,12 @@ fn sample_turn_profile() -> TurnProfile { before_first_sampling_ms: 100, sampling_ms: 700, between_sampling_overhead_ms: 50, + between_sampling_post_response_ms: 10, + between_sampling_retry_ms: 10, + between_sampling_compaction_ms: 10, + between_sampling_follow_up_ms: 10, + between_sampling_request_preparation_ms: 5, + between_sampling_other_ms: 5, tool_blocking_ms: 250, after_last_sampling_ms: 134, sampling_request_count: 2, @@ -3336,6 +3342,12 @@ fn turn_event_serializes_expected_shape() { before_first_sampling_ms: 100, sampling_ms: 700, between_sampling_overhead_ms: 50, + between_sampling_post_response_ms: 10, + between_sampling_retry_ms: 10, + between_sampling_compaction_ms: 10, + between_sampling_follow_up_ms: 10, + between_sampling_request_preparation_ms: 5, + between_sampling_other_ms: 5, tool_blocking_ms: 250, after_last_sampling_ms: 134, sampling_request_count: 2, @@ -3408,6 +3420,12 @@ fn turn_event_serializes_expected_shape() { "before_first_sampling_ms": 100, "sampling_ms": 700, "between_sampling_overhead_ms": 50, + "between_sampling_post_response_ms": 10, + "between_sampling_retry_ms": 10, + "between_sampling_compaction_ms": 10, + "between_sampling_follow_up_ms": 10, + "between_sampling_request_preparation_ms": 5, + "between_sampling_other_ms": 5, "tool_blocking_ms": 250, "after_last_sampling_ms": 134, "sampling_request_count": 2, diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index 0b6c9a0122..56b4ed0a86 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -821,6 +821,12 @@ pub(crate) struct CodexTurnEventParams { pub(crate) before_first_sampling_ms: u64, pub(crate) sampling_ms: u64, pub(crate) between_sampling_overhead_ms: u64, + pub(crate) between_sampling_post_response_ms: u64, + pub(crate) between_sampling_retry_ms: u64, + pub(crate) between_sampling_compaction_ms: u64, + pub(crate) between_sampling_follow_up_ms: u64, + pub(crate) between_sampling_request_preparation_ms: u64, + pub(crate) between_sampling_other_ms: u64, pub(crate) tool_blocking_ms: u64, pub(crate) after_last_sampling_ms: u64, pub(crate) sampling_request_count: u32, diff --git a/codex-rs/analytics/src/facts.rs b/codex-rs/analytics/src/facts.rs index a035bc98b9..f319dd5c81 100644 --- a/codex-rs/analytics/src/facts.rs +++ b/codex-rs/analytics/src/facts.rs @@ -106,6 +106,12 @@ pub struct TurnProfile { pub before_first_sampling_ms: u64, pub sampling_ms: u64, pub between_sampling_overhead_ms: u64, + pub between_sampling_post_response_ms: u64, + pub between_sampling_retry_ms: u64, + pub between_sampling_compaction_ms: u64, + pub between_sampling_follow_up_ms: u64, + pub between_sampling_request_preparation_ms: u64, + pub between_sampling_other_ms: u64, pub tool_blocking_ms: u64, pub after_last_sampling_ms: u64, pub sampling_request_count: u32, diff --git a/codex-rs/analytics/src/reducer.rs b/codex-rs/analytics/src/reducer.rs index e159c0f2a1..4a92ba1568 100644 --- a/codex-rs/analytics/src/reducer.rs +++ b/codex-rs/analytics/src/reducer.rs @@ -2429,6 +2429,12 @@ fn codex_turn_event_params( before_first_sampling_ms, sampling_ms, between_sampling_overhead_ms, + between_sampling_post_response_ms, + between_sampling_retry_ms, + between_sampling_compaction_ms, + between_sampling_follow_up_ms, + between_sampling_request_preparation_ms, + between_sampling_other_ms, tool_blocking_ms, after_last_sampling_ms, sampling_request_count, @@ -2498,6 +2504,12 @@ fn codex_turn_event_params( before_first_sampling_ms, sampling_ms, between_sampling_overhead_ms, + between_sampling_post_response_ms, + between_sampling_retry_ms, + between_sampling_compaction_ms, + between_sampling_follow_up_ms, + between_sampling_request_preparation_ms, + between_sampling_other_ms, tool_blocking_ms, after_last_sampling_ms, sampling_request_count, diff --git a/codex-rs/app-server/tests/suite/v2/turn_start.rs b/codex-rs/app-server/tests/suite/v2/turn_start.rs index aed3c58697..556d627104 100644 --- a/codex-rs/app-server/tests/suite/v2/turn_start.rs +++ b/codex-rs/app-server/tests/suite/v2/turn_start.rs @@ -931,14 +931,36 @@ async fn turn_start_tracks_turn_event_analytics() -> Result<()> { "before_first_sampling_ms", "sampling_ms", "between_sampling_overhead_ms", + "between_sampling_post_response_ms", + "between_sampling_retry_ms", + "between_sampling_compaction_ms", + "between_sampling_follow_up_ms", + "between_sampling_request_preparation_ms", + "between_sampling_other_ms", "tool_blocking_ms", "after_last_sampling_ms", ] .into_iter() .all(|field| params[field].as_u64().is_some()); + let between_sampling_breakdown_ms = [ + "between_sampling_post_response_ms", + "between_sampling_retry_ms", + "between_sampling_compaction_ms", + "between_sampling_follow_up_ms", + "between_sampling_request_preparation_ms", + "between_sampling_other_ms", + ] + .into_iter() + .filter_map(|field| params[field].as_u64()) + .sum::(); assert_eq!( json!({ "timingsAreNumbers": timings_are_numbers, + "betweenSamplingBreakdownCloses": + params["between_sampling_overhead_ms"] == between_sampling_breakdown_ms, + "retryTimingIsPositive": params["between_sampling_retry_ms"] + .as_u64() + .is_some_and(|duration| duration > 0), "toolBlockingMs": params["tool_blocking_ms"], "samplingRequestCount": params["sampling_request_count"], "samplingRetryCount": params["sampling_retry_count"], @@ -946,6 +968,8 @@ async fn turn_start_tracks_turn_event_analytics() -> Result<()> { }), json!({ "timingsAreNumbers": true, + "betweenSamplingBreakdownCloses": true, + "retryTimingIsPositive": true, "toolBlockingMs": 0, "samplingRequestCount": 2, "samplingRetryCount": 1, @@ -1040,8 +1064,23 @@ async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<() let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; let params = &event["event_params"]; + let between_sampling_breakdown_ms = [ + "between_sampling_post_response_ms", + "between_sampling_retry_ms", + "between_sampling_compaction_ms", + "between_sampling_follow_up_ms", + "between_sampling_request_preparation_ms", + "between_sampling_other_ms", + ] + .into_iter() + .filter_map(|field| params[field].as_u64()) + .sum::(); assert_eq!( json!({ + "betweenSamplingBreakdownCloses": + params["between_sampling_overhead_ms"] == between_sampling_breakdown_ms, + "retryMs": params["between_sampling_retry_ms"], + "compactionMs": params["between_sampling_compaction_ms"], "toolBlockingIsPositive": params["tool_blocking_ms"] .as_u64() .is_some_and(|duration| duration > 0), @@ -1050,6 +1089,9 @@ async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<() "status": params["status"], }), json!({ + "betweenSamplingBreakdownCloses": true, + "retryMs": 0, + "compactionMs": 0, "toolBlockingIsPositive": true, "samplingRequestCount": 2, "samplingRetryCount": 0, @@ -1060,6 +1102,150 @@ async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<() Ok(()) } +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn turn_profile_attributes_mid_turn_compaction() -> Result<()> { + let server = responses::start_mock_server().await; + let tool_call_arguments = serde_json::to_string(&json!({ + "questions": [{ + "id": "confirm_path", + "header": "Confirm", + "question": "Proceed with the plan?", + "options": [{ + "label": "Yes (Recommended)", + "description": "Continue the current plan." + }] + }] + }))?; + let tool_response = responses::sse(vec![ + responses::ev_response_created("tool-response"), + responses::ev_function_call("call1", "request_user_input", &tool_call_arguments), + responses::ev_completed_with_tokens("tool-response", /*total_tokens*/ 500_000), + ]); + let compact_response = responses::sse(vec![ + responses::ev_assistant_message("compact-message", "Summary"), + responses::ev_completed_with_tokens("compact-response", /*total_tokens*/ 200), + ]); + let response_mock = responses::mount_response_sequence( + &server, + vec![ + responses::sse_response(tool_response), + responses::sse_response(compact_response) + .set_delay(std::time::Duration::from_millis(25)), + responses::sse_response(create_final_assistant_message_sse_response("Done")?), + ], + ) + .await; + + let codex_home = TempDir::new()?; + write_mock_responses_config_toml_with_chatgpt_base_url( + codex_home.path(), + &server.uri(), + &server.uri(), + )?; + mount_analytics_capture(&server, codex_home.path()).await?; + + let mut mcp = TestAppServer::new_without_managed_config(codex_home.path()).await?; + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; + let thread_req = mcp + .send_thread_start_request(ThreadStartParams { + model: Some("mock-model".to_string()), + ..Default::default() + }) + .await?; + let thread_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(thread_req)), + ) + .await??; + let ThreadStartResponse { thread, .. } = to_response::(thread_resp)?; + + let turn_req = mcp + .send_turn_start_request(TurnStartParams { + thread_id: thread.id, + client_user_message_id: None, + input: vec![V2UserInput::Text { + text: "trigger compaction".to_string(), + text_elements: Vec::new(), + }], + collaboration_mode: Some(CollaborationMode { + mode: ModeKind::Plan, + settings: Settings { + model: "mock-model".to_string(), + reasoning_effort: Some(ReasoningEffort::Medium), + developer_instructions: None, + }, + }), + ..Default::default() + }) + .await?; + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(turn_req)), + ) + .await??; + + let server_req = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_request_message(), + ) + .await??; + let ServerRequest::ToolRequestUserInput { request_id, .. } = server_req else { + panic!("expected ToolRequestUserInput request, got: {server_req:?}"); + }; + mcp.send_response( + request_id, + json!({ + "answers": { + "confirm_path": { "answers": ["yes"] } + } + }), + ) + .await?; + + timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("turn/completed"), + ) + .await??; + + let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?; + let params = &event["event_params"]; + let between_sampling_breakdown_ms = [ + "between_sampling_post_response_ms", + "between_sampling_retry_ms", + "between_sampling_compaction_ms", + "between_sampling_follow_up_ms", + "between_sampling_request_preparation_ms", + "between_sampling_other_ms", + ] + .into_iter() + .filter_map(|field| params[field].as_u64()) + .sum::(); + assert_eq!( + json!({ + "betweenSamplingBreakdownCloses": + params["between_sampling_overhead_ms"] == between_sampling_breakdown_ms, + "compactionIncludesResponseDelay": params["between_sampling_compaction_ms"] + .as_u64() + .is_some_and(|duration| duration >= 20), + "samplingRequestCount": params["sampling_request_count"], + "samplingRetryCount": params["sampling_retry_count"], + "responseRequestCount": response_mock.requests().len(), + "status": params["status"], + }), + json!({ + "betweenSamplingBreakdownCloses": true, + "compactionIncludesResponseDelay": true, + "samplingRequestCount": 2, + "samplingRetryCount": 0, + "responseRequestCount": 3, + "status": "completed", + }) + ); + + Ok(()) +} + #[tokio::test] async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> { let responses = vec![create_final_assistant_message_sse_response("Done")?]; diff --git a/codex-rs/core/src/session/turn.rs b/codex-rs/core/src/session/turn.rs index 9d4e7d1e82..bee3388abc 100644 --- a/codex-rs/core/src/session/turn.rs +++ b/codex-rs/core/src/session/turn.rs @@ -60,6 +60,7 @@ use crate::tools::router::extension_tool_executors; use crate::tools::spec_plan::search_tool_enabled; use crate::tools::spec_plan::tool_suggest_enabled; use crate::turn_diff_tracker::TurnDiffTracker; +use crate::turn_timing::BetweenSamplingPhase; use crate::turn_timing::record_turn_ttft_metric; use crate::util::error_or_panic; use codex_analytics::AppInvocation; @@ -200,6 +201,9 @@ pub(crate) async fn run_turn( // 2. After auto-compact, when model/tool continuation needs to resume before any steer. loop { + turn_context + .turn_timing_state + .mark_between_sampling_phase(BetweenSamplingPhase::RequestPreparation); // Note that pending_input would be something like a message the user // submitted through the UI while the model was running. Though the UI // may support this, the model might not. @@ -237,6 +241,9 @@ pub(crate) async fn run_turn( .await { Ok(sampling_request_output) => { + turn_context + .turn_timing_state + .mark_between_sampling_phase(BetweenSamplingPhase::FollowUp); let SamplingRequestResult { needs_follow_up: model_needs_follow_up, last_agent_message: sampling_request_last_agent_message, @@ -271,6 +278,9 @@ pub(crate) async fn run_turn( // as long as compaction works well in getting us way below the token limit, we shouldn't worry about being in an infinite loop. if token_limit_reached && needs_follow_up { + turn_context + .turn_timing_state + .mark_between_sampling_phase(BetweenSamplingPhase::Compaction); if let Err(err) = run_auto_compact( &sess, &turn_context, @@ -1048,6 +1058,9 @@ async fn run_sampling_request( return Err(err); } + turn_context + .turn_timing_state + .mark_between_sampling_phase(BetweenSamplingPhase::Retry); handle_retryable_response_stream_error( &mut retries, max_retries, @@ -1059,6 +1072,9 @@ async fn run_sampling_request( ) .await?; turn_context.turn_timing_state.record_sampling_retry(); + turn_context + .turn_timing_state + .mark_between_sampling_phase(BetweenSamplingPhase::RequestPreparation); } } diff --git a/codex-rs/core/src/turn_timing.rs b/codex-rs/core/src/turn_timing.rs index 380e246fae..12ac9a509d 100644 --- a/codex-rs/core/src/turn_timing.rs +++ b/codex-rs/core/src/turn_timing.rs @@ -58,12 +58,13 @@ struct TurnProfileState { started_at: Option, last_transition_at: Option, active_phase: Option, + active_between_sampling_phase: Option, seen_sampling: bool, before_first_sampling: Duration, sampling: Duration, - between_sampling_overhead: Duration, + between_sampling: BetweenSamplingDurations, tool_blocking: Duration, - pending_idle_after_sampling: Duration, + pending_between_sampling: BetweenSamplingDurations, sampling_request_count: u32, sampling_retry_count: u32, completed_profile: Option, @@ -75,6 +76,60 @@ enum TurnProfilePhase { ToolBlocking, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BetweenSamplingPhase { + PostResponse, + Retry, + Compaction, + FollowUp, + RequestPreparation, +} + +#[derive(Debug, Default)] +struct BetweenSamplingDurations { + post_response: Duration, + retry: Duration, + compaction: Duration, + follow_up: Duration, + request_preparation: Duration, + other: Duration, +} + +impl BetweenSamplingDurations { + fn record(&mut self, phase: Option, duration: Duration) { + match phase { + Some(BetweenSamplingPhase::PostResponse) => self.post_response += duration, + Some(BetweenSamplingPhase::Retry) => self.retry += duration, + Some(BetweenSamplingPhase::Compaction) => self.compaction += duration, + Some(BetweenSamplingPhase::FollowUp) => self.follow_up += duration, + Some(BetweenSamplingPhase::RequestPreparation) => { + self.request_preparation += duration; + } + None => self.other += duration, + } + } + + fn total(&self) -> Duration { + self.post_response + + self.retry + + self.compaction + + self.follow_up + + self.request_preparation + + self.other + } +} + +impl std::ops::AddAssign for BetweenSamplingDurations { + fn add_assign(&mut self, rhs: Self) { + self.post_response += rhs.post_response; + self.retry += rhs.retry; + self.compaction += rhs.compaction; + self.follow_up += rhs.follow_up; + self.request_preparation += rhs.request_preparation; + self.other += rhs.other; + } +} + #[must_use] pub(crate) struct TurnProfileTimingGuard { timing: Arc, @@ -131,6 +186,11 @@ impl TurnTimingState { self.profile_state().record_sampling_retry(); } + pub(crate) fn mark_between_sampling_phase(&self, phase: BetweenSamplingPhase) { + self.profile_state() + .mark_between_sampling_phase(Instant::now(), phase); + } + pub(crate) fn begin_tool_blocking(self: &Arc) -> TurnProfileTimingGuard { let active = self.profile_state().begin_tool_blocking(Instant::now()); TurnProfileTimingGuard { @@ -209,7 +269,7 @@ impl TurnProfileState { } self.advance(now); if self.seen_sampling { - self.between_sampling_overhead += std::mem::take(&mut self.pending_idle_after_sampling); + self.between_sampling += std::mem::take(&mut self.pending_between_sampling); } self.seen_sampling = true; self.active_phase = Some(TurnProfilePhase::Sampling); @@ -223,6 +283,14 @@ impl TurnProfileState { } } + fn mark_between_sampling_phase(&mut self, now: Instant, phase: BetweenSamplingPhase) { + if self.completed_profile.is_some() || !self.seen_sampling || self.active_phase.is_some() { + return; + } + self.advance(now); + self.active_between_sampling_phase = Some(phase); + } + fn begin_tool_blocking(&mut self, now: Instant) -> bool { if self.completed_profile.is_some() || self.started_at.is_none() @@ -241,6 +309,9 @@ impl TurnProfileState { } self.advance(now); self.active_phase = None; + if phase == TurnProfilePhase::Sampling { + self.active_between_sampling_phase = Some(BetweenSamplingPhase::PostResponse); + } } fn advance(&mut self, now: Instant) { @@ -251,7 +322,10 @@ impl TurnProfileState { match self.active_phase { Some(TurnProfilePhase::Sampling) => self.sampling += elapsed, Some(TurnProfilePhase::ToolBlocking) => self.tool_blocking += elapsed, - None if self.seen_sampling => self.pending_idle_after_sampling += elapsed, + None if self.seen_sampling => { + self.pending_between_sampling + .record(self.active_between_sampling_phase, elapsed); + } None => self.before_first_sampling += elapsed, } } @@ -264,15 +338,37 @@ impl TurnProfileState { let final_phase = self.active_phase; self.advance(now); let after_last_sampling = if self.seen_sampling { - std::mem::take(&mut self.pending_idle_after_sampling) + std::mem::take(&mut self.pending_between_sampling).total() } else { Duration::ZERO }; + let between_sampling_overhead_ms = duration_to_u64_ms(self.between_sampling.total()); + let between_sampling_post_response_ms = + duration_to_u64_ms(self.between_sampling.post_response); + let between_sampling_retry_ms = duration_to_u64_ms(self.between_sampling.retry); + let between_sampling_compaction_ms = duration_to_u64_ms(self.between_sampling.compaction); + let between_sampling_follow_up_ms = duration_to_u64_ms(self.between_sampling.follow_up); + let between_sampling_request_preparation_ms = + duration_to_u64_ms(self.between_sampling.request_preparation); + let classified_between_sampling_ms = between_sampling_post_response_ms + .saturating_add(between_sampling_retry_ms) + .saturating_add(between_sampling_compaction_ms) + .saturating_add(between_sampling_follow_up_ms) + .saturating_add(between_sampling_request_preparation_ms); + debug_assert!(classified_between_sampling_ms <= between_sampling_overhead_ms); + let mut profile = TurnProfile { before_first_sampling_ms: duration_to_u64_ms(self.before_first_sampling), sampling_ms: duration_to_u64_ms(self.sampling), - between_sampling_overhead_ms: duration_to_u64_ms(self.between_sampling_overhead), + between_sampling_overhead_ms, + between_sampling_post_response_ms, + between_sampling_retry_ms, + between_sampling_compaction_ms, + between_sampling_follow_up_ms, + between_sampling_request_preparation_ms, + between_sampling_other_ms: between_sampling_overhead_ms + .saturating_sub(classified_between_sampling_ms), tool_blocking_ms: duration_to_u64_ms(self.tool_blocking), after_last_sampling_ms: duration_to_u64_ms(after_last_sampling), sampling_request_count: self.sampling_request_count, @@ -297,6 +393,7 @@ impl TurnProfileState { } self.active_phase = None; + self.active_between_sampling_phase = None; self.completed_profile = Some(profile.clone()); profile } diff --git a/codex-rs/core/src/turn_timing_tests.rs b/codex-rs/core/src/turn_timing_tests.rs index 7146f537be..1be5e1bc46 100644 --- a/codex-rs/core/src/turn_timing_tests.rs +++ b/codex-rs/core/src/turn_timing_tests.rs @@ -10,6 +10,7 @@ use std::time::Instant; use std::time::SystemTime; use std::time::UNIX_EPOCH; +use super::BetweenSamplingPhase; use super::TurnProfilePhase; use super::TurnProfileState; use super::TurnTimingState; @@ -162,11 +163,35 @@ fn turn_profile_breaks_down_sampling_blocking_and_retry_overhead() { started_at + Duration::from_millis(600), TurnProfilePhase::Sampling, ); - let _ = state.begin_tool_blocking(started_at + Duration::from_millis(600)); + let _ = state.begin_tool_blocking(started_at + Duration::from_millis(650)); state.end_phase( started_at + Duration::from_millis(900), TurnProfilePhase::ToolBlocking, ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(910), + BetweenSamplingPhase::Retry, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(940), + BetweenSamplingPhase::PostResponse, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(950), + BetweenSamplingPhase::Compaction, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(970), + BetweenSamplingPhase::FollowUp, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(980), + BetweenSamplingPhase::RequestPreparation, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(990), + BetweenSamplingPhase::PostResponse, + ); state.record_sampling_retry(); let _ = state.begin_sampling(started_at + Duration::from_millis(1_000)); state.end_phase( @@ -179,11 +204,98 @@ fn turn_profile_breaks_down_sampling_blocking_and_retry_overhead() { TurnProfile { before_first_sampling_ms: 100, sampling_ms: 700, - between_sampling_overhead_ms: 100, - tool_blocking_ms: 300, + between_sampling_overhead_ms: 150, + between_sampling_post_response_ms: 80, + between_sampling_retry_ms: 30, + between_sampling_compaction_ms: 20, + between_sampling_follow_up_ms: 10, + between_sampling_request_preparation_ms: 10, + between_sampling_other_ms: 0, + tool_blocking_ms: 250, after_last_sampling_ms: 100, sampling_request_count: 2, sampling_retry_count: 1, } ); } + +#[test] +fn turn_profile_does_not_commit_between_sampling_phases_without_another_sample() { + let started_at = Instant::now(); + let mut state = TurnProfileState::default(); + state.start(started_at); + + let _ = state.begin_sampling(started_at + Duration::from_millis(100)); + state.end_phase( + started_at + Duration::from_millis(200), + TurnProfilePhase::Sampling, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_millis(200), + BetweenSamplingPhase::Compaction, + ); + + assert_eq!( + state.complete(started_at + Duration::from_millis(300)), + TurnProfile { + before_first_sampling_ms: 100, + sampling_ms: 100, + between_sampling_overhead_ms: 0, + between_sampling_post_response_ms: 0, + between_sampling_retry_ms: 0, + between_sampling_compaction_ms: 0, + between_sampling_follow_up_ms: 0, + between_sampling_request_preparation_ms: 0, + between_sampling_other_ms: 0, + tool_blocking_ms: 0, + after_last_sampling_ms: 100, + sampling_request_count: 1, + sampling_retry_count: 0, + } + ); +} + +#[test] +fn turn_profile_assigns_between_sampling_rounding_to_other() { + let started_at = Instant::now(); + let mut state = TurnProfileState::default(); + state.start(started_at); + + let _ = state.begin_sampling(started_at); + state.end_phase( + started_at + Duration::from_millis(1), + TurnProfilePhase::Sampling, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_micros(1_400), + BetweenSamplingPhase::Retry, + ); + state.mark_between_sampling_phase( + started_at + Duration::from_micros(1_800), + BetweenSamplingPhase::RequestPreparation, + ); + let _ = state.begin_sampling(started_at + Duration::from_micros(2_200)); + state.end_phase( + started_at + Duration::from_micros(2_300), + TurnProfilePhase::Sampling, + ); + + assert_eq!( + state.complete(started_at + Duration::from_micros(2_300)), + TurnProfile { + before_first_sampling_ms: 0, + sampling_ms: 1, + between_sampling_overhead_ms: 1, + between_sampling_post_response_ms: 0, + between_sampling_retry_ms: 0, + between_sampling_compaction_ms: 0, + between_sampling_follow_up_ms: 0, + between_sampling_request_preparation_ms: 0, + between_sampling_other_ms: 1, + tool_blocking_ms: 0, + after_last_sampling_ms: 0, + sampling_request_count: 2, + sampling_retry_count: 0, + } + ); +}