|
| 1 | +// SPDX-License-Identifier: PMPL-1.0-or-later |
| 2 | +// Health status monitoring for echidna services |
| 3 | + |
| 4 | +use chrono::{DateTime, Utc}; |
| 5 | +use serde::{Deserialize, Serialize}; |
| 6 | +use std::collections::HashMap; |
| 7 | + |
| 8 | +use crate::fault_tolerance::CircuitState; |
| 9 | + |
| 10 | +/// Overall system health status |
| 11 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 12 | +pub struct HealthStatus { |
| 13 | + pub timestamp: DateTime<Utc>, |
| 14 | + pub prover_health: HashMap<String, ProverHealth>, |
| 15 | + pub gnn_model_health: ModelHealth, |
| 16 | + pub corpus_health: CorpusHealth, |
| 17 | + pub system_degradation: DegradationMode, |
| 18 | +} |
| 19 | + |
| 20 | +/// Health status of a single prover |
| 21 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 22 | +pub struct ProverHealth { |
| 23 | + pub name: String, |
| 24 | + pub is_available: bool, |
| 25 | + pub circuit_breaker_state: CircuitBreakerStateSnapshot, |
| 26 | + pub last_successful_proof: Option<DateTime<Utc>>, |
| 27 | + pub consecutive_failures: usize, |
| 28 | + pub avg_latency_ms: f64, |
| 29 | + pub success_rate: f64, // 0.0 to 1.0 |
| 30 | + pub total_invocations: u64, |
| 31 | + pub total_failures: u64, |
| 32 | +} |
| 33 | + |
| 34 | +/// Snapshot of circuit breaker state |
| 35 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 36 | +pub enum CircuitBreakerStateSnapshot { |
| 37 | + Closed, |
| 38 | + Open, |
| 39 | + HalfOpen, |
| 40 | +} |
| 41 | + |
| 42 | +impl From<CircuitState> for CircuitBreakerStateSnapshot { |
| 43 | + fn from(state: CircuitState) -> Self { |
| 44 | + match state { |
| 45 | + CircuitState::Closed => CircuitBreakerStateSnapshot::Closed, |
| 46 | + CircuitState::Open => CircuitBreakerStateSnapshot::Open, |
| 47 | + CircuitState::HalfOpen => CircuitBreakerStateSnapshot::HalfOpen, |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Health of GNN model |
| 53 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 54 | +pub struct ModelHealth { |
| 55 | + pub is_loaded: bool, |
| 56 | + pub model_checksum: Option<String>, |
| 57 | + pub last_trained: Option<DateTime<Utc>>, |
| 58 | + pub last_validation_nDCG: f32, |
| 59 | + pub last_validation_MRR: f32, |
| 60 | + pub nDCG_meets_threshold: bool, |
| 61 | + pub fallback_active: bool, |
| 62 | + pub fallback_cache_hit_rate: f64, |
| 63 | + pub fallback_cache_size: usize, |
| 64 | + pub fallback_max_latency_ms: f64, |
| 65 | +} |
| 66 | + |
| 67 | +/// Health of training corpus |
| 68 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 69 | +pub struct CorpusHealth { |
| 70 | + pub total_proofs: usize, |
| 71 | + pub total_premises: usize, |
| 72 | + pub last_updated: Option<DateTime<Utc>>, |
| 73 | + pub size_mb: f64, |
| 74 | + pub size_change_percent: f64, // % change since last check |
| 75 | +} |
| 76 | + |
| 77 | +/// System degradation mode based on health |
| 78 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 79 | +pub enum DegradationMode { |
| 80 | + /// All systems operational |
| 81 | + Normal, |
| 82 | + /// Prefer cosine fallback ~30% of time; limit provers to top 5 |
| 83 | + IncreasingFallback, |
| 84 | + /// Route all queries to cosine fallback only |
| 85 | + CosineOnly, |
| 86 | + /// Accept proofs but don't train; all fallback |
| 87 | + ReadOnly, |
| 88 | + /// Minimal mode; only accept pre-submitted proofs, no new proof search |
| 89 | + Minimal, |
| 90 | +} |
| 91 | + |
| 92 | +impl HealthStatus { |
| 93 | + pub fn new() -> Self { |
| 94 | + HealthStatus { |
| 95 | + timestamp: Utc::now(), |
| 96 | + prover_health: HashMap::new(), |
| 97 | + gnn_model_health: ModelHealth { |
| 98 | + is_loaded: false, |
| 99 | + model_checksum: None, |
| 100 | + last_trained: None, |
| 101 | + last_validation_nDCG: 0.0, |
| 102 | + last_validation_MRR: 0.0, |
| 103 | + nDCG_meets_threshold: false, |
| 104 | + fallback_active: true, |
| 105 | + fallback_cache_hit_rate: 0.0, |
| 106 | + fallback_cache_size: 0, |
| 107 | + fallback_max_latency_ms: 0.0, |
| 108 | + }, |
| 109 | + corpus_health: CorpusHealth { |
| 110 | + total_proofs: 0, |
| 111 | + total_premises: 0, |
| 112 | + last_updated: None, |
| 113 | + size_mb: 0.0, |
| 114 | + size_change_percent: 0.0, |
| 115 | + }, |
| 116 | + system_degradation: DegradationMode::Normal, |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + /// Determine required degradation based on system health |
| 121 | + pub fn compute_degradation_mode(&mut self) { |
| 122 | + let failed_provers = self |
| 123 | + .prover_health |
| 124 | + .values() |
| 125 | + .filter(|p| !p.is_available) |
| 126 | + .count(); |
| 127 | + |
| 128 | + let circuit_open_count = self |
| 129 | + .prover_health |
| 130 | + .values() |
| 131 | + .filter(|p| p.circuit_breaker_state == CircuitBreakerStateSnapshot::Open) |
| 132 | + .count(); |
| 133 | + |
| 134 | + let available_provers = self.prover_health.len() - failed_provers; |
| 135 | + |
| 136 | + // Heuristic rules for degradation (priority order: most critical first) |
| 137 | + if !self.gnn_model_health.is_loaded || !self.gnn_model_health.nDCG_meets_threshold { |
| 138 | + // GNN model not available or not meeting quality threshold |
| 139 | + self.system_degradation = DegradationMode::CosineOnly; |
| 140 | + } else if failed_provers >= 3 { |
| 141 | + // Too many failed provers |
| 142 | + self.system_degradation = DegradationMode::CosineOnly; |
| 143 | + } else if available_provers < 3 { |
| 144 | + // Critical: too few provers available |
| 145 | + self.system_degradation = DegradationMode::ReadOnly; |
| 146 | + } else if circuit_open_count >= 2 { |
| 147 | + // Multiple circuit breakers open |
| 148 | + self.system_degradation = DegradationMode::IncreasingFallback; |
| 149 | + } else if self.gnn_model_health.fallback_cache_hit_rate < 0.5 { |
| 150 | + // Fallback cache not warmed up |
| 151 | + self.system_degradation = DegradationMode::IncreasingFallback; |
| 152 | + } else { |
| 153 | + self.system_degradation = DegradationMode::Normal; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + /// Overall system health percentage |
| 158 | + pub fn health_percentage(&self) -> f64 { |
| 159 | + if self.prover_health.is_empty() { |
| 160 | + return 100.0; |
| 161 | + } |
| 162 | + |
| 163 | + let available_provers = self |
| 164 | + .prover_health |
| 165 | + .values() |
| 166 | + .filter(|p| p.is_available) |
| 167 | + .count(); |
| 168 | + let availability_rate = available_provers as f64 / self.prover_health.len() as f64; |
| 169 | + |
| 170 | + let avg_success_rate = self |
| 171 | + .prover_health |
| 172 | + .values() |
| 173 | + .map(|p| p.success_rate) |
| 174 | + .sum::<f64>() |
| 175 | + / self.prover_health.len() as f64; |
| 176 | + |
| 177 | + let gnn_health = if self.gnn_model_health.is_loaded { |
| 178 | + self.gnn_model_health.last_validation_nDCG as f64 / 1.0 |
| 179 | + } else { |
| 180 | + 0.5 // Fallback is always available |
| 181 | + }; |
| 182 | + |
| 183 | + (availability_rate * 0.4 + avg_success_rate * 0.4 + gnn_health * 0.2) * 100.0 |
| 184 | + } |
| 185 | + |
| 186 | + /// Check if degradation is active |
| 187 | + pub fn is_degraded(&self) -> bool { |
| 188 | + self.system_degradation != DegradationMode::Normal |
| 189 | + } |
| 190 | + |
| 191 | + /// List all provers in critical state (circuit open) |
| 192 | + pub fn critical_provers(&self) -> Vec<&String> { |
| 193 | + self.prover_health |
| 194 | + .iter() |
| 195 | + .filter(|(_, h)| h.circuit_breaker_state == CircuitBreakerStateSnapshot::Open) |
| 196 | + .map(|(name, _)| name) |
| 197 | + .collect() |
| 198 | + } |
| 199 | + |
| 200 | + /// Summary string for logging |
| 201 | + pub fn summary(&self) -> String { |
| 202 | + let health_pct = self.health_percentage(); |
| 203 | + let failed = self |
| 204 | + .prover_health |
| 205 | + .values() |
| 206 | + .filter(|p| !p.is_available) |
| 207 | + .count(); |
| 208 | + let critical = self.critical_provers().len(); |
| 209 | + |
| 210 | + format!( |
| 211 | + "echidna health: {:.1}% | {} provers | {} failed | {} critical | degradation: {:?}", |
| 212 | + health_pct, self.prover_health.len(), failed, critical, self.system_degradation |
| 213 | + ) |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +impl Default for HealthStatus { |
| 218 | + fn default() -> Self { |
| 219 | + Self::new() |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +#[cfg(test)] |
| 224 | +mod tests { |
| 225 | + use super::*; |
| 226 | + |
| 227 | + #[test] |
| 228 | + fn test_health_status_creation() { |
| 229 | + let health = HealthStatus::new(); |
| 230 | + assert!(health.prover_health.is_empty()); |
| 231 | + assert_eq!(health.system_degradation, DegradationMode::Normal); |
| 232 | + assert_eq!(health.health_percentage(), 100.0); |
| 233 | + } |
| 234 | + |
| 235 | + #[test] |
| 236 | + fn test_degradation_mode_computation() { |
| 237 | + let mut health = HealthStatus::new(); |
| 238 | + |
| 239 | + // Add multiple provers (at least 3) to avoid ReadOnly trigger |
| 240 | + for i in 0..5 { |
| 241 | + let name = format!("prover{}", i); |
| 242 | + let is_available = i < 4; // 4 available, 1 unavailable |
| 243 | + let circuit_state = if i == 0 { |
| 244 | + CircuitBreakerStateSnapshot::Open |
| 245 | + } else { |
| 246 | + CircuitBreakerStateSnapshot::Closed |
| 247 | + }; |
| 248 | + |
| 249 | + health.prover_health.insert( |
| 250 | + name.clone(), |
| 251 | + ProverHealth { |
| 252 | + name, |
| 253 | + is_available, |
| 254 | + circuit_breaker_state: circuit_state, |
| 255 | + last_successful_proof: None, |
| 256 | + consecutive_failures: if is_available { 0 } else { 5 }, |
| 257 | + avg_latency_ms: if is_available { 50.0 } else { 100.0 }, |
| 258 | + success_rate: if is_available { 1.0 } else { 0.5 }, |
| 259 | + total_invocations: 10, |
| 260 | + total_failures: if is_available { 0 } else { 5 }, |
| 261 | + }, |
| 262 | + ); |
| 263 | + } |
| 264 | + |
| 265 | + // Load GNN model with good metrics |
| 266 | + health.gnn_model_health.is_loaded = true; |
| 267 | + health.gnn_model_health.last_validation_nDCG = 0.65; |
| 268 | + health.gnn_model_health.nDCG_meets_threshold = true; |
| 269 | + |
| 270 | + health.compute_degradation_mode(); |
| 271 | + // One open circuit breaker should trigger IncreasingFallback |
| 272 | + assert_eq!(health.system_degradation, DegradationMode::IncreasingFallback); |
| 273 | + } |
| 274 | + |
| 275 | + #[test] |
| 276 | + fn test_critical_provers() { |
| 277 | + let mut health = HealthStatus::new(); |
| 278 | + |
| 279 | + health.prover_health.insert( |
| 280 | + "coq".to_string(), |
| 281 | + ProverHealth { |
| 282 | + name: "coq".to_string(), |
| 283 | + is_available: false, |
| 284 | + circuit_breaker_state: CircuitBreakerStateSnapshot::Open, |
| 285 | + last_successful_proof: None, |
| 286 | + consecutive_failures: 3, |
| 287 | + avg_latency_ms: 50.0, |
| 288 | + success_rate: 0.0, |
| 289 | + total_invocations: 5, |
| 290 | + total_failures: 5, |
| 291 | + }, |
| 292 | + ); |
| 293 | + |
| 294 | + let critical = health.critical_provers(); |
| 295 | + assert_eq!(critical.len(), 1); |
| 296 | + assert_eq!(critical[0], "coq"); |
| 297 | + } |
| 298 | +} |
0 commit comments