1use std::collections::BTreeMap;
15use std::sync::OnceLock;
16use std::sync::atomic::{AtomicU64, Ordering};
17use std::time::Instant;
18
19static METRICS: OnceLock<Metrics> = OnceLock::new();
20
21pub(crate) const TOOL_LATENCY_BUCKET_UPPER_MS: [u64; 9] =
22 [10, 50, 100, 250, 500, 1_000, 5_000, 60_000, i64::MAX as u64];
23
24pub(crate) const MAX_FAILURE_TEMPLATES: usize = 256;
26
27#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
29pub(crate) struct ToolCallCounter {
30 pub calls: u64,
31 pub failures: u64,
32 pub latency_us: u64,
33 pub failure_kinds: [u64; crate::core::telemetry_failure::FAILURE_KINDS.len()],
35}
36
37pub fn global_metrics() -> &'static Metrics {
38 METRICS.get_or_init(Metrics::new)
39}
40
41#[derive(Debug)]
42pub struct Metrics {
43 tool_call_consistency: std::sync::Mutex<BTreeMap<&'static str, ToolCallCounter>>,
47 failure_templates: std::sync::Mutex<BTreeMap<(&'static str, String), u64>>,
49 pub tokens_input: AtomicU64,
51 pub tokens_output: AtomicU64,
52 pub tokens_saved: AtomicU64,
53
54 pub tool_calls_total: AtomicU64,
55 pub tool_calls_error: AtomicU64,
56 pub tool_call_latency_sum_us: AtomicU64,
57 tool_call_latency_buckets: [AtomicU64; TOOL_LATENCY_BUCKET_UPPER_MS.len()],
58
59 pub search_queries_total: AtomicU64,
60 pub search_latency_sum_us: AtomicU64,
61 pub search_results_total: AtomicU64,
62
63 pub embedding_inferences_total: AtomicU64,
64 pub embedding_latency_sum_us: AtomicU64,
65 pub embedding_tokens_total: AtomicU64,
66
67 pub cache_hits: AtomicU64,
68 pub cache_misses: AtomicU64,
69
70 pub compression_calls: AtomicU64,
71 pub compression_input_bytes: AtomicU64,
72 pub compression_output_bytes: AtomicU64,
73
74 pub session_start: Instant,
75}
76
77impl Default for Metrics {
78 fn default() -> Self {
79 Self {
80 tool_call_consistency: std::sync::Mutex::new(BTreeMap::new()),
81 failure_templates: std::sync::Mutex::new(BTreeMap::new()),
82 tokens_input: AtomicU64::new(0),
83 tokens_output: AtomicU64::new(0),
84 tokens_saved: AtomicU64::new(0),
85 tool_calls_total: AtomicU64::new(0),
86 tool_calls_error: AtomicU64::new(0),
87 tool_call_latency_sum_us: AtomicU64::new(0),
88 tool_call_latency_buckets: std::array::from_fn(|_| AtomicU64::new(0)),
89 search_queries_total: AtomicU64::new(0),
90 search_latency_sum_us: AtomicU64::new(0),
91 search_results_total: AtomicU64::new(0),
92 embedding_inferences_total: AtomicU64::new(0),
93 embedding_latency_sum_us: AtomicU64::new(0),
94 embedding_tokens_total: AtomicU64::new(0),
95 cache_hits: AtomicU64::new(0),
96 cache_misses: AtomicU64::new(0),
97 compression_calls: AtomicU64::new(0),
98 compression_input_bytes: AtomicU64::new(0),
99 compression_output_bytes: AtomicU64::new(0),
100 session_start: Instant::now(),
101 }
102 }
103}
104
105impl Metrics {
106 pub fn new() -> Self {
107 Self::default()
108 }
109
110 pub fn record_tool_call(&self, latency_us: u64, success: bool) {
111 let guard = self
112 .tool_call_consistency
113 .lock()
114 .unwrap_or_else(std::sync::PoisonError::into_inner);
115 self.record_tool_call_locked(latency_us, success);
116 drop(guard);
117 }
118
119 pub fn record_named_tool_call(&self, tool: &'static str, latency_us: u64, success: bool) {
122 self.record_named_tool_outcome(
123 tool,
124 latency_us,
125 (!success).then_some(crate::core::telemetry_failure::FailureKind::Other),
126 );
127 }
128
129 pub fn record_named_tool_outcome(
131 &self,
132 tool: &'static str,
133 latency_us: u64,
134 failure: Option<crate::core::telemetry_failure::FailureKind>,
135 ) {
136 let mut per_tool = self
137 .tool_call_consistency
138 .lock()
139 .unwrap_or_else(std::sync::PoisonError::into_inner);
140 self.record_tool_call_locked(latency_us, failure.is_none());
141 let counter = per_tool.entry(tool).or_default();
142 counter.calls = counter.calls.saturating_add(1);
143 counter.latency_us = counter.latency_us.saturating_add(latency_us);
144 if let Some(kind) = failure {
145 counter.failures = counter.failures.saturating_add(1);
146 let slot = &mut counter.failure_kinds[kind.index()];
147 *slot = slot.saturating_add(1);
148 }
149 }
150
151 pub fn record_named_tool_failure(
154 &self,
155 tool: &'static str,
156 latency_us: u64,
157 failure: Option<crate::core::telemetry_failure::Failure>,
158 ) {
159 let template = failure
160 .as_ref()
161 .and_then(|failure| failure.template.clone());
162 self.record_named_tool_outcome(tool, latency_us, failure.map(|failure| failure.kind));
163 let Some(template) = template else { return };
164 let mut templates = self
165 .failure_templates
166 .lock()
167 .unwrap_or_else(std::sync::PoisonError::into_inner);
168 let key = (tool, template);
169 if templates.len() < MAX_FAILURE_TEMPLATES || templates.contains_key(&key) {
170 let count = templates.entry(key).or_default();
171 *count = count.saturating_add(1);
172 }
173 }
174
175 fn record_tool_call_locked(&self, latency_us: u64, success: bool) {
176 self.tool_calls_total.fetch_add(1, Ordering::Relaxed);
177 self.tool_call_latency_sum_us
178 .fetch_add(latency_us, Ordering::Relaxed);
179 let latency_ms = latency_us / 1_000;
180 let bucket = TOOL_LATENCY_BUCKET_UPPER_MS
181 .iter()
182 .position(|upper| latency_ms <= *upper)
183 .unwrap_or(TOOL_LATENCY_BUCKET_UPPER_MS.len() - 1);
184 self.tool_call_latency_buckets[bucket].fetch_add(1, Ordering::Relaxed);
185 if !success {
186 self.tool_calls_error.fetch_add(1, Ordering::Relaxed);
187 }
188 }
189
190 pub fn record_tokens(&self, input: u64, output: u64, saved: u64) {
191 self.tokens_input.fetch_add(input, Ordering::Relaxed);
192 self.tokens_output.fetch_add(output, Ordering::Relaxed);
193 self.tokens_saved.fetch_add(saved, Ordering::Relaxed);
194 }
195
196 pub fn record_search(&self, latency_us: u64, result_count: u64) {
197 self.search_queries_total.fetch_add(1, Ordering::Relaxed);
198 self.search_latency_sum_us
199 .fetch_add(latency_us, Ordering::Relaxed);
200 self.search_results_total
201 .fetch_add(result_count, Ordering::Relaxed);
202 }
203
204 pub fn record_embedding(&self, latency_us: u64, token_count: u64) {
205 self.embedding_inferences_total
206 .fetch_add(1, Ordering::Relaxed);
207 self.embedding_latency_sum_us
208 .fetch_add(latency_us, Ordering::Relaxed);
209 self.embedding_tokens_total
210 .fetch_add(token_count, Ordering::Relaxed);
211 }
212
213 pub fn record_cache(&self, hit: bool) {
214 if hit {
215 self.cache_hits.fetch_add(1, Ordering::Relaxed);
216 } else {
217 self.cache_misses.fetch_add(1, Ordering::Relaxed);
218 }
219 }
220
221 pub fn record_compression(&self, input_bytes: u64, output_bytes: u64) {
222 self.compression_calls.fetch_add(1, Ordering::Relaxed);
223 self.compression_input_bytes
224 .fetch_add(input_bytes, Ordering::Relaxed);
225 self.compression_output_bytes
226 .fetch_add(output_bytes, Ordering::Relaxed);
227 }
228
229 pub fn snapshot(&self) -> MetricsSnapshot {
230 let tool_calls = self.tool_calls_total.load(Ordering::Relaxed);
231 let tool_latency = self.tool_call_latency_sum_us.load(Ordering::Relaxed);
232 let cache_hits = self.cache_hits.load(Ordering::Relaxed);
233 let cache_misses = self.cache_misses.load(Ordering::Relaxed);
234 let comp_in = self.compression_input_bytes.load(Ordering::Relaxed);
235 let comp_out = self.compression_output_bytes.load(Ordering::Relaxed);
236
237 MetricsSnapshot {
238 tokens_input: self.tokens_input.load(Ordering::Relaxed),
239 tokens_output: self.tokens_output.load(Ordering::Relaxed),
240 tokens_saved: self.tokens_saved.load(Ordering::Relaxed),
241 tool_calls_total: tool_calls,
242 tool_calls_error: self.tool_calls_error.load(Ordering::Relaxed),
243 tool_call_avg_latency_ms: if tool_calls > 0 {
244 tool_latency as f64 / tool_calls as f64 / 1000.0
245 } else {
246 0.0
247 },
248 search_queries_total: self.search_queries_total.load(Ordering::Relaxed),
249 search_avg_latency_ms: {
250 let q = self.search_queries_total.load(Ordering::Relaxed);
251 if q > 0 {
252 self.search_latency_sum_us.load(Ordering::Relaxed) as f64 / q as f64 / 1000.0
253 } else {
254 0.0
255 }
256 },
257 embedding_inferences: self.embedding_inferences_total.load(Ordering::Relaxed),
258 embedding_avg_latency_ms: {
259 let e = self.embedding_inferences_total.load(Ordering::Relaxed);
260 if e > 0 {
261 self.embedding_latency_sum_us.load(Ordering::Relaxed) as f64 / e as f64 / 1000.0
262 } else {
263 0.0
264 }
265 },
266 cache_hit_rate: if cache_hits + cache_misses > 0 {
267 cache_hits as f64 / (cache_hits + cache_misses) as f64
268 } else {
269 0.0
270 },
271 compression_ratio: if comp_in > 0 {
272 1.0 - (comp_out as f64 / comp_in as f64)
273 } else {
274 0.0
275 },
276 session_uptime_secs: self.session_start.elapsed().as_secs(),
277 }
278 }
279
280 pub(crate) fn daily_telemetry_snapshot(&self) -> DailyTelemetrySnapshot {
281 let per_tool = self
282 .tool_call_consistency
283 .lock()
284 .unwrap_or_else(std::sync::PoisonError::into_inner);
285 DailyTelemetrySnapshot {
286 per_tool: per_tool.clone(),
287 tool_calls: self.tool_calls_total.load(Ordering::Relaxed),
288 tool_failures: self.tool_calls_error.load(Ordering::Relaxed),
289 tool_latency_buckets: std::array::from_fn(|index| {
290 self.tool_call_latency_buckets[index].load(Ordering::Relaxed)
291 }),
292 session_uptime_secs: self.session_start.elapsed().as_secs(),
293 tokens_input: self.tokens_input.load(Ordering::Relaxed),
294 tokens_output: self.tokens_output.load(Ordering::Relaxed),
295 failure_templates: self
296 .failure_templates
297 .lock()
298 .unwrap_or_else(std::sync::PoisonError::into_inner)
299 .clone(),
300 }
301 }
302
303 pub fn to_otel_attributes(&self) -> Vec<(&'static str, String)> {
305 let snap = self.snapshot();
306 vec![
307 ("gen_ai.usage.input_tokens", snap.tokens_input.to_string()),
308 ("gen_ai.usage.output_tokens", snap.tokens_output.to_string()),
309 ("lean_ctx.tokens.saved", snap.tokens_saved.to_string()),
310 (
311 "lean_ctx.tool.calls.total",
312 snap.tool_calls_total.to_string(),
313 ),
314 (
315 "lean_ctx.tool.calls.error",
316 snap.tool_calls_error.to_string(),
317 ),
318 (
319 "lean_ctx.tool.latency_avg_ms",
320 format!("{:.2}", snap.tool_call_avg_latency_ms),
321 ),
322 (
323 "lean_ctx.search.queries",
324 snap.search_queries_total.to_string(),
325 ),
326 (
327 "lean_ctx.search.latency_avg_ms",
328 format!("{:.2}", snap.search_avg_latency_ms),
329 ),
330 (
331 "lean_ctx.embedding.inferences",
332 snap.embedding_inferences.to_string(),
333 ),
334 (
335 "lean_ctx.embedding.latency_avg_ms",
336 format!("{:.2}", snap.embedding_avg_latency_ms),
337 ),
338 (
339 "lean_ctx.cache.hit_rate",
340 format!("{:.4}", snap.cache_hit_rate),
341 ),
342 (
343 "lean_ctx.compression.ratio",
344 format!("{:.4}", snap.compression_ratio),
345 ),
346 (
347 "lean_ctx.session.uptime_secs",
348 snap.session_uptime_secs.to_string(),
349 ),
350 ]
351 }
352}
353
354#[derive(Debug, Clone)]
355pub(crate) struct DailyTelemetrySnapshot {
356 pub tool_calls: u64,
357 pub tool_failures: u64,
358 pub tool_latency_buckets: [u64; TOOL_LATENCY_BUCKET_UPPER_MS.len()],
359 pub session_uptime_secs: u64,
360 pub per_tool: BTreeMap<&'static str, ToolCallCounter>,
361 pub tokens_input: u64,
363 pub tokens_output: u64,
364 pub failure_templates: BTreeMap<(&'static str, String), u64>,
366}
367
368#[derive(Debug, Clone)]
370pub struct MetricsSnapshot {
371 pub tokens_input: u64,
372 pub tokens_output: u64,
373 pub tokens_saved: u64,
374 pub tool_calls_total: u64,
375 pub tool_calls_error: u64,
376 pub tool_call_avg_latency_ms: f64,
377 pub search_queries_total: u64,
378 pub search_avg_latency_ms: f64,
379 pub embedding_inferences: u64,
380 pub embedding_avg_latency_ms: f64,
381 pub cache_hit_rate: f64,
382 pub compression_ratio: f64,
383 pub session_uptime_secs: u64,
384}
385
386impl MetricsSnapshot {
387 pub fn to_compact_string(&self) -> String {
388 format!(
389 "tok={}/{}/{} calls={}/{} search={} embed={} cache={:.0}% comp={:.0}% up={}s",
390 self.tokens_input,
391 self.tokens_output,
392 self.tokens_saved,
393 self.tool_calls_total,
394 self.tool_calls_error,
395 self.search_queries_total,
396 self.embedding_inferences,
397 self.cache_hit_rate * 100.0,
398 self.compression_ratio * 100.0,
399 self.session_uptime_secs,
400 )
401 }
402
403 pub fn to_json(&self) -> String {
404 serde_json::json!({
405 "gen_ai": {
406 "usage": {
407 "input_tokens": self.tokens_input,
408 "output_tokens": self.tokens_output,
409 }
410 },
411 "lean_ctx": {
412 "tokens": { "saved": self.tokens_saved },
413 "tool": {
414 "calls_total": self.tool_calls_total,
415 "calls_error": self.tool_calls_error,
416 "avg_latency_ms": self.tool_call_avg_latency_ms,
417 },
418 "search": {
419 "queries": self.search_queries_total,
420 "avg_latency_ms": self.search_avg_latency_ms,
421 },
422 "embedding": {
423 "inferences": self.embedding_inferences,
424 "avg_latency_ms": self.embedding_avg_latency_ms,
425 },
426 "cache": { "hit_rate": self.cache_hit_rate },
427 "compression": { "ratio": self.compression_ratio },
428 "session": { "uptime_secs": self.session_uptime_secs },
429 }
430 })
431 .to_string()
432 }
433}
434
435pub struct ToolCallTimer {
437 start: Instant,
438 tool_name: &'static str,
439}
440
441impl ToolCallTimer {
442 pub fn new(tool_name: &'static str) -> Self {
443 Self {
444 start: Instant::now(),
445 tool_name,
446 }
447 }
448
449 pub fn finish(self, success: bool) {
450 let elapsed = self.start.elapsed();
451 let us = elapsed.as_micros() as u64;
452 global_metrics().record_tool_call(us, success);
453 tracing::debug!(
454 tool = self.tool_name,
455 latency_ms = elapsed.as_millis() as u64,
456 success,
457 "tool_call"
458 );
459 }
460}
461
462impl Metrics {
467 pub fn to_prometheus(&self) -> String {
468 let snap = self.snapshot();
469 let budget = crate::core::budget_tracker::BudgetTracker::global().check();
470 let slo_snap = crate::core::slo::evaluate_quiet();
471 let slo_violations = slo_snap.violations.len();
472
473 let mut lines = Vec::with_capacity(32);
474
475 lines.push("# HELP lean_ctx_tokens_saved_total Total tokens saved by compression".into());
476 lines.push("# TYPE lean_ctx_tokens_saved_total counter".into());
477 lines.push(format!("lean_ctx_tokens_saved_total {}", snap.tokens_saved));
478
479 lines.push("# HELP lean_ctx_tokens_input_total Total input tokens processed".into());
480 lines.push("# TYPE lean_ctx_tokens_input_total counter".into());
481 lines.push(format!("lean_ctx_tokens_input_total {}", snap.tokens_input));
482
483 lines.push("# HELP lean_ctx_tokens_output_total Total output tokens generated".into());
484 lines.push("# TYPE lean_ctx_tokens_output_total counter".into());
485 lines.push(format!(
486 "lean_ctx_tokens_output_total {}",
487 snap.tokens_output
488 ));
489
490 lines.push("# HELP lean_ctx_compression_ratio Current compression ratio".into());
491 lines.push("# TYPE lean_ctx_compression_ratio gauge".into());
492 lines.push(format!(
493 "lean_ctx_compression_ratio {:.4}",
494 snap.compression_ratio
495 ));
496
497 lines.push("# HELP lean_ctx_tool_calls_total Total tool calls".into());
498 lines.push("# TYPE lean_ctx_tool_calls_total counter".into());
499 lines.push(format!(
500 "lean_ctx_tool_calls_total {}",
501 snap.tool_calls_total
502 ));
503
504 lines.push("# HELP lean_ctx_tool_calls_error_total Total failed tool calls".into());
505 lines.push("# TYPE lean_ctx_tool_calls_error_total counter".into());
506 lines.push(format!(
507 "lean_ctx_tool_calls_error_total {}",
508 snap.tool_calls_error
509 ));
510
511 lines.push("# HELP lean_ctx_session_cost_usd Estimated session cost in USD".into());
512 lines.push("# TYPE lean_ctx_session_cost_usd gauge".into());
513 lines.push(format!(
514 "lean_ctx_session_cost_usd {:.4}",
515 budget.cost.used_usd
516 ));
517
518 lines.push("# HELP lean_ctx_session_context_tokens Current context token count".into());
519 lines.push("# TYPE lean_ctx_session_context_tokens gauge".into());
520 lines.push(format!(
521 "lean_ctx_session_context_tokens {}",
522 budget.tokens.used
523 ));
524
525 lines.push("# HELP lean_ctx_shell_invocations_total Total shell invocations".into());
526 lines.push("# TYPE lean_ctx_shell_invocations_total counter".into());
527 lines.push(format!(
528 "lean_ctx_shell_invocations_total {}",
529 budget.shell.used
530 ));
531
532 lines.push("# HELP lean_ctx_slo_violations_total Total active SLO violations".into());
533 lines.push("# TYPE lean_ctx_slo_violations_total gauge".into());
534 lines.push(format!("lean_ctx_slo_violations_total {slo_violations}"));
535
536 lines.push("# HELP lean_ctx_cache_hit_rate Cache hit rate (0-1)".into());
537 lines.push("# TYPE lean_ctx_cache_hit_rate gauge".into());
538 lines.push(format!(
539 "lean_ctx_cache_hit_rate {:.4}",
540 snap.cache_hit_rate
541 ));
542
543 lines.push("# HELP lean_ctx_anomalies_total Total anomaly detections".into());
544 lines.push("# TYPE lean_ctx_anomalies_total gauge".into());
545 let anomaly_count = crate::core::anomaly::summary()
546 .iter()
547 .filter(|m| m.count > 0)
548 .count();
549 lines.push(format!("lean_ctx_anomalies_total {anomaly_count}"));
550
551 let verify_snap = crate::core::output_verification::stats_snapshot();
552 lines.push("# HELP lean_ctx_verification_pass_total Total verification passes".into());
553 lines.push("# TYPE lean_ctx_verification_pass_total counter".into());
554 lines.push(format!(
555 "lean_ctx_verification_pass_total {}",
556 verify_snap.pass
557 ));
558
559 lines.push("# HELP lean_ctx_verification_warn_total Total verification warnings".into());
560 lines.push("# TYPE lean_ctx_verification_warn_total counter".into());
561 lines.push(format!(
562 "lean_ctx_verification_warn_total {}",
563 verify_snap.warn_items
564 ));
565
566 lines.push(
567 "# HELP lean_ctx_verification_warn_runs_total Total runs with verification warnings"
568 .into(),
569 );
570 lines.push("# TYPE lean_ctx_verification_warn_runs_total counter".into());
571 lines.push(format!(
572 "lean_ctx_verification_warn_runs_total {}",
573 verify_snap.warn_runs
574 ));
575
576 lines.push("# HELP lean_ctx_verification_pass_rate Verification pass rate".into());
577 lines.push("# TYPE lean_ctx_verification_pass_rate gauge".into());
578 lines.push(format!(
579 "lean_ctx_verification_pass_rate {:.4}",
580 verify_snap.pass_rate
581 ));
582
583 lines.push("# HELP lean_ctx_info_loss_score Average info loss score (0..1)".into());
584 lines.push("# TYPE lean_ctx_info_loss_score gauge".into());
585 lines.push(format!(
586 "lean_ctx_info_loss_score {:.6}",
587 verify_snap.avg_info_loss_score
588 ));
589
590 lines.push("# HELP lean_ctx_session_uptime_seconds Session uptime in seconds".into());
591 lines.push("# TYPE lean_ctx_session_uptime_seconds gauge".into());
592 lines.push(format!(
593 "lean_ctx_session_uptime_seconds {}",
594 snap.session_uptime_secs
595 ));
596
597 let (ledger_tokens, ledger_usd) = ledger_totals_cached();
600 lines.push(
601 "# HELP lean_ctx_ledger_tokens_saved_total Verified tokens saved (signed ledger)"
602 .into(),
603 );
604 lines.push("# TYPE lean_ctx_ledger_tokens_saved_total counter".into());
605 lines.push(format!(
606 "lean_ctx_ledger_tokens_saved_total {ledger_tokens}"
607 ));
608
609 lines.push(
610 "# HELP lean_ctx_cost_saved_usd_total Verified cost saved in USD (signed ledger)"
611 .into(),
612 );
613 lines.push("# TYPE lean_ctx_cost_saved_usd_total counter".into());
614 lines.push(format!("lean_ctx_cost_saved_usd_total {ledger_usd:.4}"));
615
616 lines.push("# HELP lean_ctx_info Deployment metadata for tag joins".into());
622 lines.push("# TYPE lean_ctx_info gauge".into());
623 lines.push(format!("lean_ctx_info{{{}}} 1", info_labels()));
624
625 lines.join("\n") + "\n"
626 }
627}
628
629fn escape_label(v: &str) -> String {
631 v.replace('\\', "\\\\")
632 .replace('"', "\\\"")
633 .replace('\n', "\\n")
634}
635
636pub fn info_tags() -> Vec<(&'static str, String)> {
641 let project = std::env::current_dir()
642 .ok()
643 .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
644 .unwrap_or_else(|| "unknown".to_string());
645 let model = crate::hook_handlers::load_detected_model()
646 .map_or_else(|| "unknown".to_string(), |(name, _)| name);
647 vec![
648 ("project", project),
649 ("profile", crate::core::profiles::active_profile_name()),
650 ("agent_role", crate::core::roles::active_role_name()),
651 ("model", model),
652 ("version", env!("CARGO_PKG_VERSION").to_string()),
653 ]
654}
655
656fn info_labels() -> String {
658 info_tags()
659 .iter()
660 .map(|(k, v)| format!("{k}=\"{}\"", escape_label(v)))
661 .collect::<Vec<_>>()
662 .join(",")
663}
664
665pub(crate) fn ledger_totals_cached() -> (u64, f64) {
668 use std::sync::Mutex;
669 use std::time::{Duration, Instant};
670 static CACHE: Mutex<Option<(Instant, (u64, f64))>> = Mutex::new(None);
671
672 let Ok(mut guard) = CACHE.lock() else {
673 return (0, 0.0);
674 };
675 if let Some((at, totals)) = *guard
676 && at.elapsed() < Duration::from_secs(30)
677 {
678 return totals;
679 }
680 let summary = crate::core::savings_ledger::summary();
681 let totals = (summary.net_saved_tokens(), summary.saved_usd);
682 *guard = Some((Instant::now(), totals));
683 totals
684}
685
686#[cfg(test)]
687mod tests {
688 use super::*;
689
690 #[test]
691 fn record_tool_call() {
692 let m = Metrics::new();
693 m.record_tool_call(5000, true);
694 m.record_tool_call(3000, false);
695
696 let snap = m.snapshot();
697 assert_eq!(snap.tool_calls_total, 2);
698 assert_eq!(snap.tool_calls_error, 1);
699 assert!(snap.tool_call_avg_latency_ms > 0.0);
700 }
701
702 #[test]
703 fn named_tool_call_moves_totals_and_per_tool_counter_together() {
704 let m = Metrics::new();
705 m.record_named_tool_call("ctx_read", 1_000, true);
706 m.record_named_tool_call("ctx_read", 2_000, false);
707 m.record_named_tool_call("ctx_shell", 3_000, true);
708
709 let snap = m.daily_telemetry_snapshot();
710 assert_eq!(snap.tool_calls, 3);
711 assert_eq!(snap.tool_failures, 1);
712 assert_eq!(
713 snap.per_tool.get("ctx_read"),
714 Some(&ToolCallCounter {
715 calls: 2,
716 failures: 1,
717 latency_us: 3_000,
718 failure_kinds: {
719 let mut kinds = [0; crate::core::telemetry_failure::FAILURE_KINDS.len()];
720 kinds[crate::core::telemetry_failure::FailureKind::Other.index()] = 1;
721 kinds
722 },
723 })
724 );
725 assert_eq!(
726 snap.per_tool.get("ctx_shell"),
727 Some(&ToolCallCounter {
728 calls: 1,
729 failures: 0,
730 latency_us: 3_000,
731 ..ToolCallCounter::default()
732 })
733 );
734 }
735
736 #[test]
737 fn concurrent_daily_snapshot_never_observes_partial_tool_call() {
738 let metrics = std::sync::Arc::new(Metrics::new());
739 let writers = (0..4)
740 .map(|worker| {
741 let metrics = std::sync::Arc::clone(&metrics);
742 std::thread::spawn(move || {
743 for call in 0..1_000 {
744 metrics.record_tool_call((call + 1) * 1_000, (call + worker) % 3 != 0);
745 }
746 })
747 })
748 .collect::<Vec<_>>();
749 while writers.iter().any(|writer| !writer.is_finished()) {
750 let snapshot = metrics.daily_telemetry_snapshot();
751 assert_eq!(
752 snapshot.tool_latency_buckets.iter().sum::<u64>(),
753 snapshot.tool_calls
754 );
755 assert!(snapshot.tool_failures <= snapshot.tool_calls);
756 }
757 for writer in writers {
758 writer.join().expect("writer");
759 }
760 let snapshot = metrics.daily_telemetry_snapshot();
761 assert_eq!(snapshot.tool_calls, 4_000);
762 assert_eq!(
763 snapshot.tool_latency_buckets.iter().sum::<u64>(),
764 snapshot.tool_calls
765 );
766 assert!(snapshot.tool_failures <= snapshot.tool_calls);
767 }
768
769 #[test]
770 fn record_tokens() {
771 let m = Metrics::new();
772 m.record_tokens(100, 50, 200);
773 m.record_tokens(150, 75, 300);
774
775 let snap = m.snapshot();
776 assert_eq!(snap.tokens_input, 250);
777 assert_eq!(snap.tokens_output, 125);
778 assert_eq!(snap.tokens_saved, 500);
779 }
780
781 #[test]
782 fn record_search() {
783 let m = Metrics::new();
784 m.record_search(2000, 5);
785 m.record_search(4000, 3);
786
787 let snap = m.snapshot();
788 assert_eq!(snap.search_queries_total, 2);
789 assert!((snap.search_avg_latency_ms - 3.0).abs() < 0.01);
790 }
791
792 #[test]
793 fn cache_hit_rate() {
794 let m = Metrics::new();
795 m.record_cache(true);
796 m.record_cache(true);
797 m.record_cache(false);
798
799 let snap = m.snapshot();
800 assert!((snap.cache_hit_rate - 0.6667).abs() < 0.01);
801 }
802
803 #[test]
804 fn compression_ratio() {
805 let m = Metrics::new();
806 m.record_compression(1000, 200);
807
808 let snap = m.snapshot();
809 assert!((snap.compression_ratio - 0.8).abs() < 0.01);
810 }
811
812 #[test]
813 fn snapshot_compact_string() {
814 let m = Metrics::new();
815 m.record_tokens(100, 50, 200);
816 m.record_tool_call(5000, true);
817 let compact = m.snapshot().to_compact_string();
818 assert!(compact.contains("tok=100/50/200"));
819 assert!(compact.contains("calls=1/0"));
820 }
821
822 #[test]
823 fn snapshot_json() {
824 let m = Metrics::new();
825 m.record_tokens(100, 50, 200);
826 let json = m.snapshot().to_json();
827 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
828 assert_eq!(parsed["gen_ai"]["usage"]["input_tokens"], 100);
829 assert_eq!(parsed["lean_ctx"]["tokens"]["saved"], 200);
830 }
831
832 #[test]
833 fn otel_attributes() {
834 let m = Metrics::new();
835 m.record_tokens(100, 50, 200);
836 let attrs = m.to_otel_attributes();
837 assert!(
838 attrs
839 .iter()
840 .any(|(k, v)| *k == "gen_ai.usage.input_tokens" && v == "100")
841 );
842 }
843
844 #[test]
845 fn global_metrics_singleton() {
846 let m1 = global_metrics();
847 let m2 = global_metrics();
848 assert!(std::ptr::eq(m1, m2));
849 }
850
851 #[test]
852 fn tool_call_timer() {
853 let timer = ToolCallTimer::new("test_tool");
854 std::thread::sleep(std::time::Duration::from_millis(5));
855 timer.finish(true);
856 }
857}