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