interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / evaluator / mod.rs

527 lines · 19365 bytes Raw Blame History
1pub mod layers;
2pub mod metrics;
3pub mod stats;
4
5pub use layers::*;
6pub use metrics::{
7 LatencyDistribution, LatencyTimer, ProcessMetricsSnapshot, RusageMetrics, StatmMetrics,
8};
9pub use stats::{
10 BootstrapEstimate, FastPrng, FishersExactResult, PairedSample, StatisticalEngine,
11 TailNonInferiorityResult,
12};
13
14use p256::ecdsa::signature::{Signer, Verifier};
15use p256::ecdsa::{Signature, SigningKey, VerifyingKey};
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18use std::fs;
19use std::path::Path;
20
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
22pub struct EvaluationMetricsSummary {
23 pub latency_delta_pct: f64,
24 pub p_value: f64,
25 pub p95_ci_upper_degradation_pct: f64,
26 pub p99_ci_upper_degradation_pct: f64,
27 pub rss_growth_pct: f64,
28 pub candidate_resident_mb: u64,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
32pub struct EvaluationReceipt {
33 pub cycle_id: String,
34 pub candidate_id: String,
35 pub parent_id: String,
36 pub evaluated_at: String,
37 pub evaluator_version: String,
38 pub passed_all_hard_invariants: bool,
39 pub passed_statistical_gates: bool,
40 pub admitted: bool,
41 pub layer_results: Vec<LayerResult>,
42 pub metrics_summary: Option<EvaluationMetricsSummary>,
43 pub receipt_digest: String,
44 pub signature: Option<String>,
45 /// Receipt format. 1 (or absent, for records written before version 2) signs only the ids,
46 /// the admitted flag and the layer results. 2 also signs `binding`. See docs/RECEIPT-V2.md.
47 #[serde(default = "receipt_format_v1")]
48 pub format_version: u32,
49 /// Version 2 only: what exactly was evaluated, against which holdout set and policy.
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub binding: Option<ReceiptBindingV2>,
52}
53
54fn receipt_format_v1() -> u32 {
55 1
56}
57
58/// The identity a version 2 receipt signs, so a score cannot be paired with another change.
59#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
60pub struct ReceiptBindingV2 {
61 /// Path of the changed file, relative to the candidate root.
62 pub subject_path: String,
63 /// SHA-256 (hex) of the exact bytes of `subject_path` in the evaluated candidate.
64 pub subject_sha256: String,
65 /// Digest of the holdout directory (docs/RECEIPT-V2.md, "Holdout set digest").
66 pub holdout_set_sha256: String,
67 pub holdouts_total: u64,
68 pub holdouts_passed: u64,
69 /// SHA-256 (hex) of the exact policy file bytes the judge was given.
70 pub policy_sha256: String,
71 /// SHA-256 (hex) of the judge executable that produced the receipt.
72 pub evaluator_binary_sha256: String,
73}
74
75/// Length-prefixed field encoding for the version 2 digest: u64 little-endian length, then bytes.
76/// Writes one length-prefixed field (u64 little-endian length, then the bytes).
77pub fn put_field(h: &mut Sha256, bytes: &[u8]) {
78 h.update((bytes.len() as u64).to_le_bytes());
79 h.update(bytes);
80}
81
82pub const RECEIPT_V2_DOMAIN: &str = "spark-rsi.evaluation-receipt.v2";
83
84impl EvaluationReceipt {
85 pub fn compute_digest(
86 cycle_id: &str,
87 candidate_id: &str,
88 parent_id: &str,
89 admitted: bool,
90 layers: &[LayerResult],
91 ) -> String {
92 let mut hasher = Sha256::new();
93 hasher.update(cycle_id.as_bytes());
94 hasher.update(candidate_id.as_bytes());
95 hasher.update(parent_id.as_bytes());
96 hasher.update(if admitted { b"1" } else { b"0" });
97
98 for lr in layers {
99 hasher.update(lr.layer_name.as_bytes());
100 hasher.update(if lr.passed { b"1" } else { b"0" });
101 hasher.update(lr.score.to_le_bytes());
102 hasher.update(lr.summary.as_bytes());
103 }
104
105 hex::encode(hasher.finalize())
106 }
107
108 pub fn save_to_file(&self, path: &Path) -> Result<(), String> {
109 if let Some(parent) = path.parent() {
110 fs::create_dir_all(parent).map_err(|e| e.to_string())?;
111 }
112 let content = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
113 fs::write(path, content).map_err(|e| e.to_string())?;
114 Ok(())
115 }
116
117 pub fn load_from_file(path: &Path) -> Result<Self, String> {
118 let content = fs::read_to_string(path).map_err(|e| e.to_string())?;
119 serde_json::from_str(&content).map_err(|e| e.to_string())
120 }
121
122 /// Recomputes the digest for the receipt's own format. A version 1 receipt that carries a
123 /// binding, a version 2 receipt without one, and unknown versions never verify.
124 pub fn verify_digest(&self) -> bool {
125 match (self.format_version, &self.binding) {
126 (1, None) => {
127 let expected = Self::compute_digest(
128 &self.cycle_id,
129 &self.candidate_id,
130 &self.parent_id,
131 self.admitted,
132 &self.layer_results,
133 );
134 self.receipt_digest == expected
135 }
136 (2, Some(_)) => self
137 .compute_digest_v2()
138 .is_ok_and(|d| d == self.receipt_digest),
139 _ => false,
140 }
141 }
142
143 /// Version 2 digest (docs/RECEIPT-V2.md): SHA-256 over length-prefixed fields in a fixed order.
144 pub fn compute_digest_v2(&self) -> Result<String, String> {
145 let b = self
146 .binding
147 .as_ref()
148 .ok_or("version 2 digest needs a binding")?;
149 let mut h = Sha256::new();
150 put_field(&mut h, RECEIPT_V2_DOMAIN.as_bytes());
151 for s in [
152 &self.cycle_id,
153 &self.candidate_id,
154 &self.parent_id,
155 &self.evaluated_at,
156 &self.evaluator_version,
157 &b.evaluator_binary_sha256,
158 &b.subject_path,
159 &b.subject_sha256,
160 &b.holdout_set_sha256,
161 &b.policy_sha256,
162 ] {
163 put_field(&mut h, s.as_bytes());
164 }
165 put_field(&mut h, &b.holdouts_total.to_le_bytes());
166 put_field(&mut h, &b.holdouts_passed.to_le_bytes());
167 for flag in [
168 self.admitted,
169 self.passed_all_hard_invariants,
170 self.passed_statistical_gates,
171 ] {
172 put_field(&mut h, &[flag as u8]);
173 }
174 put_field(&mut h, &(self.layer_results.len() as u64).to_le_bytes());
175 for lr in &self.layer_results {
176 put_field(&mut h, lr.layer_name.as_bytes());
177 put_field(&mut h, &[lr.is_hard_invariant as u8]);
178 put_field(&mut h, &[lr.passed as u8]);
179 put_field(&mut h, &lr.score.to_bits().to_le_bytes());
180 put_field(&mut h, lr.summary.as_bytes());
181 put_field(&mut h, &(lr.violations.len() as u64).to_le_bytes());
182 for v in &lr.violations {
183 put_field(&mut h, v.as_bytes());
184 }
185 }
186 match &self.metrics_summary {
187 None => put_field(&mut h, &[0u8]),
188 Some(m) => {
189 put_field(&mut h, &[1u8]);
190 for x in [
191 m.latency_delta_pct,
192 m.p_value,
193 m.p95_ci_upper_degradation_pct,
194 m.p99_ci_upper_degradation_pct,
195 m.rss_growth_pct,
196 ] {
197 put_field(&mut h, &x.to_bits().to_le_bytes());
198 }
199 put_field(&mut h, &m.candidate_resident_mb.to_le_bytes());
200 }
201 }
202 Ok(hex::encode(h.finalize()))
203 }
204
205 /// Turns this receipt into version 2 with `binding`, recomputes the digest and signs it.
206 pub fn bind_and_sign_v2(
207 &mut self,
208 binding: ReceiptBindingV2,
209 signing_key: &SigningKey,
210 ) -> Result<(), String> {
211 self.format_version = 2;
212 self.binding = Some(binding);
213 self.receipt_digest = self.compute_digest_v2()?;
214 self.sign(signing_key);
215 Ok(())
216 }
217
218 /// The promotion check: version 2 only, valid signature under the judge's key, and the
219 /// signed identity equal to what the caller is about to promote. Version 1 receipts stay
220 /// verifiable with `verify_signature` for history but are never enough here.
221 pub fn verify_for_promotion(
222 &self,
223 judge_key: &VerifyingKey,
224 subject_sha256: &str,
225 policy_sha256: &str,
226 holdout_set_sha256: &str,
227 ) -> Result<(), String> {
228 if self.format_version != 2 {
229 return Err(format!(
230 "receipt format {} is not sufficient for promotion (version 2 required)",
231 self.format_version
232 ));
233 }
234 if !self.verify_signature(judge_key) {
235 return Err("receipt signature or digest does not verify under the judge key".into());
236 }
237 let b = self
238 .binding
239 .as_ref()
240 .ok_or("version 2 receipt without binding")?;
241 if b.subject_sha256 != subject_sha256 {
242 return Err(format!(
243 "receipt subject {} is not the change being promoted ({})",
244 b.subject_sha256, subject_sha256
245 ));
246 }
247 if b.policy_sha256 != policy_sha256 {
248 return Err("receipt policy digest differs from the pinned policy".into());
249 }
250 if b.holdout_set_sha256 != holdout_set_sha256 {
251 return Err("receipt holdout set differs from the pinned holdout set".into());
252 }
253 if !self.admitted {
254 return Err("judge did not admit the candidate".into());
255 }
256 Ok(())
257 }
258
259 pub fn sign(&mut self, signing_key: &SigningKey) {
260 let digest_bytes = hex::decode(&self.receipt_digest)
261 .unwrap_or_else(|_| self.receipt_digest.as_bytes().to_vec());
262 let signature: Signature = signing_key.sign(&digest_bytes);
263 self.signature = Some(format!("tpm2-p256:{}", hex::encode(signature.to_bytes())));
264 }
265
266 pub fn verify_signature(&self, verifying_key: &VerifyingKey) -> bool {
267 if !self.verify_digest() {
268 return false;
269 }
270 let Some(sig_str) = &self.signature else {
271 return false;
272 };
273 let raw_hex = if let Some(stripped) = sig_str.strip_prefix("tpm2-p256:") {
274 stripped
275 } else {
276 sig_str
277 };
278 let Ok(sig_bytes) = hex::decode(raw_hex) else {
279 return false;
280 };
281 let Ok(signature) = Signature::from_slice(&sig_bytes) else {
282 return false;
283 };
284 let digest_bytes = hex::decode(&self.receipt_digest)
285 .unwrap_or_else(|_| self.receipt_digest.as_bytes().to_vec());
286 verifying_key.verify(&digest_bytes, &signature).is_ok()
287 }
288}
289
290pub struct ObjectiveEvaluator;
291
292impl ObjectiveEvaluator {
293 pub fn evaluate_candidate(
294 cycle_id: &str,
295 candidate_id: &str,
296 parent_id: &str,
297 correctness: CorrectnessEvaluation,
298 security: SecurityEvaluation,
299 style: StyleEvaluation,
300 performance: PerformanceEvaluation,
301 resource_efficiency: ResourceEfficiencyEvaluation,
302 longitudinal_replay: LongitudinalReplayEvaluation,
303 ) -> EvaluationReceipt {
304 let layer_results = vec![
305 correctness.to_layer_result(),
306 security.to_layer_result(),
307 style.to_layer_result(),
308 performance.to_layer_result(),
309 resource_efficiency.to_layer_result(),
310 longitudinal_replay.to_layer_result(),
311 ];
312
313 let passed_all_hard_invariants =
314 correctness.passed && security.passed && style.passed && longitudinal_replay.passed;
315
316 let passed_statistical_gates = performance.passed && resource_efficiency.passed;
317
318 let admitted = passed_all_hard_invariants && passed_statistical_gates;
319
320 let receipt_digest = EvaluationReceipt::compute_digest(
321 cycle_id,
322 candidate_id,
323 parent_id,
324 admitted,
325 &layer_results,
326 );
327
328 let metrics_summary = Some(EvaluationMetricsSummary {
329 latency_delta_pct: performance.bootstrap_estimate.delta_pct,
330 p_value: performance.bootstrap_estimate.p_value,
331 p95_ci_upper_degradation_pct: performance.p95_non_inferiority.ci_95_upper_pct,
332 p99_ci_upper_degradation_pct: performance.p99_non_inferiority.ci_95_upper_pct,
333 rss_growth_pct: resource_efficiency.rss_growth_pct,
334 candidate_resident_mb: (resource_efficiency.candidate_rss_kb / 1024) as u64,
335 });
336
337 EvaluationReceipt {
338 cycle_id: cycle_id.to_string(),
339 candidate_id: candidate_id.to_string(),
340 parent_id: parent_id.to_string(),
341 evaluated_at: chrono::Utc::now().to_rfc3339(),
342 evaluator_version: crate::version().to_string(),
343 passed_all_hard_invariants,
344 passed_statistical_gates,
345 admitted,
346 layer_results,
347 metrics_summary,
348 receipt_digest,
349 signature: None,
350 format_version: 1,
351 binding: None,
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use super::*;
359
360 #[test]
361 fn test_objective_evaluator_all_pass() {
362 let correctness = CorrectnessLayer::evaluate_synthetic(true, 10, 0, 2, 0, true);
363 let security =
364 SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0);
365 let style = StyleLayer::evaluate_text("Clean text without violations.");
366 let perf = PerformanceEvaluation {
367 bootstrap_estimate: BootstrapEstimate {
368 sample_size: 30,
369 resamples_count: 1000,
370 observed_parent_mean: 100.0,
371 observed_candidate_mean: 80.0,
372 observed_delta_mean: -20.0,
373 delta_pct: -20.0,
374 ci_99_lower: -25.0,
375 ci_99_upper: -15.0,
376 p_value: 0.0001,
377 is_statistically_significant: true,
378 },
379 p95_non_inferiority: TailNonInferiorityResult {
380 percentile: 95.0,
381 parent_val: 110.0,
382 candidate_val: 90.0,
383 observed_degradation_pct: -18.18,
384 ci_95_upper_pct: 0.5,
385 non_inferiority_margin_pct: 1.0,
386 passes_non_inferiority: true,
387 },
388 p99_non_inferiority: TailNonInferiorityResult {
389 percentile: 99.0,
390 parent_val: 120.0,
391 candidate_val: 95.0,
392 observed_degradation_pct: -20.83,
393 ci_95_upper_pct: 0.8,
394 non_inferiority_margin_pct: 1.0,
395 passes_non_inferiority: true,
396 },
397 target_metric_improved: true,
398 non_target_metrics_safe: true,
399 passed: true,
400 violations: vec![],
401 };
402 let res_eff = ResourceEfficiencyEvaluation {
403 parent_rss_kb: 50_000,
404 candidate_rss_kb: 50_200,
405 rss_growth_pct: 0.4,
406 rss_growth_within_budget: true,
407 host_memory_within_budget: true,
408 context_switches_delta: 0,
409 passed: true,
410 violations: vec![],
411 };
412 let long_rep = LongitudinalReplayLayer::evaluate_results(
413 &LongitudinalReplayLayer::builtin_regression_corpus(),
414 );
415
416 let mut receipt = ObjectiveEvaluator::evaluate_candidate(
417 "cycle-001",
418 "cand-001",
419 "parent-000",
420 correctness,
421 security,
422 style,
423 perf,
424 res_eff,
425 long_rep,
426 );
427
428 assert!(receipt.passed_all_hard_invariants);
429 assert!(receipt.passed_statistical_gates);
430 assert!(receipt.admitted);
431 assert!(receipt.verify_digest());
432 assert_eq!(receipt.layer_results.len(), 6);
433
434 // Test real ECDSA P-256 signing and verification
435 let signing_key = SigningKey::from_bytes(&[42u8; 32].into()).unwrap();
436 let verifying_key = VerifyingKey::from(&signing_key);
437
438 receipt.sign(&signing_key);
439 assert!(receipt.signature.is_some());
440 assert!(receipt.verify_signature(&verifying_key));
441
442 // Tampered receipt fails signature verification
443 let mut tampered = receipt.clone();
444 tampered.candidate_id = "attacker-modified-cand".to_string();
445 tampered.receipt_digest = EvaluationReceipt::compute_digest(
446 &tampered.cycle_id,
447 &tampered.candidate_id,
448 &tampered.parent_id,
449 tampered.admitted,
450 &tampered.layer_results,
451 );
452 assert!(!tampered.verify_signature(&verifying_key));
453 }
454
455 #[test]
456 fn test_objective_evaluator_hard_invariant_rejection() {
457 let correctness = CorrectnessLayer::evaluate_synthetic(false, 0, 0, 0, 0, true);
458 let security =
459 SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0);
460 let style = StyleLayer::evaluate_text("Clean text.");
461 let perf = PerformanceEvaluation {
462 bootstrap_estimate: BootstrapEstimate {
463 sample_size: 30,
464 resamples_count: 1000,
465 observed_parent_mean: 100.0,
466 observed_candidate_mean: 80.0,
467 observed_delta_mean: -20.0,
468 delta_pct: -20.0,
469 ci_99_lower: -25.0,
470 ci_99_upper: -15.0,
471 p_value: 0.0001,
472 is_statistically_significant: true,
473 },
474 p95_non_inferiority: TailNonInferiorityResult {
475 percentile: 95.0,
476 parent_val: 110.0,
477 candidate_val: 90.0,
478 observed_degradation_pct: -18.18,
479 ci_95_upper_pct: 0.5,
480 non_inferiority_margin_pct: 1.0,
481 passes_non_inferiority: true,
482 },
483 p99_non_inferiority: TailNonInferiorityResult {
484 percentile: 99.0,
485 parent_val: 120.0,
486 candidate_val: 95.0,
487 observed_degradation_pct: -20.83,
488 ci_95_upper_pct: 0.8,
489 non_inferiority_margin_pct: 1.0,
490 passes_non_inferiority: true,
491 },
492 target_metric_improved: true,
493 non_target_metrics_safe: true,
494 passed: true,
495 violations: vec![],
496 };
497 let res_eff = ResourceEfficiencyEvaluation {
498 parent_rss_kb: 50_000,
499 candidate_rss_kb: 50_200,
500 rss_growth_pct: 0.4,
501 rss_growth_within_budget: true,
502 host_memory_within_budget: true,
503 context_switches_delta: 0,
504 passed: true,
505 violations: vec![],
506 };
507 let long_rep = LongitudinalReplayLayer::evaluate_results(
508 &LongitudinalReplayLayer::builtin_regression_corpus(),
509 );
510
511 let receipt = ObjectiveEvaluator::evaluate_candidate(
512 "cycle-002",
513 "cand-002",
514 "parent-000",
515 correctness,
516 security,
517 style,
518 perf,
519 res_eff,
520 long_rep,
521 );
522
523 assert!(!receipt.passed_all_hard_invariants);
524 assert!(!receipt.admitted);
525 assert!(receipt.verify_digest());
526 }
527}