spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / src / actor / judge.rs
| 1 | use clap::Parser; |
| 2 | use p256::ecdsa::SigningKey; |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | use sha2::{Digest, Sha256}; |
| 5 | use spark_rsi::evaluator::layers::{ |
| 6 | CorrectnessLayer, DefectTestResult, LongitudinalReplayLayer, PerformanceLayer, |
| 7 | ResourceEfficiencyLayer, SecurityLayer, StyleLayer, |
| 8 | }; |
| 9 | use spark_rsi::evaluator::metrics::{LatencyTimer, RusageMetrics, StatmMetrics}; |
| 10 | use spark_rsi::evaluator::{put_field, EvaluationReceipt, ObjectiveEvaluator, ReceiptBindingV2}; |
| 11 | use spark_rsi::isolation::CandidateJailRunner; |
| 12 | use std::collections::BTreeSet; |
| 13 | use std::fs; |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | use std::process::Command; |
| 16 | |
| 17 | #[derive(Parser, Debug, Clone)] |
| 18 | #[command( |
| 19 | name = "spark-rsi-judge", |
| 20 | about = "Unprivileged Blind Judge binary executing holdouts and emitting EvaluationReceipt" |
| 21 | )] |
| 22 | pub struct JudgeCli { |
| 23 | #[arg(long, default_value = "cycle-genesis")] |
| 24 | pub cycle_id: String, |
| 25 | |
| 26 | #[arg(long, default_value = "cand-001")] |
| 27 | pub candidate_id: String, |
| 28 | |
| 29 | #[arg(long, default_value = "parent-000")] |
| 30 | pub parent_id: String, |
| 31 | |
| 32 | #[arg(long, default_value = ".")] |
| 33 | pub candidate_path: String, |
| 34 | |
| 35 | #[arg(long, default_value = ".")] |
| 36 | pub parent_path: String, |
| 37 | |
| 38 | #[arg(long, default_value = ".rsi/holdouts")] |
| 39 | pub holdouts_dir: String, |
| 40 | |
| 41 | #[arg(long, default_value = ".rsi/eval_outputs")] |
| 42 | pub output_dir: String, |
| 43 | |
| 44 | #[arg(long, default_value_t = 1.0)] |
| 45 | pub non_inferiority_margin_pct: f64, |
| 46 | |
| 47 | #[arg(long)] |
| 48 | pub signing_key_hex: Option<String>, |
| 49 | |
| 50 | #[arg(long)] |
| 51 | pub signing_key_file: Option<String>, |
| 52 | |
| 53 | #[arg(long)] |
| 54 | pub require_latency_improvement: bool, |
| 55 | |
| 56 | /// Version 2: the one file (relative to the candidate tree) whose exact bytes the receipt binds. |
| 57 | /// Requires --policy-file. Without it the judge emits a version 1 receipt. |
| 58 | #[arg(long, requires = "policy_file")] |
| 59 | pub subject_path: Option<String>, |
| 60 | |
| 61 | /// Version 2: the evaluation policy (pins the holdout set digest, threshold and targets). |
| 62 | #[arg(long, requires = "subject_path")] |
| 63 | pub policy_file: Option<String>, |
| 64 | |
| 65 | /// Executable to run for holdouts and benchmarks, relative to each tree (or, with |
| 66 | /// --build-release, the binary name under the judge's own build directory). |
| 67 | #[arg(long)] |
| 68 | pub executable: Option<String>, |
| 69 | |
| 70 | /// Build parent and candidate with `cargo build --release --offline --locked` into a fresh |
| 71 | /// judge-owned target directory instead of trusting any binary already in the trees. |
| 72 | #[arg(long, requires = "executable")] |
| 73 | pub build_release: bool, |
| 74 | |
| 75 | /// Print the SEC1 hex public key for the configured signing key and exit. |
| 76 | #[arg(long)] |
| 77 | pub public_key: bool, |
| 78 | |
| 79 | /// Load --holdouts-dir strictly, print its holdout-set digest and exit (for pinning it in a |
| 80 | /// policy file). |
| 81 | #[arg(long)] |
| 82 | pub print_holdout_digest: bool, |
| 83 | } |
| 84 | |
| 85 | /// Domain prefix of the holdout-set digest (docs/RECEIPT-V2.md). |
| 86 | pub const HOLDOUT_SET_DOMAIN: &str = "spark-rsi.holdout-set.v1"; |
| 87 | |
| 88 | /// Operator-owned evaluation policy for version 2 receipts. The judge refuses to evaluate when the |
| 89 | /// holdout directory does not hash to `holdout_set_sha256`, when the subject is not an allowed |
| 90 | /// target, or when the subject falls under a protected path. |
| 91 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] |
| 92 | #[serde(deny_unknown_fields)] |
| 93 | pub struct EvaluationPolicy { |
| 94 | pub policy_id: String, |
| 95 | pub holdout_set_sha256: String, |
| 96 | pub min_holdout_pass_ratio: f64, |
| 97 | pub require_admitted: bool, |
| 98 | pub allowed_targets: Vec<String>, |
| 99 | pub protected_paths: Vec<String>, |
| 100 | /// Latency non-inferiority margin in percent for this evaluation. Absent = the judge's |
| 101 | /// configured margin. Part of the policy bytes, so the signed `policy_sha256` covers it. |
| 102 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 103 | pub non_inferiority_margin_pct: Option<f64>, |
| 104 | } |
| 105 | |
| 106 | impl EvaluationPolicy { |
| 107 | /// Loads the policy and returns it with the SHA-256 of its exact file bytes. |
| 108 | pub fn load(path: &Path) -> Result<(Self, String), String> { |
| 109 | let bytes = |
| 110 | fs::read(path).map_err(|e| format!("cannot read policy file {:?}: {}", path, e))?; |
| 111 | let policy: Self = serde_json::from_slice(&bytes) |
| 112 | .map_err(|e| format!("policy file {:?} is invalid: {}", path, e))?; |
| 113 | if !policy.require_admitted { |
| 114 | return Err( |
| 115 | "policy require_admitted must be true; promotion never skips admission".into(), |
| 116 | ); |
| 117 | } |
| 118 | if !(policy.min_holdout_pass_ratio > 0.0 && policy.min_holdout_pass_ratio <= 1.0) { |
| 119 | return Err("policy min_holdout_pass_ratio must be in (0, 1]".into()); |
| 120 | } |
| 121 | if policy.holdout_set_sha256.len() != 64 || hex::decode(&policy.holdout_set_sha256).is_err() |
| 122 | { |
| 123 | return Err("policy holdout_set_sha256 must be 64 hex characters".into()); |
| 124 | } |
| 125 | if policy |
| 126 | .non_inferiority_margin_pct |
| 127 | .is_some_and(|m| !(m.is_finite() && m >= 0.0)) |
| 128 | { |
| 129 | return Err( |
| 130 | "policy non_inferiority_margin_pct must be a finite non-negative number".into(), |
| 131 | ); |
| 132 | } |
| 133 | if policy.allowed_targets.is_empty() { |
| 134 | return Err("policy allowed_targets must name at least one file".into()); |
| 135 | } |
| 136 | // Paths are compared as strings: an unclean entry (`./src`, `/`, `src/../x`) would |
| 137 | // silently protect or allow nothing it appears to. |
| 138 | if let Some(p) = policy |
| 139 | .allowed_targets |
| 140 | .iter() |
| 141 | .chain(&policy.protected_paths) |
| 142 | .find(|p| !is_clean_relative(p.trim_end_matches('/'))) |
| 143 | { |
| 144 | return Err(format!("policy path {:?} is not a clean relative path", p)); |
| 145 | } |
| 146 | Ok((policy, hex::encode(Sha256::digest(&bytes)))) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// What a version 2 evaluation binds: the subject file and the policy it was judged under. |
| 151 | #[derive(Debug, Clone)] |
| 152 | pub struct V2Request { |
| 153 | pub subject_path: String, |
| 154 | pub policy: EvaluationPolicy, |
| 155 | pub policy_sha256: String, |
| 156 | } |
| 157 | |
| 158 | /// A relative path with no `..`, no root and no empty components. |
| 159 | fn is_clean_relative(p: &str) -> bool { |
| 160 | !p.is_empty() |
| 161 | && !p.starts_with('/') |
| 162 | && p.split('/').all(|c| !c.is_empty() && c != "." && c != "..") |
| 163 | } |
| 164 | |
| 165 | fn path_is_under(path: &str, prefix: &str) -> bool { |
| 166 | let prefix = prefix.trim_end_matches('/'); |
| 167 | path == prefix || path.starts_with(&format!("{}/", prefix)) |
| 168 | } |
| 169 | |
| 170 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 171 | pub struct HoldoutCase { |
| 172 | pub id: String, |
| 173 | pub name: String, |
| 174 | pub input: String, |
| 175 | pub expected_output: String, |
| 176 | pub category: String, |
| 177 | } |
| 178 | |
| 179 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 180 | pub struct HoldoutSuite { |
| 181 | pub suite_id: String, |
| 182 | pub name: String, |
| 183 | pub cases: Vec<HoldoutCase>, |
| 184 | } |
| 185 | |
| 186 | impl HoldoutSuite { |
| 187 | pub fn builtin_suites() -> Vec<Self> { |
| 188 | vec![ |
| 189 | HoldoutSuite { |
| 190 | suite_id: "HOLD-INV-001".to_string(), |
| 191 | name: "Invariant & Boundary Holdouts".to_string(), |
| 192 | cases: vec![ |
| 193 | HoldoutCase { |
| 194 | id: "INV-01".to_string(), |
| 195 | name: "Empty input handling".to_string(), |
| 196 | input: "".to_string(), |
| 197 | expected_output: "EMPTY_OK".to_string(), |
| 198 | category: "boundary".to_string(), |
| 199 | }, |
| 200 | HoldoutCase { |
| 201 | id: "INV-02".to_string(), |
| 202 | name: "Zero latency divide by zero protection".to_string(), |
| 203 | input: "0".to_string(), |
| 204 | expected_output: "DIV0_GUARDED".to_string(), |
| 205 | category: "robustness".to_string(), |
| 206 | }, |
| 207 | ], |
| 208 | }, |
| 209 | HoldoutSuite { |
| 210 | suite_id: "HOLD-STY-002".to_string(), |
| 211 | name: "Sovereign Voice Style Holdouts".to_string(), |
| 212 | cases: vec![ |
| 213 | HoldoutCase { |
| 214 | id: "STY-01".to_string(), |
| 215 | name: "Zero em and en dashes".to_string(), |
| 216 | input: "check_unicode_dashes".to_string(), |
| 217 | expected_output: "DASHES_PROHIBITED".to_string(), |
| 218 | category: "style".to_string(), |
| 219 | }, |
| 220 | HoldoutCase { |
| 221 | id: "STY-02".to_string(), |
| 222 | name: "Zero forbidden buzzwords".to_string(), |
| 223 | input: "scan_forbidden_lexicon".to_string(), |
| 224 | expected_output: "BUZZWORDS_CLEARED".to_string(), |
| 225 | category: "style".to_string(), |
| 226 | }, |
| 227 | ], |
| 228 | }, |
| 229 | ] |
| 230 | } |
| 231 | |
| 232 | pub fn load_from_dir(dir: &Path) -> Result<Vec<Self>, String> { |
| 233 | Self::load_strict(dir).map(|(suites, _)| suites) |
| 234 | } |
| 235 | |
| 236 | /// Loads every holdout suite and returns them with the holdout-set digest. Fails closed on |
| 237 | /// anything other than regular `.json` files, on a file that does not parse, on an empty |
| 238 | /// suite or case field, and on duplicate case ids. Nothing is skipped silently. |
| 239 | pub fn load_strict(dir: &Path) -> Result<(Vec<Self>, String), String> { |
| 240 | if !dir.is_dir() { |
| 241 | return Err(format!( |
| 242 | "Holdouts directory does not exist: {:?}. Production evaluation fails closed.", |
| 243 | dir |
| 244 | )); |
| 245 | } |
| 246 | let entries = fs::read_dir(dir) |
| 247 | .map_err(|e| format!("Failed to read holdouts directory {:?}: {}", dir, e))?; |
| 248 | let mut names = Vec::new(); |
| 249 | for entry in entries { |
| 250 | let entry = entry.map_err(|e| format!("Failed to read holdouts directory: {}", e))?; |
| 251 | let name = entry |
| 252 | .file_name() |
| 253 | .into_string() |
| 254 | .map_err(|n| format!("holdout entry {:?} has a non-UTF-8 name", n))?; |
| 255 | let kind = entry |
| 256 | .file_type() |
| 257 | .map_err(|e| format!("cannot stat holdout entry {}: {}", name, e))?; |
| 258 | if !kind.is_file() || !name.ends_with(".json") { |
| 259 | return Err(format!( |
| 260 | "unexpected holdout entry {:?}: only regular .json files are allowed. Production evaluation fails closed.", |
| 261 | name |
| 262 | )); |
| 263 | } |
| 264 | names.push(name); |
| 265 | } |
| 266 | if names.is_empty() { |
| 267 | return Err(format!( |
| 268 | "No valid holdout suites found in {:?}. Production evaluation fails closed.", |
| 269 | dir |
| 270 | )); |
| 271 | } |
| 272 | names.sort(); |
| 273 | |
| 274 | let mut h = Sha256::new(); |
| 275 | put_field(&mut h, HOLDOUT_SET_DOMAIN.as_bytes()); |
| 276 | put_field(&mut h, &(names.len() as u64).to_le_bytes()); |
| 277 | let mut suites = Vec::new(); |
| 278 | let mut ids = BTreeSet::new(); |
| 279 | for name in &names { |
| 280 | let bytes = fs::read(dir.join(name)) |
| 281 | .map_err(|e| format!("cannot read holdout file {}: {}", name, e))?; |
| 282 | let suite: HoldoutSuite = serde_json::from_slice(&bytes).map_err(|e| { |
| 283 | format!( |
| 284 | "holdout file {} is corrupt: {}. Production evaluation fails closed.", |
| 285 | name, e |
| 286 | ) |
| 287 | })?; |
| 288 | if suite.cases.is_empty() { |
| 289 | return Err(format!( |
| 290 | "holdout file {} has no cases (incomplete suite)", |
| 291 | name |
| 292 | )); |
| 293 | } |
| 294 | for case in &suite.cases { |
| 295 | if case.id.is_empty() || case.expected_output.is_empty() { |
| 296 | return Err(format!( |
| 297 | "holdout file {} has an incomplete case (empty id or expected output)", |
| 298 | name |
| 299 | )); |
| 300 | } |
| 301 | if !ids.insert(case.id.clone()) { |
| 302 | return Err(format!("duplicate holdout case id {}", case.id)); |
| 303 | } |
| 304 | } |
| 305 | put_field(&mut h, name.as_bytes()); |
| 306 | put_field(&mut h, &Sha256::digest(&bytes)); |
| 307 | suites.push(suite); |
| 308 | } |
| 309 | Ok((suites, hex::encode(h.finalize()))) |
| 310 | } |
| 311 | |
| 312 | pub fn save_to_dir(&self, dir: &Path) -> Result<(), String> { |
| 313 | fs::create_dir_all(dir).map_err(|e| e.to_string())?; |
| 314 | let filename = format!("{}.json", self.suite_id); |
| 315 | let path = dir.join(filename); |
| 316 | let content = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; |
| 317 | fs::write(path, content).map_err(|e| e.to_string())?; |
| 318 | Ok(()) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | pub struct BlindJudge { |
| 323 | pub holdouts_dir: PathBuf, |
| 324 | pub output_dir: PathBuf, |
| 325 | pub signing_key: Option<SigningKey>, |
| 326 | pub require_latency_improvement: bool, |
| 327 | pub non_inferiority_margin_pct: f64, |
| 328 | /// When false, compile-dependent correctness layers are skipped. |
| 329 | /// Non-code proposals (markdown sanitization) cannot change build or ABI behavior, |
| 330 | /// and the sandbox cannot resolve sibling path dependencies for a rebuild. |
| 331 | pub require_build_verification: bool, |
| 332 | /// Executable to run, relative to each tree (or the binary name under the judge build dir). |
| 333 | pub executable: Option<PathBuf>, |
| 334 | /// Build both trees into a fresh judge-owned target directory before evaluating. |
| 335 | pub build_release: bool, |
| 336 | /// When set, the judge binds and signs a version 2 receipt. |
| 337 | pub v2: Option<V2Request>, |
| 338 | } |
| 339 | |
| 340 | impl BlindJudge { |
| 341 | pub fn new(holdouts_dir: PathBuf, output_dir: PathBuf) -> Self { |
| 342 | Self { |
| 343 | holdouts_dir, |
| 344 | output_dir, |
| 345 | signing_key: None, |
| 346 | require_latency_improvement: false, |
| 347 | non_inferiority_margin_pct: 5.0, |
| 348 | require_build_verification: true, |
| 349 | executable: None, |
| 350 | build_release: false, |
| 351 | v2: None, |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | pub fn with_non_inferiority_margin(mut self, margin: f64) -> Self { |
| 356 | self.non_inferiority_margin_pct = margin; |
| 357 | self |
| 358 | } |
| 359 | |
| 360 | pub fn with_signing_key(mut self, key: SigningKey) -> Self { |
| 361 | self.signing_key = Some(key); |
| 362 | self |
| 363 | } |
| 364 | |
| 365 | pub fn with_require_latency_improvement(mut self, req: bool) -> Self { |
| 366 | self.require_latency_improvement = req; |
| 367 | self |
| 368 | } |
| 369 | |
| 370 | pub fn with_executable(mut self, exe: PathBuf, build_release: bool) -> Self { |
| 371 | self.executable = Some(exe); |
| 372 | self.build_release = build_release; |
| 373 | self |
| 374 | } |
| 375 | |
| 376 | pub fn with_v2(mut self, req: V2Request) -> Self { |
| 377 | self.v2 = Some(req); |
| 378 | self |
| 379 | } |
| 380 | |
| 381 | pub fn evaluate_cycle( |
| 382 | &self, |
| 383 | cycle_id: &str, |
| 384 | candidate_id: &str, |
| 385 | parent_id: &str, |
| 386 | candidate_path: &Path, |
| 387 | parent_path: &Path, |
| 388 | ) -> Result<EvaluationReceipt, String> { |
| 389 | // 0. Production evaluation fails closed if no authorized cryptographic signing key is configured |
| 390 | let signing_key = self.signing_key.as_ref().ok_or_else(|| { |
| 391 | "No authorized cryptographic signing key provided to BlindJudge. Production evaluation fails closed.".to_string() |
| 392 | })?; |
| 393 | |
| 394 | // 1. Production evaluation fails closed if holdouts directory is missing or empty |
| 395 | let (suites, holdout_set_sha256) = HoldoutSuite::load_strict(&self.holdouts_dir)?; |
| 396 | |
| 397 | // 1b. Version 2 preflight: pinned holdout set, allowed subject, nothing else changed. |
| 398 | let subject_sha256_before = match &self.v2 { |
| 399 | Some(req) => { |
| 400 | Some(self.v2_preflight(req, &holdout_set_sha256, parent_path, candidate_path)?) |
| 401 | } |
| 402 | None => None, |
| 403 | }; |
| 404 | |
| 405 | let mut total_holdouts: usize = 0; |
| 406 | let mut passed_holdouts = 0; |
| 407 | let mut holdout_violations = Vec::new(); |
| 408 | |
| 409 | // 2. Candidate binary must exist; production evaluation fails closed if not built |
| 410 | let (parent_bin, candidate_bin) = |
| 411 | self.resolve_binaries(cycle_id, parent_path, candidate_path)?; |
| 412 | |
| 413 | // 3. Execute actual holdout cases strictly through Bubblewrap jail |
| 414 | let jail_runner = CandidateJailRunner::new(&candidate_bin); |
| 415 | |
| 416 | for suite in &suites { |
| 417 | for case in &suite.cases { |
| 418 | total_holdouts += 1; |
| 419 | let actual_output = match jail_runner.execute(&["holdout", &case.input]) { |
| 420 | Ok((true, stdout, _)) => stdout.trim().to_string(), |
| 421 | Ok((false, _, stderr)) => format!("EXEC_FAIL:{}", stderr.trim()), |
| 422 | Err(e) => format!("JAIL_ERR:{}", e), |
| 423 | }; |
| 424 | |
| 425 | if actual_output == case.expected_output { |
| 426 | passed_holdouts += 1; |
| 427 | } else { |
| 428 | holdout_violations.push(format!( |
| 429 | "Holdout '{}' ({}) assertion failed: expected '{}', got '{}'", |
| 430 | case.name, case.id, case.expected_output, actual_output |
| 431 | )); |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | // 4. Extract real diff and changed files between parent and candidate |
| 437 | let (modified_files, patch_diff, style_text) = |
| 438 | compute_candidate_diff(parent_path, candidate_path)?; |
| 439 | |
| 440 | let correctness = if !self.require_build_verification { |
| 441 | // Non-code proposal: build, unit, integration, and ABI gates carry no signal. |
| 442 | CorrectnessLayer::evaluate_synthetic(true, 1, 0, 0, 0, true) |
| 443 | } else if candidate_path.join("Cargo.toml").exists() { |
| 444 | CorrectnessLayer::evaluate_repo(candidate_path) |
| 445 | } else { |
| 446 | CorrectnessLayer::evaluate_synthetic( |
| 447 | true, |
| 448 | passed_holdouts, |
| 449 | total_holdouts.saturating_sub(passed_holdouts), |
| 450 | 8, |
| 451 | 0, |
| 452 | true, |
| 453 | ) |
| 454 | }; |
| 455 | |
| 456 | let security = SecurityLayer::evaluate_candidate(&modified_files, &patch_diff, 0); |
| 457 | |
| 458 | let style = StyleLayer::evaluate_text(if style_text.is_empty() { |
| 459 | "Native compiled Rust execution running on DGX Spark GB10." |
| 460 | } else { |
| 461 | &style_text |
| 462 | }); |
| 463 | |
| 464 | // 5. Paired-workload benchmark execution for latency & resource metrics |
| 465 | let (parent_latencies, candidate_latencies, parent_rusage, candidate_rusage) = |
| 466 | run_paired_benchmarks_bins(&parent_bin, &candidate_bin, 20)?; |
| 467 | |
| 468 | let performance = PerformanceLayer::evaluate_latencies_with_policy( |
| 469 | &parent_latencies, |
| 470 | &candidate_latencies, |
| 471 | true, |
| 472 | self.require_latency_improvement, |
| 473 | self.non_inferiority_margin_pct, |
| 474 | 5000, |
| 475 | Some(42), |
| 476 | )?; |
| 477 | |
| 478 | let candidate_statm = StatmMetrics::read_self().ok(); |
| 479 | let resource_efficiency = ResourceEfficiencyLayer::evaluate( |
| 480 | &parent_rusage, |
| 481 | &candidate_rusage, |
| 482 | candidate_statm.as_ref(), |
| 483 | Some(49_152), |
| 484 | ); |
| 485 | |
| 486 | let mut replay_cases = LongitudinalReplayLayer::builtin_regression_corpus(); |
| 487 | if !holdout_violations.is_empty() { |
| 488 | for v in holdout_violations { |
| 489 | replay_cases.push(DefectTestResult { |
| 490 | defect_id: "HOLD-FAIL".to_string(), |
| 491 | title: "Blind holdout test suite assertion failure".to_string(), |
| 492 | passed: false, |
| 493 | details: Some(v), |
| 494 | }); |
| 495 | } |
| 496 | } |
| 497 | let longitudinal_replay = LongitudinalReplayLayer::evaluate_results(&replay_cases); |
| 498 | |
| 499 | let mut receipt = ObjectiveEvaluator::evaluate_candidate( |
| 500 | cycle_id, |
| 501 | candidate_id, |
| 502 | parent_id, |
| 503 | correctness, |
| 504 | security, |
| 505 | style, |
| 506 | performance, |
| 507 | resource_efficiency, |
| 508 | longitudinal_replay, |
| 509 | ); |
| 510 | |
| 511 | // 6. Sign receipt with authorized cryptographic key |
| 512 | match (&self.v2, subject_sha256_before) { |
| 513 | (Some(req), Some(subject_sha256)) => { |
| 514 | // The subject must still be the bytes that were checked before the run. |
| 515 | let after = sha256_file(&candidate_path.join(&req.subject_path))?; |
| 516 | if after != subject_sha256 { |
| 517 | return Err("subject file changed during evaluation; refusing to sign".into()); |
| 518 | } |
| 519 | let total = total_holdouts as u64; |
| 520 | let passed = passed_holdouts as u64; |
| 521 | if total == 0 |
| 522 | || (passed as f64) < req.policy.min_holdout_pass_ratio * (total as f64) |
| 523 | { |
| 524 | receipt.admitted = false; |
| 525 | } |
| 526 | let exe = std::env::current_exe() |
| 527 | .map_err(|e| format!("cannot locate the judge binary: {}", e))?; |
| 528 | let binding = ReceiptBindingV2 { |
| 529 | subject_path: req.subject_path.clone(), |
| 530 | subject_sha256, |
| 531 | holdout_set_sha256: holdout_set_sha256.clone(), |
| 532 | holdouts_total: total, |
| 533 | holdouts_passed: passed, |
| 534 | policy_sha256: req.policy_sha256.clone(), |
| 535 | evaluator_binary_sha256: sha256_file(&exe)?, |
| 536 | }; |
| 537 | receipt.bind_and_sign_v2(binding, signing_key)?; |
| 538 | } |
| 539 | _ => receipt.sign(signing_key), |
| 540 | } |
| 541 | |
| 542 | let out_path = self.output_dir.join(format!("{}.json", cycle_id)); |
| 543 | receipt.save_to_file(&out_path)?; |
| 544 | |
| 545 | Ok(receipt) |
| 546 | } |
| 547 | |
| 548 | /// Checks everything a version 2 receipt will claim before any candidate code runs, and |
| 549 | /// returns the SHA-256 of the subject bytes. |
| 550 | fn v2_preflight( |
| 551 | &self, |
| 552 | req: &V2Request, |
| 553 | holdout_set_sha256: &str, |
| 554 | parent_path: &Path, |
| 555 | candidate_path: &Path, |
| 556 | ) -> Result<String, String> { |
| 557 | if holdout_set_sha256 != req.policy.holdout_set_sha256 { |
| 558 | return Err(format!( |
| 559 | "holdout set digest {} does not match the policy's pinned {}; refusing to evaluate", |
| 560 | holdout_set_sha256, req.policy.holdout_set_sha256 |
| 561 | )); |
| 562 | } |
| 563 | let subject = req.subject_path.as_str(); |
| 564 | if !is_clean_relative(subject) { |
| 565 | return Err(format!( |
| 566 | "subject path {:?} is not a clean relative path", |
| 567 | subject |
| 568 | )); |
| 569 | } |
| 570 | if !req.policy.allowed_targets.iter().any(|t| t == subject) { |
| 571 | return Err(format!( |
| 572 | "subject {} is not an allowed target in the policy", |
| 573 | subject |
| 574 | )); |
| 575 | } |
| 576 | if let Some(p) = req |
| 577 | .policy |
| 578 | .protected_paths |
| 579 | .iter() |
| 580 | .find(|p| path_is_under(subject, p)) |
| 581 | { |
| 582 | return Err(format!("subject {} is under protected path {}", subject, p)); |
| 583 | } |
| 584 | // The program that runs must come from the compared trees: built here, or a named file |
| 585 | // outside the directories the comparison skips. Never searched for. |
| 586 | match (&self.executable, self.build_release) { |
| 587 | (None, _) => return Err( |
| 588 | "a version 2 evaluation names its executable; refusing to search the trees for one" |
| 589 | .into(), |
| 590 | ), |
| 591 | (Some(exe), false) => { |
| 592 | let e = exe.to_str().unwrap_or(""); |
| 593 | if !is_clean_relative(e) |
| 594 | || path_is_under(e, "target") |
| 595 | || e.split('/').any(|c| c == ".git") |
| 596 | { |
| 597 | return Err(format!( |
| 598 | "without a judge build the executable {:?} must be a clean relative path the tree comparison covers (not under target or .git)", |
| 599 | exe |
| 600 | )); |
| 601 | } |
| 602 | } |
| 603 | (Some(_), true) => {} |
| 604 | } |
| 605 | let changed = strict_changed_paths(parent_path, candidate_path)?; |
| 606 | if changed != [subject.to_string()] { |
| 607 | return Err(format!( |
| 608 | "candidate must differ from parent in exactly the subject {}; differs in {:?}", |
| 609 | subject, changed |
| 610 | )); |
| 611 | } |
| 612 | sha256_file(&candidate_path.join(subject)) |
| 613 | } |
| 614 | |
| 615 | /// Finds (or, with `build_release`, builds) the parent and candidate executables. |
| 616 | fn resolve_binaries( |
| 617 | &self, |
| 618 | cycle_id: &str, |
| 619 | parent_path: &Path, |
| 620 | candidate_path: &Path, |
| 621 | ) -> Result<(PathBuf, PathBuf), String> { |
| 622 | let Some(exe) = &self.executable else { |
| 623 | let parent = find_executable(parent_path).ok_or_else(|| { |
| 624 | format!( |
| 625 | "Parent executable binary not found in {:?}. Paired benchmarks require compiled binaries.", |
| 626 | parent_path |
| 627 | ) |
| 628 | })?; |
| 629 | let candidate = find_executable(candidate_path).ok_or_else(|| { |
| 630 | format!( |
| 631 | "Candidate executable not found at {:?}. Candidates must be compiled before evaluation.", |
| 632 | candidate_path |
| 633 | ) |
| 634 | })?; |
| 635 | return Ok((parent, candidate)); |
| 636 | }; |
| 637 | if !self.build_release { |
| 638 | let pick = |base: &Path| -> Result<PathBuf, String> { |
| 639 | let p = base.join(exe); |
| 640 | if p.is_file() { |
| 641 | Ok(p) |
| 642 | } else { |
| 643 | Err(format!("executable {:?} not found", p)) |
| 644 | } |
| 645 | }; |
| 646 | return Ok((pick(parent_path)?, pick(candidate_path)?)); |
| 647 | } |
| 648 | // Absolute: cargo runs inside each tree, so a relative target dir would land in the tree. |
| 649 | let build_root = std::path::absolute(&self.output_dir) |
| 650 | .map_err(|e| format!("cannot resolve output dir {:?}: {}", self.output_dir, e))? |
| 651 | .join(format!("build-{}", cycle_id)); |
| 652 | if build_root.exists() { |
| 653 | fs::remove_dir_all(&build_root) |
| 654 | .map_err(|e| format!("cannot clear build dir {:?}: {}", build_root, e))?; |
| 655 | } |
| 656 | let build = |tree: &Path, side: &str| -> Result<PathBuf, String> { |
| 657 | let target = build_root.join(side); |
| 658 | fs::create_dir_all(&target) |
| 659 | .map_err(|e| format!("cannot create build dir {:?}: {}", target, e))?; |
| 660 | let out = sandboxed_cargo_build(tree, &target) |
| 661 | .output() |
| 662 | .map_err(|e| format!("cannot start the sandboxed build for {}: {}", side, e))?; |
| 663 | if !out.status.success() { |
| 664 | return Err(format!( |
| 665 | "{} build failed: {}", |
| 666 | side, |
| 667 | String::from_utf8_lossy(&out.stderr) |
| 668 | )); |
| 669 | } |
| 670 | let bin = target.join("release").join(exe); |
| 671 | if bin.is_file() { |
| 672 | Ok(bin) |
| 673 | } else { |
| 674 | Err(format!("{} build produced no {:?}", side, bin)) |
| 675 | } |
| 676 | }; |
| 677 | Ok(( |
| 678 | build(parent_path, "parent")?, |
| 679 | build(candidate_path, "candidate")?, |
| 680 | )) |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | /// `cargo build --release --offline --locked` for `tree` in the judge's sandbox |
| 685 | /// (`isolation::sandboxed_cargo`). |
| 686 | fn sandboxed_cargo_build(tree: &Path, target: &Path) -> Command { |
| 687 | spark_rsi::isolation::sandboxed_cargo( |
| 688 | tree, |
| 689 | target, |
| 690 | &["build", "--release", "--offline", "--locked"], |
| 691 | ) |
| 692 | } |
| 693 | |
| 694 | pub fn sha256_file(path: &Path) -> Result<String, String> { |
| 695 | let bytes = fs::read(path).map_err(|e| format!("cannot read {:?}: {}", path, e))?; |
| 696 | Ok(hex::encode(Sha256::digest(&bytes))) |
| 697 | } |
| 698 | |
| 699 | /// Every path that differs between the two trees (added, removed or changed bytes), sorted. |
| 700 | /// Unlike `compute_candidate_diff` this includes dotfiles; it skips only `.git` and a top-level |
| 701 | /// `target`. Symlinks and other special files are refused. |
| 702 | pub fn strict_changed_paths(parent: &Path, candidate: &Path) -> Result<Vec<String>, String> { |
| 703 | fn walk(base: &Path, dir: &Path, acc: &mut BTreeSet<String>) -> Result<(), String> { |
| 704 | for entry in fs::read_dir(dir).map_err(|e| format!("cannot read {:?}: {}", dir, e))? { |
| 705 | let entry = entry.map_err(|e| e.to_string())?; |
| 706 | let path = entry.path(); |
| 707 | let rel = path |
| 708 | .strip_prefix(base) |
| 709 | .map_err(|e| e.to_string())? |
| 710 | .to_str() |
| 711 | .ok_or_else(|| format!("non-UTF-8 path {:?}", path))? |
| 712 | .to_string(); |
| 713 | let name = entry.file_name(); |
| 714 | if dir == base && (name == ".git" || name == "target") { |
| 715 | continue; |
| 716 | } |
| 717 | // Only the root .git and target are skipped; a nested one would hide a change. |
| 718 | if name == ".git" { |
| 719 | return Err(format!("refusing nested .git entry {:?} in tree", rel)); |
| 720 | } |
| 721 | let kind = entry.file_type().map_err(|e| e.to_string())?; |
| 722 | if kind.is_dir() { |
| 723 | walk(base, &path, acc)?; |
| 724 | } else if kind.is_file() { |
| 725 | acc.insert(rel); |
| 726 | } else { |
| 727 | return Err(format!( |
| 728 | "refusing special file or symlink {:?} in tree", |
| 729 | rel |
| 730 | )); |
| 731 | } |
| 732 | } |
| 733 | Ok(()) |
| 734 | } |
| 735 | let (mut p, mut c) = (BTreeSet::new(), BTreeSet::new()); |
| 736 | walk(parent, parent, &mut p)?; |
| 737 | walk(candidate, candidate, &mut c)?; |
| 738 | let mut changed = Vec::new(); |
| 739 | for rel in p.union(&c) { |
| 740 | let same = p.contains(rel) |
| 741 | && c.contains(rel) |
| 742 | && fs::read(parent.join(rel)).map_err(|e| e.to_string())? |
| 743 | == fs::read(candidate.join(rel)).map_err(|e| e.to_string())?; |
| 744 | if !same { |
| 745 | changed.push(rel.clone()); |
| 746 | } |
| 747 | } |
| 748 | Ok(changed) |
| 749 | } |
| 750 | |
| 751 | pub fn find_executable(base: &Path) -> Option<PathBuf> { |
| 752 | if base.is_file() { |
| 753 | return Some(base.to_path_buf()); |
| 754 | } |
| 755 | let cand1 = base.join("spark-rsi"); |
| 756 | if cand1.is_file() { |
| 757 | return Some(cand1); |
| 758 | } |
| 759 | let cand2 = base.join("target/release/spark-rsi"); |
| 760 | if cand2.is_file() { |
| 761 | return Some(cand2); |
| 762 | } |
| 763 | let cand3 = base.join("target/debug/spark-rsi"); |
| 764 | if cand3.is_file() { |
| 765 | return Some(cand3); |
| 766 | } |
| 767 | |
| 768 | None |
| 769 | } |
| 770 | |
| 771 | pub fn compute_candidate_diff( |
| 772 | parent_path: &Path, |
| 773 | candidate_path: &Path, |
| 774 | ) -> Result<(Vec<String>, String, String), String> { |
| 775 | let mut modified_files = Vec::new(); |
| 776 | let mut patch_diff = String::new(); |
| 777 | let mut style_text = String::new(); |
| 778 | |
| 779 | if parent_path == candidate_path { |
| 780 | if candidate_path.join(".git").exists() || Path::new(".git").exists() { |
| 781 | let diff_out = Command::new("git") |
| 782 | // The tree is candidate-controlled: no fsmonitor or hook program from its .git/config. |
| 783 | .args(["-c", "core.fsmonitor=", "-c", "core.hooksPath=/dev/null"]) |
| 784 | .arg("-C") |
| 785 | .arg(candidate_path) |
| 786 | .args(["diff", "HEAD"]) |
| 787 | .output(); |
| 788 | if let Ok(out) = diff_out { |
| 789 | patch_diff = String::from_utf8_lossy(&out.stdout).to_string(); |
| 790 | } |
| 791 | let files_out = Command::new("git") |
| 792 | // The tree is candidate-controlled: no fsmonitor or hook program from its .git/config. |
| 793 | .args(["-c", "core.fsmonitor=", "-c", "core.hooksPath=/dev/null"]) |
| 794 | .arg("-C") |
| 795 | .arg(candidate_path) |
| 796 | .args(["diff", "--name-only", "HEAD"]) |
| 797 | .output(); |
| 798 | if let Ok(out) = files_out { |
| 799 | let stdout = String::from_utf8_lossy(&out.stdout); |
| 800 | for line in stdout.lines() { |
| 801 | let trimmed = line.trim(); |
| 802 | if !trimmed.is_empty() { |
| 803 | modified_files.push(trimmed.to_string()); |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | } |
| 808 | style_text = patch_diff.clone(); |
| 809 | return Ok((modified_files, patch_diff, style_text)); |
| 810 | } |
| 811 | |
| 812 | let mut cand_files = Vec::new(); |
| 813 | collect_files_recursive(candidate_path, candidate_path, &mut cand_files)?; |
| 814 | |
| 815 | for (rel_path, abs_cand) in &cand_files { |
| 816 | let abs_parent = parent_path.join(rel_path); |
| 817 | if !abs_parent.exists() { |
| 818 | modified_files.push(rel_path.clone()); |
| 819 | let cand_content = fs::read_to_string(abs_cand).unwrap_or_default(); |
| 820 | patch_diff.push_str(&format!( |
| 821 | "+++ {} |
| 822 | ", |
| 823 | rel_path |
| 824 | )); |
| 825 | for line in cand_content.lines() { |
| 826 | patch_diff.push_str(&format!( |
| 827 | "+ {} |
| 828 | ", |
| 829 | line |
| 830 | )); |
| 831 | } |
| 832 | style_text.push_str(&cand_content); |
| 833 | style_text.push('\n'); |
| 834 | } else { |
| 835 | let cand_bytes = fs::read(abs_cand).unwrap_or_default(); |
| 836 | let parent_bytes = fs::read(&abs_parent).unwrap_or_default(); |
| 837 | if cand_bytes != parent_bytes { |
| 838 | modified_files.push(rel_path.clone()); |
| 839 | let cand_content = String::from_utf8_lossy(&cand_bytes); |
| 840 | let parent_content = String::from_utf8_lossy(&parent_bytes); |
| 841 | patch_diff.push_str(&format!( |
| 842 | "--- a/{} |
| 843 | +++ b/{} |
| 844 | ", |
| 845 | rel_path, rel_path |
| 846 | )); |
| 847 | for line in cand_content.lines() { |
| 848 | if !parent_content.contains(line) { |
| 849 | patch_diff.push_str(&format!( |
| 850 | "+ {} |
| 851 | ", |
| 852 | line |
| 853 | )); |
| 854 | } |
| 855 | } |
| 856 | style_text.push_str(&cand_content); |
| 857 | style_text.push('\n'); |
| 858 | } |
| 859 | } |
| 860 | } |
| 861 | |
| 862 | let mut parent_files = Vec::new(); |
| 863 | collect_files_recursive(parent_path, parent_path, &mut parent_files)?; |
| 864 | for (rel_path, _) in parent_files { |
| 865 | if !candidate_path.join(&rel_path).exists() { |
| 866 | modified_files.push(rel_path.clone()); |
| 867 | patch_diff.push_str(&format!( |
| 868 | "--- a/{} |
| 869 | ", |
| 870 | rel_path |
| 871 | )); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | Ok((modified_files, patch_diff, style_text)) |
| 876 | } |
| 877 | |
| 878 | fn collect_files_recursive( |
| 879 | base: &Path, |
| 880 | current: &Path, |
| 881 | acc: &mut Vec<(String, PathBuf)>, |
| 882 | ) -> Result<(), String> { |
| 883 | if !current.exists() { |
| 884 | return Ok(()); |
| 885 | } |
| 886 | let mut entries = Vec::new(); |
| 887 | for entry in fs::read_dir(current).map_err(|e| e.to_string())?.flatten() { |
| 888 | entries.push(entry.path()); |
| 889 | } |
| 890 | entries.sort(); |
| 891 | |
| 892 | for path in entries { |
| 893 | let name = path |
| 894 | .file_name() |
| 895 | .and_then(|n| n.to_str()) |
| 896 | .unwrap_or_default(); |
| 897 | if name == "target" || name == ".git" || name == "node_modules" || name.starts_with(".") { |
| 898 | continue; |
| 899 | } |
| 900 | if path.is_dir() { |
| 901 | collect_files_recursive(base, &path, acc)?; |
| 902 | } else if path.is_file() { |
| 903 | let rel = path |
| 904 | .strip_prefix(base) |
| 905 | .map_err(|e| e.to_string())? |
| 906 | .to_string_lossy() |
| 907 | .to_string(); |
| 908 | acc.push((rel, path)); |
| 909 | } |
| 910 | } |
| 911 | Ok(()) |
| 912 | } |
| 913 | |
| 914 | pub fn run_paired_benchmarks( |
| 915 | parent_path: &Path, |
| 916 | candidate_path: &Path, |
| 917 | iterations: usize, |
| 918 | ) -> Result<(Vec<f64>, Vec<f64>, RusageMetrics, RusageMetrics), String> { |
| 919 | let parent_bin = find_executable(parent_path).ok_or_else(|| { |
| 920 | format!( |
| 921 | "Parent executable binary not found in {:?}. Paired benchmarks require compiled binaries.", |
| 922 | parent_path |
| 923 | ) |
| 924 | })?; |
| 925 | let candidate_bin = find_executable(candidate_path).ok_or_else(|| { |
| 926 | format!( |
| 927 | "Candidate executable binary not found in {:?}. Paired benchmarks require compiled binaries.", |
| 928 | candidate_path |
| 929 | ) |
| 930 | })?; |
| 931 | run_paired_benchmarks_bins(&parent_bin, &candidate_bin, iterations) |
| 932 | } |
| 933 | |
| 934 | pub fn run_paired_benchmarks_bins( |
| 935 | parent_bin: &Path, |
| 936 | candidate_bin: &Path, |
| 937 | iterations: usize, |
| 938 | ) -> Result<(Vec<f64>, Vec<f64>, RusageMetrics, RusageMetrics), String> { |
| 939 | let parent_runner = CandidateJailRunner::new(parent_bin); |
| 940 | let candidate_runner = CandidateJailRunner::new(candidate_bin); |
| 941 | |
| 942 | // Execute warm-up runs outside the measurement window to prime page caches and namespaces |
| 943 | for w in 0..2 { |
| 944 | let warm_arg = format!("warmup-case-{}", w); |
| 945 | let _ = parent_runner.execute(&["holdout", &warm_arg]); |
| 946 | let _ = candidate_runner.execute(&["holdout", &warm_arg]); |
| 947 | } |
| 948 | |
| 949 | let mut parent_latencies = Vec::with_capacity(iterations); |
| 950 | let mut candidate_latencies = Vec::with_capacity(iterations); |
| 951 | let mut parent_rusage = RusageMetrics::default(); |
| 952 | let mut candidate_rusage = RusageMetrics::default(); |
| 953 | |
| 954 | for i in 0..iterations { |
| 955 | let input_arg = format!("benchmark-case-{}", i); |
| 956 | |
| 957 | // Interleave execution with A/B/B/A alternating order to eliminate order and thermal bias |
| 958 | if i % 2 == 0 { |
| 959 | // Parent then Candidate |
| 960 | let p_before = RusageMetrics::capture_children() |
| 961 | .map_err(|e| format!("Failed to capture parent baseline: {}", e))?; |
| 962 | let timer = LatencyTimer::start(); |
| 963 | let (p_ok, _, p_err) = |
| 964 | parent_runner |
| 965 | .execute(&["holdout", &input_arg]) |
| 966 | .map_err(|e| { |
| 967 | format!("Jail execution failed for parent on iteration {}: {}", i, e) |
| 968 | })?; |
| 969 | if !p_ok { |
| 970 | return Err(format!( |
| 971 | "Parent execution exited with error on iteration {}: {}", |
| 972 | i, p_err |
| 973 | )); |
| 974 | } |
| 975 | parent_latencies.push(timer.elapsed_us()); |
| 976 | let p_after = RusageMetrics::capture_children() |
| 977 | .map_err(|e| format!("Failed to capture parent child rusage: {}", e))?; |
| 978 | parent_rusage.accumulate(&p_after.diff(&p_before)); |
| 979 | |
| 980 | let c_before = RusageMetrics::capture_children() |
| 981 | .map_err(|e| format!("Failed to capture candidate baseline: {}", e))?; |
| 982 | let timer = LatencyTimer::start(); |
| 983 | let (c_ok, _, c_err) = |
| 984 | candidate_runner |
| 985 | .execute(&["holdout", &input_arg]) |
| 986 | .map_err(|e| { |
| 987 | format!( |
| 988 | "Jail execution failed for candidate on iteration {}: {}", |
| 989 | i, e |
| 990 | ) |
| 991 | })?; |
| 992 | if !c_ok { |
| 993 | return Err(format!( |
| 994 | "Candidate execution exited with error on iteration {}: {}", |
| 995 | i, c_err |
| 996 | )); |
| 997 | } |
| 998 | candidate_latencies.push(timer.elapsed_us()); |
| 999 | let c_after = RusageMetrics::capture_children() |
| 1000 | .map_err(|e| format!("Failed to capture candidate child rusage: {}", e))?; |
| 1001 | candidate_rusage.accumulate(&c_after.diff(&c_before)); |
| 1002 | } else { |
| 1003 | // Candidate then Parent |
| 1004 | let c_before = RusageMetrics::capture_children() |
| 1005 | .map_err(|e| format!("Failed to capture candidate baseline: {}", e))?; |
| 1006 | let timer = LatencyTimer::start(); |
| 1007 | let (c_ok, _, c_err) = |
| 1008 | candidate_runner |
| 1009 | .execute(&["holdout", &input_arg]) |
| 1010 | .map_err(|e| { |
| 1011 | format!( |
| 1012 | "Jail execution failed for candidate on iteration {}: {}", |
| 1013 | i, e |
| 1014 | ) |
| 1015 | })?; |
| 1016 | if !c_ok { |
| 1017 | return Err(format!( |
| 1018 | "Candidate execution exited with error on iteration {}: {}", |
| 1019 | i, c_err |
| 1020 | )); |
| 1021 | } |
| 1022 | candidate_latencies.push(timer.elapsed_us()); |
| 1023 | let c_after = RusageMetrics::capture_children() |
| 1024 | .map_err(|e| format!("Failed to capture candidate child rusage: {}", e))?; |
| 1025 | candidate_rusage.accumulate(&c_after.diff(&c_before)); |
| 1026 | |
| 1027 | let p_before = RusageMetrics::capture_children() |
| 1028 | .map_err(|e| format!("Failed to capture parent baseline: {}", e))?; |
| 1029 | let timer = LatencyTimer::start(); |
| 1030 | let (p_ok, _, p_err) = |
| 1031 | parent_runner |
| 1032 | .execute(&["holdout", &input_arg]) |
| 1033 | .map_err(|e| { |
| 1034 | format!("Jail execution failed for parent on iteration {}: {}", i, e) |
| 1035 | })?; |
| 1036 | if !p_ok { |
| 1037 | return Err(format!( |
| 1038 | "Parent execution exited with error on iteration {}: {}", |
| 1039 | i, p_err |
| 1040 | )); |
| 1041 | } |
| 1042 | parent_latencies.push(timer.elapsed_us()); |
| 1043 | let p_after = RusageMetrics::capture_children() |
| 1044 | .map_err(|e| format!("Failed to capture parent child rusage: {}", e))?; |
| 1045 | parent_rusage.accumulate(&p_after.diff(&p_before)); |
| 1046 | } |
| 1047 | } |
| 1048 | |
| 1049 | Ok(( |
| 1050 | parent_latencies, |
| 1051 | candidate_latencies, |
| 1052 | parent_rusage, |
| 1053 | candidate_rusage, |
| 1054 | )) |
| 1055 | } |
| 1056 | |
| 1057 | pub fn run_judge_cli(cli: JudgeCli) -> Result<EvaluationReceipt, Box<dyn std::error::Error>> { |
| 1058 | if cli.print_holdout_digest { |
| 1059 | let (_, digest) = HoldoutSuite::load_strict(Path::new(&cli.holdouts_dir))?; |
| 1060 | println!("{}", digest); |
| 1061 | std::process::exit(0); |
| 1062 | } |
| 1063 | let mut judge = BlindJudge::new( |
| 1064 | PathBuf::from(&cli.holdouts_dir), |
| 1065 | PathBuf::from(&cli.output_dir), |
| 1066 | ) |
| 1067 | .with_require_latency_improvement(cli.require_latency_improvement) |
| 1068 | .with_non_inferiority_margin(cli.non_inferiority_margin_pct); |
| 1069 | |
| 1070 | let key_opt = if let Some(ref hex_str) = cli.signing_key_hex { |
| 1071 | let bytes = hex::decode(hex_str.trim())?; |
| 1072 | Some(SigningKey::from_slice(&bytes)?) |
| 1073 | } else if let Some(ref file_path) = cli.signing_key_file { |
| 1074 | let content = fs::read_to_string(file_path)?; |
| 1075 | let bytes = hex::decode(content.trim())?; |
| 1076 | Some(SigningKey::from_slice(&bytes)?) |
| 1077 | } else if let Ok(hex_str) = std::env::var("RSI_JUDGE_SIGNING_KEY") { |
| 1078 | let bytes = hex::decode(hex_str.trim())?; |
| 1079 | Some(SigningKey::from_slice(&bytes)?) |
| 1080 | } else { |
| 1081 | None |
| 1082 | }; |
| 1083 | |
| 1084 | if cli.public_key { |
| 1085 | let key = key_opt.ok_or("--public-key needs a signing key")?; |
| 1086 | println!( |
| 1087 | "{}", |
| 1088 | hex::encode(key.verifying_key().to_sec1_point(false).as_bytes()) |
| 1089 | ); |
| 1090 | std::process::exit(0); |
| 1091 | } |
| 1092 | |
| 1093 | if let Some(key) = key_opt { |
| 1094 | judge = judge.with_signing_key(key); |
| 1095 | } |
| 1096 | if let Some(exe) = &cli.executable { |
| 1097 | judge = judge.with_executable(PathBuf::from(exe), cli.build_release); |
| 1098 | } |
| 1099 | if let (Some(subject), Some(policy_file)) = (&cli.subject_path, &cli.policy_file) { |
| 1100 | let (policy, policy_sha256) = EvaluationPolicy::load(Path::new(policy_file))?; |
| 1101 | if let Some(m) = policy.non_inferiority_margin_pct { |
| 1102 | judge = judge.with_non_inferiority_margin(m); |
| 1103 | } |
| 1104 | judge = judge.with_v2(V2Request { |
| 1105 | subject_path: subject.clone(), |
| 1106 | policy, |
| 1107 | policy_sha256, |
| 1108 | }); |
| 1109 | } |
| 1110 | |
| 1111 | let receipt = judge.evaluate_cycle( |
| 1112 | &cli.cycle_id, |
| 1113 | &cli.candidate_id, |
| 1114 | &cli.parent_id, |
| 1115 | Path::new(&cli.candidate_path), |
| 1116 | Path::new(&cli.parent_path), |
| 1117 | )?; |
| 1118 | |
| 1119 | println!("{}", serde_json::to_string_pretty(&receipt)?); |
| 1120 | |
| 1121 | if !receipt.admitted { |
| 1122 | std::process::exit(1); |
| 1123 | } |
| 1124 | |
| 1125 | Ok(receipt) |
| 1126 | } |
| 1127 | |
| 1128 | #[allow(dead_code)] |
| 1129 | fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 1130 | let cli = JudgeCli::parse(); |
| 1131 | run_judge_cli(cli)?; |
| 1132 | Ok(()) |
| 1133 | } |
| 1134 | |
| 1135 | #[cfg(test)] |
| 1136 | mod tests { |
| 1137 | use super::*; |
| 1138 | use p256::ecdsa::VerifyingKey; |
| 1139 | |
| 1140 | fn find_test_executable() -> PathBuf { |
| 1141 | if let Ok(cargo_bin) = std::env::var("CARGO_BIN_EXE_spark-rsi") { |
| 1142 | let p = PathBuf::from(cargo_bin); |
| 1143 | if p.is_file() { |
| 1144 | return p; |
| 1145 | } |
| 1146 | } |
| 1147 | let cand1 = Path::new("target/release/spark-rsi"); |
| 1148 | if cand1.is_file() { |
| 1149 | return cand1.to_path_buf(); |
| 1150 | } |
| 1151 | let cand2 = Path::new("target/debug/spark-rsi"); |
| 1152 | if cand2.is_file() { |
| 1153 | return cand2.to_path_buf(); |
| 1154 | } |
| 1155 | let cand3 = Path::new(env!("CARGO_MANIFEST_DIR")).join("target/release/spark-rsi"); |
| 1156 | if cand3.is_file() { |
| 1157 | return cand3; |
| 1158 | } |
| 1159 | panic!("Test executable not found"); |
| 1160 | } |
| 1161 | |
| 1162 | #[test] |
| 1163 | fn test_holdout_suite_builtin_and_save_load() { |
| 1164 | let tmp = tempfile::tempdir().unwrap(); |
| 1165 | let suites = HoldoutSuite::builtin_suites(); |
| 1166 | assert_eq!(suites.len(), 2); |
| 1167 | |
| 1168 | suites[0].save_to_dir(tmp.path()).unwrap(); |
| 1169 | let loaded = HoldoutSuite::load_from_dir(tmp.path()).unwrap(); |
| 1170 | assert_eq!(loaded.len(), 1); |
| 1171 | assert_eq!(loaded[0].suite_id, "HOLD-INV-001"); |
| 1172 | } |
| 1173 | |
| 1174 | #[test] |
| 1175 | fn test_holdout_suite_load_missing_fails_closed() { |
| 1176 | let tmp = tempfile::tempdir().unwrap(); |
| 1177 | let non_existent = tmp.path().join("non_existent"); |
| 1178 | assert!(HoldoutSuite::load_from_dir(&non_existent).is_err()); |
| 1179 | |
| 1180 | let empty = tmp.path().join("empty"); |
| 1181 | fs::create_dir_all(&empty).unwrap(); |
| 1182 | assert!(HoldoutSuite::load_from_dir(&empty).is_err()); |
| 1183 | } |
| 1184 | |
| 1185 | #[test] |
| 1186 | fn test_blind_judge_fails_closed_without_signing_key() { |
| 1187 | let tmp = tempfile::tempdir().unwrap(); |
| 1188 | let holdouts = tmp.path().join("holdouts"); |
| 1189 | let outputs = tmp.path().join("eval_outputs"); |
| 1190 | let candidate = tmp.path().join("candidate"); |
| 1191 | fs::create_dir_all(&candidate).unwrap(); |
| 1192 | let parent = tmp.path().join("parent"); |
| 1193 | fs::create_dir_all(&parent).unwrap(); |
| 1194 | |
| 1195 | for s in HoldoutSuite::builtin_suites() { |
| 1196 | s.save_to_dir(&holdouts).unwrap(); |
| 1197 | } |
| 1198 | |
| 1199 | // Copy spark-rsi executable so find_executable finds it |
| 1200 | if let Some(exe) = find_executable(Path::new(".")) { |
| 1201 | let _ = fs::copy(&exe, candidate.join("spark-rsi")); |
| 1202 | let _ = fs::copy(&exe, parent.join("spark-rsi")); |
| 1203 | } |
| 1204 | |
| 1205 | let judge = BlindJudge::new(holdouts, outputs); |
| 1206 | let res = judge.evaluate_cycle("cycle-no-key", "cand-01", "parent-00", &candidate, &parent); |
| 1207 | |
| 1208 | assert!(res.is_err()); |
| 1209 | assert!(res.unwrap_err().contains("signing key")); |
| 1210 | } |
| 1211 | |
| 1212 | #[test] |
| 1213 | fn test_blind_judge_evaluate_cycle_admission_and_verification() { |
| 1214 | let tmp = tempfile::tempdir().unwrap(); |
| 1215 | let holdouts = tmp.path().join("holdouts"); |
| 1216 | let outputs = tmp.path().join("eval_outputs"); |
| 1217 | let candidate = tmp.path().join("candidate"); |
| 1218 | fs::create_dir_all(&candidate).unwrap(); |
| 1219 | let parent = tmp.path().join("parent"); |
| 1220 | fs::create_dir_all(&parent).unwrap(); |
| 1221 | |
| 1222 | for s in HoldoutSuite::builtin_suites() { |
| 1223 | s.save_to_dir(&holdouts).unwrap(); |
| 1224 | } |
| 1225 | |
| 1226 | let exe = find_test_executable(); |
| 1227 | fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); |
| 1228 | fs::copy(&exe, parent.join("spark-rsi")).unwrap(); |
| 1229 | |
| 1230 | let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); |
| 1231 | let verifying_key = VerifyingKey::from(&signing_key); |
| 1232 | |
| 1233 | let judge = BlindJudge::new(holdouts, outputs.clone()) |
| 1234 | .with_signing_key(signing_key) |
| 1235 | .with_non_inferiority_margin(1000.0); |
| 1236 | |
| 1237 | let receipt = judge |
| 1238 | .evaluate_cycle("cycle-test-01", "cand-01", "parent-00", &candidate, &parent) |
| 1239 | .unwrap(); |
| 1240 | |
| 1241 | assert!( |
| 1242 | receipt.admitted, |
| 1243 | "Failed layers: {:?}", |
| 1244 | receipt.layer_results |
| 1245 | ); |
| 1246 | assert!(receipt.passed_all_hard_invariants); |
| 1247 | assert!(receipt.passed_statistical_gates); |
| 1248 | assert!(receipt.verify_digest()); |
| 1249 | assert!(receipt.signature.is_some()); |
| 1250 | assert!(receipt.verify_signature(&verifying_key)); |
| 1251 | |
| 1252 | let output_file = outputs.join("cycle-test-01.json"); |
| 1253 | assert!(output_file.exists()); |
| 1254 | |
| 1255 | let loaded = EvaluationReceipt::load_from_file(&output_file).unwrap(); |
| 1256 | assert_eq!(loaded.cycle_id, "cycle-test-01"); |
| 1257 | assert!(loaded.verify_digest()); |
| 1258 | assert!(loaded.verify_signature(&verifying_key)); |
| 1259 | } |
| 1260 | |
| 1261 | #[test] |
| 1262 | fn test_blind_judge_rejects_candidate_with_failing_holdout() { |
| 1263 | let tmp = tempfile::tempdir().unwrap(); |
| 1264 | let holdouts = tmp.path().join("holdouts"); |
| 1265 | let outputs = tmp.path().join("eval_outputs"); |
| 1266 | let candidate = tmp.path().join("candidate"); |
| 1267 | fs::create_dir_all(&candidate).unwrap(); |
| 1268 | let parent = tmp.path().join("parent"); |
| 1269 | fs::create_dir_all(&parent).unwrap(); |
| 1270 | |
| 1271 | // Create a custom holdout case that fails |
| 1272 | let failing_suite = HoldoutSuite { |
| 1273 | suite_id: "HOLD-FAIL-01".to_string(), |
| 1274 | name: "Impossible Holdout".to_string(), |
| 1275 | cases: vec![HoldoutCase { |
| 1276 | id: "IMP-01".to_string(), |
| 1277 | name: "Unattainable response".to_string(), |
| 1278 | input: "impossible_query".to_string(), |
| 1279 | expected_output: "EXPECT_MAGIC_STRING".to_string(), |
| 1280 | category: "robustness".to_string(), |
| 1281 | }], |
| 1282 | }; |
| 1283 | failing_suite.save_to_dir(&holdouts).unwrap(); |
| 1284 | |
| 1285 | let exe = find_test_executable(); |
| 1286 | fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); |
| 1287 | fs::copy(&exe, parent.join("spark-rsi")).unwrap(); |
| 1288 | |
| 1289 | let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); |
| 1290 | let judge = BlindJudge::new(holdouts, outputs).with_signing_key(signing_key); |
| 1291 | let receipt = judge |
| 1292 | .evaluate_cycle("cycle-fail-01", "cand-01", "parent-00", &candidate, &parent) |
| 1293 | .unwrap(); |
| 1294 | |
| 1295 | assert!(!receipt.admitted); |
| 1296 | assert!(!receipt.passed_all_hard_invariants); |
| 1297 | } |
| 1298 | } |