Skip to main content

oxios_kernel/
metrics.rs

1//! Metrics — Prometheus-compatible counters, gauges, and histograms.
2//!
3//! This module provides in-process metrics without external dependencies.
4//! Exposed via GET /api/metrics in Prometheus text format.
5
6#![allow(missing_docs)]
7
8use parking_lot::{Mutex, RwLock};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11/// Thread-safe metrics registry.
12#[derive(Default)]
13pub struct MetricsRegistry {
14    counters: RwLock<Vec<Counter>>,
15    gauges: RwLock<Vec<Gauge>>,
16    histograms: RwLock<Vec<Histogram>>,
17}
18
19impl MetricsRegistry {
20    /// Create a new metrics registry.
21    pub fn new() -> Self {
22        Self::default()
23    }
24
25    /// Register a new counter and return a handle.
26    pub fn counter(
27        &self,
28        name: &'static str,
29        help: &'static str,
30        labels: &[(&'static str, &'static str)],
31    ) -> CounterHandle {
32        let mut counters = self.counters.write();
33        let id = counters.len();
34        counters.push(Counter {
35            name: name.into(),
36            help: help.into(),
37            labels: labels.into(),
38            value: AtomicU64::new(0),
39        });
40        CounterHandle { id }
41    }
42
43    /// Register a new gauge and return a handle.
44    pub fn gauge(&self, name: &'static str, help: &'static str, initial: f64) -> GaugeHandle {
45        let mut gauges = self.gauges.write();
46        let id = gauges.len();
47        gauges.push(Gauge {
48            name: name.into(),
49            help: help.into(),
50            value: Mutex::new(initial),
51        });
52        GaugeHandle { id }
53    }
54
55    /// Register a new histogram and return a handle.
56    pub fn histogram(
57        &self,
58        name: &'static str,
59        help: &'static str,
60        buckets: Vec<f64>,
61    ) -> HistogramHandle {
62        let mut histograms = self.histograms.write();
63        let id = histograms.len();
64        let counts: Vec<usize> = vec![0; buckets.len() + 1];
65        histograms.push(Histogram {
66            name: name.into(),
67            help: help.into(),
68            buckets: buckets.clone(),
69            counts: RwLock::new(counts),
70            sum: Mutex::new(0.0),
71            count: Mutex::new(0u64),
72        });
73        HistogramHandle { id, buckets }
74    }
75
76    /// Export all metrics in Prometheus text format.
77    pub fn export(&self) -> String {
78        let mut out = String::new();
79
80        // Counters
81        {
82            let counters = self.counters.read();
83            for c in counters.iter() {
84                out.push_str(&format!("# HELP {} {}\n", c.name, c.help));
85                out.push_str(&format!("# TYPE {} counter\n", c.name));
86                let value = c.value.load(Ordering::Relaxed);
87                let labels_str = if c.labels.is_empty() {
88                    String::new()
89                } else {
90                    format!(
91                        "{{{}}}",
92                        c.labels
93                            .iter()
94                            .map(|(k, v)| format!("{}=\"{}\"", k, v))
95                            .collect::<Vec<_>>()
96                            .join(",")
97                    )
98                };
99                out.push_str(&format!("{}{} {}\n", c.name, labels_str, value));
100            }
101        }
102
103        // Gauges
104        {
105            let gauges = self.gauges.read();
106            for g in gauges.iter() {
107                out.push_str(&format!("# HELP {} {}\n", g.name, g.help));
108                out.push_str(&format!("# TYPE {} gauge\n", g.name));
109                let value = *g.value.lock();
110                out.push_str(&format!("{} {}\n", g.name, value));
111            }
112        }
113
114        // Histograms
115        {
116            let histograms = self.histograms.read();
117            for h in histograms.iter() {
118                out.push_str(&format!("# HELP {} {}\n", h.name, h.help));
119                out.push_str(&format!("# TYPE {} histogram\n", h.name));
120                let sum = *h.sum.lock();
121                let count = *h.count.lock();
122                let bucket_values = h.buckets.clone();
123                let counts = h.counts.read();
124                let mut cumulative = 0usize;
125                for (i, _) in bucket_values.iter().enumerate() {
126                    cumulative += counts[i];
127                    let boundary = bucket_values[i];
128                    out.push_str(&format!(
129                        "{}{{le=\"{}\"}} {}\n",
130                        h.name, boundary, cumulative
131                    ));
132                }
133                // +Inf bucket
134                out.push_str(&format!("{}{{le=\"+Inf\"}} {}\n", h.name, cumulative));
135                out.push_str(&format!("{}_sum {} \n", h.name, sum));
136                out.push_str(&format!("{}_count {} \n", h.name, count));
137            }
138        }
139
140        out
141    }
142}
143
144/// Global metrics registry.
145static REGISTRY: std::sync::OnceLock<MetricsRegistry> = std::sync::OnceLock::new();
146
147/// Get the global metrics registry.
148pub fn registry() -> &'static MetricsRegistry {
149    REGISTRY.get_or_init(MetricsRegistry::new)
150}
151
152#[derive(Clone)]
153pub struct CounterHandle {
154    id: usize,
155}
156
157impl CounterHandle {
158    /// Increment the counter by 1.
159    pub fn inc(&self) {
160        let r = registry();
161        let counters = r.counters.read();
162        if let Some(c) = counters.get(self.id) {
163            c.value.fetch_add(1, Ordering::Relaxed);
164        }
165    }
166}
167
168#[derive(Clone)]
169pub struct GaugeHandle {
170    id: usize,
171}
172
173impl GaugeHandle {
174    /// Set the gauge to a specific value.
175    pub fn set(&self, v: f64) {
176        let r = registry();
177        let gauges = r.gauges.read();
178        if let Some(g) = gauges.get(self.id) {
179            *g.value.lock() = v;
180        }
181    }
182
183    /// Increment the gauge by 1.
184    pub fn inc(&self) {
185        let r = registry();
186        let gauges = r.gauges.read();
187        if let Some(g) = gauges.get(self.id) {
188            let mut val = g.value.lock();
189            *val += 1.0;
190        }
191    }
192
193    /// Decrement the gauge by 1.
194    pub fn dec(&self) {
195        let r = registry();
196        let gauges = r.gauges.read();
197        if let Some(g) = gauges.get(self.id) {
198            let mut val = g.value.lock();
199            *val -= 1.0;
200        }
201    }
202}
203
204#[derive(Clone)]
205pub struct HistogramHandle {
206    id: usize,
207    buckets: Vec<f64>,
208}
209
210impl HistogramHandle {
211    /// Observe a value, adding it to the histogram.
212    pub fn observe(&self, value: f64) {
213        let r = registry();
214        let histograms = r.histograms.read();
215        if let Some(h) = histograms.get(self.id) {
216            {
217                let mut sum = h.sum.lock();
218                *sum += value;
219            }
220            {
221                let mut count = h.count.lock();
222                *count += 1;
223            }
224            {
225                let mut counts = h.counts.write();
226                for (i, boundary) in self.buckets.iter().enumerate() {
227                    if value <= *boundary {
228                        counts[i] += 1;
229                    }
230                }
231                // +Inf bucket
232                counts[self.buckets.len()] += 1;
233            }
234        }
235    }
236}
237
238struct Counter {
239    name: String,
240    help: String,
241    labels: Vec<(&'static str, &'static str)>,
242    value: AtomicU64,
243}
244
245struct Gauge {
246    name: String,
247    help: String,
248    value: Mutex<f64>,
249}
250
251struct Histogram {
252    name: String,
253    help: String,
254    buckets: Vec<f64>,
255    counts: RwLock<Vec<usize>>,
256    sum: Mutex<f64>,
257    count: Mutex<u64>,
258}
259
260/// Metrics handles initialized at startup.
261#[derive(Clone)]
262pub struct MetricsHandles {
263    pub agents_forked: CounterHandle,
264    pub agents_completed: CounterHandle,
265    pub agents_failed: CounterHandle,
266    pub orch_duration: HistogramHandle,
267    pub messages: CounterHandle,
268    /// LLM circuit breaker state: 0=closed, 1=open, 2=half_open.
269    pub llm_circuit_breaker_state: GaugeHandle,
270}
271
272impl MetricsHandles {
273    /// Increment agents_forked counter.
274    pub fn inc_agents_forked(&self) {
275        self.agents_forked.inc();
276    }
277
278    /// Increment agents_completed counter.
279    pub fn inc_agents_completed(&self) {
280        self.agents_completed.inc();
281    }
282
283    /// Increment agents_failed counter.
284    pub fn inc_agents_failed(&self) {
285        self.agents_failed.inc();
286    }
287
288    /// Increment messages counter.
289    pub fn inc_messages(&self) {
290        self.messages.inc();
291    }
292
293    /// Observe orchestration duration.
294    pub fn observe_orch_duration(&self, value: f64) {
295        self.orch_duration.observe(value);
296    }
297}
298
299/// Global lazy metric handles.
300static METRICS: std::sync::OnceLock<MetricsHandles> = std::sync::OnceLock::new();
301
302/// Get or create the metrics handles.
303pub fn get_metrics() -> &'static MetricsHandles {
304    METRICS.get_or_init(|| {
305        let r = registry();
306        MetricsHandles {
307            agents_forked: r.counter("oxios_agents_forked_total", "Total agents forked", &[]),
308            agents_completed: r.counter(
309                "oxios_agents_completed_total",
310                "Total agents completed",
311                &[],
312            ),
313            agents_failed: r.counter("oxios_agents_failed_total", "Total agents failed", &[]),
314            orch_duration: r.histogram(
315                "oxios_orchestration_duration_seconds",
316                "Orchestration duration",
317                vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
318            ),
319            messages: r.counter("oxios_messages_processed_total", "Messages processed", &[]),
320            llm_circuit_breaker_state: r.gauge(
321                "oxios_llm_circuit_breaker_state",
322                "LLM circuit breaker state: 0=closed, 1=open, 2=half_open",
323                0.0,
324            ),
325        }
326    })
327}
328
329/// Register all built-in metrics. Call once at startup.
330pub fn register_builtin_metrics() {
331    let r = registry();
332
333    // Agent metrics
334    r.counter("oxios_agents_forked_total", "Total agents forked", &[]);
335    r.gauge("oxios_agents_running", "Currently running agents", 0.0);
336    r.counter(
337        "oxios_agents_completed_total",
338        "Total agents completed",
339        &[],
340    );
341    r.counter("oxios_agents_failed_total", "Total agents failed", &[]);
342
343    // Message metrics
344    r.counter(
345        "oxios_messages_processed_total",
346        "User messages processed",
347        &[],
348    );
349    r.histogram(
350        "oxios_orchestration_duration_seconds",
351        "Full orchestration duration",
352        vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
353    );
354    r.histogram(
355        "oxios_phase_duration_seconds",
356        "Phase duration",
357        vec![0.01, 0.05, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0],
358    );
359
360    // LLM metrics
361    r.counter("oxios_llm_calls_total", "LLM API calls", &[]);
362    r.histogram(
363        "oxios_llm_duration_seconds",
364        "LLM call duration",
365        vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0],
366    );
367    r.counter("oxios_llm_errors_total", "LLM API errors", &[]);
368
369    // Tool metrics
370    r.counter("oxios_tool_calls_total", "Tool calls", &[]);
371    r.histogram(
372        "oxios_tool_duration_seconds",
373        "Tool call duration",
374        vec![0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
375    );
376    r.counter("oxios_tool_errors_total", "Tool errors", &[]);
377
378    // Memory metrics
379    r.gauge("oxios_memory_entries_total", "Total memory entries", 0.0);
380    r.counter("oxios_memory_recall_total", "Memory recall operations", &[]);
381
382    // Container metrics
383    r.counter("oxios_exec_total", "Exec calls", &[]);
384    r.histogram(
385        "oxios_exec_duration_seconds",
386        "Exec duration",
387        vec![0.1, 0.5, 1.0, 5.0, 10.0, 30.0],
388    );
389
390    // Session metrics
391    r.gauge("oxios_active_sessions", "Active sessions", 0.0);
392
393    // Initialize get_metrics() handles
394    let _ = get_metrics();
395}