Skip to main content

omega_cognitive_kernel/api/
metrics.rs

1//! Operational metrics snapshot and Prometheus text format export.
2
3use serde::Serialize;
4
5/// Read-only, in-memory operational metrics for export to monitoring systems.
6///
7/// The snapshot contains only counts, scalar gauges, and gate state. It does
8/// not include user goals, state paths, or other persisted content, and taking
9/// it performs no I/O or memory sampling. Counts named `retained_*` describe
10/// bounded in-memory history rather than lifetime totals.
11#[derive(Debug, Clone, PartialEq, Serialize)]
12#[non_exhaustive]
13pub struct KernelMetricsSnapshot {
14    /// Total number of kernel steps completed in the current persisted state.
15    pub steps_total: u64,
16    /// Number of cases currently resident in case memory.
17    pub cases_in_memory: usize,
18    /// Configured capacity of case memory.
19    pub case_memory_capacity: usize,
20    /// Number of strategies currently resident in strategy memory.
21    pub strategies_in_memory: usize,
22    /// Number of active cognitive modules.
23    pub active_modules: usize,
24    /// Number of patches retained in the bounded L1 patch history.
25    pub retained_patch_history: usize,
26    /// Current average prediction error.
27    pub average_prediction_error: f64,
28    /// Current adaptation score.
29    pub adaptation_score: f64,
30    /// Current error-damping factor.
31    pub error_damping: f64,
32    /// Current exploration bonus.
33    pub explore_bonus: f64,
34    /// Current risk tolerance.
35    pub risk_tolerance: f64,
36    /// Maximum risk permitted by the active policy.
37    pub max_risk: f64,
38    /// Whether L1 self-modification is enabled.
39    pub self_modify_enabled: bool,
40    /// Whether the L2 meta-controller is enabled.
41    pub l2_enabled: bool,
42    /// Whether L2 is currently in a fixed-point regime.
43    pub l2_in_fixed_point: bool,
44    /// Whether L2 is operating in defensive mode.
45    pub l2_defensive_mode: bool,
46    /// Current L2 gate state.
47    pub l2_gate_state: crate::l2::control::L2GateState,
48    /// Number of steps spent in the current L2 regime or arm.
49    pub l2_dwell_steps: u64,
50    /// Most recent L2 alignment score.
51    pub l2_alignment_score: f64,
52    /// L2 policy learning-rate parameter.
53    pub l2_alpha: f64,
54    /// L2 policy regularization parameter.
55    pub l2_beta: f64,
56    /// Current Lyapunov stability potential.
57    pub l2_lyapunov_potential: f64,
58    /// Residual used by the L2 Dayan stability calculation.
59    pub l2_dayan_residual: f64,
60    /// Whether the stability monitor vetoed an L2 change.
61    pub l2_lyapunov_veto: bool,
62    /// Whether the most recent L2 lookup hit the meta-cache.
63    pub l2_meta_cache_hit: bool,
64    /// Number of entries currently held by the L2 meta-cache.
65    pub l2_meta_cache_entries: usize,
66    /// Steps remaining before another L2 policy commit is allowed.
67    pub l2_commit_cooldown_remaining: u64,
68    /// Number of consecutive negative consequences observed by L2.
69    pub l2_negative_consequence_streak: u32,
70    /// Most recent consequence score observed by L2.
71    pub l2_last_consequence_score: f64,
72}
73
74#[cfg(feature = "std")]
75impl KernelMetricsSnapshot {
76    /// Formats every field in this snapshot as Prometheus text exposition.
77    ///
78    /// The output is a single, unlabeled sample per field. `steps_total` is a
79    /// counter; all other values are gauges because they describe current
80    /// state, bounded resident counts, or the most recently observed scores.
81    /// Boolean fields are encoded as `0` or `1`. The L2 gate state is encoded
82    /// as `0` for dormant and `1` for active. Non-finite floating-point values
83    /// are exported as `0` so that the exposition never contains `NaN` or an
84    /// infinity token. HELP strings are escaped according to the Prometheus
85    /// text format. This exporter adds no metrics beyond fields already held
86    /// by the snapshot and performs no I/O.
87    ///
88    /// This method is available only with the crate's `std` feature, like the
89    /// product-facing `Kernel` API. It does not change the `no_std` build or
90    /// add an allocation requirement to that path.
91    ///
92    /// # Examples
93    ///
94    /// ```
95    /// use omega_cognitive_kernel::{persist::MemoryStateStore, Kernel};
96    ///
97    /// fn main() -> omega_cognitive_kernel::Result<()> {
98    ///     let kernel = Kernel::open_with_store(Box::new(MemoryStateStore::new()))?;
99    ///     let text = kernel.metrics_snapshot().to_prometheus_text();
100    ///     assert!(text.contains("# TYPE omega_kernel_steps_total counter\n"));
101    ///     assert!(text.contains("omega_kernel_steps_total 0\n"));
102    ///     assert!(!text.contains("NaN"));
103    ///     assert!(!text.contains("Inf"));
104    ///     Ok(())
105    /// }
106    /// ```
107    pub fn to_prometheus_text(&self) -> String {
108        use crate::l2::control::L2GateState;
109
110        let mut output = String::new();
111        write_prometheus_metric(
112            &mut output,
113            "omega_kernel_steps_total",
114            "counter",
115            "Total number of kernel steps completed in the current persisted state.",
116            self.steps_total,
117        );
118        write_prometheus_metric(
119            &mut output,
120            "omega_kernel_cases_in_memory",
121            "gauge",
122            "Number of cases currently resident in case memory.",
123            self.cases_in_memory,
124        );
125        write_prometheus_metric(
126            &mut output,
127            "omega_kernel_case_memory_capacity",
128            "gauge",
129            "Configured capacity of case memory, in cases.",
130            self.case_memory_capacity,
131        );
132        write_prometheus_metric(
133            &mut output,
134            "omega_kernel_strategies_in_memory",
135            "gauge",
136            "Number of strategies currently resident in strategy memory.",
137            self.strategies_in_memory,
138        );
139        write_prometheus_metric(
140            &mut output,
141            "omega_kernel_active_modules",
142            "gauge",
143            "Number of active cognitive modules.",
144            self.active_modules,
145        );
146        write_prometheus_metric(
147            &mut output,
148            "omega_kernel_retained_patch_history",
149            "gauge",
150            "Number of patches retained in the bounded L1 patch history.",
151            self.retained_patch_history,
152        );
153        write_prometheus_metric(
154            &mut output,
155            "omega_kernel_average_prediction_error",
156            "gauge",
157            "Current average prediction error.",
158            finite_prometheus_value(self.average_prediction_error),
159        );
160        write_prometheus_metric(
161            &mut output,
162            "omega_kernel_adaptation_score",
163            "gauge",
164            "Current adaptation score.",
165            finite_prometheus_value(self.adaptation_score),
166        );
167        write_prometheus_metric(
168            &mut output,
169            "omega_kernel_error_damping",
170            "gauge",
171            "Current error-damping factor.",
172            finite_prometheus_value(self.error_damping),
173        );
174        write_prometheus_metric(
175            &mut output,
176            "omega_kernel_explore_bonus",
177            "gauge",
178            "Current exploration bonus.",
179            finite_prometheus_value(self.explore_bonus),
180        );
181        write_prometheus_metric(
182            &mut output,
183            "omega_kernel_risk_tolerance",
184            "gauge",
185            "Current risk tolerance.",
186            finite_prometheus_value(self.risk_tolerance),
187        );
188        write_prometheus_metric(
189            &mut output,
190            "omega_kernel_max_risk",
191            "gauge",
192            "Maximum risk permitted by the active policy.",
193            finite_prometheus_value(self.max_risk),
194        );
195        write_prometheus_metric(
196            &mut output,
197            "omega_kernel_self_modify_enabled",
198            "gauge",
199            "Whether L1 self-modification is enabled, encoded as 0 or 1.",
200            u8::from(self.self_modify_enabled),
201        );
202        write_prometheus_metric(
203            &mut output,
204            "omega_kernel_l2_enabled",
205            "gauge",
206            "Whether the L2 meta-controller is enabled, encoded as 0 or 1.",
207            u8::from(self.l2_enabled),
208        );
209        write_prometheus_metric(
210            &mut output,
211            "omega_kernel_l2_in_fixed_point",
212            "gauge",
213            "Whether L2 is in a fixed-point regime, encoded as 0 or 1.",
214            u8::from(self.l2_in_fixed_point),
215        );
216        write_prometheus_metric(
217            &mut output,
218            "omega_kernel_l2_defensive_mode",
219            "gauge",
220            "Whether L2 is in defensive mode, encoded as 0 or 1.",
221            u8::from(self.l2_defensive_mode),
222        );
223        write_prometheus_metric(
224            &mut output,
225            "omega_kernel_l2_gate_state",
226            "gauge",
227            "L2 gate state: 0 is dormant and 1 is active.",
228            match self.l2_gate_state {
229                L2GateState::Dormant => 0,
230                L2GateState::Active => 1,
231            },
232        );
233        write_prometheus_metric(
234            &mut output,
235            "omega_kernel_l2_dwell_steps",
236            "gauge",
237            "Number of steps spent in the current L2 regime or arm.",
238            self.l2_dwell_steps,
239        );
240        write_prometheus_metric(
241            &mut output,
242            "omega_kernel_l2_alignment_score",
243            "gauge",
244            "Most recent L2 alignment score.",
245            finite_prometheus_value(self.l2_alignment_score),
246        );
247        write_prometheus_metric(
248            &mut output,
249            "omega_kernel_l2_alpha",
250            "gauge",
251            "L2 policy learning-rate parameter.",
252            finite_prometheus_value(self.l2_alpha),
253        );
254        write_prometheus_metric(
255            &mut output,
256            "omega_kernel_l2_beta",
257            "gauge",
258            "L2 policy regularization parameter.",
259            finite_prometheus_value(self.l2_beta),
260        );
261        write_prometheus_metric(
262            &mut output,
263            "omega_kernel_l2_lyapunov_potential",
264            "gauge",
265            "Current Lyapunov stability potential.",
266            finite_prometheus_value(self.l2_lyapunov_potential),
267        );
268        write_prometheus_metric(
269            &mut output,
270            "omega_kernel_l2_dayan_residual",
271            "gauge",
272            "Residual used by the L2 Dayan stability calculation.",
273            finite_prometheus_value(self.l2_dayan_residual),
274        );
275        write_prometheus_metric(
276            &mut output,
277            "omega_kernel_l2_lyapunov_veto",
278            "gauge",
279            "Whether the stability monitor vetoed an L2 change, encoded as 0 or 1.",
280            u8::from(self.l2_lyapunov_veto),
281        );
282        write_prometheus_metric(
283            &mut output,
284            "omega_kernel_l2_meta_cache_hit",
285            "gauge",
286            "Whether the most recent L2 lookup hit the meta-cache, encoded as 0 or 1.",
287            u8::from(self.l2_meta_cache_hit),
288        );
289        write_prometheus_metric(
290            &mut output,
291            "omega_kernel_l2_meta_cache_entries",
292            "gauge",
293            "Number of entries currently held by the L2 meta-cache.",
294            self.l2_meta_cache_entries,
295        );
296        write_prometheus_metric(
297            &mut output,
298            "omega_kernel_l2_commit_cooldown_remaining",
299            "gauge",
300            "Steps remaining before another L2 policy commit is allowed.",
301            self.l2_commit_cooldown_remaining,
302        );
303        write_prometheus_metric(
304            &mut output,
305            "omega_kernel_l2_negative_consequence_streak",
306            "gauge",
307            "Number of consecutive negative consequences observed by L2.",
308            self.l2_negative_consequence_streak,
309        );
310        write_prometheus_metric(
311            &mut output,
312            "omega_kernel_l2_last_consequence_score",
313            "gauge",
314            "Most recent consequence score observed by L2.",
315            finite_prometheus_value(self.l2_last_consequence_score),
316        );
317        output
318    }
319}
320
321#[cfg(feature = "std")]
322fn finite_prometheus_value(value: f64) -> f64 {
323    if value.is_finite() {
324        value
325    } else {
326        0.0
327    }
328}
329
330#[cfg(feature = "std")]
331fn write_prometheus_metric(
332    output: &mut String,
333    name: &str,
334    metric_type: &str,
335    help: &str,
336    value: impl core::fmt::Display,
337) {
338    use core::fmt::Write as _;
339
340    let _ = write!(output, "# HELP {name} ");
341    for character in help.chars() {
342        match character {
343            '\\' => output.push_str("\\\\"),
344            '\n' => output.push_str("\\n"),
345            character => output.push(character),
346        }
347    }
348    output.push('\n');
349    let _ = writeln!(output, "# TYPE {name} {metric_type}");
350    let _ = writeln!(output, "{name} {value}");
351}
352
353#[cfg(test)]
354mod prometheus_export_tests {
355    use super::{finite_prometheus_value, write_prometheus_metric};
356
357    #[test]
358    fn non_finite_samples_are_replaced_with_zero() {
359        assert_eq!(finite_prometheus_value(f64::NAN), 0.0);
360        assert_eq!(finite_prometheus_value(f64::INFINITY), 0.0);
361        assert_eq!(finite_prometheus_value(f64::NEG_INFINITY), 0.0);
362        assert_eq!(finite_prometheus_value(1.25), 1.25);
363    }
364
365    #[test]
366    fn help_text_escapes_backslashes_and_newlines() {
367        let mut output = String::new();
368        write_prometheus_metric(
369            &mut output,
370            "test_metric",
371            "gauge",
372            "slash\\backslash\nline",
373            7,
374        );
375
376        assert_eq!(
377            output,
378            "# HELP test_metric slash\\\\backslash\\nline\n# TYPE test_metric gauge\ntest_metric 7\n"
379        );
380    }
381}