Skip to main content

lean_ctx/core/
slo.rs

1//! Context SLOs — configurable service level objectives for context metrics.
2//!
3//! Loads SLO definitions from `.lean-ctx/slos.toml` and evaluates them
4//! against live session counters after each tool call.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::path::PathBuf;
9use std::sync::{Mutex, OnceLock};
10use std::time::{Duration, Instant};
11
12use crate::core::budget_tracker::BudgetTracker;
13use crate::core::events;
14
15// ---------------------------------------------------------------------------
16// Configuration types
17// ---------------------------------------------------------------------------
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct SloConfig {
21    #[serde(default)]
22    pub slo: Vec<SloDefinition>,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct SloDefinition {
27    pub name: String,
28    pub metric: SloMetric,
29    pub threshold: f64,
30    #[serde(default)]
31    pub direction: SloDirection,
32    #[serde(default)]
33    pub action: SloAction,
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum SloMetric {
39    SessionContextTokens,
40    SessionCostUsd,
41    CompressionRatio,
42    ShellInvocations,
43    ToolCallsTotal,
44    ToolCallCount,
45}
46
47#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum SloDirection {
50    #[default]
51    Max,
52    Min,
53}
54
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum SloAction {
58    #[default]
59    Warn,
60    Throttle,
61    Block,
62}
63
64// ---------------------------------------------------------------------------
65// Runtime state
66// ---------------------------------------------------------------------------
67
68#[derive(Debug, Clone, Serialize)]
69pub struct SloStatus {
70    pub name: String,
71    pub metric: SloMetric,
72    pub threshold: f64,
73    pub actual: f64,
74    pub direction: SloDirection,
75    pub action: SloAction,
76    pub violated: bool,
77}
78
79#[derive(Debug, Clone, Serialize)]
80pub struct SloSnapshot {
81    pub slos: Vec<SloStatus>,
82    pub violations: Vec<SloStatus>,
83    pub worst_action: Option<SloAction>,
84}
85
86#[derive(Debug, Default)]
87struct ViolationHistory {
88    entries: Vec<ViolationEntry>,
89}
90
91#[derive(Debug, Clone, Serialize)]
92pub struct ViolationEntry {
93    pub timestamp: String,
94    pub slo_name: String,
95    pub metric: SloMetric,
96    pub threshold: f64,
97    pub actual: f64,
98    pub action: SloAction,
99}
100
101static SLO_CONFIG: OnceLock<Mutex<Vec<SloDefinition>>> = OnceLock::new();
102static VIOLATION_LOG: OnceLock<Mutex<ViolationHistory>> = OnceLock::new();
103static EMIT_STATE: OnceLock<Mutex<HashMap<String, EmitState>>> = OnceLock::new();
104
105const VIOLATION_DEBOUNCE: Duration = Duration::from_secs(30);
106
107#[derive(Debug, Default, Clone)]
108struct EmitState {
109    last_violated: bool,
110    last_emit: Option<Instant>,
111}
112
113fn config_store() -> &'static Mutex<Vec<SloDefinition>> {
114    SLO_CONFIG.get_or_init(|| Mutex::new(load_slos_from_disk()))
115}
116
117fn violation_store() -> &'static Mutex<ViolationHistory> {
118    VIOLATION_LOG.get_or_init(|| Mutex::new(ViolationHistory::default()))
119}
120
121fn emit_state_store() -> &'static Mutex<HashMap<String, EmitState>> {
122    EMIT_STATE.get_or_init(|| Mutex::new(HashMap::new()))
123}
124
125// ---------------------------------------------------------------------------
126// Loading
127// ---------------------------------------------------------------------------
128
129fn slo_toml_paths() -> Vec<PathBuf> {
130    let mut paths = Vec::new();
131
132    if let Ok(dir) = crate::core::data_dir::lean_ctx_data_dir() {
133        paths.push(dir.join("slos.toml"));
134    }
135
136    if let Ok(home) = std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) {
137        paths.push(PathBuf::from(home).join(".lean-ctx").join("slos.toml"));
138    }
139
140    if let Ok(cwd) = std::env::current_dir() {
141        paths.push(cwd.join(".lean-ctx").join("slos.toml"));
142    }
143
144    paths
145}
146
147fn load_slos_from_disk() -> Vec<SloDefinition> {
148    for path in slo_toml_paths() {
149        if let Ok(content) = std::fs::read_to_string(&path) {
150            match toml::from_str::<SloConfig>(&content) {
151                Ok(cfg) => return cfg.slo,
152                Err(e) => {
153                    eprintln!("[lean-ctx] slo: parse error in {}: {e}", path.display());
154                }
155            }
156        }
157    }
158    default_slos()
159}
160
161fn default_slos() -> Vec<SloDefinition> {
162    vec![
163        SloDefinition {
164            name: "context_budget".into(),
165            metric: SloMetric::SessionContextTokens,
166            threshold: 200_000.0,
167            direction: SloDirection::Max,
168            action: SloAction::Warn,
169        },
170        SloDefinition {
171            name: "cost_per_session".into(),
172            metric: SloMetric::SessionCostUsd,
173            threshold: 5.0,
174            direction: SloDirection::Max,
175            action: SloAction::Throttle,
176        },
177        SloDefinition {
178            name: "compression_efficiency".into(),
179            metric: SloMetric::CompressionRatio,
180            // CompressionRatio = sent/original. Lower is better.
181            // Warn only when compression is poor (e.g. >75% of original tokens still sent).
182            threshold: 0.75,
183            direction: SloDirection::Max,
184            action: SloAction::Warn,
185        },
186    ]
187}
188
189pub fn reload() {
190    let fresh = load_slos_from_disk();
191    if let Ok(mut store) = config_store().lock() {
192        *store = fresh;
193    }
194}
195
196pub fn active_slos() -> Vec<SloDefinition> {
197    config_store().lock().map(|s| s.clone()).unwrap_or_default()
198}
199
200// ---------------------------------------------------------------------------
201// Evaluation
202// ---------------------------------------------------------------------------
203
204fn read_metric(metric: SloMetric) -> f64 {
205    let tracker = BudgetTracker::global();
206    match metric {
207        SloMetric::SessionContextTokens => tracker.tokens_used() as f64,
208        SloMetric::SessionCostUsd => tracker.cost_usd(),
209        SloMetric::ShellInvocations => tracker.shell_used() as f64,
210        SloMetric::CompressionRatio => {
211            let ledger = crate::core::context_ledger::ContextLedger::load();
212            if ledger.entries.is_empty() {
213                0.0
214            } else {
215                ledger.compression_ratio()
216            }
217        }
218        SloMetric::ToolCallsTotal | SloMetric::ToolCallCount => tracker.tool_calls_count() as f64,
219    }
220}
221
222fn is_violated(actual: f64, threshold: f64, direction: SloDirection) -> bool {
223    match direction {
224        SloDirection::Max => actual > threshold,
225        SloDirection::Min => actual < threshold,
226    }
227}
228
229pub fn evaluate() -> SloSnapshot {
230    let defs = active_slos();
231    let mut slos = Vec::with_capacity(defs.len());
232    let mut violations = Vec::new();
233    let now = Instant::now();
234    let mut emit_state = emit_state_store()
235        .lock()
236        .unwrap_or_else(std::sync::PoisonError::into_inner);
237
238    for def in &defs {
239        let actual = read_metric(def.metric);
240        let violated = is_violated(actual, def.threshold, def.direction);
241
242        let status = SloStatus {
243            name: def.name.clone(),
244            metric: def.metric,
245            threshold: def.threshold,
246            actual,
247            direction: def.direction,
248            action: def.action,
249            violated,
250        };
251
252        if violated {
253            let st = emit_state.entry(def.name.clone()).or_default();
254            let is_first = !st.last_violated;
255            let is_due = st
256                .last_emit
257                .is_none_or(|t| t.elapsed() >= VIOLATION_DEBOUNCE);
258            if is_first || is_due {
259                st.last_emit = Some(now);
260                record_violation(&status);
261                emit_slo_event(&status);
262            }
263            st.last_violated = true;
264            violations.push(status.clone());
265        } else if let Some(st) = emit_state.get_mut(&def.name) {
266            st.last_violated = false;
267        }
268
269        slos.push(status);
270    }
271
272    let worst_action = violations.iter().map(|v| v.action).max_by_key(|a| match a {
273        SloAction::Warn => 0,
274        SloAction::Throttle => 1,
275        SloAction::Block => 2,
276    });
277
278    SloSnapshot {
279        slos,
280        violations,
281        worst_action,
282    }
283}
284
285pub fn evaluate_quiet() -> SloSnapshot {
286    // Record that SLO evaluation happened (count-only observability).
287    crate::core::verification_observability::record_slo_eval();
288    let defs = active_slos();
289    let mut slos = Vec::with_capacity(defs.len());
290    let mut violations = Vec::new();
291
292    for def in &defs {
293        let actual = read_metric(def.metric);
294        let violated = is_violated(actual, def.threshold, def.direction);
295
296        let status = SloStatus {
297            name: def.name.clone(),
298            metric: def.metric,
299            threshold: def.threshold,
300            actual,
301            direction: def.direction,
302            action: def.action,
303            violated,
304        };
305
306        if violated {
307            violations.push(status.clone());
308        }
309        slos.push(status);
310    }
311
312    let worst_action = violations.iter().map(|v| v.action).max_by_key(|a| match a {
313        SloAction::Warn => 0,
314        SloAction::Throttle => 1,
315        SloAction::Block => 2,
316    });
317
318    SloSnapshot {
319        slos,
320        violations,
321        worst_action,
322    }
323}
324
325fn record_violation(status: &SloStatus) {
326    if let Ok(mut hist) = violation_store().lock() {
327        let entry = ViolationEntry {
328            timestamp: chrono::Local::now()
329                .format("%Y-%m-%dT%H:%M:%S%.3f")
330                .to_string(),
331            slo_name: status.name.clone(),
332            metric: status.metric,
333            threshold: status.threshold,
334            actual: status.actual,
335            action: status.action,
336        };
337        hist.entries.push(entry);
338        if hist.entries.len() > 500 {
339            let excess = hist.entries.len() - 500;
340            hist.entries.drain(..excess);
341        }
342    }
343}
344
345fn emit_slo_event(status: &SloStatus) {
346    events::emit(events::EventKind::SloViolation {
347        slo_name: status.name.clone(),
348        metric: format!("{:?}", status.metric),
349        threshold: status.threshold,
350        actual: status.actual,
351        action: format!("{:?}", status.action),
352    });
353}
354
355pub fn violation_history(limit: usize) -> Vec<ViolationEntry> {
356    violation_store()
357        .lock()
358        .map(|h| {
359            let start = h.entries.len().saturating_sub(limit);
360            h.entries[start..].to_vec()
361        })
362        .unwrap_or_default()
363}
364
365pub fn clear_violations() {
366    if let Ok(mut hist) = violation_store().lock() {
367        hist.entries.clear();
368    }
369}
370
371// ---------------------------------------------------------------------------
372// Formatting
373// ---------------------------------------------------------------------------
374
375impl SloSnapshot {
376    pub fn format_compact(&self) -> String {
377        let total = self.slos.len();
378        let violated = self.violations.len();
379        let mut out = format!("SLOs: {}/{} passing", total - violated, total);
380
381        for v in &self.violations {
382            out.push_str(&format!(
383                "\n  !! {} ({:?}): {:.2} vs threshold {:.2} → {:?}",
384                v.name, v.metric, v.actual, v.threshold, v.action
385            ));
386        }
387
388        out
389    }
390
391    pub fn should_block(&self) -> bool {
392        self.worst_action == Some(SloAction::Block)
393    }
394
395    pub fn should_throttle(&self) -> bool {
396        matches!(
397            self.worst_action,
398            Some(SloAction::Throttle | SloAction::Block)
399        )
400    }
401}
402
403impl std::fmt::Display for SloMetric {
404    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405        match self {
406            Self::SessionContextTokens => write!(f, "session_context_tokens"),
407            Self::SessionCostUsd => write!(f, "session_cost_usd"),
408            Self::CompressionRatio => write!(f, "compression_ratio"),
409            Self::ShellInvocations => write!(f, "shell_invocations"),
410            Self::ToolCallsTotal => write!(f, "tool_calls_total"),
411            Self::ToolCallCount => write!(f, "tool_call_count"),
412        }
413    }
414}
415
416impl std::fmt::Display for SloAction {
417    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
418        match self {
419            Self::Warn => write!(f, "warn"),
420            Self::Throttle => write!(f, "throttle"),
421            Self::Block => write!(f, "block"),
422        }
423    }
424}
425
426// ---------------------------------------------------------------------------
427// Tests
428// ---------------------------------------------------------------------------
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    #[test]
435    fn default_slos_are_valid() {
436        let defs = default_slos();
437        assert_eq!(defs.len(), 3);
438        assert_eq!(defs[0].name, "context_budget");
439        assert_eq!(defs[1].action, SloAction::Throttle);
440        assert_eq!(defs[2].direction, SloDirection::Max);
441    }
442
443    #[test]
444    fn violation_detection_max() {
445        assert!(is_violated(60_000.0, 50_000.0, SloDirection::Max));
446        assert!(!is_violated(40_000.0, 50_000.0, SloDirection::Max));
447    }
448
449    #[test]
450    fn violation_detection_min() {
451        assert!(is_violated(0.2, 0.3, SloDirection::Min));
452        assert!(!is_violated(0.5, 0.3, SloDirection::Min));
453    }
454
455    #[test]
456    fn slo_config_parses_from_toml() {
457        let toml_str = r#"
458[[slo]]
459name = "test_budget"
460metric = "session_context_tokens"
461threshold = 100000
462action = "warn"
463
464[[slo]]
465name = "test_cost"
466metric = "session_cost_usd"
467threshold = 2.0
468action = "block"
469direction = "max"
470"#;
471        let cfg: SloConfig = toml::from_str(toml_str).unwrap();
472        assert_eq!(cfg.slo.len(), 2);
473        assert_eq!(cfg.slo[0].name, "test_budget");
474        assert_eq!(cfg.slo[0].metric, SloMetric::SessionContextTokens);
475        assert_eq!(cfg.slo[1].action, SloAction::Block);
476    }
477
478    #[test]
479    fn snapshot_format_compact() {
480        let snap = SloSnapshot {
481            slos: vec![
482                SloStatus {
483                    name: "budget".into(),
484                    metric: SloMetric::SessionContextTokens,
485                    threshold: 50000.0,
486                    actual: 30000.0,
487                    direction: SloDirection::Max,
488                    action: SloAction::Warn,
489                    violated: false,
490                },
491                SloStatus {
492                    name: "cost".into(),
493                    metric: SloMetric::SessionCostUsd,
494                    threshold: 1.0,
495                    actual: 2.5,
496                    direction: SloDirection::Max,
497                    action: SloAction::Block,
498                    violated: true,
499                },
500            ],
501            violations: vec![SloStatus {
502                name: "cost".into(),
503                metric: SloMetric::SessionCostUsd,
504                threshold: 1.0,
505                actual: 2.5,
506                direction: SloDirection::Max,
507                action: SloAction::Block,
508                violated: true,
509            }],
510            worst_action: Some(SloAction::Block),
511        };
512        let out = snap.format_compact();
513        assert!(out.contains("1/2 passing"));
514        assert!(out.contains("cost"));
515        assert!(snap.should_block());
516    }
517
518    #[test]
519    fn snapshot_no_violations() {
520        let snap = SloSnapshot {
521            slos: vec![SloStatus {
522                name: "ok".into(),
523                metric: SloMetric::SessionContextTokens,
524                threshold: 100_000.0,
525                actual: 5000.0,
526                direction: SloDirection::Max,
527                action: SloAction::Warn,
528                violated: false,
529            }],
530            violations: vec![],
531            worst_action: None,
532        };
533        assert!(!snap.should_block());
534        assert!(!snap.should_throttle());
535        assert!(snap.format_compact().contains("1/1 passing"));
536    }
537
538    #[test]
539    fn violation_history_capped() {
540        clear_violations();
541        for i in 0..10 {
542            record_violation(&SloStatus {
543                name: format!("slo_{i}"),
544                metric: SloMetric::SessionContextTokens,
545                threshold: 100.0,
546                actual: 200.0,
547                direction: SloDirection::Max,
548                action: SloAction::Warn,
549                violated: true,
550            });
551        }
552        let hist = violation_history(5);
553        assert_eq!(hist.len(), 5);
554        assert_eq!(hist[0].slo_name, "slo_5");
555    }
556}