spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / propose / hypothesis.rs
| 1 | use serde::{Deserialize, Serialize}; |
| 2 | |
| 3 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 4 | pub struct ProtectedMetric { |
| 5 | pub name: String, |
| 6 | pub max_allowed_degradation_pct: f64, |
| 7 | } |
| 8 | |
| 9 | /// Target metric of an exploratory hypothesis: it makes no performance claim, so |
| 10 | /// `baseline_value` and `predicted_delta_pct` carry no meaning and must be zero. |
| 11 | pub const EXPLORATORY_TARGET_METRIC: &str = "structural_ranking"; |
| 12 | |
| 13 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 14 | pub struct HypothesisContract { |
| 15 | pub id: String, |
| 16 | pub cycle_id: String, |
| 17 | pub observed_problem: String, |
| 18 | pub suspected_root_cause: String, |
| 19 | pub target_metric: String, |
| 20 | pub baseline_value: f64, |
| 21 | pub predicted_delta_pct: f64, |
| 22 | pub protected_metrics: Vec<ProtectedMetric>, |
| 23 | pub falsification_test: String, |
| 24 | pub confidence_score: f64, |
| 25 | } |
| 26 | |
| 27 | impl HypothesisContract { |
| 28 | pub fn new( |
| 29 | id: &str, |
| 30 | cycle_id: &str, |
| 31 | observed_problem: &str, |
| 32 | suspected_root_cause: &str, |
| 33 | target_metric: &str, |
| 34 | baseline_value: f64, |
| 35 | predicted_delta_pct: f64, |
| 36 | ) -> Self { |
| 37 | Self { |
| 38 | id: id.to_string(), |
| 39 | cycle_id: cycle_id.to_string(), |
| 40 | observed_problem: observed_problem.to_string(), |
| 41 | suspected_root_cause: suspected_root_cause.to_string(), |
| 42 | target_metric: target_metric.to_string(), |
| 43 | baseline_value, |
| 44 | predicted_delta_pct, |
| 45 | protected_metrics: vec![ |
| 46 | ProtectedMetric { |
| 47 | name: "p95_latency".to_string(), |
| 48 | max_allowed_degradation_pct: 1.0, |
| 49 | }, |
| 50 | ProtectedMetric { |
| 51 | name: "p99_latency".to_string(), |
| 52 | max_allowed_degradation_pct: 1.0, |
| 53 | }, |
| 54 | ProtectedMetric { |
| 55 | name: "max_rss_kb".to_string(), |
| 56 | max_allowed_degradation_pct: 2.0, |
| 57 | }, |
| 58 | ], |
| 59 | falsification_test: String::new(), |
| 60 | confidence_score: 0.85, |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | /// A hypothesis with no performance claim: no baseline number, no predicted percentage. |
| 65 | /// Used when the top-ranked stage has no measured latency (cold start). |
| 66 | pub fn exploratory( |
| 67 | id: &str, |
| 68 | cycle_id: &str, |
| 69 | observed_problem: &str, |
| 70 | suspected_root_cause: &str, |
| 71 | ) -> Self { |
| 72 | let mut c = Self::new( |
| 73 | id, |
| 74 | cycle_id, |
| 75 | observed_problem, |
| 76 | suspected_root_cause, |
| 77 | EXPLORATORY_TARGET_METRIC, |
| 78 | 0.0, |
| 79 | 0.0, |
| 80 | ); |
| 81 | c.confidence_score = 0.0; |
| 82 | c |
| 83 | } |
| 84 | |
| 85 | /// Builds the hypothesis for the top-ranked stage. It carries a numeric latency target only |
| 86 | /// when that stage's latency is measured; otherwise it is exploratory and claims nothing. |
| 87 | pub fn from_bottleneck( |
| 88 | id: &str, |
| 89 | cycle_id: &str, |
| 90 | b: &crate::graph::BottleneckRank, |
| 91 | target_improvement_pct: f64, |
| 92 | ) -> Self { |
| 93 | match b.latency_median_us { |
| 94 | Some(median) => Self::new( |
| 95 | id, |
| 96 | cycle_id, |
| 97 | &format!( |
| 98 | "Stage '{}' has measured median latency {:.1} us (centrality={:.4})", |
| 99 | b.node_name, median, b.centrality |
| 100 | ), |
| 101 | &format!("Latency on '{}': {}", b.node_name, b.causal_explanation), |
| 102 | "latency_median_us", |
| 103 | median, |
| 104 | target_improvement_pct, |
| 105 | ), |
| 106 | None => Self::exploratory( |
| 107 | id, |
| 108 | cycle_id, |
| 109 | &format!( |
| 110 | "Stage '{}' ranks first by structural position (centrality={:.4}); no latency is measured", |
| 111 | b.node_name, b.centrality |
| 112 | ), |
| 113 | &format!("Structural ranking: {}", b.causal_explanation), |
| 114 | ), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | pub fn is_exploratory(&self) -> bool { |
| 119 | self.target_metric == EXPLORATORY_TARGET_METRIC |
| 120 | } |
| 121 | |
| 122 | /// The numeric latency claim `(baseline_us, predicted_improvement_pct)`, or None when the |
| 123 | /// hypothesis is exploratory. |
| 124 | pub fn latency_claim(&self) -> Option<(f64, f64)> { |
| 125 | (!self.is_exploratory()).then_some((self.baseline_value, self.predicted_delta_pct)) |
| 126 | } |
| 127 | |
| 128 | pub fn with_falsification_test(mut self, test_code: &str) -> Self { |
| 129 | self.falsification_test = test_code.to_string(); |
| 130 | self |
| 131 | } |
| 132 | |
| 133 | pub fn with_protected_metric(mut self, name: &str, max_degradation_pct: f64) -> Self { |
| 134 | self.protected_metrics.push(ProtectedMetric { |
| 135 | name: name.to_string(), |
| 136 | max_allowed_degradation_pct: max_degradation_pct, |
| 137 | }); |
| 138 | self |
| 139 | } |
| 140 | |
| 141 | pub fn validate(&self) -> Result<(), String> { |
| 142 | if self.observed_problem.trim().is_empty() { |
| 143 | return Err("HypothesisContract must specify a non-empty observed_problem".to_string()); |
| 144 | } |
| 145 | if self.suspected_root_cause.trim().is_empty() { |
| 146 | return Err( |
| 147 | "HypothesisContract must specify a non-empty suspected_root_cause".to_string(), |
| 148 | ); |
| 149 | } |
| 150 | if self.target_metric.trim().is_empty() { |
| 151 | return Err("HypothesisContract must specify a target_metric".to_string()); |
| 152 | } |
| 153 | if self.is_exploratory() { |
| 154 | if self.baseline_value != 0.0 || self.predicted_delta_pct != 0.0 { |
| 155 | return Err( |
| 156 | "an exploratory HypothesisContract must carry no baseline and no predicted delta" |
| 157 | .to_string(), |
| 158 | ); |
| 159 | } |
| 160 | return Ok(()); |
| 161 | } |
| 162 | if !self.baseline_value.is_finite() || !self.predicted_delta_pct.is_finite() { |
| 163 | return Err( |
| 164 | "HypothesisContract baseline and predicted delta must be finite".to_string(), |
| 165 | ); |
| 166 | } |
| 167 | if self.predicted_delta_pct.abs() < 1e-6 { |
| 168 | return Err("HypothesisContract predicted_delta_pct cannot be zero".to_string()); |
| 169 | } |
| 170 | if self.confidence_score < 0.0 || self.confidence_score > 1.0 { |
| 171 | return Err("HypothesisContract confidence_score must be in [0.0, 1.0]".to_string()); |
| 172 | } |
| 173 | Ok(()) |
| 174 | } |
| 175 | |
| 176 | pub fn format_prompt_directive(&self) -> String { |
| 177 | let target = match self.latency_claim() { |
| 178 | Some((baseline, delta)) => format!( |
| 179 | "{} (Baseline: {:.2}, Expected Improvement: {:.1}%)", |
| 180 | self.target_metric, baseline, delta |
| 181 | ), |
| 182 | None => format!( |
| 183 | "{} (exploratory, no performance claim: no latency was measured)", |
| 184 | self.target_metric |
| 185 | ), |
| 186 | }; |
| 187 | let mut text = format!( |
| 188 | "FALSIFIABLE HYPOTHESIS CONTRACT (ID: {}):\n\ |
| 189 | - Observed Problem: {}\n\ |
| 190 | - Suspected Root Cause: {}\n\ |
| 191 | - Target Metric: {}\n\ |
| 192 | - Protected Non-Target Metrics:\n", |
| 193 | self.id, self.observed_problem, self.suspected_root_cause, target |
| 194 | ); |
| 195 | |
| 196 | for pm in &self.protected_metrics { |
| 197 | text.push_str(&format!( |
| 198 | " * {} <= +{:.1}% max degradation\n", |
| 199 | pm.name, pm.max_allowed_degradation_pct |
| 200 | )); |
| 201 | } |
| 202 | |
| 203 | if !self.falsification_test.is_empty() { |
| 204 | text.push_str(&format!( |
| 205 | "- Falsification Condition: {}\n", |
| 206 | self.falsification_test |
| 207 | )); |
| 208 | } |
| 209 | |
| 210 | text |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | #[cfg(test)] |
| 215 | mod tests { |
| 216 | use super::*; |
| 217 | |
| 218 | #[test] |
| 219 | fn test_hypothesis_contract_validation_and_directive() { |
| 220 | let contract = HypothesisContract::new( |
| 221 | "hypo-001", |
| 222 | "cycle-01", |
| 223 | "Tail latency p95 spiked on holdout test case", |
| 224 | "Unsynchronized lock contention in sequence allocator", |
| 225 | "p95_latency", |
| 226 | 2450.0, |
| 227 | 15.0, |
| 228 | ) |
| 229 | .with_falsification_test("assert_eq!(allocator.contention_count(), 0)"); |
| 230 | |
| 231 | assert!(contract.validate().is_ok()); |
| 232 | |
| 233 | let directive = contract.format_prompt_directive(); |
| 234 | assert!(directive.contains("FALSIFIABLE HYPOTHESIS CONTRACT")); |
| 235 | assert!(directive.contains("Unsynchronized lock contention")); |
| 236 | assert!(directive.contains("assert_eq!(allocator.contention_count(), 0)")); |
| 237 | } |
| 238 | |
| 239 | #[test] |
| 240 | fn exploratory_hypothesis_is_valid_without_a_delta_and_claims_nothing() { |
| 241 | let c = HypothesisContract::exploratory("hypo-x", "cycle-01", "Stage ranks first", "Cause"); |
| 242 | assert!(c.is_exploratory()); |
| 243 | assert!(c.validate().is_ok()); |
| 244 | assert_eq!(c.latency_claim(), None); |
| 245 | let d = c.format_prompt_directive(); |
| 246 | assert!(d.contains("no performance claim")); |
| 247 | assert!(!d.contains("Baseline")); |
| 248 | let mut forged = c.clone(); |
| 249 | forged.predicted_delta_pct = 15.0; |
| 250 | assert!(forged.validate().is_err()); |
| 251 | } |
| 252 | |
| 253 | #[test] |
| 254 | fn test_hypothesis_contract_rejects_empty_problem() { |
| 255 | let invalid = |
| 256 | HypothesisContract::new("hypo-bad", "cycle-01", "", "Cause", "p95", 100.0, 5.0); |
| 257 | assert!(invalid.validate().is_err()); |
| 258 | } |
| 259 | } |