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    /// Increment the counter by `n`.
168    pub fn inc_by(&self, n: u64) {
169        if n == 0 {
170            return;
171        }
172        let r = registry();
173        let counters = r.counters.read();
174        if let Some(c) = counters.get(self.id) {
175            c.value.fetch_add(n, Ordering::Relaxed);
176        }
177    }
178}
179
180#[derive(Clone)]
181pub struct GaugeHandle {
182    id: usize,
183}
184
185impl GaugeHandle {
186    /// Set the gauge to a specific value.
187    pub fn set(&self, v: f64) {
188        let r = registry();
189        let gauges = r.gauges.read();
190        if let Some(g) = gauges.get(self.id) {
191            *g.value.lock() = v;
192        }
193    }
194
195    /// Increment the gauge by 1.
196    pub fn inc(&self) {
197        let r = registry();
198        let gauges = r.gauges.read();
199        if let Some(g) = gauges.get(self.id) {
200            let mut val = g.value.lock();
201            *val += 1.0;
202        }
203    }
204
205    /// Decrement the gauge by 1.
206    pub fn dec(&self) {
207        let r = registry();
208        let gauges = r.gauges.read();
209        if let Some(g) = gauges.get(self.id) {
210            let mut val = g.value.lock();
211            *val -= 1.0;
212        }
213    }
214}
215
216#[derive(Clone)]
217pub struct HistogramHandle {
218    id: usize,
219    buckets: Vec<f64>,
220}
221
222impl HistogramHandle {
223    /// Observe a value, adding it to the histogram.
224    pub fn observe(&self, value: f64) {
225        let r = registry();
226        let histograms = r.histograms.read();
227        if let Some(h) = histograms.get(self.id) {
228            {
229                let mut sum = h.sum.lock();
230                *sum += value;
231            }
232            {
233                let mut count = h.count.lock();
234                *count += 1;
235            }
236            {
237                let mut counts = h.counts.write();
238                for (i, boundary) in self.buckets.iter().enumerate() {
239                    if value <= *boundary {
240                        counts[i] += 1;
241                    }
242                }
243                // +Inf bucket
244                counts[self.buckets.len()] += 1;
245            }
246        }
247    }
248}
249
250struct Counter {
251    name: String,
252    help: String,
253    labels: Vec<(&'static str, &'static str)>,
254    value: AtomicU64,
255}
256
257struct Gauge {
258    name: String,
259    help: String,
260    value: Mutex<f64>,
261}
262
263struct Histogram {
264    name: String,
265    help: String,
266    buckets: Vec<f64>,
267    counts: RwLock<Vec<usize>>,
268    sum: Mutex<f64>,
269    count: Mutex<u64>,
270}
271
272/// Metrics handles initialized at startup.
273#[derive(Clone)]
274pub struct MetricsHandles {
275    pub agents_forked: CounterHandle,
276    pub agents_completed: CounterHandle,
277    pub agents_failed: CounterHandle,
278    pub orch_duration: HistogramHandle,
279    pub messages: CounterHandle,
280    /// LLM circuit breaker state: 0=closed, 1=open, 2=half_open.
281    pub llm_circuit_breaker_state: GaugeHandle,
282    /// Tool execution metrics.
283    pub tool_calls: CounterHandle,
284    pub tool_errors: CounterHandle,
285    pub tool_duration: HistogramHandle,
286    /// LLM call metrics.
287    pub llm_calls: CounterHandle,
288    pub llm_errors: CounterHandle,
289    /// Audit trail events dropped because the bus subscriber lagged.
290    /// Non-zero indicates the audit pipeline can't keep up with the
291    /// event rate; investigate bus capacity or high-frequency publishers.
292    pub audit_lagged_events: CounterHandle,
293}
294
295impl MetricsHandles {
296    /// Increment agents_forked counter.
297    pub fn inc_agents_forked(&self) {
298        self.agents_forked.inc();
299    }
300
301    /// Increment agents_completed counter.
302    pub fn inc_agents_completed(&self) {
303        self.agents_completed.inc();
304    }
305
306    /// Increment agents_failed counter.
307    pub fn inc_agents_failed(&self) {
308        self.agents_failed.inc();
309    }
310
311    /// Increment messages counter.
312    pub fn inc_messages(&self) {
313        self.messages.inc();
314    }
315
316    /// Observe orchestration duration.
317    pub fn observe_orch_duration(&self, value: f64) {
318        self.orch_duration.observe(value);
319    }
320}
321
322/// Global lazy metric handles.
323static METRICS: std::sync::OnceLock<MetricsHandles> = std::sync::OnceLock::new();
324
325/// Get or create the metrics handles.
326pub fn get_metrics() -> &'static MetricsHandles {
327    METRICS.get_or_init(|| {
328        let r = registry();
329        MetricsHandles {
330            agents_forked: r.counter("oxios_agents_forked_total", "Total agents forked", &[]),
331            agents_completed: r.counter(
332                "oxios_agents_completed_total",
333                "Total agents completed",
334                &[],
335            ),
336            agents_failed: r.counter("oxios_agents_failed_total", "Total agents failed", &[]),
337            orch_duration: r.histogram(
338                "oxios_orchestration_duration_seconds",
339                "Orchestration duration",
340                vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
341            ),
342            messages: r.counter("oxios_messages_processed_total", "Messages processed", &[]),
343            llm_circuit_breaker_state: r.gauge(
344                "oxios_llm_circuit_breaker_state",
345                "LLM circuit breaker state: 0=closed, 1=open, 2=half_open",
346                0.0,
347            ),
348            tool_calls: r.counter("oxios_tool_calls_total", "Tool calls", &[]),
349            tool_errors: r.counter("oxios_tool_errors_total", "Tool errors", &[]),
350            tool_duration: r.histogram(
351                "oxios_tool_duration_seconds",
352                "Tool call duration",
353                vec![0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
354            ),
355            llm_calls: r.counter("oxios_llm_calls_total", "LLM API calls", &[]),
356            llm_errors: r.counter("oxios_llm_errors_total", "LLM API errors", &[]),
357            audit_lagged_events: r.counter(
358                "oxios_audit_lagged_events_total",
359                "Audit events dropped due to broadcast subscriber lag",
360                &[],
361            ),
362        }
363    })
364}
365
366/// Register all built-in metrics. Call once at startup.
367pub fn register_builtin_metrics() {
368    let r = registry();
369
370    // Agent metrics
371    r.counter("oxios_agents_forked_total", "Total agents forked", &[]);
372    r.gauge("oxios_agents_running", "Currently running agents", 0.0);
373    r.counter(
374        "oxios_agents_completed_total",
375        "Total agents completed",
376        &[],
377    );
378    r.counter("oxios_agents_failed_total", "Total agents failed", &[]);
379
380    // Message metrics
381    r.counter(
382        "oxios_messages_processed_total",
383        "User messages processed",
384        &[],
385    );
386    r.histogram(
387        "oxios_orchestration_duration_seconds",
388        "Full orchestration duration",
389        vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
390    );
391
392    // RFC-024 §11: web↔daemon reliability metrics. Registered here so they
393    // appear on /metrics from startup; the corresponding increment sites
394    // live in oxios-gateway (deliver/timeout/replay) and the web routes
395    // (SSE/WS reconnect, asset swap, readiness state).
396    r.counter(
397        "oxios_gateway_messages_total",
398        "Outgoing messages (label: result=delivered|dropped|resynced|timed_out)",
399        &[],
400    );
401    r.counter(
402        "oxios_gateway_replay_requests_total",
403        "Replay requests (label: outcome=replay|resync)",
404        &[],
405    );
406    r.counter(
407        "oxios_sse_reconnects_total",
408        "SSE reconnects (label: reason=ok|lag|error|unauthorized)",
409        &[],
410    );
411    r.counter(
412        "oxios_ws_reconnects_total",
413        "WS reconnects (label: reason=ok|lag|error|unauthorized)",
414        &[],
415    );
416    r.counter(
417        "oxios_web_dist_swaps_total",
418        "Atomic web-dist swaps (RFC-024 SP3)",
419        &[],
420    );
421    r.gauge(
422        "oxios_readiness_state",
423        "0 = warming up, 1 = ready (RFC-024 SP4)",
424        0.0,
425    );
426    r.histogram(
427        "oxios_phase_duration_seconds",
428        "Phase duration",
429        vec![0.01, 0.05, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0],
430    );
431
432    // LLM metrics
433    r.counter("oxios_llm_calls_total", "LLM API calls", &[]);
434    r.histogram(
435        "oxios_llm_duration_seconds",
436        "LLM call duration",
437        vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0],
438    );
439    r.counter("oxios_llm_errors_total", "LLM API errors", &[]);
440    // Audit pipeline metric (state-area F4): events silently dropped when
441    // the audit trail subscriber falls behind the broadcast bus.
442    r.counter(
443        "oxios_audit_lagged_events_total",
444        "Audit events dropped due to broadcast subscriber lag",
445        &[],
446    );
447
448    // Tool metrics
449    r.counter("oxios_tool_calls_total", "Tool calls", &[]);
450    r.histogram(
451        "oxios_tool_duration_seconds",
452        "Tool call duration",
453        vec![0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
454    );
455    r.counter("oxios_tool_errors_total", "Tool errors", &[]);
456
457    // Memory metrics
458    r.gauge("oxios_memory_entries_total", "Total memory entries", 0.0);
459    r.counter("oxios_memory_recall_total", "Memory recall operations", &[]);
460
461    // Container metrics
462    r.counter("oxios_exec_total", "Exec calls", &[]);
463    r.histogram(
464        "oxios_exec_duration_seconds",
465        "Exec duration",
466        vec![0.1, 0.5, 1.0, 5.0, 10.0, 30.0],
467    );
468
469    // Session metrics
470    r.gauge("oxios_active_sessions", "Active sessions", 0.0);
471
472    // Initialize get_metrics() handles
473    let _ = get_metrics();
474}