spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / tests / test_receipt_v2.rs
| 1 | //! Version 2 evaluation receipts (docs/RECEIPT-V2.md): the signed score binds the exact change, |
| 2 | //! holdout set, policy and evaluator, and promotion refuses anything else. |
| 3 | |
| 4 | use p256::ecdsa::SigningKey; |
| 5 | use sha2::{Digest, Sha256}; |
| 6 | use spark_rsi::actor::judge::{ |
| 7 | strict_changed_paths, BlindJudge, EvaluationPolicy, HoldoutSuite, V2Request, |
| 8 | }; |
| 9 | use spark_rsi::evaluator::layers::{CorrectnessLayer, LayerResult}; |
| 10 | use spark_rsi::evaluator::{EvaluationMetricsSummary, EvaluationReceipt, ReceiptBindingV2}; |
| 11 | use spark_rsi::promotion_gate::{check_v2_promotion, PromotionSubject}; |
| 12 | use std::fs; |
| 13 | use std::path::Path; |
| 14 | |
| 15 | const README: &[u8] = b"A plain readme for the candidate.\n"; |
| 16 | |
| 17 | fn key(seed: u8) -> SigningKey { |
| 18 | SigningKey::from_slice(&[seed; 32]).unwrap() |
| 19 | } |
| 20 | |
| 21 | fn sha(bytes: &[u8]) -> String { |
| 22 | hex::encode(Sha256::digest(bytes)) |
| 23 | } |
| 24 | |
| 25 | fn layer(name: &str, passed: bool, score: f64) -> LayerResult { |
| 26 | LayerResult { |
| 27 | layer_name: name.to_string(), |
| 28 | is_hard_invariant: true, |
| 29 | passed, |
| 30 | score, |
| 31 | summary: format!("{} summary", name), |
| 32 | violations: Vec::new(), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | fn base_receipt() -> EvaluationReceipt { |
| 37 | EvaluationReceipt { |
| 38 | cycle_id: "cycle-v2".to_string(), |
| 39 | candidate_id: "cand-v2".to_string(), |
| 40 | parent_id: "parent-v2".to_string(), |
| 41 | evaluated_at: "2026-10-08T22:00:00Z".to_string(), |
| 42 | evaluator_version: "1.0.0".to_string(), |
| 43 | passed_all_hard_invariants: true, |
| 44 | passed_statistical_gates: true, |
| 45 | admitted: true, |
| 46 | layer_results: vec![ |
| 47 | layer("correctness", true, 1.0), |
| 48 | layer("security", true, 1.0), |
| 49 | ], |
| 50 | metrics_summary: Some(EvaluationMetricsSummary { |
| 51 | latency_delta_pct: -1.0, |
| 52 | p_value: 0.01, |
| 53 | p95_ci_upper_degradation_pct: 0.5, |
| 54 | p99_ci_upper_degradation_pct: 0.7, |
| 55 | rss_growth_pct: 0.1, |
| 56 | candidate_resident_mb: 12, |
| 57 | }), |
| 58 | receipt_digest: String::new(), |
| 59 | signature: None, |
| 60 | format_version: 1, |
| 61 | binding: None, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn binding(holdout_set_sha256: &str, policy_sha256: &str) -> ReceiptBindingV2 { |
| 66 | ReceiptBindingV2 { |
| 67 | subject_path: "README.md".to_string(), |
| 68 | subject_sha256: sha(README), |
| 69 | holdout_set_sha256: holdout_set_sha256.to_string(), |
| 70 | holdouts_total: 4, |
| 71 | holdouts_passed: 4, |
| 72 | policy_sha256: policy_sha256.to_string(), |
| 73 | evaluator_binary_sha256: sha(b"judge-binary"), |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | fn v2_receipt(judge: &SigningKey, holdout: &str, policy: &str) -> EvaluationReceipt { |
| 78 | let mut r = base_receipt(); |
| 79 | r.bind_and_sign_v2(binding(holdout, policy), judge).unwrap(); |
| 80 | r |
| 81 | } |
| 82 | |
| 83 | fn policy_json(holdout_set_sha256: &str) -> String { |
| 84 | serde_json::json!({ |
| 85 | "policy_id": "vac-m5-test", |
| 86 | "holdout_set_sha256": holdout_set_sha256, |
| 87 | "min_holdout_pass_ratio": 1.0, |
| 88 | "require_admitted": true, |
| 89 | "allowed_targets": ["README.md"], |
| 90 | "protected_paths": ["holdouts", "policy", ".rsi"], |
| 91 | }) |
| 92 | .to_string() |
| 93 | } |
| 94 | |
| 95 | fn write_policy(dir: &Path, holdout_set_sha256: &str) -> (String, String) { |
| 96 | let path = dir.join("policy.json"); |
| 97 | let text = policy_json(holdout_set_sha256); |
| 98 | fs::write(&path, &text).unwrap(); |
| 99 | (path.to_string_lossy().to_string(), sha(text.as_bytes())) |
| 100 | } |
| 101 | |
| 102 | fn pub_hex(k: &SigningKey) -> String { |
| 103 | hex::encode(k.verifying_key().to_sec1_point(false).as_bytes()) |
| 104 | } |
| 105 | |
| 106 | // ---------------------------------------------------------------- receipt format |
| 107 | |
| 108 | #[test] |
| 109 | fn v2_round_trip_verifies_for_promotion() { |
| 110 | let judge = key(7); |
| 111 | let h = sha(b"holdouts"); |
| 112 | let p = sha(b"policy"); |
| 113 | let r = v2_receipt(&judge, &h, &p); |
| 114 | assert_eq!(r.format_version, 2); |
| 115 | assert!(r.verify_signature(judge.verifying_key())); |
| 116 | r.verify_for_promotion(judge.verifying_key(), &sha(README), &p, &h) |
| 117 | .unwrap(); |
| 118 | // Survives a JSON round trip unchanged. |
| 119 | let back: EvaluationReceipt = |
| 120 | serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap(); |
| 121 | assert_eq!(back, r); |
| 122 | back.verify_for_promotion(judge.verifying_key(), &sha(README), &p, &h) |
| 123 | .unwrap(); |
| 124 | } |
| 125 | |
| 126 | #[test] |
| 127 | fn v1_receipts_still_verify_but_never_promote() { |
| 128 | let judge = key(7); |
| 129 | let mut r = base_receipt(); |
| 130 | r.receipt_digest = EvaluationReceipt::compute_digest( |
| 131 | &r.cycle_id, |
| 132 | &r.candidate_id, |
| 133 | &r.parent_id, |
| 134 | r.admitted, |
| 135 | &r.layer_results, |
| 136 | ); |
| 137 | r.sign(&judge); |
| 138 | assert!( |
| 139 | r.verify_signature(judge.verifying_key()), |
| 140 | "history stays verifiable" |
| 141 | ); |
| 142 | let err = r |
| 143 | .verify_for_promotion(judge.verifying_key(), &sha(README), "p", "h") |
| 144 | .unwrap_err(); |
| 145 | assert!(err.contains("not sufficient"), "{}", err); |
| 146 | } |
| 147 | |
| 148 | #[test] |
| 149 | fn old_records_without_new_fields_load_as_version_1() { |
| 150 | let judge = key(7); |
| 151 | let mut r = base_receipt(); |
| 152 | r.receipt_digest = EvaluationReceipt::compute_digest( |
| 153 | &r.cycle_id, |
| 154 | &r.candidate_id, |
| 155 | &r.parent_id, |
| 156 | r.admitted, |
| 157 | &r.layer_results, |
| 158 | ); |
| 159 | r.sign(&judge); |
| 160 | let mut v = serde_json::to_value(&r).unwrap(); |
| 161 | v.as_object_mut().unwrap().remove("format_version"); |
| 162 | v.as_object_mut().unwrap().remove("binding"); |
| 163 | let old: EvaluationReceipt = serde_json::from_value(v).unwrap(); |
| 164 | assert_eq!(old.format_version, 1); |
| 165 | assert!(old.binding.is_none()); |
| 166 | assert!(old.verify_signature(judge.verifying_key())); |
| 167 | } |
| 168 | |
| 169 | #[test] |
| 170 | fn format_and_binding_must_agree() { |
| 171 | let judge = key(7); |
| 172 | // A version 2 receipt relabelled as version 1 keeps its binding: refused. |
| 173 | let mut r = v2_receipt(&judge, "h", "p"); |
| 174 | r.format_version = 1; |
| 175 | assert!(!r.verify_signature(judge.verifying_key())); |
| 176 | // A version 2 receipt with the binding stripped: refused. |
| 177 | let mut r = v2_receipt(&judge, "h", "p"); |
| 178 | r.binding = None; |
| 179 | assert!(!r.verify_signature(judge.verifying_key())); |
| 180 | // Unknown versions: refused. |
| 181 | let mut r = v2_receipt(&judge, "h", "p"); |
| 182 | r.format_version = 3; |
| 183 | assert!(!r.verify_signature(judge.verifying_key())); |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn substituted_change_is_refused() { |
| 188 | let judge = key(7); |
| 189 | let r = v2_receipt(&judge, "h", "p"); |
| 190 | let other = sha(b"A different change.\n"); |
| 191 | let err = r |
| 192 | .verify_for_promotion(judge.verifying_key(), &other, "p", "h") |
| 193 | .unwrap_err(); |
| 194 | assert!(err.contains("not the change being promoted"), "{}", err); |
| 195 | // Rewriting the bound subject digest to match breaks the signature. |
| 196 | let mut forged = r.clone(); |
| 197 | forged.binding.as_mut().unwrap().subject_sha256 = other.clone(); |
| 198 | assert!(forged |
| 199 | .verify_for_promotion(judge.verifying_key(), &other, "p", "h") |
| 200 | .is_err()); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn substituted_scores_are_refused() { |
| 205 | let judge = key(7); |
| 206 | let base = v2_receipt(&judge, "h", "p"); |
| 207 | let mutations: Vec<(&str, Box<dyn Fn(&mut EvaluationReceipt)>)> = vec![ |
| 208 | ("layer score", Box::new(|r| r.layer_results[0].score = 0.5)), |
| 209 | ( |
| 210 | "layer passed", |
| 211 | Box::new(|r| r.layer_results[1].passed = false), |
| 212 | ), |
| 213 | ( |
| 214 | "hard flag", |
| 215 | Box::new(|r| r.layer_results[0].is_hard_invariant = false), |
| 216 | ), |
| 217 | ( |
| 218 | "violations", |
| 219 | Box::new(|r| r.layer_results[0].violations.push("x".into())), |
| 220 | ), |
| 221 | ( |
| 222 | "summary", |
| 223 | Box::new(|r| r.layer_results[0].summary.push('!')), |
| 224 | ), |
| 225 | ( |
| 226 | "layer dropped", |
| 227 | Box::new(|r| { |
| 228 | r.layer_results.pop(); |
| 229 | }), |
| 230 | ), |
| 231 | ("admitted", Box::new(|r| r.admitted = !r.admitted)), |
| 232 | ( |
| 233 | "statistical gates", |
| 234 | Box::new(|r| r.passed_statistical_gates = false), |
| 235 | ), |
| 236 | ( |
| 237 | "hard invariants", |
| 238 | Box::new(|r| r.passed_all_hard_invariants = false), |
| 239 | ), |
| 240 | ( |
| 241 | "holdouts passed", |
| 242 | Box::new(|r| r.binding.as_mut().unwrap().holdouts_passed = 3), |
| 243 | ), |
| 244 | ( |
| 245 | "holdouts total", |
| 246 | Box::new(|r| r.binding.as_mut().unwrap().holdouts_total = 5), |
| 247 | ), |
| 248 | ( |
| 249 | "metrics", |
| 250 | Box::new(|r| r.metrics_summary.as_mut().unwrap().p_value = 0.5), |
| 251 | ), |
| 252 | ("metrics removed", Box::new(|r| r.metrics_summary = None)), |
| 253 | ("evaluated at", Box::new(|r| r.evaluated_at.push('Z'))), |
| 254 | ( |
| 255 | "evaluator version", |
| 256 | Box::new(|r| r.evaluator_version = "9".into()), |
| 257 | ), |
| 258 | ( |
| 259 | "evaluator binary", |
| 260 | Box::new(|r| r.binding.as_mut().unwrap().evaluator_binary_sha256 = sha(b"other")), |
| 261 | ), |
| 262 | ( |
| 263 | "subject path", |
| 264 | Box::new(|r| r.binding.as_mut().unwrap().subject_path = "src/lib.rs".into()), |
| 265 | ), |
| 266 | ( |
| 267 | "candidate id", |
| 268 | Box::new(|r| r.candidate_id = "cand-other".into()), |
| 269 | ), |
| 270 | ]; |
| 271 | for (what, m) in mutations { |
| 272 | let mut r = base.clone(); |
| 273 | m(&mut r); |
| 274 | assert!( |
| 275 | !r.verify_signature(judge.verifying_key()), |
| 276 | "changing {} must break the signature", |
| 277 | what |
| 278 | ); |
| 279 | // Recomputing the digest does not help without the judge key. |
| 280 | r.receipt_digest = r.compute_digest_v2().unwrap(); |
| 281 | assert!( |
| 282 | !r.verify_signature(judge.verifying_key()), |
| 283 | "changing {} and re-digesting must still fail", |
| 284 | what |
| 285 | ); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn wrong_signing_key_is_refused() { |
| 291 | let judge = key(7); |
| 292 | let proposer = key(9); |
| 293 | // Signed by the proposer instead of the judge. |
| 294 | let r = v2_receipt(&proposer, "h", "p"); |
| 295 | let err = r |
| 296 | .verify_for_promotion(judge.verifying_key(), &sha(README), "p", "h") |
| 297 | .unwrap_err(); |
| 298 | assert!(err.contains("signature"), "{}", err); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn altered_policy_or_holdouts_are_refused() { |
| 303 | let judge = key(7); |
| 304 | let r = v2_receipt(&judge, "h", "p"); |
| 305 | assert!(r |
| 306 | .verify_for_promotion(judge.verifying_key(), &sha(README), "p-altered", "h") |
| 307 | .unwrap_err() |
| 308 | .contains("policy")); |
| 309 | assert!(r |
| 310 | .verify_for_promotion(judge.verifying_key(), &sha(README), "p", "h-altered") |
| 311 | .unwrap_err() |
| 312 | .contains("holdout")); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn not_admitted_is_refused() { |
| 317 | let judge = key(7); |
| 318 | let mut r = base_receipt(); |
| 319 | r.admitted = false; |
| 320 | r.bind_and_sign_v2(binding("h", "p"), &judge).unwrap(); |
| 321 | assert!(r |
| 322 | .verify_for_promotion(judge.verifying_key(), &sha(README), "p", "h") |
| 323 | .unwrap_err() |
| 324 | .contains("did not admit")); |
| 325 | } |
| 326 | |
| 327 | // ---------------------------------------------------------------- promotion gate |
| 328 | |
| 329 | #[test] |
| 330 | fn promotion_gate_accepts_bound_receipt_and_refuses_everything_else() { |
| 331 | let tmp = tempfile::tempdir().unwrap(); |
| 332 | let judge = key(7); |
| 333 | let daemon = key(9); |
| 334 | let holdout = sha(b"holdouts"); |
| 335 | let (policy_path, policy_sha) = write_policy(tmp.path(), &holdout); |
| 336 | let r = v2_receipt(&judge, &holdout, &policy_sha); |
| 337 | let jk = pub_hex(&judge); |
| 338 | let subject_sha = sha(README); |
| 339 | let subject = PromotionSubject::same("parent-v2", "README.md", &subject_sha); |
| 340 | |
| 341 | check_v2_promotion( |
| 342 | &r, |
| 343 | Some(&jk), |
| 344 | daemon.verifying_key(), |
| 345 | Some(&policy_path), |
| 346 | &subject, |
| 347 | ) |
| 348 | .unwrap(); |
| 349 | |
| 350 | // Missing judge key, missing policy: fail closed. |
| 351 | assert!(check_v2_promotion( |
| 352 | &r, |
| 353 | None, |
| 354 | daemon.verifying_key(), |
| 355 | Some(&policy_path), |
| 356 | &subject |
| 357 | ) |
| 358 | .unwrap_err() |
| 359 | .contains("fails closed")); |
| 360 | assert!( |
| 361 | check_v2_promotion(&r, Some(&jk), daemon.verifying_key(), None, &subject) |
| 362 | .unwrap_err() |
| 363 | .contains("fails closed") |
| 364 | ); |
| 365 | // The judge key must not be the promoter's own key. |
| 366 | assert!(check_v2_promotion( |
| 367 | &r, |
| 368 | Some(&jk), |
| 369 | judge.verifying_key(), |
| 370 | Some(&policy_path), |
| 371 | &subject |
| 372 | ) |
| 373 | .unwrap_err() |
| 374 | .contains("separate")); |
| 375 | // Pinned key is someone else's: signature refused. |
| 376 | let wrong = pub_hex(&key(11)); |
| 377 | assert!(check_v2_promotion( |
| 378 | &r, |
| 379 | Some(&wrong), |
| 380 | daemon.verifying_key(), |
| 381 | Some(&policy_path), |
| 382 | &subject |
| 383 | ) |
| 384 | .is_err()); |
| 385 | // Substituted change. |
| 386 | assert!(check_v2_promotion( |
| 387 | &r, |
| 388 | Some(&jk), |
| 389 | daemon.verifying_key(), |
| 390 | Some(&policy_path), |
| 391 | &PromotionSubject::same("parent-v2", "README.md", &sha(b"other bytes")) |
| 392 | ) |
| 393 | .is_err()); |
| 394 | // The receipt covers README.md; the change replaces another file with the same bytes. |
| 395 | assert!(check_v2_promotion( |
| 396 | &r, |
| 397 | Some(&jk), |
| 398 | daemon.verifying_key(), |
| 399 | Some(&policy_path), |
| 400 | &PromotionSubject::same("parent-v2", "src/lib.rs", &subject_sha) |
| 401 | ) |
| 402 | .unwrap_err() |
| 403 | .contains("covers README.md")); |
| 404 | // The staged bytes on disk differ from the change's bytes. |
| 405 | let other = sha(b"staged bytes"); |
| 406 | assert!(check_v2_promotion( |
| 407 | &r, |
| 408 | Some(&jk), |
| 409 | daemon.verifying_key(), |
| 410 | Some(&policy_path), |
| 411 | &PromotionSubject { |
| 412 | parent_id: "parent-v2", |
| 413 | path: "README.md", |
| 414 | content_sha256: &subject_sha, |
| 415 | disk_sha256: &other, |
| 416 | } |
| 417 | ) |
| 418 | .unwrap_err() |
| 419 | .contains("staged README.md")); |
| 420 | // The same bytes, judged against another parent: refused. |
| 421 | assert!(check_v2_promotion( |
| 422 | &r, |
| 423 | Some(&jk), |
| 424 | daemon.verifying_key(), |
| 425 | Some(&policy_path), |
| 426 | &PromotionSubject::same("another-parent", "README.md", &subject_sha) |
| 427 | ) |
| 428 | .unwrap_err() |
| 429 | .contains("against parent parent-v2")); |
| 430 | // The operator's policy file changes after the evaluation: refused. |
| 431 | fs::write( |
| 432 | &policy_path, |
| 433 | policy_json(&holdout).replace("vac-m5-test", "vac-m5-edited"), |
| 434 | ) |
| 435 | .unwrap(); |
| 436 | assert!(check_v2_promotion( |
| 437 | &r, |
| 438 | Some(&jk), |
| 439 | daemon.verifying_key(), |
| 440 | Some(&policy_path), |
| 441 | &subject |
| 442 | ) |
| 443 | .unwrap_err() |
| 444 | .contains("policy")); |
| 445 | } |
| 446 | |
| 447 | #[test] |
| 448 | fn promotion_gate_refuses_below_threshold_and_v1() { |
| 449 | let tmp = tempfile::tempdir().unwrap(); |
| 450 | let judge = key(7); |
| 451 | let daemon = key(9); |
| 452 | let holdout = sha(b"holdouts"); |
| 453 | let (policy_path, policy_sha) = write_policy(tmp.path(), &holdout); |
| 454 | let mut r = base_receipt(); |
| 455 | let mut b = binding(&holdout, &policy_sha); |
| 456 | b.holdouts_passed = 3; |
| 457 | r.bind_and_sign_v2(b, &judge).unwrap(); |
| 458 | let jk = pub_hex(&judge); |
| 459 | assert!(check_v2_promotion( |
| 460 | &r, |
| 461 | Some(&jk), |
| 462 | daemon.verifying_key(), |
| 463 | Some(&policy_path), |
| 464 | &PromotionSubject::same("parent-v2", "README.md", &sha(README)) |
| 465 | ) |
| 466 | .unwrap_err() |
| 467 | .contains("threshold")); |
| 468 | |
| 469 | let mut v1 = base_receipt(); |
| 470 | v1.receipt_digest = EvaluationReceipt::compute_digest( |
| 471 | &v1.cycle_id, |
| 472 | &v1.candidate_id, |
| 473 | &v1.parent_id, |
| 474 | v1.admitted, |
| 475 | &v1.layer_results, |
| 476 | ); |
| 477 | v1.sign(&judge); |
| 478 | assert!(check_v2_promotion( |
| 479 | &v1, |
| 480 | Some(&jk), |
| 481 | daemon.verifying_key(), |
| 482 | Some(&policy_path), |
| 483 | &PromotionSubject::same("parent-v2", "README.md", &sha(README)) |
| 484 | ) |
| 485 | .unwrap_err() |
| 486 | .contains("not sufficient")); |
| 487 | } |
| 488 | |
| 489 | #[test] |
| 490 | fn policy_that_waives_admission_is_rejected() { |
| 491 | let tmp = tempfile::tempdir().unwrap(); |
| 492 | let path = tmp.path().join("p.json"); |
| 493 | fs::write( |
| 494 | &path, |
| 495 | policy_json(&sha(b"h")).replace("\"require_admitted\":true", "\"require_admitted\":false"), |
| 496 | ) |
| 497 | .unwrap(); |
| 498 | assert!(EvaluationPolicy::load(&path) |
| 499 | .unwrap_err() |
| 500 | .contains("require_admitted")); |
| 501 | fs::write(&path, policy_json(&sha(b"h")).replace("1.0", "0.0")).unwrap(); |
| 502 | assert!(EvaluationPolicy::load(&path).is_err()); |
| 503 | fs::write(&path, r#"{"policy_id":"x"}"#).unwrap(); |
| 504 | assert!(EvaluationPolicy::load(&path).is_err()); |
| 505 | } |
| 506 | |
| 507 | // ---------------------------------------------------------------- holdout set |
| 508 | |
| 509 | fn holdout_dir(tmp: &Path) -> std::path::PathBuf { |
| 510 | let dir = tmp.join("holdouts"); |
| 511 | for s in HoldoutSuite::builtin_suites() { |
| 512 | s.save_to_dir(&dir).unwrap(); |
| 513 | } |
| 514 | dir |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn holdout_set_digest_is_stable_and_content_bound() { |
| 519 | let tmp = tempfile::tempdir().unwrap(); |
| 520 | let dir = holdout_dir(tmp.path()); |
| 521 | let (suites, d1) = HoldoutSuite::load_strict(&dir).unwrap(); |
| 522 | assert_eq!(suites.len(), 2); |
| 523 | let (_, d2) = HoldoutSuite::load_strict(&dir).unwrap(); |
| 524 | assert_eq!(d1, d2); |
| 525 | // Editing one expected answer changes the digest. |
| 526 | let f = dir.join("HOLD-INV-001.json"); |
| 527 | let text = fs::read_to_string(&f) |
| 528 | .unwrap() |
| 529 | .replace("EMPTY_OK", "EMPTY_OK2"); |
| 530 | fs::write(&f, text).unwrap(); |
| 531 | let (_, d3) = HoldoutSuite::load_strict(&dir).unwrap(); |
| 532 | assert_ne!(d1, d3); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn incomplete_or_corrupted_holdouts_are_rejected() { |
| 537 | type Breaker = Box<dyn Fn(&Path)>; |
| 538 | let breakers: Vec<(&str, Breaker)> = vec![ |
| 539 | ( |
| 540 | "corrupted file", |
| 541 | Box::new(|d| fs::write(d.join("HOLD-INV-001.json"), "{not json").unwrap()), |
| 542 | ), |
| 543 | ( |
| 544 | "truncated file", |
| 545 | Box::new(|d| { |
| 546 | let f = d.join("HOLD-INV-001.json"); |
| 547 | let t = fs::read_to_string(&f).unwrap(); |
| 548 | fs::write(&f, &t[..t.len() / 2]).unwrap(); |
| 549 | }), |
| 550 | ), |
| 551 | ( |
| 552 | "empty suite", |
| 553 | Box::new(|d| { |
| 554 | fs::write( |
| 555 | d.join("EMPTY.json"), |
| 556 | r#"{"suite_id":"E","name":"E","cases":[]}"#, |
| 557 | ) |
| 558 | .unwrap() |
| 559 | }), |
| 560 | ), |
| 561 | ( |
| 562 | "missing expected output", |
| 563 | Box::new(|d| { |
| 564 | fs::write( |
| 565 | d.join("BAD.json"), |
| 566 | r#"{"suite_id":"B","name":"B","cases":[{"id":"B-1","name":"b","input":"x","expected_output":"","category":"c"}]}"#, |
| 567 | ) |
| 568 | .unwrap() |
| 569 | }), |
| 570 | ), |
| 571 | ( |
| 572 | "duplicate case id", |
| 573 | Box::new(|d| { |
| 574 | fs::copy( |
| 575 | d.join("HOLD-INV-001.json"), |
| 576 | d.join("HOLD-INV-001-copy.json"), |
| 577 | ) |
| 578 | .unwrap(); |
| 579 | }), |
| 580 | ), |
| 581 | ( |
| 582 | "stray non-json file", |
| 583 | Box::new(|d| fs::write(d.join("notes.txt"), "x").unwrap()), |
| 584 | ), |
| 585 | ( |
| 586 | "subdirectory", |
| 587 | Box::new(|d| fs::create_dir(d.join("more")).unwrap()), |
| 588 | ), |
| 589 | ( |
| 590 | "symlink", |
| 591 | Box::new(|d| { |
| 592 | std::os::unix::fs::symlink(d.join("HOLD-INV-001.json"), d.join("link.json")) |
| 593 | .unwrap() |
| 594 | }), |
| 595 | ), |
| 596 | ( |
| 597 | "all files removed", |
| 598 | Box::new(|d| { |
| 599 | for e in fs::read_dir(d).unwrap() { |
| 600 | fs::remove_file(e.unwrap().path()).unwrap(); |
| 601 | } |
| 602 | }), |
| 603 | ), |
| 604 | ( |
| 605 | "directory missing", |
| 606 | Box::new(|d| fs::remove_dir_all(d).unwrap()), |
| 607 | ), |
| 608 | ]; |
| 609 | for (what, brk) in breakers { |
| 610 | let tmp = tempfile::tempdir().unwrap(); |
| 611 | let dir = holdout_dir(tmp.path()); |
| 612 | brk(&dir); |
| 613 | assert!( |
| 614 | HoldoutSuite::load_strict(&dir).is_err(), |
| 615 | "{} must fail closed", |
| 616 | what |
| 617 | ); |
| 618 | assert!( |
| 619 | HoldoutSuite::load_from_dir(&dir).is_err(), |
| 620 | "{} (v1 loader)", |
| 621 | what |
| 622 | ); |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | // ---------------------------------------------------------------- judge, end to end |
| 627 | |
| 628 | struct Trees { |
| 629 | _tmp: tempfile::TempDir, |
| 630 | root: std::path::PathBuf, |
| 631 | parent: std::path::PathBuf, |
| 632 | candidate: std::path::PathBuf, |
| 633 | holdouts: std::path::PathBuf, |
| 634 | } |
| 635 | |
| 636 | fn trees() -> Trees { |
| 637 | let tmp = tempfile::tempdir().unwrap(); |
| 638 | let root = tmp.path().to_path_buf(); |
| 639 | let exe = Path::new(env!("CARGO_BIN_EXE_spark-rsi")); |
| 640 | let parent = root.join("parent"); |
| 641 | let candidate = root.join("candidate"); |
| 642 | for t in [&parent, &candidate] { |
| 643 | fs::create_dir_all(t.join("bin")).unwrap(); |
| 644 | fs::copy(exe, t.join("bin/spark-rsi")).unwrap(); |
| 645 | } |
| 646 | fs::write(parent.join("README.md"), b"The old readme.\n").unwrap(); |
| 647 | fs::write(candidate.join("README.md"), README).unwrap(); |
| 648 | let holdouts = holdout_dir(&root); |
| 649 | Trees { |
| 650 | _tmp: tmp, |
| 651 | root, |
| 652 | parent, |
| 653 | candidate, |
| 654 | holdouts, |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | fn v2_judge(t: &Trees, policy_holdout_digest: &str, subject: &str) -> (BlindJudge, String, String) { |
| 659 | let (policy_path, policy_sha) = write_policy(&t.root, policy_holdout_digest); |
| 660 | let (policy, loaded_sha) = EvaluationPolicy::load(Path::new(&policy_path)).unwrap(); |
| 661 | assert_eq!(loaded_sha, policy_sha); |
| 662 | let mut judge = BlindJudge::new(t.holdouts.clone(), t.root.join("out")) |
| 663 | .with_signing_key(key(7)) |
| 664 | .with_non_inferiority_margin(1000.0) |
| 665 | .with_executable("bin/spark-rsi".into(), false) |
| 666 | .with_v2(V2Request { |
| 667 | subject_path: subject.to_string(), |
| 668 | policy, |
| 669 | policy_sha256: policy_sha.clone(), |
| 670 | }); |
| 671 | judge.require_build_verification = false; |
| 672 | (judge, policy_path, policy_sha) |
| 673 | } |
| 674 | |
| 675 | #[test] |
| 676 | fn judge_signs_v2_bound_to_subject_policy_and_holdouts() { |
| 677 | let t = trees(); |
| 678 | fs::create_dir_all(t.root.join("out")).unwrap(); |
| 679 | let (_, holdout_digest) = HoldoutSuite::load_strict(&t.holdouts).unwrap(); |
| 680 | let (judge, policy_path, policy_sha) = v2_judge(&t, &holdout_digest, "README.md"); |
| 681 | let r = judge |
| 682 | .evaluate_cycle("cyc-v2", "cand", "par", &t.candidate, &t.parent) |
| 683 | .unwrap(); |
| 684 | let b = r.binding.clone().expect("v2 binding"); |
| 685 | assert_eq!(r.format_version, 2); |
| 686 | assert_eq!(b.subject_path, "README.md"); |
| 687 | assert_eq!(b.subject_sha256, sha(README)); |
| 688 | assert_eq!(b.holdout_set_sha256, holdout_digest); |
| 689 | assert_eq!(b.policy_sha256, policy_sha); |
| 690 | assert_eq!(b.holdouts_total, 4); |
| 691 | assert_eq!(b.holdouts_passed, 4); |
| 692 | assert_eq!(b.evaluator_binary_sha256.len(), 64); |
| 693 | assert!( |
| 694 | r.admitted, |
| 695 | "candidate should be admitted: {:?}", |
| 696 | r.layer_results |
| 697 | ); |
| 698 | check_v2_promotion( |
| 699 | &r, |
| 700 | Some(&pub_hex(&key(7))), |
| 701 | key(9).verifying_key(), |
| 702 | Some(&policy_path), |
| 703 | &PromotionSubject::same("par", "README.md", &sha(README)), |
| 704 | ) |
| 705 | .unwrap(); |
| 706 | } |
| 707 | |
| 708 | #[test] |
| 709 | fn judge_refuses_holdout_set_that_differs_from_policy() { |
| 710 | let t = trees(); |
| 711 | let (judge, _, _) = v2_judge(&t, &sha(b"some other holdout set"), "README.md"); |
| 712 | let err = judge |
| 713 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 714 | .unwrap_err(); |
| 715 | assert!(err.contains("does not match the policy"), "{}", err); |
| 716 | } |
| 717 | |
| 718 | #[test] |
| 719 | fn judge_refuses_subject_outside_policy_or_protected() { |
| 720 | let t = trees(); |
| 721 | let (_, holdout_digest) = HoldoutSuite::load_strict(&t.holdouts).unwrap(); |
| 722 | for subject in [ |
| 723 | "src/lib.rs", |
| 724 | "../README.md", |
| 725 | "/etc/passwd", |
| 726 | "holdouts/x.json", |
| 727 | ] { |
| 728 | let (judge, _, _) = v2_judge(&t, &holdout_digest, subject); |
| 729 | assert!( |
| 730 | judge |
| 731 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 732 | .is_err(), |
| 733 | "subject {} must be refused", |
| 734 | subject |
| 735 | ); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | #[test] |
| 740 | fn judge_refuses_candidate_that_changes_more_than_the_subject() { |
| 741 | let t = trees(); |
| 742 | let (_, holdout_digest) = HoldoutSuite::load_strict(&t.holdouts).unwrap(); |
| 743 | // A hidden build-config change rides along with the subject. |
| 744 | fs::create_dir_all(t.candidate.join(".cargo")).unwrap(); |
| 745 | fs::write(t.candidate.join(".cargo/config.toml"), "[build]\n").unwrap(); |
| 746 | let (judge, _, _) = v2_judge(&t, &holdout_digest, "README.md"); |
| 747 | let err = judge |
| 748 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 749 | .unwrap_err(); |
| 750 | assert!(err.contains("exactly the subject"), "{}", err); |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn judge_refuses_incomplete_holdouts() { |
| 755 | let t = trees(); |
| 756 | let (_, holdout_digest) = HoldoutSuite::load_strict(&t.holdouts).unwrap(); |
| 757 | fs::write(t.holdouts.join("HOLD-STY-002.json"), "{").unwrap(); |
| 758 | let (judge, _, _) = v2_judge(&t, &holdout_digest, "README.md"); |
| 759 | let err = judge |
| 760 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 761 | .unwrap_err(); |
| 762 | assert!(err.contains("corrupt"), "{}", err); |
| 763 | } |
| 764 | |
| 765 | #[test] |
| 766 | fn strict_diff_sees_dotfiles_and_skips_only_git_and_target() { |
| 767 | let t = trees(); |
| 768 | assert_eq!( |
| 769 | strict_changed_paths(&t.parent, &t.candidate).unwrap(), |
| 770 | vec!["README.md".to_string()] |
| 771 | ); |
| 772 | fs::create_dir_all(t.candidate.join("target/release")).unwrap(); |
| 773 | fs::write(t.candidate.join("target/release/x"), "x").unwrap(); |
| 774 | fs::create_dir_all(t.candidate.join(".git")).unwrap(); |
| 775 | fs::write(t.candidate.join(".git/HEAD"), "x").unwrap(); |
| 776 | assert_eq!( |
| 777 | strict_changed_paths(&t.parent, &t.candidate).unwrap().len(), |
| 778 | 1 |
| 779 | ); |
| 780 | fs::write(t.candidate.join(".env"), "x").unwrap(); |
| 781 | assert_eq!( |
| 782 | strict_changed_paths(&t.parent, &t.candidate).unwrap().len(), |
| 783 | 2 |
| 784 | ); |
| 785 | } |
| 786 | |
| 787 | #[test] |
| 788 | fn strict_diff_refuses_nested_git_entries() { |
| 789 | let t = trees(); |
| 790 | fs::create_dir_all(t.candidate.join("src")).unwrap(); |
| 791 | fs::write(t.candidate.join("src/.git"), "gitdir: elsewhere").unwrap(); |
| 792 | let err = strict_changed_paths(&t.parent, &t.candidate).unwrap_err(); |
| 793 | assert!(err.contains("nested .git"), "{}", err); |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn judge_refuses_an_executable_the_tree_comparison_cannot_cover() { |
| 798 | let t = trees(); |
| 799 | let (_, holdout_digest) = HoldoutSuite::load_strict(&t.holdouts).unwrap(); |
| 800 | // A prebuilt program under the skipped target directory. |
| 801 | for tree in [&t.parent, &t.candidate] { |
| 802 | fs::create_dir_all(tree.join("target/release")).unwrap(); |
| 803 | fs::copy( |
| 804 | tree.join("bin/spark-rsi"), |
| 805 | tree.join("target/release/spark-rsi"), |
| 806 | ) |
| 807 | .unwrap(); |
| 808 | } |
| 809 | let (judge, _, _) = v2_judge(&t, &holdout_digest, "README.md"); |
| 810 | let judge = judge.with_executable("target/release/spark-rsi".into(), false); |
| 811 | let err = judge |
| 812 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 813 | .unwrap_err(); |
| 814 | assert!(err.contains("tree comparison covers"), "{}", err); |
| 815 | // No named executable: the judge never searches the trees for one. |
| 816 | let (mut judge, _, _) = v2_judge(&t, &holdout_digest, "README.md"); |
| 817 | judge.executable = None; |
| 818 | let err = judge |
| 819 | .evaluate_cycle("c", "cand", "par", &t.candidate, &t.parent) |
| 820 | .unwrap_err(); |
| 821 | assert!(err.contains("names its executable"), "{}", err); |
| 822 | } |
| 823 | |
| 824 | #[test] |
| 825 | fn policy_paths_must_be_clean() { |
| 826 | let tmp = tempfile::tempdir().unwrap(); |
| 827 | let digest = sha(b"holdouts"); |
| 828 | for (field, value) in [ |
| 829 | ("protected_paths", serde_json::json!(["./src"])), |
| 830 | ("protected_paths", serde_json::json!(["/"])), |
| 831 | ("protected_paths", serde_json::json!([""])), |
| 832 | ("allowed_targets", serde_json::json!(["../README.md"])), |
| 833 | ("allowed_targets", serde_json::json!([])), |
| 834 | ] { |
| 835 | let mut p: serde_json::Value = serde_json::from_str(&policy_json(&digest)).unwrap(); |
| 836 | p[field] = value.clone(); |
| 837 | let path = tmp.path().join("p.json"); |
| 838 | fs::write(&path, p.to_string()).unwrap(); |
| 839 | assert!( |
| 840 | EvaluationPolicy::load(&path).is_err(), |
| 841 | "{} = {} must be refused", |
| 842 | field, |
| 843 | value |
| 844 | ); |
| 845 | } |
| 846 | } |
| 847 | |
| 848 | /// The judge builds candidate code inside a sandbox: a file outside the tree (standing in for the |
| 849 | /// judge's signing key) cannot be read at build time, so `include_str!` of it fails the build. |
| 850 | #[test] |
| 851 | fn judge_build_cannot_read_files_outside_the_tree() { |
| 852 | if !spark_rsi::not_run::user_scope_or_not_run("judge_build_cannot_read_files_outside_the_tree") |
| 853 | { |
| 854 | return; |
| 855 | } |
| 856 | let probe = std::process::Command::new("bwrap") |
| 857 | .args([ |
| 858 | "--unshare-user", |
| 859 | "--unshare-net", |
| 860 | "--ro-bind", |
| 861 | "/", |
| 862 | "/", |
| 863 | "true", |
| 864 | ]) |
| 865 | .status(); |
| 866 | if !probe.is_ok_and(|s| s.success()) { |
| 867 | eprintln!("SKIP: bubblewrap cannot create a user namespace on this host"); |
| 868 | return; |
| 869 | } |
| 870 | let tmp = tempfile::tempdir().unwrap(); |
| 871 | let secret = tmp.path().join("judge.key"); |
| 872 | fs::write(&secret, "not-for-candidates").unwrap(); |
| 873 | let crate_toml = |
| 874 | "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n"; |
| 875 | let lock = "version = 4\n\n[[package]]\nname = \"probe\"\nversion = \"0.1.0\"\n"; |
| 876 | let parent = tmp.path().join("parent"); |
| 877 | let candidate = tmp.path().join("candidate"); |
| 878 | for (tree, main) in [ |
| 879 | (&parent, "fn main() {}\n".to_string()), |
| 880 | ( |
| 881 | &candidate, |
| 882 | format!( |
| 883 | "const K: &str = include_str!({:?});\nfn main() {{ println!(\"{{}}\", K); }}\n", |
| 884 | secret |
| 885 | ), |
| 886 | ), |
| 887 | ] { |
| 888 | fs::create_dir_all(tree.join("src")).unwrap(); |
| 889 | fs::write(tree.join("Cargo.toml"), crate_toml).unwrap(); |
| 890 | fs::write(tree.join("Cargo.lock"), lock).unwrap(); |
| 891 | fs::write(tree.join("src/main.rs"), main).unwrap(); |
| 892 | } |
| 893 | // Outside the sandbox the candidate builds (the include works), so the refusal below is the |
| 894 | // sandbox and not a broken fixture. |
| 895 | let plain = std::process::Command::new("cargo") |
| 896 | .args(["build", "--release", "--offline", "--locked", "-q"]) |
| 897 | .env("CARGO_TARGET_DIR", tmp.path().join("plain-target")) |
| 898 | .current_dir(&candidate) |
| 899 | .status() |
| 900 | .unwrap(); |
| 901 | assert!(plain.success(), "control build outside the sandbox failed"); |
| 902 | |
| 903 | let holdouts = holdout_dir(tmp.path()); |
| 904 | let mut judge = BlindJudge::new(holdouts, tmp.path().join("out")) |
| 905 | .with_signing_key(key(7)) |
| 906 | .with_executable("probe".into(), true); |
| 907 | judge.require_build_verification = false; |
| 908 | let err = judge |
| 909 | .evaluate_cycle("c", "cand", "par", &candidate, &parent) |
| 910 | .unwrap_err(); |
| 911 | assert!(err.contains("candidate build failed"), "{}", err); |
| 912 | assert!(err.contains("judge.key"), "{}", err); |
| 913 | } |
| 914 | |
| 915 | /// The judge's own `cargo check` / `cargo test` on candidate source (the correctness layer) runs |
| 916 | /// in the same sandbox as its build: a candidate that reads a file outside its tree (standing in |
| 917 | /// for the judge's signing key) at compile time fails there, while the same tree builds outside |
| 918 | /// the sandbox and a harmless tree passes inside it. |
| 919 | #[test] |
| 920 | fn judge_correctness_check_cannot_read_files_outside_the_tree() { |
| 921 | if !spark_rsi::not_run::user_scope_or_not_run( |
| 922 | "judge_correctness_check_cannot_read_files_outside_the_tree", |
| 923 | ) { |
| 924 | return; |
| 925 | } |
| 926 | let probe = std::process::Command::new("bwrap") |
| 927 | .args([ |
| 928 | "--unshare-user", |
| 929 | "--unshare-net", |
| 930 | "--ro-bind", |
| 931 | "/", |
| 932 | "/", |
| 933 | "true", |
| 934 | ]) |
| 935 | .status(); |
| 936 | if !probe.is_ok_and(|s| s.success()) { |
| 937 | eprintln!("SKIP: bubblewrap cannot create a user namespace on this host"); |
| 938 | return; |
| 939 | } |
| 940 | let tmp = tempfile::tempdir().unwrap(); |
| 941 | let secret = tmp.path().join("judge.key"); |
| 942 | fs::write(&secret, "not-for-candidates").unwrap(); |
| 943 | let crate_toml = |
| 944 | "[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2021\"\n[workspace]\n"; |
| 945 | let lock = "version = 4\n\n[[package]]\nname = \"probe\"\nversion = \"0.1.0\"\n"; |
| 946 | let tree = |name: &str, lib: String| { |
| 947 | let t = tmp.path().join(name); |
| 948 | fs::create_dir_all(t.join("src")).unwrap(); |
| 949 | fs::write(t.join("Cargo.toml"), crate_toml).unwrap(); |
| 950 | fs::write(t.join("Cargo.lock"), lock).unwrap(); |
| 951 | fs::write(t.join("src/lib.rs"), lib).unwrap(); |
| 952 | t |
| 953 | }; |
| 954 | let harmless = tree( |
| 955 | "harmless", |
| 956 | "pub fn f() -> u8 { 1 }\n#[test]\nfn t() { assert_eq!(f(), 1); }\n".into(), |
| 957 | ); |
| 958 | let thief = tree( |
| 959 | "thief", |
| 960 | format!("pub const K: &str = include_str!({:?});\n", secret), |
| 961 | ); |
| 962 | |
| 963 | let plain = std::process::Command::new("cargo") |
| 964 | .args(["check", "--offline", "--locked", "-q"]) |
| 965 | .env("CARGO_TARGET_DIR", tmp.path().join("plain-target")) |
| 966 | .current_dir(&thief) |
| 967 | .status() |
| 968 | .unwrap(); |
| 969 | assert!(plain.success(), "control check outside the sandbox failed"); |
| 970 | |
| 971 | let ok = CorrectnessLayer::evaluate_repo(&harmless); |
| 972 | assert!( |
| 973 | ok.compilation_passed && ok.unit_tests_passed == 1 && ok.passed, |
| 974 | "{:?}", |
| 975 | ok |
| 976 | ); |
| 977 | // Tests that do not even build report no failed count, but the exit status still fails them. |
| 978 | let broken = tree( |
| 979 | "broken", |
| 980 | "pub fn f() -> u8 { 1 }\n#[test]\nfn t() { let _x: u8 = \"no\"; }\n".into(), |
| 981 | ); |
| 982 | let b = CorrectnessLayer::evaluate_repo(&broken); |
| 983 | assert!( |
| 984 | b.compilation_passed && b.unit_tests_failed == 0 && !b.passed, |
| 985 | "{:?}", |
| 986 | b |
| 987 | ); |
| 988 | let refused = CorrectnessLayer::evaluate_repo(&thief); |
| 989 | assert!(!refused.compilation_passed, "{:?}", refused); |
| 990 | assert!( |
| 991 | refused.failures.iter().any(|f| f.contains("judge.key")), |
| 992 | "{:?}", |
| 993 | refused.failures |
| 994 | ); |
| 995 | } |