spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / evaluator / metrics.rs
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | use std::fs; |
| 3 | use std::path::Path; |
| 4 | use std::time::Instant; |
| 5 | |
| 6 | pub fn system_page_size_kb() -> u64 { |
| 7 | #[cfg(unix)] |
| 8 | { |
| 9 | let ps = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; |
| 10 | if ps > 0 { |
| 11 | return (ps as u64) / 1024; |
| 12 | } |
| 13 | } |
| 14 | 4 |
| 15 | } |
| 16 | |
| 17 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 18 | pub struct RusageMetrics { |
| 19 | pub user_time_us: u64, |
| 20 | pub system_time_us: u64, |
| 21 | pub max_rss_kb: i64, |
| 22 | pub voluntary_context_switches: i64, |
| 23 | pub involuntary_context_switches: i64, |
| 24 | } |
| 25 | |
| 26 | impl RusageMetrics { |
| 27 | pub fn capture_self() -> Result<Self, String> { |
| 28 | Self::capture(libc::RUSAGE_SELF) |
| 29 | } |
| 30 | |
| 31 | pub fn capture_children() -> Result<Self, String> { |
| 32 | Self::capture(libc::RUSAGE_CHILDREN) |
| 33 | } |
| 34 | |
| 35 | fn capture(who: libc::c_int) -> Result<Self, String> { |
| 36 | unsafe { |
| 37 | let mut usage: libc::rusage = std::mem::zeroed(); |
| 38 | let ret = libc::getrusage(who, &mut usage); |
| 39 | if ret != 0 { |
| 40 | return Err(format!("libc::getrusage failed with exit code {}", ret)); |
| 41 | } |
| 42 | let user_us = (usage.ru_utime.tv_sec as u64) |
| 43 | .saturating_mul(1_000_000) |
| 44 | .saturating_add(usage.ru_utime.tv_usec as u64); |
| 45 | let sys_us = (usage.ru_stime.tv_sec as u64) |
| 46 | .saturating_mul(1_000_000) |
| 47 | .saturating_add(usage.ru_stime.tv_usec as u64); |
| 48 | |
| 49 | Ok(Self { |
| 50 | user_time_us: user_us, |
| 51 | system_time_us: sys_us, |
| 52 | max_rss_kb: usage.ru_maxrss as i64, |
| 53 | voluntary_context_switches: usage.ru_nvcsw as i64, |
| 54 | involuntary_context_switches: usage.ru_nivcsw as i64, |
| 55 | }) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn diff(&self, baseline: &Self) -> Self { |
| 60 | Self { |
| 61 | user_time_us: self.user_time_us.saturating_sub(baseline.user_time_us), |
| 62 | system_time_us: self.system_time_us.saturating_sub(baseline.system_time_us), |
| 63 | max_rss_kb: self.max_rss_kb.max(baseline.max_rss_kb), |
| 64 | voluntary_context_switches: self |
| 65 | .voluntary_context_switches |
| 66 | .saturating_sub(baseline.voluntary_context_switches), |
| 67 | involuntary_context_switches: self |
| 68 | .involuntary_context_switches |
| 69 | .saturating_sub(baseline.involuntary_context_switches), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | pub fn accumulate(&mut self, delta: &Self) { |
| 74 | self.user_time_us = self.user_time_us.saturating_add(delta.user_time_us); |
| 75 | self.system_time_us = self.system_time_us.saturating_add(delta.system_time_us); |
| 76 | self.max_rss_kb = self.max_rss_kb.max(delta.max_rss_kb); |
| 77 | self.voluntary_context_switches = self |
| 78 | .voluntary_context_switches |
| 79 | .saturating_add(delta.voluntary_context_switches); |
| 80 | self.involuntary_context_switches = self |
| 81 | .involuntary_context_switches |
| 82 | .saturating_add(delta.involuntary_context_switches); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl Default for RusageMetrics { |
| 87 | fn default() -> Self { |
| 88 | Self { |
| 89 | user_time_us: 0, |
| 90 | system_time_us: 0, |
| 91 | max_rss_kb: 0, |
| 92 | voluntary_context_switches: 0, |
| 93 | involuntary_context_switches: 0, |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 99 | pub struct StatmMetrics { |
| 100 | pub total_pages: u64, |
| 101 | pub resident_pages: u64, |
| 102 | pub shared_pages: u64, |
| 103 | pub text_pages: u64, |
| 104 | pub data_pages: u64, |
| 105 | pub resident_kb: u64, |
| 106 | } |
| 107 | |
| 108 | impl StatmMetrics { |
| 109 | pub fn read_pid(pid: u32) -> Result<Self, String> { |
| 110 | let path = format!("/proc/{}/statm", pid); |
| 111 | Self::read_path(Path::new(&path)) |
| 112 | } |
| 113 | |
| 114 | pub fn read_self() -> Result<Self, String> { |
| 115 | Self::read_path(Path::new("/proc/self/statm")) |
| 116 | } |
| 117 | |
| 118 | pub fn read_path(path: &Path) -> Result<Self, String> { |
| 119 | let content = fs::read_to_string(path) |
| 120 | .map_err(|e| format!("Failed to read statm file at {:?}: {}", path, e))?; |
| 121 | Self::parse_statm(&content) |
| 122 | } |
| 123 | |
| 124 | pub fn parse_statm(content: &str) -> Result<Self, String> { |
| 125 | let tokens: Vec<&str> = content.split_whitespace().collect(); |
| 126 | if tokens.len() < 6 { |
| 127 | return Err("Malformed statm content: expected at least 6 tokens".to_string()); |
| 128 | } |
| 129 | |
| 130 | let total_pages: u64 = tokens[0] |
| 131 | .parse() |
| 132 | .map_err(|e| format!("Invalid total_pages: {}", e))?; |
| 133 | let resident_pages: u64 = tokens[1] |
| 134 | .parse() |
| 135 | .map_err(|e| format!("Invalid resident_pages: {}", e))?; |
| 136 | let shared_pages: u64 = tokens[2] |
| 137 | .parse() |
| 138 | .map_err(|e| format!("Invalid shared_pages: {}", e))?; |
| 139 | let text_pages: u64 = tokens[3] |
| 140 | .parse() |
| 141 | .map_err(|e| format!("Invalid text_pages: {}", e))?; |
| 142 | let data_pages: u64 = tokens[5] |
| 143 | .parse() |
| 144 | .map_err(|e| format!("Invalid data_pages: {}", e))?; |
| 145 | |
| 146 | let page_size_kb = system_page_size_kb(); |
| 147 | let resident_kb = resident_pages.saturating_mul(page_size_kb); |
| 148 | |
| 149 | Ok(Self { |
| 150 | total_pages, |
| 151 | resident_pages, |
| 152 | shared_pages, |
| 153 | text_pages, |
| 154 | data_pages, |
| 155 | resident_kb, |
| 156 | }) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | pub struct LatencyTimer { |
| 161 | start: Instant, |
| 162 | } |
| 163 | |
| 164 | impl LatencyTimer { |
| 165 | pub fn start() -> Self { |
| 166 | Self { |
| 167 | start: Instant::now(), |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | pub fn elapsed_us(&self) -> f64 { |
| 172 | self.start.elapsed().as_nanos() as f64 / 1_000.0 |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 177 | pub struct LatencyDistribution { |
| 178 | pub count: usize, |
| 179 | pub min_us: f64, |
| 180 | pub max_us: f64, |
| 181 | pub mean_us: f64, |
| 182 | pub stddev_us: f64, |
| 183 | pub p50_us: f64, |
| 184 | pub p95_us: f64, |
| 185 | pub p99_us: f64, |
| 186 | pub throughput_ops_per_sec: f64, |
| 187 | pub total_wall_time_us: u64, |
| 188 | } |
| 189 | |
| 190 | impl LatencyDistribution { |
| 191 | pub fn from_samples(samples: &[f64], total_wall_time_us: u64) -> Result<Self, String> { |
| 192 | if samples.is_empty() { |
| 193 | return Err("Cannot construct LatencyDistribution from zero samples".to_string()); |
| 194 | } |
| 195 | |
| 196 | let mut sorted = samples.to_vec(); |
| 197 | sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); |
| 198 | |
| 199 | let count = sorted.len(); |
| 200 | let min_us = sorted[0]; |
| 201 | let max_us = sorted[count - 1]; |
| 202 | |
| 203 | let sum: f64 = sorted.iter().sum(); |
| 204 | let mean_us = sum / (count as f64); |
| 205 | |
| 206 | let variance: f64 = sorted |
| 207 | .iter() |
| 208 | .map(|val| { |
| 209 | let diff = val - mean_us; |
| 210 | diff * diff |
| 211 | }) |
| 212 | .sum::<f64>() |
| 213 | / (count as f64); |
| 214 | let stddev_us = variance.sqrt(); |
| 215 | |
| 216 | let p50_us = Self::calculate_percentile(&sorted, 50.0); |
| 217 | let p95_us = Self::calculate_percentile(&sorted, 95.0); |
| 218 | let p99_us = Self::calculate_percentile(&sorted, 99.0); |
| 219 | |
| 220 | let throughput_ops_per_sec = if total_wall_time_us > 0 { |
| 221 | ((count as f64) * 1_000_000.0) / (total_wall_time_us as f64) |
| 222 | } else { |
| 223 | 0.0 |
| 224 | }; |
| 225 | |
| 226 | Ok(Self { |
| 227 | count, |
| 228 | min_us, |
| 229 | max_us, |
| 230 | mean_us, |
| 231 | stddev_us, |
| 232 | p50_us, |
| 233 | p95_us, |
| 234 | p99_us, |
| 235 | throughput_ops_per_sec, |
| 236 | total_wall_time_us, |
| 237 | }) |
| 238 | } |
| 239 | |
| 240 | pub fn calculate_percentile(sorted_samples: &[f64], pct: f64) -> f64 { |
| 241 | let n = sorted_samples.len(); |
| 242 | if n == 0 { |
| 243 | return 0.0; |
| 244 | } |
| 245 | if n == 1 { |
| 246 | return sorted_samples[0]; |
| 247 | } |
| 248 | |
| 249 | let clamped_pct = pct.clamp(0.0, 100.0); |
| 250 | let rank = (clamped_pct / 100.0) * ((n - 1) as f64); |
| 251 | let low_idx = rank.floor() as usize; |
| 252 | let high_idx = rank.ceil() as usize; |
| 253 | |
| 254 | if low_idx == high_idx { |
| 255 | sorted_samples[low_idx] |
| 256 | } else { |
| 257 | let weight = rank - (low_idx as f64); |
| 258 | sorted_samples[low_idx] * (1.0 - weight) + sorted_samples[high_idx] * weight |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 264 | pub struct ProcessMetricsSnapshot { |
| 265 | pub rusage: RusageMetrics, |
| 266 | pub statm: Option<StatmMetrics>, |
| 267 | pub latencies: Option<LatencyDistribution>, |
| 268 | pub timestamp_utc: String, |
| 269 | } |
| 270 | |
| 271 | impl ProcessMetricsSnapshot { |
| 272 | pub fn capture_current() -> Result<Self, String> { |
| 273 | let rusage = RusageMetrics::capture_self()?; |
| 274 | let statm = StatmMetrics::read_self().ok(); |
| 275 | Ok(Self { |
| 276 | rusage, |
| 277 | statm, |
| 278 | latencies: None, |
| 279 | timestamp_utc: chrono::Utc::now().to_rfc3339(), |
| 280 | }) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | #[cfg(test)] |
| 285 | mod tests { |
| 286 | use super::*; |
| 287 | |
| 288 | #[test] |
| 289 | fn test_rusage_capture_self() { |
| 290 | let metrics = RusageMetrics::capture_self().expect("capture_self should succeed"); |
| 291 | assert!(metrics.max_rss_kb > 0); |
| 292 | } |
| 293 | |
| 294 | #[test] |
| 295 | fn test_statm_parse() { |
| 296 | let sample = "12345 6789 1234 500 0 4500 0\n"; |
| 297 | let statm = StatmMetrics::parse_statm(sample).expect("parse_statm should succeed"); |
| 298 | assert_eq!(statm.total_pages, 12345); |
| 299 | assert_eq!(statm.resident_pages, 6789); |
| 300 | assert_eq!(statm.shared_pages, 1234); |
| 301 | assert_eq!(statm.text_pages, 500); |
| 302 | assert_eq!(statm.data_pages, 4500); |
| 303 | let expected_kb = 6789 * system_page_size_kb(); |
| 304 | assert_eq!(statm.resident_kb, expected_kb); |
| 305 | } |
| 306 | |
| 307 | #[test] |
| 308 | fn test_statm_read_self() { |
| 309 | let statm = StatmMetrics::read_self(); |
| 310 | assert!(statm.is_ok()); |
| 311 | let val = statm.unwrap(); |
| 312 | assert!(val.resident_pages > 0); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn test_latency_distribution_empty() { |
| 317 | let res = LatencyDistribution::from_samples(&[], 1000); |
| 318 | assert!(res.is_err()); |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn test_latency_distribution_single() { |
| 323 | let res = LatencyDistribution::from_samples(&[150.0], 1000).unwrap(); |
| 324 | assert_eq!(res.count, 1); |
| 325 | assert_eq!(res.min_us, 150.0); |
| 326 | assert_eq!(res.max_us, 150.0); |
| 327 | assert_eq!(res.mean_us, 150.0); |
| 328 | assert_eq!(res.p50_us, 150.0); |
| 329 | assert_eq!(res.p95_us, 150.0); |
| 330 | assert_eq!(res.p99_us, 150.0); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn test_latency_distribution_multiple() { |
| 335 | let mut samples = Vec::new(); |
| 336 | for i in 1..=100 { |
| 337 | samples.push(i as f64); |
| 338 | } |
| 339 | let res = LatencyDistribution::from_samples(&samples, 1_000_000).unwrap(); |
| 340 | assert_eq!(res.count, 100); |
| 341 | assert_eq!(res.min_us, 1.0); |
| 342 | assert_eq!(res.max_us, 100.0); |
| 343 | assert!((res.mean_us - 50.5).abs() < 1e-6); |
| 344 | assert!((res.p50_us - 50.5).abs() < 1e-6); |
| 345 | assert!((res.p95_us - 95.05).abs() < 1e-6); |
| 346 | assert!((res.p99_us - 99.01).abs() < 1e-6); |
| 347 | assert!((res.throughput_ops_per_sec - 100.0).abs() < 1e-6); |
| 348 | } |
| 349 | } |