diff --git a/src/actor/judge.rs b/src/actor/judge.rs index e564183..013f3d0 100644 --- a/src/actor/judge.rs +++ b/src/actor/judge.rs @@ -1,13 +1,13 @@ use clap::Parser; use p256::ecdsa::SigningKey; use serde::{Deserialize, Serialize}; -use sha2::Digest; use spark_rsi::evaluator::layers::{ CorrectnessLayer, DefectTestResult, LongitudinalReplayLayer, PerformanceLayer, ResourceEfficiencyLayer, SecurityLayer, StyleLayer, }; use spark_rsi::evaluator::metrics::{LatencyTimer, RusageMetrics, StatmMetrics}; use spark_rsi::evaluator::{EvaluationReceipt, ObjectiveEvaluator}; +use spark_rsi::isolation::CandidateJailRunner; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; @@ -38,6 +38,15 @@ pub struct JudgeCli { #[arg(long, default_value = ".rsi/eval_outputs")] pub output_dir: String, + + #[arg(long)] + pub signing_key_hex: Option, + + #[arg(long)] + pub signing_key_file: Option, + + #[arg(long)] + pub require_latency_improvement: bool, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -102,30 +111,37 @@ impl HoldoutSuite { ] } - pub fn load_from_dir(dir: &Path) -> Vec { + pub fn load_from_dir(dir: &Path) -> Result, String> { if !dir.exists() { - return Self::builtin_suites(); + return Err(format!( + "Holdouts directory does not exist: {:?}. Production evaluation fails closed.", + dir + )); } let mut suites = Vec::new(); - if let Ok(entries) = fs::read_dir(dir) { - for entry in entries.flatten() { - let path = entry.path(); - if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("json") { - if let Ok(content) = fs::read_to_string(&path) { - if let Ok(suite) = serde_json::from_str::(&content) { - suites.push(suite); - } + let entries = fs::read_dir(dir) + .map_err(|e| format!("Failed to read holdouts directory {:?}: {}", dir, e))?; + + for entry in entries.flatten() { + let path = entry.path(); + if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("json") { + if let Ok(content) = fs::read_to_string(&path) { + if let Ok(suite) = serde_json::from_str::(&content) { + suites.push(suite); } } } } if suites.is_empty() { - Self::builtin_suites() - } else { - suites + return Err(format!( + "No valid holdout suites found in {:?}. Production evaluation fails closed.", + dir + )); } + + Ok(suites) } pub fn save_to_dir(&self, dir: &Path) -> Result<(), String> { @@ -142,6 +158,7 @@ pub struct BlindJudge { pub holdouts_dir: PathBuf, pub output_dir: PathBuf, pub signing_key: Option, + pub require_latency_improvement: bool, } impl BlindJudge { @@ -150,6 +167,7 @@ impl BlindJudge { holdouts_dir, output_dir, signing_key: None, + require_latency_improvement: false, } } @@ -158,6 +176,11 @@ impl BlindJudge { self } + pub fn with_require_latency_improvement(mut self, req: bool) -> Self { + self.require_latency_improvement = req; + self + } + pub fn evaluate_cycle( &self, cycle_id: &str, @@ -166,27 +189,31 @@ impl BlindJudge { candidate_path: &Path, parent_path: &Path, ) -> Result { - let suites = HoldoutSuite::load_from_dir(&self.holdouts_dir); - let mut total_holdouts = 0; + // 1. Production evaluation fails closed if holdouts directory is missing or empty + let suites = HoldoutSuite::load_from_dir(&self.holdouts_dir)?; + + let mut total_holdouts: usize = 0; let mut passed_holdouts = 0; let mut holdout_violations = Vec::new(); - let candidate_bin = find_executable(candidate_path); + // 2. Candidate binary must exist; production evaluation fails closed if not built + let candidate_bin = find_executable(candidate_path).ok_or_else(|| { + format!( + "Candidate executable not found at {:?}. Candidates must be compiled before evaluation.", + candidate_path + ) + })?; + + // 3. Execute actual holdout cases strictly through Bubblewrap jail + let jail_runner = CandidateJailRunner::new(&candidate_bin); - // 1. Execute actual holdout cases against candidate for suite in &suites { for case in &suite.cases { total_holdouts += 1; - let actual_output = if let Some(ref bin) = candidate_bin { - let out = Command::new(bin) - .args(["holdout", &case.input]) - .output(); - match out { - Ok(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(), - Err(e) => format!("EXEC_ERR:{}", e), - } - } else { - spark_rsi::evaluate_holdout_case(&case.input) + let actual_output = match jail_runner.execute(&["holdout", &case.input]) { + Ok((true, stdout, _)) => stdout.trim().to_string(), + Ok((false, _, stderr)) => format!("EXEC_FAIL:{}", stderr.trim()), + Err(e) => format!("JAIL_ERR:{}", e), }; if actual_output == case.expected_output { @@ -200,7 +227,7 @@ impl BlindJudge { } } - // 2. Extract real diff and changed files between parent and candidate + // 4. Extract real diff and changed files between parent and candidate let (modified_files, patch_diff, style_text) = compute_candidate_diff(parent_path, candidate_path)?; @@ -210,7 +237,7 @@ impl BlindJudge { CorrectnessLayer::evaluate_synthetic( true, passed_holdouts, - total_holdouts - passed_holdouts, + total_holdouts.saturating_sub(passed_holdouts), 8, 0, true, @@ -231,14 +258,15 @@ impl BlindJudge { }, ); - // 3. Paired-workload benchmark execution for latency & resource metrics + // 5. Paired-workload benchmark execution for latency & resource metrics let (parent_latencies, candidate_latencies, parent_rusage, candidate_rusage) = run_paired_benchmarks(parent_path, candidate_path, 30)?; - let performance = PerformanceLayer::evaluate_latencies( + let performance = PerformanceLayer::evaluate_latencies_with_policy( &parent_latencies, &candidate_latencies, true, + self.require_latency_improvement, 5000, Some(42), )?; @@ -276,12 +304,11 @@ impl BlindJudge { longitudinal_replay, ); - // 4. Compute and sign receipt with real cryptographic ECDSA P-256 signature - let signing_key = self.signing_key.clone().unwrap_or_else(|| { - let seed = [77u8; 32]; - SigningKey::from_bytes(&seed.into()).expect("Valid ECDSA signing key") - }); - receipt.sign(&signing_key); + // 6. Sign receipt with authorized cryptographic key; fail closed if missing + let signing_key = self.signing_key.as_ref().ok_or_else(|| { + "No authorized cryptographic signing key provided to BlindJudge. Production evaluation fails closed.".to_string() + })?; + receipt.sign(signing_key); let out_path = self.output_dir.join(format!("{}.json", cycle_id)); receipt.save_to_file(&out_path)?; @@ -290,20 +317,20 @@ impl BlindJudge { } } -fn find_executable(base: &Path) -> Option { +pub fn find_executable(base: &Path) -> Option { if base.is_file() { return Some(base.to_path_buf()); } - let cand1 = base.join("target/release/spark-rsi"); - if cand1.exists() { + let cand1 = base.join("spark-rsi"); + if cand1.is_file() { return Some(cand1); } - let cand2 = base.join("spark-rsi"); - if cand2.exists() { + let cand2 = base.join("target/release/spark-rsi"); + if cand2.is_file() { return Some(cand2); } - let cand3 = base.join("bin/spark-rsi"); - if cand3.exists() { + let cand3 = base.join("target/debug/spark-rsi"); + if cand3.is_file() { return Some(cand3); } None @@ -318,7 +345,6 @@ pub fn compute_candidate_diff( let mut style_text = String::new(); if parent_path == candidate_path { - // Inspect git status / diff if candidate is a git working tree if candidate_path.join(".git").exists() || Path::new(".git").exists() { let diff_out = Command::new("git") .arg("-C") @@ -355,9 +381,11 @@ pub fn compute_candidate_diff( if !abs_parent.exists() { modified_files.push(rel_path.clone()); let cand_content = fs::read_to_string(abs_cand).unwrap_or_default(); - patch_diff.push_str(&format!("+++ {}\n", rel_path)); + patch_diff.push_str(&format!("+++ {} +", rel_path)); for line in cand_content.lines() { - patch_diff.push_str(&format!("+ {}\n", line)); + patch_diff.push_str(&format!("+ {} +", line)); } style_text.push_str(&cand_content); style_text.push('\n'); @@ -368,10 +396,13 @@ pub fn compute_candidate_diff( modified_files.push(rel_path.clone()); let cand_content = String::from_utf8_lossy(&cand_bytes); let parent_content = String::from_utf8_lossy(&parent_bytes); - patch_diff.push_str(&format!("--- a/{}\n+++ b/{}\n", rel_path, rel_path)); + patch_diff.push_str(&format!("--- a/{} ++++ b/{} +", rel_path, rel_path)); for line in cand_content.lines() { if !parent_content.contains(line) { - patch_diff.push_str(&format!("+ {}\n", line)); + patch_diff.push_str(&format!("+ {} +", line)); } } style_text.push_str(&cand_content); @@ -380,13 +411,13 @@ pub fn compute_candidate_diff( } } - // Check for deleted files let mut parent_files = Vec::new(); collect_files_recursive(parent_path, parent_path, &mut parent_files)?; for (rel_path, _) in parent_files { if !candidate_path.join(&rel_path).exists() { modified_files.push(rel_path.clone()); - patch_diff.push_str(&format!("--- a/{}\n", rel_path)); + patch_diff.push_str(&format!("--- a/{} +", rel_path)); } } @@ -431,74 +462,87 @@ pub fn run_paired_benchmarks( candidate_path: &Path, iterations: usize, ) -> Result<(Vec, Vec, RusageMetrics, RusageMetrics), String> { + let parent_bin = find_executable(parent_path).ok_or_else(|| { + format!( + "Parent executable binary not found in {:?}. Paired benchmarks require compiled binaries.", + parent_path + ) + })?; + let candidate_bin = find_executable(candidate_path).ok_or_else(|| { + format!( + "Candidate executable binary not found in {:?}. Paired benchmarks require compiled binaries.", + candidate_path + ) + })?; + + let parent_runner = CandidateJailRunner::new(&parent_bin); + let candidate_runner = CandidateJailRunner::new(&candidate_bin); + + // Capture child rusage baseline before parent workload + let parent_rusage_before = RusageMetrics::capture_children() + .map_err(|e| format!("Failed to capture parent child rusage baseline: {}", e))?; let mut parent_latencies = Vec::with_capacity(iterations); - let mut candidate_latencies = Vec::with_capacity(iterations); - - // Check for speedup marker for candidate - let speedup_factor = if let Ok(s) = fs::read_to_string(candidate_path.join(".rsi_speedup")) { - s.trim().parse::().unwrap_or(0.80) - } else { - 0.80 // Baseline candidate improvement assumption when not regressed - }; - - let parent_bin = find_executable(parent_path); - let candidate_bin = find_executable(candidate_path); - for i in 0..iterations { let input_arg = format!("benchmark-case-{}", i); - - // Run parent workload - let t_p = LatencyTimer::start(); - if let Some(ref bin) = parent_bin { - let _ = Command::new(bin).args(["holdout", &input_arg]).output(); - } else { - let mut hasher = sha2::Sha256::new(); - for _ in 0..300 { - hasher.update(input_arg.as_bytes()); - } - let _ = hasher.finalize(); + let timer = LatencyTimer::start(); + let (success, _stdout, stderr) = parent_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| format!("Jail execution failed for parent on iteration {}: {}", i, e))?; + if !success { + return Err(format!("Parent execution exited with error on iteration {}: {}", i, stderr)); } - let p_lat = (t_p.elapsed_us().max(10.0)) + (i as f64) * 0.5; - parent_latencies.push(p_lat); + parent_latencies.push(timer.elapsed_us()); + } + let parent_rusage_after = RusageMetrics::capture_children() + .map_err(|e| format!("Failed to capture parent child rusage final: {}", e))?; + let parent_rusage = parent_rusage_after.diff(&parent_rusage_before); - // Run candidate workload - let t_c = LatencyTimer::start(); - if let Some(ref bin) = candidate_bin { - let _ = Command::new(bin).args(["holdout", &input_arg]).output(); - } else { - let mut hasher = sha2::Sha256::new(); - for _ in 0..300 { - hasher.update(input_arg.as_bytes()); - } - let _ = hasher.finalize(); + // Capture child rusage baseline before candidate workload + let candidate_rusage_before = RusageMetrics::capture_children() + .map_err(|e| format!("Failed to capture candidate child rusage baseline: {}", e))?; + let mut candidate_latencies = Vec::with_capacity(iterations); + for i in 0..iterations { + let input_arg = format!("benchmark-case-{}", i); + let timer = LatencyTimer::start(); + let (success, _stdout, stderr) = candidate_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| format!("Jail execution failed for candidate on iteration {}: {}", i, e))?; + if !success { + return Err(format!("Candidate execution exited with error on iteration {}: {}", i, stderr)); } - let c_lat = ((t_c.elapsed_us().max(10.0)) * speedup_factor) + (i as f64) * 0.4; - candidate_latencies.push(c_lat); + candidate_latencies.push(timer.elapsed_us()); } - - let parent_rusage = RusageMetrics { - user_time_us: 10_000, - system_time_us: 5_000, - max_rss_kb: 50_000, - voluntary_context_switches: 100, - involuntary_context_switches: 20, - }; - let candidate_rusage = RusageMetrics { - user_time_us: (10_000.0 * speedup_factor) as u64, - system_time_us: (5_000.0 * speedup_factor) as u64, - max_rss_kb: 50_300, // 0.6% growth <= 2.0% - voluntary_context_switches: 80, - involuntary_context_switches: 15, - }; + let candidate_rusage_after = RusageMetrics::capture_children() + .map_err(|e| format!("Failed to capture candidate child rusage final: {}", e))?; + let candidate_rusage = candidate_rusage_after.diff(&candidate_rusage_before); Ok((parent_latencies, candidate_latencies, parent_rusage, candidate_rusage)) } pub fn run_judge_cli(cli: JudgeCli) -> Result> { - let judge = BlindJudge::new( + let mut judge = BlindJudge::new( PathBuf::from(&cli.holdouts_dir), PathBuf::from(&cli.output_dir), - ); + ) + .with_require_latency_improvement(cli.require_latency_improvement); + + let key_opt = if let Some(ref hex_str) = cli.signing_key_hex { + let bytes = hex::decode(hex_str.trim())?; + Some(SigningKey::from_slice(&bytes)?) + } else if let Some(ref file_path) = cli.signing_key_file { + let content = fs::read_to_string(file_path)?; + let bytes = hex::decode(content.trim())?; + Some(SigningKey::from_slice(&bytes)?) + } else if let Ok(hex_str) = std::env::var("RSI_JUDGE_SIGNING_KEY") { + let bytes = hex::decode(hex_str.trim())?; + Some(SigningKey::from_slice(&bytes)?) + } else { + None + }; + + if let Some(key) = key_opt { + judge = judge.with_signing_key(key); + } let receipt = judge.evaluate_cycle( &cli.cycle_id, @@ -529,6 +573,28 @@ mod tests { use super::*; use p256::ecdsa::VerifyingKey; + fn find_test_executable() -> PathBuf { + if let Ok(cargo_bin) = std::env::var("CARGO_BIN_EXE_spark-rsi") { + let p = PathBuf::from(cargo_bin); + if p.is_file() { + return p; + } + } + let cand1 = Path::new("target/release/spark-rsi"); + if cand1.is_file() { + return cand1.to_path_buf(); + } + let cand2 = Path::new("target/debug/spark-rsi"); + if cand2.is_file() { + return cand2.to_path_buf(); + } + let cand3 = Path::new("/home/drakestapleton/workspace/spark-rsi/target/release/spark-rsi"); + if cand3.is_file() { + return cand3.to_path_buf(); + } + panic!("Test executable not found"); + } + #[test] fn test_holdout_suite_builtin_and_save_load() { let tmp = tempfile::tempdir().unwrap(); @@ -536,11 +602,55 @@ mod tests { assert_eq!(suites.len(), 2); suites[0].save_to_dir(tmp.path()).unwrap(); - let loaded = HoldoutSuite::load_from_dir(tmp.path()); + let loaded = HoldoutSuite::load_from_dir(tmp.path()).unwrap(); assert_eq!(loaded.len(), 1); assert_eq!(loaded[0].suite_id, "HOLD-INV-001"); } + #[test] + fn test_holdout_suite_load_missing_fails_closed() { + let tmp = tempfile::tempdir().unwrap(); + let non_existent = tmp.path().join("non_existent"); + assert!(HoldoutSuite::load_from_dir(&non_existent).is_err()); + + let empty = tmp.path().join("empty"); + fs::create_dir_all(&empty).unwrap(); + assert!(HoldoutSuite::load_from_dir(&empty).is_err()); + } + + #[test] + fn test_blind_judge_fails_closed_without_signing_key() { + let tmp = tempfile::tempdir().unwrap(); + let holdouts = tmp.path().join("holdouts"); + let outputs = tmp.path().join("eval_outputs"); + let candidate = tmp.path().join("candidate"); + fs::create_dir_all(&candidate).unwrap(); + let parent = tmp.path().join("parent"); + fs::create_dir_all(&parent).unwrap(); + + for s in HoldoutSuite::builtin_suites() { + s.save_to_dir(&holdouts).unwrap(); + } + + // Copy spark-rsi executable so find_executable finds it + if let Some(exe) = find_executable(Path::new(".")) { + let _ = fs::copy(&exe, candidate.join("spark-rsi")); + let _ = fs::copy(&exe, parent.join("spark-rsi")); + } + + let judge = BlindJudge::new(holdouts, outputs); + let res = judge.evaluate_cycle( + "cycle-no-key", + "cand-01", + "parent-00", + &candidate, + &parent, + ); + + assert!(res.is_err()); + assert!(res.unwrap_err().contains("signing key")); + } + #[test] fn test_blind_judge_evaluate_cycle_admission_and_verification() { let tmp = tempfile::tempdir().unwrap(); @@ -551,6 +661,14 @@ mod tests { let parent = tmp.path().join("parent"); fs::create_dir_all(&parent).unwrap(); + for s in HoldoutSuite::builtin_suites() { + s.save_to_dir(&holdouts).unwrap(); + } + + let exe = find_test_executable(); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); let verifying_key = VerifyingKey::from(&signing_key); @@ -607,7 +725,12 @@ mod tests { }; failing_suite.save_to_dir(&holdouts).unwrap(); - let judge = BlindJudge::new(holdouts, outputs); + let exe = find_test_executable(); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + + let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); + let judge = BlindJudge::new(holdouts, outputs).with_signing_key(signing_key); let receipt = judge .evaluate_cycle( "cycle-fail-01", diff --git a/src/daemon.rs b/src/daemon.rs index 84dee66..00fe1bf 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -1,10 +1,15 @@ +use crate::actor::judge::BlindJudge; use crate::balance::BalanceKernel; +use crate::evaluator::EvaluationReceipt; use crate::models::{RsiConfig, RsiCycleResult}; use crate::observe::observe_codebase; use crate::propose::ProposalGenerator; use crate::ratify::Ratifier; +use crate::supervisor::{GenerationInfo, HostSupervisor}; use crate::verifier::InvariantVerifier; -use std::path::Path; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::process::Command; use std::time::Instant; use uuid::Uuid; @@ -16,14 +21,16 @@ impl RsiEngine { let cycle_id = format!("cycle-{}", Uuid::new_v4().simple()); let repo_path = Path::new(&config.target_repo); - // 1. Observe + // 1. Observe codebase metrics let telemetry = observe_codebase(repo_path)?; - // 2. Propose (check if an unslop sanitization or optimization proposal is needed) + // 2. Propose improvement let mut maybe_proposal = ProposalGenerator::scan_and_propose_unslop(repo_path); let mut maybe_invariants = None; let maybe_balance; + let mut maybe_receipt: Option = None; + let mut maybe_generation: Option = None; let mut maybe_ratification = None; let mut success = true; @@ -45,19 +52,90 @@ impl RsiEngine { let is_balanced = balance_verdict.verdict == "balanced"; maybe_balance = Some(balance_verdict); - // 5. Ratify: if invariants passed and balance is maintained - if passed && is_balanced { - let rat = Ratifier::ratify_proposal( - proposal, - &inv_report, - repo_path, - &config.cortex_url, - &config.cortex_space, - ) - .await?; - maybe_ratification = Some(rat); - } else { + if !passed || !is_balanced { success = false; + } else { + // 5. Objective Evaluation via BlindJudge if holdouts exist or are configured + let holdouts_path = config + .holdouts_dir + .as_ref() + .map(PathBuf::from) + .unwrap_or_else(|| repo_path.join(".rsi").join("holdouts")); + + let mut judge_admitted = true; + if holdouts_path.exists() { + // Ensure candidate executable exists in sandbox + if crate::actor::judge::find_executable(&sandbox_dir).is_none() { + let _ = Command::new("cargo") + .arg("build") + .current_dir(&sandbox_dir) + .output(); + } + + let output_dir = Path::new(&config.sandbox_root).join("eval_outputs"); + let mut judge = BlindJudge::new(holdouts_path, output_dir); + judge.require_latency_improvement = config.require_latency_improvement; + + if let Some(ref key_hex) = config.signing_key_hex { + let key_bytes = hex::decode(key_hex) + .map_err(|e| format!("Invalid signing_key_hex: {}", e))?; + let signing_key = p256::ecdsa::SigningKey::from_slice(&key_bytes) + .map_err(|e| format!("Invalid P-256 signing key: {}", e))?; + judge = judge.with_signing_key(signing_key); + } + + match judge.evaluate_cycle(&cycle_id, &proposal.id, "parent", &sandbox_dir, repo_path) { + Ok(receipt) => { + judge_admitted = receipt.admitted; + maybe_receipt = Some(receipt); + } + Err(e) => { + tracing::warn!("BlindJudge evaluation failed closed: {}", e); + judge_admitted = false; + } + } + } + + if !judge_admitted { + success = false; + } else { + // 6. Candidate Promotion via HostSupervisor rather than in-place mutation + let rsi_root = repo_path.join(&config.rsi_root); + let supervisor = HostSupervisor::new(&rsi_root, 49_152); + let manifest_digest = maybe_receipt + .as_ref() + .map(|r| r.receipt_digest.clone()) + .unwrap_or_else(|| { + let mut hasher = Sha256::new(); + hasher.update(proposal.proposed_patch.as_bytes()); + format!("{:x}", hasher.finalize()) + }); + + // Stage generation directory under supervisor + let mut gen_info = supervisor.stage_generation( + &proposal.id, + &sandbox_dir, + &manifest_digest, + )?; + + // Atomic symlink swap: switches active generation + supervisor.atomic_symlink_swap(&proposal.id)?; + + // Record canary transaction + supervisor.record_canary_transaction(&mut gen_info, true, 1)?; + maybe_generation = Some(gen_info); + + // 7. Ratify proposal and record to git & Cortex memory + let rat = Ratifier::ratify_proposal( + proposal, + &inv_report, + repo_path, + &config.cortex_url, + &config.cortex_space, + ) + .await?; + maybe_ratification = Some(rat); + } } } else { // Still run balance check on current state @@ -77,6 +155,8 @@ impl RsiEngine { proposal: maybe_proposal, invariants: maybe_invariants, balance: maybe_balance, + receipt: maybe_receipt, + generation: maybe_generation, ratification: maybe_ratification, success, elapsed_ms, @@ -94,11 +174,12 @@ impl RsiEngine { match Self::run_cycle(&config).await { Ok(res) => { tracing::info!( - "RSI cycle {} completed in {:.2}ms (success: {}, proposed: {})", + "RSI cycle {} completed in {:.2}ms (success: {}, proposed: {}, admitted: {})", res.cycle_id, res.elapsed_ms, res.success, - res.proposal.is_some() + res.proposal.is_some(), + res.receipt.as_ref().map(|r| r.admitted).unwrap_or(true) ); } Err(e) => { diff --git a/src/evaluator/layers/performance.rs b/src/evaluator/layers/performance.rs index 791b28d..d427950 100644 --- a/src/evaluator/layers/performance.rs +++ b/src/evaluator/layers/performance.rs @@ -52,6 +52,24 @@ impl PerformanceLayer { target_is_latency_reduction: bool, resamples: usize, seed: Option, + ) -> Result { + Self::evaluate_latencies_with_policy( + parent_latencies_us, + candidate_latencies_us, + target_is_latency_reduction, + true, + resamples, + seed, + ) + } + + pub fn evaluate_latencies_with_policy( + parent_latencies_us: &[f64], + candidate_latencies_us: &[f64], + target_is_latency_reduction: bool, + require_significant_improvement: bool, + resamples: usize, + seed: Option, ) -> Result { let mut violations = Vec::new(); @@ -108,7 +126,11 @@ impl PerformanceLayer { } let non_target_metrics_safe = p95_res.passes_non_inferiority && p99_res.passes_non_inferiority; - let passed = target_metric_improved && non_target_metrics_safe; + let passed = if require_significant_improvement { + target_metric_improved && non_target_metrics_safe + } else { + non_target_metrics_safe + }; Ok(PerformanceEvaluation { bootstrap_estimate: boot, diff --git a/src/isolation/container.rs b/src/isolation/container.rs index 636ac6a..126068d 100644 --- a/src/isolation/container.rs +++ b/src/isolation/container.rs @@ -139,7 +139,11 @@ impl BuildJail { pub fn build_bwrap_args(&self, command: &[&str]) -> Vec { let mut args = vec![ - "--unshare-all".to_string(), + "--unshare-user".to_string(), + "--unshare-ipc".to_string(), + "--unshare-pid".to_string(), + "--unshare-net".to_string(), + "--unshare-uts".to_string(), "--die-with-parent".to_string(), "--ro-bind".to_string(), "/usr".to_string(), @@ -262,6 +266,107 @@ impl GpuEvaluationJail { } } +#[derive(Debug, Clone)] +pub struct CandidateJailRunner { + pub candidate_bin: PathBuf, + pub working_dir: Option, + pub limits: SandboxLimits, +} + +impl CandidateJailRunner { + pub fn new(candidate_bin: &Path) -> Self { + Self { + candidate_bin: candidate_bin.to_path_buf(), + working_dir: None, + limits: SandboxLimits::new(49152, 800, 256, 30), + } + } + + pub fn with_working_dir(mut self, dir: &Path) -> Self { + self.working_dir = Some(dir.to_path_buf()); + self + } + + pub fn with_timeout_seconds(mut self, timeout_seconds: u64) -> Self { + self.limits.timeout_seconds = timeout_seconds; + self + } + + pub fn build_bwrap_args(&self, command_args: &[&str]) -> Vec { + let mut args = vec![ + "--unshare-user".to_string(), + "--unshare-ipc".to_string(), + "--unshare-pid".to_string(), + "--unshare-net".to_string(), + "--unshare-uts".to_string(), + "--die-with-parent".to_string(), + "--ro-bind".to_string(), + "/usr".to_string(), + "/usr".to_string(), + "--ro-bind".to_string(), + "/lib".to_string(), + "/lib".to_string(), + "--proc".to_string(), + "/proc".to_string(), + "--dev".to_string(), + "/dev".to_string(), + "--tmpfs".to_string(), + "/tmp".to_string(), + ]; + + if Path::new("/lib64").exists() { + args.push("--ro-bind".to_string()); + args.push("/lib64".to_string()); + args.push("/lib64".to_string()); + } + if Path::new("/bin").exists() { + args.push("--ro-bind".to_string()); + args.push("/bin".to_string()); + args.push("/bin".to_string()); + } + + let bin_dir = self + .candidate_bin + .parent() + .unwrap_or_else(|| Path::new("/")); + args.push("--ro-bind".to_string()); + args.push(bin_dir.display().to_string()); + args.push("/app".to_string()); + + let bin_name = self + .candidate_bin + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("candidate"); + let in_jail_bin = format!("/app/{}", bin_name); + + if let Some(ref work) = self.working_dir { + args.push("--bind".to_string()); + args.push(work.display().to_string()); + args.push("/workspace".to_string()); + args.push("--chdir".to_string()); + args.push("/workspace".to_string()); + } else { + args.push("--chdir".to_string()); + args.push("/tmp".to_string()); + } + + args.push(in_jail_bin); + for arg in command_args { + args.push(arg.to_string()); + } + + args + } + + pub fn execute(&self, command_args: &[&str]) -> Result<(bool, String, String), String> { + let args = self.build_bwrap_args(command_args); + let mut cmd = Command::new("bwrap"); + cmd.args(&args); + execute_with_timeout(cmd, self.limits.timeout_seconds) + } +} + #[cfg(test)] mod tests { use super::*; @@ -295,7 +400,7 @@ mod tests { ); let args = jail.build_bwrap_args(&["cargo", "build"]); - assert!(args.contains(&"--unshare-all".to_string())); + assert!(args.contains(&"--unshare-net".to_string())); assert!(args.contains(&"--die-with-parent".to_string())); assert!(args.contains(&"/output".to_string())); assert!(args.contains(&"cargo".to_string())); diff --git a/src/isolation/mod.rs b/src/isolation/mod.rs index f954e1f..a499251 100644 --- a/src/isolation/mod.rs +++ b/src/isolation/mod.rs @@ -3,7 +3,7 @@ pub mod manifest; pub mod rollback; pub mod root_of_trust; -pub use container::{BuildJail, GpuEvaluationJail, SandboxLimits}; +pub use container::{BuildJail, CandidateJailRunner, GpuEvaluationJail, SandboxLimits}; pub use manifest::{ArtifactManifest, ArtifactRecord, CandidateManifest}; pub use rollback::RollbackCheckpoint; pub use root_of_trust::RootOfTrust; diff --git a/src/lib.rs b/src/lib.rs index 3b54aca..f86c607 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,7 +26,7 @@ pub use evaluator::{ StatmMetrics, StyleEvaluation, StyleLayer, TailNonInferiorityResult, }; pub use isolation::{ - ArtifactManifest, ArtifactRecord, BuildJail, CandidateManifest, GpuEvaluationJail, + ArtifactManifest, ArtifactRecord, BuildJail, CandidateJailRunner, CandidateManifest, GpuEvaluationJail, RollbackCheckpoint, RootOfTrust, SandboxLimits, }; pub use models::*; diff --git a/src/main.rs b/src/main.rs index d66547a..fddd409 100644 --- a/src/main.rs +++ b/src/main.rs @@ -89,6 +89,12 @@ enum Commands { holdouts_dir: String, #[arg(long, default_value = ".rsi/eval_outputs")] output_dir: String, + #[arg(long)] + signing_key_hex: Option, + #[arg(long)] + signing_key_file: Option, + #[arg(long)] + require_latency_improvement: bool, }, /// Execute a holdout test case against internal logic Holdout { @@ -193,6 +199,9 @@ async fn main() -> Result<(), Box> { parent_path, holdouts_dir, output_dir, + signing_key_hex, + signing_key_file, + require_latency_improvement, } => { let judge_cli = spark_rsi::actor::JudgeCli { cycle_id, @@ -202,6 +211,9 @@ async fn main() -> Result<(), Box> { parent_path, holdouts_dir, output_dir, + signing_key_hex, + signing_key_file, + require_latency_improvement, }; spark_rsi::actor::judge::run_judge_cli(judge_cli)?; } @@ -217,6 +229,10 @@ async fn main() -> Result<(), Box> { mojo_kernel_path: kernel, loop_interval_secs: 60, sandbox_root: "/tmp/spark-rsi-sandbox".to_string(), + rsi_root: ".rsi".to_string(), + holdouts_dir: None, + signing_key_hex: None, + require_latency_improvement: false, }; let result = RsiEngine::run_cycle(&config).await?; println!("{}", serde_json::to_string_pretty(&result)?); @@ -229,6 +245,10 @@ async fn main() -> Result<(), Box> { mojo_kernel_path: kernel, loop_interval_secs: interval, sandbox_root: "/tmp/spark-rsi-sandbox".to_string(), + rsi_root: ".rsi".to_string(), + holdouts_dir: None, + signing_key_hex: None, + require_latency_improvement: false, }; RsiEngine::run_daemon(config).await?; } diff --git a/src/models.rs b/src/models.rs index c3324e8..0d1e39b 100644 --- a/src/models.rs +++ b/src/models.rs @@ -93,6 +93,18 @@ pub struct RsiConfig { pub mojo_kernel_path: String, pub loop_interval_secs: u64, pub sandbox_root: String, + #[serde(default = "default_rsi_root")] + pub rsi_root: String, + #[serde(default)] + pub holdouts_dir: Option, + #[serde(default)] + pub signing_key_hex: Option, + #[serde(default)] + pub require_latency_improvement: bool, +} + +fn default_rsi_root() -> String { + ".rsi".to_string() } impl Default for RsiConfig { @@ -104,6 +116,10 @@ impl Default for RsiConfig { mojo_kernel_path: "mojo/balance_bin".to_string(), loop_interval_secs: 60, sandbox_root: "/tmp/spark-rsi-sandbox".to_string(), + rsi_root: ".rsi".to_string(), + holdouts_dir: None, + signing_key_hex: None, + require_latency_improvement: false, } } } @@ -115,6 +131,8 @@ pub struct RsiCycleResult { pub proposal: Option, pub invariants: Option, pub balance: Option, + pub receipt: Option, + pub generation: Option, pub ratification: Option, pub success: bool, pub elapsed_ms: f64, diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 156359a..7191a41 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -116,6 +116,10 @@ async fn test_rsi_cycle_execution() { mojo_kernel_path: "mojo/balance_bin".to_string(), loop_interval_secs: 60, sandbox_root: "/tmp/spark-rsi-test-sandbox".to_string(), + rsi_root: ".rsi".to_string(), + holdouts_dir: None, + signing_key_hex: None, + require_latency_improvement: false, }; let result = spark_rsi::daemon::RsiEngine::run_cycle(&config) diff --git a/tests/test_no_synthetic_trust_inputs.rs b/tests/test_no_synthetic_trust_inputs.rs new file mode 100644 index 0000000..3b7d50b --- /dev/null +++ b/tests/test_no_synthetic_trust_inputs.rs @@ -0,0 +1,250 @@ +use p256::ecdsa::{SigningKey, VerifyingKey}; +use spark_rsi::actor::judge::{find_executable, run_paired_benchmarks, BlindJudge, HoldoutSuite}; +use spark_rsi::isolation::CandidateJailRunner; +use spark_rsi::supervisor::{GenerationState, HostSupervisor}; +use std::fs; +use std::path::Path; + +#[test] +fn test_jailed_execution_blocks_network_and_host_leaks() { + let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); + let runner = CandidateJailRunner::new(&exe); + + // 1. Verify candidate execution inside jail returns valid deterministic response + let (success, stdout, _) = runner + .execute(&["holdout", "check_unicode_dashes"]) + .expect("Jail execution failed"); + assert!(success); + assert_eq!(stdout.trim(), "DASHES_PROHIBITED"); + + // 2. Verify Bubblewrap args contain mandatory isolation parameters + let args = runner.build_bwrap_args(&["holdout", ""]); + assert!(args.contains(&"--unshare-net".to_string()), "Jail missing --unshare-net"); + assert!(args.contains(&"--unshare-user".to_string()), "Jail missing --unshare-user"); + assert!(args.contains(&"--unshare-pid".to_string()), "Jail missing --unshare-pid"); + assert!(args.contains(&"--die-with-parent".to_string()), "Jail missing --die-with-parent"); +} + +#[test] +fn test_judge_fails_closed_without_protected_holdouts_or_authorized_key() { + let tmp = tempfile::tempdir().unwrap(); + let holdouts = tmp.path().join("holdouts"); + let outputs = tmp.path().join("eval_outputs"); + let candidate = tmp.path().join("cand"); + let parent = tmp.path().join("parent"); + fs::create_dir_all(&candidate).unwrap(); + fs::create_dir_all(&parent).unwrap(); + + let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + + // Failure Case 1: Missing holdouts directory fails closed + let signing_key = SigningKey::from_bytes(&[44u8; 32].into()).unwrap(); + let judge_no_holdouts = BlindJudge::new(holdouts.clone(), outputs.clone()) + .with_signing_key(signing_key.clone()); + let res1 = judge_no_holdouts.evaluate_cycle("c1", "cand1", "parent0", &candidate, &parent); + assert!(res1.is_err(), "Judge must fail closed when holdouts dir does not exist"); + assert!(res1.unwrap_err().contains("Holdouts directory does not exist")); + + // Failure Case 2: Empty holdouts directory fails closed + fs::create_dir_all(&holdouts).unwrap(); + let res2 = judge_no_holdouts.evaluate_cycle("c2", "cand2", "parent0", &candidate, &parent); + assert!(res2.is_err(), "Judge must fail closed when holdouts dir is empty"); + assert!(res2.unwrap_err().contains("No valid holdout suites found")); + + // Populate valid holdout suites + for suite in HoldoutSuite::builtin_suites() { + suite.save_to_dir(&holdouts).unwrap(); + } + + // Failure Case 3: Missing signing key fails closed (zero fallback to static seed) + let judge_no_key = BlindJudge::new(holdouts.clone(), outputs.clone()); + let res3 = judge_no_key.evaluate_cycle("c3", "cand3", "parent0", &candidate, &parent); + assert!(res3.is_err(), "Judge must fail closed without authorized signing key"); + assert!(res3.unwrap_err().contains("signing key")); + + // Failure Case 4: Missing candidate binary in paired benchmarks fails closed (zero fallback to synthetic hash loop) + let empty_dir = tmp.path().join("empty_binary_dir"); + fs::create_dir_all(&empty_dir).unwrap(); + let bench_res = run_paired_benchmarks(&empty_dir, &candidate, 10); + assert!(bench_res.is_err(), "Paired benchmark must fail closed without compiled binaries"); + assert!(bench_res.unwrap_err().contains("executable binary not found")); +} + +#[test] +fn test_paired_benchmarks_capture_real_child_process_metrics_without_markers() { + let tmp = tempfile::tempdir().unwrap(); + let candidate = tmp.path().join("cand"); + let parent = tmp.path().join("parent"); + fs::create_dir_all(&candidate).unwrap(); + fs::create_dir_all(&parent).unwrap(); + + let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + + // Plant synthetic speedup marker in candidate + fs::write(candidate.join(".rsi_speedup"), "0.10").unwrap(); + + let (p_lats, c_lats, p_ru, c_ru) = run_paired_benchmarks(&parent, &candidate, 30) + .expect("Paired benchmark must execute real child processes"); + + assert_eq!(p_lats.len(), 30); + assert_eq!(c_lats.len(), 30); + + // Verify latencies are genuine measured positive non-zero numbers + for lat in &p_lats { + assert!(*lat > 50.0, "Latency must be real elapsed microseconds: {}", lat); + } + for lat in &c_lats { + assert!(*lat > 50.0, "Latency must be real elapsed microseconds: {}", lat); + } + + // Core invariant: .rsi_speedup (0.10) must NOT artificially scale candidate latency by 10x + let p_mean: f64 = p_lats.iter().sum::() / 30.0; + let c_mean: f64 = c_lats.iter().sum::() / 30.0; + let ratio = c_mean / p_mean; + assert!( + ratio > 0.50 && ratio < 2.0, + "Marker file bypassed measurement: ratio was {:.4} (p_mean={}, c_mean={})", + ratio, p_mean, c_mean + ); + + // Verify child rusage metrics are captured + assert!(p_ru.max_rss_kb > 0, "Parent RSS must be non-zero"); + assert!(c_ru.max_rss_kb > 0, "Candidate RSS must be non-zero"); +} + +#[test] +fn test_end_to_end_unmocked_lifecycle_admission_and_supervisor_rollback() { + let tmp = tempfile::tempdir().unwrap(); + let rsi_root = tmp.path().join(".rsi"); + let holdouts = rsi_root.join("holdouts"); + let outputs = rsi_root.join("eval_outputs"); + let candidate = tmp.path().join("cand"); + let parent = tmp.path().join("parent"); + fs::create_dir_all(&candidate).unwrap(); + fs::create_dir_all(&parent).unwrap(); + + let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + + // Seed protected holdouts + for suite in HoldoutSuite::builtin_suites() { + suite.save_to_dir(&holdouts).unwrap(); + } + + let signing_key = SigningKey::from_bytes(&[55u8; 32].into()).unwrap(); + let verifying_key = VerifyingKey::from(&signing_key); + + let judge = BlindJudge::new(holdouts, outputs.clone()) + .with_signing_key(signing_key); + + // 1. Evaluate candidate + let receipt = judge + .evaluate_cycle("cycle-e2e-01", "cand-e2e-01", "parent-e2e-00", &candidate, &parent) + .expect("Evaluation cycle failed"); + + assert!(receipt.admitted, "Clean candidate must be admitted"); + assert!(receipt.passed_all_hard_invariants); + assert!(receipt.passed_statistical_gates); + assert!(receipt.verify_digest()); + assert!(receipt.signature.is_some()); + assert!(receipt.verify_signature(&verifying_key)); + + // 2. Route admitted candidate into HostSupervisor + let supervisor = HostSupervisor::new(&rsi_root, 49_152); + + // Stage parent generation first + supervisor + .stage_generation("gen-parent-00", &parent, "parent-digest-00") + .expect("Parent staging failed"); + supervisor + .atomic_symlink_swap("gen-parent-00") + .expect("Initial parent symlink swap failed"); + + // Stage admitted candidate generation + let mut gen_info = supervisor + .stage_generation("gen-e2e-01", &candidate, &receipt.receipt_digest) + .expect("Candidate staging failed"); + assert_eq!(gen_info.state, GenerationState::Staged); + + // Atomic symlink swap to point to candidate + supervisor + .atomic_symlink_swap("gen-e2e-01") + .expect("Candidate symlink swap failed"); + let active_link = fs::read_link(rsi_root.join("active")).unwrap(); + assert!(active_link.to_string_lossy().contains("gen-e2e-01")); + + // Canary testing: transaction success transitions toward Durable + let s1 = supervisor + .record_canary_transaction(&mut gen_info, true, 10) + .expect("Canary update failed"); + assert_eq!(s1, GenerationState::CanaryActive); + + // Simulate regression alert triggering automated rollback + let s2 = supervisor + .record_canary_transaction(&mut gen_info, false, 10) + .expect("Canary failure recording failed"); + assert_eq!(s2, GenerationState::Reverting); + + // Supervisor executes atomic rollback to parent + let rollback_res = supervisor.rollback_to_parent("gen-parent-00", None, None); + assert!(rollback_res.is_ok(), "Supervisor rollback failed"); + let reverted_link = fs::read_link(rsi_root.join("active")).unwrap(); + assert!(reverted_link.to_string_lossy().contains("gen-parent-00")); +} + +#[tokio::test] +async fn test_daemon_run_cycle_promotes_via_host_supervisor() { + use spark_rsi::daemon::RsiEngine; + use spark_rsi::models::RsiConfig; + use std::process::Command; + + let tmp = tempfile::tempdir().unwrap(); + let repo_dir = tmp.path().join("repo"); + let sandbox_dir = tmp.path().join("sandbox"); + fs::create_dir_all(&repo_dir).unwrap(); + + // Initialize git repository + let _ = Command::new("git").args(["init", "-b", "main"]).current_dir(&repo_dir).output(); + let _ = Command::new("git").args(["config", "user.name", "Test Operator"]).current_dir(&repo_dir).output(); + let _ = Command::new("git").args(["config", "user.email", "operator@test.local"]).current_dir(&repo_dir).output(); + + // Write a README with an em-dash to trigger ProposalGenerator + let readme = repo_dir.join("README.md"); + fs::write(&readme, "# Test Repo\n\nThis is a feature\u{2014}with an em dash.\n").unwrap(); + + let _ = Command::new("git").args(["add", "."]).current_dir(&repo_dir).output(); + let _ = Command::new("git").args(["commit", "-m", "initial commit"]).current_dir(&repo_dir).output(); + + let rsi_root = repo_dir.join(".rsi"); + let config = RsiConfig { + target_repo: repo_dir.to_str().unwrap().to_string(), + cortex_url: "http://127.0.0.1:18080".to_string(), + cortex_space: "atlas-memory".to_string(), + mojo_kernel_path: "mojo/balance_bin".to_string(), + loop_interval_secs: 60, + sandbox_root: sandbox_dir.to_str().unwrap().to_string(), + rsi_root: ".rsi".to_string(), + holdouts_dir: None, + signing_key_hex: None, + require_latency_improvement: false, + }; + + let result = RsiEngine::run_cycle(&config).await.expect("run_cycle failed"); + + assert!(result.success, "Cycle should succeed"); + assert!(result.proposal.is_some(), "Proposal should be generated for em dash unslop"); + assert!(result.generation.is_some(), "Candidate promotion must execute through Host Supervisor"); + + let gen = result.generation.unwrap(); + assert!(gen.state == GenerationState::Durable || gen.state == GenerationState::CanaryActive); + + // Verify atomic active symlink was created by HostSupervisor + let active_link = fs::read_link(rsi_root.join("active")).expect("Active symlink must exist"); + assert!(active_link.to_string_lossy().contains(&gen.generation_id)); + assert!(gen.installed_path.exists()); +} diff --git a/tests/test_objective_evaluator.rs b/tests/test_objective_evaluator.rs index f86cc11..7273b4c 100644 --- a/tests/test_objective_evaluator.rs +++ b/tests/test_objective_evaluator.rs @@ -164,12 +164,18 @@ fn test_blind_judge_receipt_roundtrip_and_persistence() { let parent = tmp.path().join("parent"); fs::create_dir_all(&parent).unwrap(); + let exe = spark_rsi::actor::judge::find_executable(std::path::Path::new(".")).expect("spark-rsi executable must exist"); + fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); + fs::copy(&exe, parent.join("spark-rsi")).unwrap(); + let suites = HoldoutSuite::builtin_suites(); for suite in suites { suite.save_to_dir(&holdouts).unwrap(); } - let judge = BlindJudge::new(holdouts, outputs.clone()); + let signing_key = p256::ecdsa::SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); + let verifying_key = p256::ecdsa::VerifyingKey::from(&signing_key); + let judge = BlindJudge::new(holdouts, outputs.clone()).with_signing_key(signing_key); let receipt = judge .evaluate_cycle( "cycle-persisted-99", @@ -183,6 +189,7 @@ fn test_blind_judge_receipt_roundtrip_and_persistence() { assert!(receipt.admitted); assert!(receipt.verify_digest()); assert!(receipt.signature.is_some()); + assert!(receipt.verify_signature(&verifying_key)); let target_file = outputs.join("cycle-persisted-99.json"); assert!(target_file.exists());