返回 CodeWhale
session_metrics.rs
根目录 / crates / tui / src / tui / session_metrics.rs
1 //! Session metrics: the shared accumulators behind the metrics line and
2 //! the detailed `turns · steps │ LLM · tools │ TTFT · avg tok/s │ cache │ in` ledger.
3 //!
4 //! Every number here is sourced from runtime evidence the engine already
5 //! emits — never from transcript timestamps or estimates:
6 //!
7 //! - **turns**: `Event::TurnStarted` count (`App::turn_counter`).
8 //! - **steps**: model calls (`Event::TurnUsage`) plus tool calls
9 //! (`Event::ToolCallComplete`) — the agent's step count.
10 //! - **LLM**: sum of model-call wall time. Uses `TurnUsage::request_ms`
11 //! (dispatch → usage receipt) when the engine measured dispatch, else the
12 //! stream duration it always reports.
13 //! - **tools**: sum of tool wall time from `ToolCallStarted` → `ToolCallComplete`
14 //! by tool id (the runtime's own clock, taken when the events drain).
15 //! - **TTFT avg**: mean of `TurnUsage::first_token_ms` over the model calls
16 //! that reported one.
17 //! - **avg tok/s**: sum of provider-reported output tokens divided by the sum
18 //! of measured request seconds (`request_ms`), across this loaded session's
19 //! completed usage receipts. This is effective request throughput, including
20 //! connection setup, time to first token, and pauses within the response;
21 //! it is not a decoder-speed measurement or a live text-token estimate.
22 //! Streaming and non-streaming calls use the same dispatch-to-receipt clock.
23 //! Tool execution and idle time between calls are excluded. A transparent
24 //! retry before any content uses the replacement request's clock; a billed
25 //! response with usage is counted even if a later retry is needed. Calls
26 //! without a positive measured request duration (including aggregate REPL
27 //! child receipts) are excluded from both numerator and denominator. The
28 //! normalized `Usage::output_tokens` receipt is canonical; separate reasoning
29 //! counts are not added again and streamed estimates never enter this average.
30 //! - **cache**: provider-reported prompt-cache hit tokens over hit + miss
31 //! (`SessionState::total_cache_hit_tokens` / `total_cache_miss_tokens`).
32 //! - **in**: provider-reported input tokens (`SessionState::total_input_tokens`).
33 //!
34 //! When a provider never reports a metric, or its evidence has not arrived
35 //! yet, the cell is omitted. Nothing here is estimated or captioned.
36 //!
37 //! The infoline and detailed ledger consume the same rate. The infoline keeps
38 //! the last measured session average while a request is in flight; it does not
39 //! divide a text estimate by a turn timer that also includes tools and waits.
40
41 use std::collections::HashMap;
42 use std::time::{Duration, Instant};
43
44 #[cfg(test)]
45 use codewhale_localization::{Locale, MessageId, tr};
46
47 /// Runtime accumulators behind the strip. Lives on [`crate::tui::app::App`],
48 /// resets with the token breakdown when a session is loaded, so the numbers
49 /// describe this runtime session — the same scope as the token ledger.
50 #[derive(Debug, Clone, Default)]
51 pub struct SessionMetrics {
52 /// Model calls that reported usage (`Event::TurnUsage`).
53 pub model_calls: u64,
54 /// Tool calls that completed (`Event::ToolCallComplete`).
55 pub tool_calls: u64,
56 /// Sum of model-call wall time.
57 pub llm_time: Duration,
58 /// Sum of tool wall time.
59 pub tool_time: Duration,
60 /// Sum of reported time-to-first-token values.
61 ttft_total: Duration,
62 /// How many model calls reported a time-to-first-token.
63 ttft_samples: u64,
64 /// Output tokens from calls that also reported a positive request duration.
65 rate_output_tokens: u64,
66 /// Dispatch-to-receipt time from exactly the same calls.
67 rate_request_time: Duration,
68 /// Tools currently running, keyed by tool id, with the instant their
69 /// start event drained.
70 tool_started: HashMap<String, Instant>,
71 }
72
73 impl SessionMetrics {
74 /// Fold one model-call usage receipt into the accumulators.
75 pub fn record_model_call(
76 &mut self,
77 output_tokens: u32,
78 duration_ms: u64,
79 first_token_ms: Option<u64>,
80 request_ms: Option<u64>,
81 ) {
82 self.model_calls = self.model_calls.saturating_add(1);
83 let call_ms = request_ms.unwrap_or(duration_ms);
84 self.llm_time = self.llm_time.saturating_add(Duration::from_millis(call_ms));
85 if let Some(ttft) = first_token_ms {
86 self.ttft_total = self.ttft_total.saturating_add(Duration::from_millis(ttft));
87 self.ttft_samples = self.ttft_samples.saturating_add(1);
88 }
89 if let Some(request_ms) = request_ms.filter(|millis| *millis > 0) {
90 self.rate_output_tokens = self
91 .rate_output_tokens
92 .saturating_add(u64::from(output_tokens));
93 self.rate_request_time = self
94 .rate_request_time
95 .saturating_add(Duration::from_millis(request_ms));
96 }
97 }
98
99 /// Note that a tool started; the matching completion closes the timer.
100 pub fn record_tool_started(&mut self, tool_id: &str) {
101 self.record_tool_started_at(tool_id, Instant::now());
102 }
103
104 fn record_tool_started_at(&mut self, tool_id: &str, at: Instant) {
105 self.tool_started.insert(tool_id.to_string(), at);
106 }
107
108 /// Note that a tool completed. Counts the call even when its start was
109 /// never seen (a replayed or foreign completion), but only accrues time
110 /// when the runtime saw both edges.
111 pub fn record_tool_completed(&mut self, tool_id: &str) {
112 self.record_tool_completed_at(tool_id, Instant::now());
113 }
114
115 fn record_tool_completed_at(&mut self, tool_id: &str, at: Instant) {
116 self.tool_calls = self.tool_calls.saturating_add(1);
117 if let Some(started) = self.tool_started.remove(tool_id) {
118 self.tool_time = self
119 .tool_time
120 .saturating_add(at.saturating_duration_since(started));
121 }
122 }
123
124 /// Drop in-flight tool timers (turn interrupted or failed): a tool that
125 /// never completed must not leak into the next turn's accounting.
126 pub fn clear_in_flight(&mut self) {
127 self.tool_started.clear();
128 }
129
130 /// Model calls plus tool calls.
131 #[must_use]
132 pub fn steps(&self) -> u64 {
133 self.model_calls.saturating_add(self.tool_calls)
134 }
135
136 /// Mean time-to-first-token, when at least one call reported it.
137 #[must_use]
138 pub fn ttft_average(&self) -> Option<Duration> {
139 if self.ttft_samples == 0 {
140 return None;
141 }
142 Some(self.ttft_total / u32::try_from(self.ttft_samples).unwrap_or(u32::MAX))
143 }
144
145 /// Session-average output tokens per measured request second. See the
146 /// module documentation for included time and receipt coverage.
147 #[must_use]
148 pub fn tokens_per_second(&self) -> Option<f64> {
149 let secs = self.rate_request_time.as_secs_f64();
150 if self.rate_output_tokens == 0 || !secs.is_finite() || secs <= 0.0 {
151 return None;
152 }
153 Some(self.rate_output_tokens as f64 / secs)
154 }
155 }
156
157 pub use codewhale_command_contract::config_policy::StatusMetrics as MetricsSnapshot;
158 #[cfg(test)]
159 use codewhale_command_contract::metrics::{MetricGroupCells, RenderedStrip, Separators};
160 pub use codewhale_command_contract::metrics::{format_duration, format_rate, format_tokens};
161
162 #[cfg(test)]
163 fn build_groups(snapshot: MetricsSnapshot, locale: Locale) -> Vec<MetricGroupCells> {
164 codewhale_command_contract::metrics::build_groups(
165 snapshot,
166 &codewhale_command_contract::metrics::MetricLabels {
167 cache: tr(locale, MessageId::SessionMetricsCache).into_owned(),
168 input: tr(locale, MessageId::SessionMetricsInput).into_owned(),
169 llm: tr(locale, MessageId::SessionMetricsLlm).into_owned(),
170 step: tr(locale, MessageId::SessionMetricsStep).into_owned(),
171 steps: tr(locale, MessageId::SessionMetricsSteps).into_owned(),
172 tokens_per_second: tr(locale, MessageId::SessionMetricsTokensPerSecond).into_owned(),
173 tools: tr(locale, MessageId::SessionMetricsTools).into_owned(),
174 ttft: tr(locale, MessageId::SessionMetricsTtft).into_owned(),
175 turn: tr(locale, MessageId::SessionMetricsTurn).into_owned(),
176 turns: tr(locale, MessageId::SessionMetricsTurns).into_owned(),
177 },
178 )
179 }
180
181 pub use codewhale_command_contract::facets::DebugCacheRates as CacheRates;
182
183 fn hit_percent(hit: u64, miss: u64, write: u64) -> Option<u8> {
184 let total = hit.saturating_add(miss).saturating_add(write);
185 (total > 0).then(|| u8::try_from((hit.saturating_mul(100) + total / 2) / total).unwrap_or(100))
186 }
187
188 #[must_use]
189 pub fn cache_rates(app: &crate::tui::app::App) -> CacheRates {
190 let parent_hit = u64::from(app.session.displayed_total_cache_hit_tokens());
191 let parent_miss = u64::from(app.session.displayed_total_cache_miss_tokens());
192 let parent_write = u64::from(app.session.displayed_total_cache_write_tokens());
193 let agent_write = app.session.subagent_cache_write_tokens.unwrap_or(0);
194 let agents = app
195 .session
196 .subagent_cache_hit_tokens
197 .zip(app.session.subagent_cache_miss_tokens);
198 CacheRates {
199 parent: hit_percent(parent_hit, parent_miss, parent_write),
200 agents: agents.and_then(|(hit, miss)| hit_percent(hit, miss, agent_write)),
201 combined: agents.and_then(|(hit, miss)| {
202 hit_percent(
203 parent_hit.saturating_add(hit),
204 parent_miss.saturating_add(miss),
205 parent_write.saturating_add(agent_write),
206 )
207 }),
208 }
209 }
210
211 /// Snapshot the live app state into the strip's inputs.
212 #[must_use]
213 pub fn snapshot_from_app(app: &crate::tui::app::App) -> MetricsSnapshot {
214 // The footer rate is this conversation's own requests; sub-agent cache
215 // is shown beside it, labelled, in PRICE and `/cache` (#6565).
216 let cache_hit_percent = cache_rates(app).parent;
217 MetricsSnapshot {
218 turns: app.turn_counter,
219 steps: app.session_metrics.steps(),
220 llm_time: app.session_metrics.llm_time,
221 tool_time: app.session_metrics.tool_time,
222 ttft_avg: app.session_metrics.ttft_average(),
223 tokens_per_second: app.session_metrics.tokens_per_second(),
224 cache_hit_percent,
225 input_tokens: u64::from(app.session.displayed_total_input_tokens()),
226 }
227 }
228
229 /// The complete, untrimmed strip text — what `/status` prints.
230 #[must_use]
231 #[cfg(test)]
232 pub(crate) fn full_text(snapshot: MetricsSnapshot, locale: Locale, ascii_safe: bool) -> String {
233 RenderedStrip {
234 groups: build_groups(snapshot, locale),
235 separators: Separators::for_ascii(ascii_safe),
236 }
237 .text()
238 }
239
240 #[cfg(test)]
241 mod tests {
242 use super::*;
243
244 fn sample() -> MetricsSnapshot {
245 MetricsSnapshot {
246 turns: 4,
247 steps: 108,
248 llm_time: Duration::from_secs(11 * 60 + 46),
249 tool_time: Duration::from_secs(60 + 52),
250 ttft_avg: Some(Duration::from_millis(1_500)),
251 tokens_per_second: Some(120.0),
252 cache_hit_percent: Some(99),
253 input_tokens: 9_300_000,
254 }
255 }
256
257 #[test]
258 fn durations_format_like_the_harness_strip() {
259 assert_eq!(format_duration(Duration::ZERO), "0s");
260 assert_eq!(format_duration(Duration::from_millis(320)), "320ms");
261 assert_eq!(format_duration(Duration::from_millis(1_500)), "1.5s");
262 assert_eq!(format_duration(Duration::from_millis(1_549)), "1.5s");
263 assert_eq!(format_duration(Duration::from_secs(59)), "59.0s");
264 assert_eq!(format_duration(Duration::from_secs(11 * 60 + 46)), "11m46s");
265 assert_eq!(format_duration(Duration::from_secs(3_600 + 120)), "1h02m");
266 }
267
268 #[test]
269 fn tokens_and_rates_format_compactly() {
270 assert_eq!(format_tokens(842), "842");
271 assert_eq!(format_tokens(12_345), "12.3K");
272 assert_eq!(format_tokens(128_000), "128K");
273 assert_eq!(format_tokens(9_300_000), "9.3M");
274 assert_eq!(format_tokens(1_200_000_000), "1.2B");
275 assert_eq!(format_rate(120.4), "120");
276 assert_eq!(format_rate(7.46), "7.5");
277 }
278
279 #[test]
280 fn full_strip_matches_the_reference_layout() {
281 let text = full_text(sample(), Locale::En, false);
282 assert_eq!(
283 text,
284 "4 turns · 108 steps │ LLM 11m46s · Tool call 1m52s │ TTFT avg 1.5s · 120 avg tok/s │ Cache hit 99% │ Input 9.3M"
285 );
286 let ascii = full_text(sample(), Locale::En, true);
287 assert!(ascii.is_ascii(), "{ascii}");
288 assert!(ascii.contains(" | LLM 11m46s . Tool call 1m52s | "));
289 }
290
291 #[test]
292 fn idle_snapshot_paints_nothing() {
293 let text = full_text(MetricsSnapshot::default(), Locale::En, false);
294 assert_eq!(text, "");
295 }
296
297 #[test]
298 fn absent_evidence_omits_the_cell_instead_of_a_placeholder() {
299 let mut snapshot = sample();
300 snapshot.cache_hit_percent = None;
301 snapshot.ttft_avg = None;
302 snapshot.tokens_per_second = None;
303 snapshot.input_tokens = 0;
304 let text = full_text(snapshot, Locale::En, false);
305 assert_eq!(text, "4 turns · 108 steps │ LLM 11m46s · Tool call 1m52s");
306 assert!(!text.contains('—'), "{text}");
307
308 // A partially reported latency group keeps only the reported cell.
309 snapshot.ttft_avg = Some(Duration::from_millis(900));
310 let text = full_text(snapshot, Locale::En, false);
311 assert!(text.ends_with("│ TTFT avg 900ms"), "{text}");
312 snapshot.ttft_avg = None;
313 snapshot.tokens_per_second = Some(88.0);
314 let text = full_text(snapshot, Locale::En, false);
315 assert!(text.ends_with("│ 88 avg tok/s"), "{text}");
316 }
317
318 #[test]
319 fn singular_labels_for_one_turn_and_one_step() {
320 let snapshot = MetricsSnapshot {
321 turns: 1,
322 steps: 1,
323 ..MetricsSnapshot::default()
324 };
325 let text = full_text(snapshot, Locale::En, false);
326 assert_eq!(text, "1 turn · 1 step", "{text}");
327 }
328
329 #[test]
330 fn every_shipped_locale_has_short_labels() {
331 for locale in Locale::shipped_complete() {
332 let text = full_text(sample(), *locale, false);
333 assert!(text.contains("4 "), "{}: {text}", locale.tag());
334 assert!(text.contains("11m46s"), "{}: {text}", locale.tag());
335 for group in build_groups(sample(), *locale) {
336 for cell in group.cells {
337 assert!(
338 cell.label.chars().count() <= 12,
339 "{}: label `{}` is too long for the strip",
340 locale.tag(),
341 cell.label
342 );
343 }
344 }
345 }
346 }
347
348 #[test]
349 fn accumulators_derive_ttft_and_rate_from_reported_calls() {
350 let mut metrics = SessionMetrics::default();
351 // 100 output tokens over a 2 s stream, first token after 500 ms, whole
352 // call 2.4 s including connection setup.
353 metrics.record_model_call(100, 2_000, Some(500), Some(2_400));
354 // A call that reported no first token (empty response) still counts
355 // for LLM time but not for TTFT.
356 metrics.record_model_call(20, 1_000, None, Some(1_100));
357 assert_eq!(metrics.model_calls, 2);
358 assert_eq!(metrics.llm_time, Duration::from_millis(3_500));
359 assert_eq!(metrics.ttft_average(), Some(Duration::from_millis(500)));
360 let rate = metrics.tokens_per_second().expect("rate");
361 assert!((rate - 120.0 / 3.5).abs() < 1e-9, "{rate}");
362
363 // Missing request_ms falls back to the stream duration.
364 metrics.record_model_call(0, 700, None, None);
365 assert_eq!(metrics.llm_time, Duration::from_millis(4_200));
366 // A duration without individual request timing cannot enter the rate.
367 assert!((metrics.tokens_per_second().unwrap() - 120.0 / 3.5).abs() < 1e-9);
368 }
369
370 #[test]
371 fn request_average_covers_ttft_stream_pauses_tools_and_non_streaming_calls() {
372 let mut metrics = SessionMetrics::default();
373 let t0 = Instant::now();
374 let connected = t0 + Duration::from_millis(200);
375 let first_token = t0 + Duration::from_secs(1);
376 let pause_started = t0 + Duration::from_secs(2);
377 let pause_finished = pause_started + Duration::from_secs(1);
378 let first_receipt = pause_finished + Duration::from_secs(2);
379 let millis = |duration: Duration| u64::try_from(duration.as_millis()).unwrap();
380 metrics.record_model_call(
381 120,
382 millis(first_receipt.duration_since(connected)),
383 Some(millis(first_token.duration_since(t0))),
384 Some(millis(first_receipt.duration_since(t0))),
385 );
386 assert_eq!(metrics.tokens_per_second(), Some(24.0));
387
388 // Thirty seconds of tool work and ten seconds idle are not model time.
389 metrics.record_tool_started_at("build", first_receipt);
390 let tool_finished = first_receipt + Duration::from_secs(30);
391 metrics.record_tool_completed_at("build", tool_finished);
392 let second_dispatch = tool_finished + Duration::from_secs(10);
393 assert_eq!(metrics.tokens_per_second(), Some(24.0));
394 let second_receipt = second_dispatch + Duration::from_secs(3);
395 metrics.record_model_call(
396 60,
397 2_800,
398 Some(500),
399 Some(millis(second_receipt.duration_since(second_dispatch))),
400 );
401
402 // A buffered/non-streaming call has a real request clock even though
403 // its adapter reports no stream duration or first-content timestamp.
404 let third_dispatch = second_receipt + Duration::from_secs(20);
405 let third_receipt = third_dispatch + Duration::from_secs(2);
406 metrics.record_model_call(
407 80,
408 0,
409 None,
410 Some(millis(third_receipt.duration_since(third_dispatch))),
411 );
412 assert_eq!(metrics.tokens_per_second(), Some(26.0)); // 260 / (5 + 3 + 2)
413 assert_eq!(metrics.ttft_average(), Some(Duration::from_millis(750)));
414 assert_eq!(metrics.tool_time, Duration::from_secs(30));
415
416 // Aggregate child or legacy receipts and zero-duration cache receipts
417 // cannot contribute tokens without their matching request denominator.
418 metrics.record_model_call(1_000, 9_000, None, None);
419 metrics.record_model_call(300, 0, None, Some(0));
420 assert_eq!(metrics.tokens_per_second(), Some(26.0));
421 // A measured, empty response consumes time and produces zero output.
422 metrics.record_model_call(0, 1_000, None, Some(1_000));
423 assert!((metrics.tokens_per_second().unwrap() - 260.0 / 11.0).abs() < 1e-9);
424 }
425
426 #[test]
427 fn tool_time_needs_both_edges_and_in_flight_timers_are_dropped() {
428 let mut metrics = SessionMetrics::default();
429 let t0 = Instant::now();
430 metrics.record_tool_started_at("a", t0);
431 metrics.record_tool_completed_at("a", t0 + Duration::from_millis(1_500));
432 // Completion without a seen start counts the call, not the time.
433 metrics.record_tool_completed_at("ghost", t0 + Duration::from_secs(9));
434 assert_eq!(metrics.tool_calls, 2);
435 assert_eq!(metrics.tool_time, Duration::from_millis(1_500));
436 assert_eq!(metrics.steps(), 2);
437
438 metrics.record_tool_started_at("b", t0);
439 metrics.clear_in_flight();
440 metrics.record_tool_completed_at("b", t0 + Duration::from_secs(5));
441 assert_eq!(metrics.tool_time, Duration::from_millis(1_500));
442 }
443
444 #[test]
445 fn cache_rates_count_writes_in_agent_and_combined_input() {
446 let mut app = crate::tui::app::App::new(
447 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
448 &codewhale_runtime::config::Config::default(),
449 );
450 assert_eq!(cache_rates(&app), CacheRates::default());
451 app.session.total_cache_hit_tokens = 800;
452 app.session.total_cache_miss_tokens = 200;
453 app.session.subagent_cache_hit_tokens = Some(600);
454 app.session.subagent_cache_miss_tokens = Some(0);
455 app.session.subagent_cache_write_tokens = Some(400);
456 assert_eq!(
457 cache_rates(&app),
458 CacheRates {
459 parent: Some(80),
460 agents: Some(60),
461 combined: Some(70),
462 }
463 );
464 // Writes are input in both scopes, including an in-flight parent call.
465 app.session.total_cache_write_tokens = 200;
466 app.session.pending_turn_cache_write_tokens = 400;
467 assert_eq!(
468 cache_rates(&app),
469 CacheRates {
470 parent: Some(50),
471 agents: Some(60),
472 combined: Some(54),
473 }
474 );
475 app.session.reset_token_breakdown();
476 app.session.subagent_cache_hit_tokens = Some(0);
477 app.session.subagent_cache_miss_tokens = Some(0);
478 app.session.subagent_cache_write_tokens = Some(400);
479 assert_eq!(
480 cache_rates(&app),
481 CacheRates {
482 parent: None,
483 agents: Some(0),
484 combined: Some(0),
485 }
486 );
487 }
488
489 #[test]
490 fn sub_agent_cache_is_shown_beside_the_parent_rate_never_folded_into_it() {
491 // #6565: the footer rate keeps meaning this conversation's requests;
492 // agents and the token-weighted combination are labelled beside it.
493 let mut app = crate::tui::app::App::new(
494 crate::tui::test_support::test_tui_options(std::path::PathBuf::from(".")),
495 &codewhale_runtime::config::Config::default(),
496 );
497 assert_eq!(cache_rates(&app), CacheRates::default());
498 assert_eq!(
499 cache_rates(&app).labelled("parent", "agents", "combined"),
500 None
501 );
502
503 app.session.total_cache_hit_tokens = 800;
504 app.session.total_cache_miss_tokens = 200;
505 assert_eq!(snapshot_from_app(&app).cache_hit_percent, Some(80));
506 assert_eq!(
507 cache_rates(&app)
508 .labelled("parent", "agents", "combined")
509 .as_deref(),
510 Some("80%")
511 );
512
513 app.session.subagent_cache_hit_tokens = Some(200);
514 app.session.subagent_cache_miss_tokens = Some(800);
515 let rates = cache_rates(&app);
516 assert_eq!(
517 rates,
518 CacheRates {
519 parent: Some(80),
520 agents: Some(20),
521 combined: Some(50),
522 }
523 );
524 assert_eq!(
525 rates.labelled("parent", "agents", "combined").as_deref(),
526 Some("parent 80% · agents 20% · combined 50%")
527 );
528 // The footer figure did not move.
529 assert_eq!(snapshot_from_app(&app).cache_hit_percent, Some(80));
530
531 // A loaded session starts the scope over, like the parent totals.
532 app.session.reset_token_breakdown();
533 assert_eq!(app.session.subagent_cache_hit_tokens, None);
534 }
535 }
536
536 lines RUST