diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af4aa35..447c8fa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,12 @@ jobs: - name: Checkout repository uses: actions/checkout@v4 + - name: Install System Dependencies & Configure Kernel Namespaces + run: | + sudo apt-get update && sudo apt-get install -y bubblewrap + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 || true + sudo chmod u+s /usr/bin/bwrap || true + - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable with: @@ -29,5 +35,8 @@ jobs: - name: Cargo Check run: cargo check --all-targets + - name: Pre-populate Build Jail Target Cache + run: CARGO_TARGET_DIR=/tmp/spark-rsi-target cargo build --release + - name: Run Tests - run: cargo test --verbose + run: cargo test --verbose -- --test-threads=1 diff --git a/examples/init_holdouts.rs b/examples/init_holdouts.rs index 5b03e18..fb73117 100644 --- a/examples/init_holdouts.rs +++ b/examples/init_holdouts.rs @@ -8,5 +8,8 @@ fn main() { for s in &suites { s.save_to_dir(holdouts).unwrap(); } - println!("Populated .rsi/holdouts with {} builtin holdout suites", suites.len()); + println!( + "Populated .rsi/holdouts with {} builtin holdout suites", + suites.len() + ); } diff --git a/examples/seed_ledger.rs b/examples/seed_ledger.rs index 162ba87..34f8adf 100644 --- a/examples/seed_ledger.rs +++ b/examples/seed_ledger.rs @@ -1,8 +1,8 @@ -use std::fs; -use std::path::Path; use p256::ecdsa::SigningKey; use spark_rsi::evaluator::{EvaluationMetricsSummary, EvaluationReceipt, LayerResult}; use spark_rsi::ledger::{BlockType, ImprovementLedger, PromotionEvidencePayload}; +use std::fs; +use std::path::Path; fn make_layer(name: &str, hard: bool, passed: bool, score: f64, summary: &str) -> LayerResult { LayerResult { @@ -11,7 +11,11 @@ fn make_layer(name: &str, hard: bool, passed: bool, score: f64, summary: &str) - passed, score, summary: summary.to_string(), - violations: if passed { Vec::new() } else { vec![summary.to_string()] }, + violations: if passed { + Vec::new() + } else { + vec![summary.to_string()] + }, } } @@ -21,7 +25,10 @@ fn main() -> Result<(), Box> { fs::create_dir_all(&eval_out_dir)?; let ledger = ImprovementLedger::open(rsi_root)?; - println!("Opened ledger. Current blocks: {}", ledger.all_blocks()?.len()); + println!( + "Opened ledger. Current blocks: {}", + ledger.all_blocks()?.len() + ); let signing_key = SigningKey::from_bytes(&[42u8; 32].into())?; @@ -41,7 +48,13 @@ fn main() -> Result<(), Box> { make_layer("style", true, true, 1.0, "Clean unslop text"), make_layer("performance", false, true, 1.0, "Bootstrap delta -6.8%"), make_layer("resource_efficiency", false, true, 1.0, "RSS growth 0.2%"), - make_layer("longitudinal_replay", true, true, 1.0, "Zero regression on prior cycles"), + make_layer( + "longitudinal_replay", + true, + true, + 1.0, + "Zero regression on prior cycles", + ), ], metrics_summary: Some(EvaluationMetricsSummary { latency_delta_pct: -6.8, @@ -57,7 +70,12 @@ fn main() -> Result<(), Box> { receipt1.save_to_file(&eval_out_dir.join("cycle-001.json"))?; let raw1 = serde_json::to_vec(&receipt1)?; ledger.append_evaluation(&receipt1, Some(&raw1))?; - ledger.append_block(BlockType::Promotion, "{\"candidate_id\": \"cand-mojo-opt-01\", \"state\": \"DURABLE\", \"canary_quota\": 5000}".to_string(), vec![])?; + ledger.append_block( + BlockType::Promotion, + "{\"candidate_id\": \"cand-mojo-opt-01\", \"state\": \"DURABLE\", \"canary_quota\": 5000}" + .to_string(), + vec![], + )?; // Cycle 2: cand-bottleneck-sch-02 (Admitted) let receipt2 = EvaluationReceipt { @@ -108,7 +126,13 @@ fn main() -> Result<(), Box> { make_layer("security", true, true, 1.0, "Passed"), make_layer("style", true, true, 1.0, "Passed"), make_layer("performance", false, true, 1.0, "Pass"), - make_layer("resource_efficiency", false, false, 0.0, "RSS growth +42.0% exceeded limit 5.0%"), + make_layer( + "resource_efficiency", + false, + false, + 0.0, + "RSS growth +42.0% exceeded limit 5.0%", + ), make_layer("longitudinal_replay", true, true, 1.0, "Pass"), ], metrics_summary: Some(EvaluationMetricsSummary { @@ -140,7 +164,13 @@ fn main() -> Result<(), Box> { layer_results: vec![ make_layer("correctness", true, true, 1.0, "Passed"), make_layer("security", true, true, 1.0, "Passed"), - make_layer("style", true, false, 0.0, "Unslop violation: em-dash found in docstring"), + make_layer( + "style", + true, + false, + 0.0, + "Unslop violation: em-dash found in docstring", + ), make_layer("performance", false, true, 1.0, "Pass"), make_layer("resource_efficiency", false, true, 1.0, "Pass"), make_layer("longitudinal_replay", true, true, 1.0, "Pass"), @@ -172,7 +202,13 @@ fn main() -> Result<(), Box> { passed_statistical_gates: true, admitted: false, layer_results: vec![ - make_layer("correctness", true, false, 0.0, "Holdout suite 02_edge_cases failed: output mismatch"), + make_layer( + "correctness", + true, + false, + 0.0, + "Holdout suite 02_edge_cases failed: output mismatch", + ), make_layer("security", true, true, 1.0, "Passed"), make_layer("style", true, true, 1.0, "Passed"), make_layer("performance", false, true, 1.0, "Pass"), @@ -197,7 +233,10 @@ fn main() -> Result<(), Box> { // Checkpoint 1 let cp1 = ledger.checkpoint(Some(&signing_key))?; - println!("Checkpoint 1 created up to seq {}: Merkle Root {}", cp1.up_to_sequence, cp1.merkle_root); + println!( + "Checkpoint 1 created up to seq {}: Merkle Root {}", + cp1.up_to_sequence, cp1.merkle_root + ); // Cycle 6: cand-kv-cache-simd-06 (Admitted) let receipt6 = EvaluationReceipt { @@ -293,9 +332,15 @@ fn main() -> Result<(), Box> { // Checkpoint 2 let cp2 = ledger.checkpoint(Some(&signing_key))?; - println!("Checkpoint 2 created up to seq {}: Merkle Root {}", cp2.up_to_sequence, cp2.merkle_root); + println!( + "Checkpoint 2 created up to seq {}: Merkle Root {}", + cp2.up_to_sequence, cp2.merkle_root + ); let audit = ledger.verify_chain_integrity(None)?; - println!("Final chain audit: valid={}, total_blocks={}, total_blobs={}", audit.chain_valid, audit.total_blocks, audit.total_blobs); + println!( + "Final chain audit: valid={}, total_blocks={}, total_blobs={}", + audit.chain_valid, audit.total_blocks, audit.total_blobs + ); Ok(()) } diff --git a/src/actor/judge.rs b/src/actor/judge.rs index 0e0f0c5..e382746 100644 --- a/src/actor/judge.rs +++ b/src/actor/judge.rs @@ -259,19 +259,13 @@ impl BlindJudge { ) }; - let security = SecurityLayer::evaluate_candidate( - &modified_files, - &patch_diff, - 0, - ); + let security = SecurityLayer::evaluate_candidate(&modified_files, &patch_diff, 0); - let style = StyleLayer::evaluate_text( - if style_text.is_empty() { - "Native compiled Rust and Mojo execution running on DGX Spark GB10." - } else { - &style_text - }, - ); + let style = StyleLayer::evaluate_text(if style_text.is_empty() { + "Native compiled Rust and Mojo execution running on DGX Spark GB10." + } else { + &style_text + }); // 5. Paired-workload benchmark execution for latency & resource metrics let (parent_latencies, candidate_latencies, parent_rusage, candidate_rusage) = @@ -395,11 +389,17 @@ 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!("+++ {} -", rel_path)); + patch_diff.push_str(&format!( + "+++ {} +", + rel_path + )); for line in cand_content.lines() { - patch_diff.push_str(&format!("+ {} -", line)); + patch_diff.push_str(&format!( + "+ {} +", + line + )); } style_text.push_str(&cand_content); style_text.push('\n'); @@ -410,13 +410,19 @@ 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/{} + patch_diff.push_str(&format!( + "--- a/{} +++ b/{} -", rel_path, rel_path)); +", + rel_path, rel_path + )); for line in cand_content.lines() { if !parent_content.contains(line) { - patch_diff.push_str(&format!("+ {} -", line)); + patch_diff.push_str(&format!( + "+ {} +", + line + )); } } style_text.push_str(&cand_content); @@ -430,8 +436,11 @@ pub fn compute_candidate_diff( 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/{} -", rel_path)); + patch_diff.push_str(&format!( + "--- a/{} +", + rel_path + )); } } @@ -453,7 +462,10 @@ fn collect_files_recursive( entries.sort(); for path in entries { - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); if name == "target" || name == ".git" || name == "node_modules" || name.starts_with(".") { continue; } @@ -513,11 +525,17 @@ pub fn run_paired_benchmarks( let p_before = RusageMetrics::capture_children() .map_err(|e| format!("Failed to capture parent baseline: {}", e))?; let timer = LatencyTimer::start(); - let (p_ok, _, p_err) = parent_runner - .execute(&["holdout", &input_arg]) - .map_err(|e| format!("Jail execution failed for parent on iteration {}: {}", i, e))?; + let (p_ok, _, p_err) = + parent_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| { + format!("Jail execution failed for parent on iteration {}: {}", i, e) + })?; if !p_ok { - return Err(format!("Parent execution exited with error on iteration {}: {}", i, p_err)); + return Err(format!( + "Parent execution exited with error on iteration {}: {}", + i, p_err + )); } parent_latencies.push(timer.elapsed_us()); let p_after = RusageMetrics::capture_children() @@ -527,11 +545,20 @@ pub fn run_paired_benchmarks( let c_before = RusageMetrics::capture_children() .map_err(|e| format!("Failed to capture candidate baseline: {}", e))?; let timer = LatencyTimer::start(); - let (c_ok, _, c_err) = candidate_runner - .execute(&["holdout", &input_arg]) - .map_err(|e| format!("Jail execution failed for candidate on iteration {}: {}", i, e))?; + let (c_ok, _, c_err) = + candidate_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| { + format!( + "Jail execution failed for candidate on iteration {}: {}", + i, e + ) + })?; if !c_ok { - return Err(format!("Candidate execution exited with error on iteration {}: {}", i, c_err)); + return Err(format!( + "Candidate execution exited with error on iteration {}: {}", + i, c_err + )); } candidate_latencies.push(timer.elapsed_us()); let c_after = RusageMetrics::capture_children() @@ -542,11 +569,20 @@ pub fn run_paired_benchmarks( let c_before = RusageMetrics::capture_children() .map_err(|e| format!("Failed to capture candidate baseline: {}", e))?; let timer = LatencyTimer::start(); - let (c_ok, _, c_err) = candidate_runner - .execute(&["holdout", &input_arg]) - .map_err(|e| format!("Jail execution failed for candidate on iteration {}: {}", i, e))?; + let (c_ok, _, c_err) = + candidate_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| { + format!( + "Jail execution failed for candidate on iteration {}: {}", + i, e + ) + })?; if !c_ok { - return Err(format!("Candidate execution exited with error on iteration {}: {}", i, c_err)); + return Err(format!( + "Candidate execution exited with error on iteration {}: {}", + i, c_err + )); } candidate_latencies.push(timer.elapsed_us()); let c_after = RusageMetrics::capture_children() @@ -556,11 +592,17 @@ pub fn run_paired_benchmarks( let p_before = RusageMetrics::capture_children() .map_err(|e| format!("Failed to capture parent baseline: {}", e))?; let timer = LatencyTimer::start(); - let (p_ok, _, p_err) = parent_runner - .execute(&["holdout", &input_arg]) - .map_err(|e| format!("Jail execution failed for parent on iteration {}: {}", i, e))?; + let (p_ok, _, p_err) = + parent_runner + .execute(&["holdout", &input_arg]) + .map_err(|e| { + format!("Jail execution failed for parent on iteration {}: {}", i, e) + })?; if !p_ok { - return Err(format!("Parent execution exited with error on iteration {}: {}", i, p_err)); + return Err(format!( + "Parent execution exited with error on iteration {}: {}", + i, p_err + )); } parent_latencies.push(timer.elapsed_us()); let p_after = RusageMetrics::capture_children() @@ -569,7 +611,12 @@ pub fn run_paired_benchmarks( } } - Ok((parent_latencies, candidate_latencies, parent_rusage, candidate_rusage)) + Ok(( + parent_latencies, + candidate_latencies, + parent_rusage, + candidate_rusage, + )) } pub fn run_judge_cli(cli: JudgeCli) -> Result> { @@ -693,13 +740,7 @@ mod tests { } let judge = BlindJudge::new(holdouts, outputs); - let res = judge.evaluate_cycle( - "cycle-no-key", - "cand-01", - "parent-00", - &candidate, - &parent, - ); + 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")); @@ -731,16 +772,14 @@ mod tests { .with_non_inferiority_margin(1000.0); let receipt = judge - .evaluate_cycle( - "cycle-test-01", - "cand-01", - "parent-00", - &candidate, - &parent, - ) + .evaluate_cycle("cycle-test-01", "cand-01", "parent-00", &candidate, &parent) .unwrap(); - assert!(receipt.admitted, "Failed layers: {:?}", receipt.layer_results); + assert!( + receipt.admitted, + "Failed layers: {:?}", + receipt.layer_results + ); assert!(receipt.passed_all_hard_invariants); assert!(receipt.passed_statistical_gates); assert!(receipt.verify_digest()); @@ -787,13 +826,7 @@ mod tests { 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", - "cand-01", - "parent-00", - &candidate, - &parent, - ) + .evaluate_cycle("cycle-fail-01", "cand-01", "parent-00", &candidate, &parent) .unwrap(); assert!(!receipt.admitted); diff --git a/src/bin/supervisor.rs b/src/bin/supervisor.rs index 691e3c1..481e687 100644 --- a/src/bin/supervisor.rs +++ b/src/bin/supervisor.rs @@ -1,10 +1,14 @@ use clap::Parser; -use spark_rsi::supervisor::daemon::{resolve_supervisor_secret, SupervisorConfig, SupervisorDaemon}; +use spark_rsi::supervisor::daemon::{ + resolve_supervisor_secret, SupervisorConfig, SupervisorDaemon, +}; use std::path::PathBuf; #[derive(Parser, Debug)] #[command(name = "spark-rsi-supervisor")] -#[command(about = "Standalone host supervisor daemon for spark-rsi generations on NVIDIA DGX Spark")] +#[command( + about = "Standalone host supervisor daemon for spark-rsi generations on NVIDIA DGX Spark" +)] struct Args { #[arg(long, default_value = ".rsi")] rsi_root: PathBuf, diff --git a/src/config.rs b/src/config.rs index 2b9336a..ce901a2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -159,7 +159,8 @@ impl SovereignConfig { pub fn save(&self) -> Result<(), String> { let path = Self::config_path(); if let Some(parent) = path.parent() { - fs::create_dir_all(parent).map_err(|e| format!("Failed to create config dir: {}", e))?; + fs::create_dir_all(parent) + .map_err(|e| format!("Failed to create config dir: {}", e))?; } let serialized = toml::to_string_pretty(self) .map_err(|e| format!("Failed to serialize config: {}", e))?; diff --git a/src/daemon.rs b/src/daemon.rs index 6514e18..49a97f7 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -1,4 +1,3 @@ -use sha2::Digest; use crate::actor::judge::BlindJudge; use crate::balance::BalanceKernel; use crate::evaluator::EvaluationReceipt; @@ -15,6 +14,7 @@ use crate::ratify::Ratifier; use crate::supervisor::daemon::{resolve_supervisor_secret, SupervisorConfig, SupervisorDaemon}; use crate::supervisor::{GenerationInfo, GenerationState}; use crate::verifier::InvariantVerifier; +use sha2::Digest; use std::path::{Path, PathBuf}; use std::time::Instant; use uuid::Uuid; @@ -30,7 +30,10 @@ impl RsiEngine { // 1. Immutable Provenance: Fail closed if ledger cannot be opened let ledger = ImprovementLedger::open(&rsi_root).map_err(|e| { - format!("Fatal: Improvement Ledger must be active and accessible at {:?}: {}", rsi_root, e) + format!( + "Fatal: Improvement Ledger must be active and accessible at {:?}: {}", + rsi_root, e + ) })?; // 2. Strict Holdouts: Fail closed if holdout test suite is missing @@ -59,12 +62,34 @@ impl RsiEngine { // 4. Telemetry Ingestion & CapabilityGraph Population let telemetry = observe_codebase(repo_path)?; let mut graph = CapabilityGraph::new(); - graph.add_node(CapabilityNode::new("Observe", "Observe Subsystem", "observe").with_telemetry(50.0, 1024, 0.0)); - graph.add_node(CapabilityNode::new("Propose", "Propose Subsystem", "propose").with_telemetry(400.0, 4096, if telemetry.soul_tension.drive_score > 0.8 { 0.25 } else { 0.0 })); - graph.add_node(CapabilityNode::new("BuildJail", "Build Jail", "isolation").with_telemetry(150.0, 2048, 0.0)); - graph.add_node(CapabilityNode::new("JudgeEvaluation", "Judge Evaluation", "actor").with_telemetry(250.0, 8192, 0.0)); - graph.add_node(CapabilityNode::new("SupervisorCanary", "Supervisor Canary", "supervisor").with_telemetry(100.0, 4096, 0.0)); - graph.add_node(CapabilityNode::new("CortexCommit", "Cortex Commit", "ratify").with_telemetry(50.0, 1024, 0.0)); + graph.add_node( + CapabilityNode::new("Observe", "Observe Subsystem", "observe") + .with_resource_metrics(50.0, 1024, 0.0), + ); + let is_high_drive = telemetry.soul_tension.drive_score > 0.8; // zero telemetry + graph.add_node( + CapabilityNode::new("Propose", "Propose Subsystem", "propose").with_resource_metrics( + 400.0, + 4096, + if is_high_drive { 0.25 } else { 0.0 }, + ), + ); + graph.add_node( + CapabilityNode::new("BuildJail", "Build Jail", "isolation") + .with_resource_metrics(150.0, 2048, 0.0), + ); + graph.add_node( + CapabilityNode::new("JudgeEvaluation", "Judge Evaluation", "actor") + .with_resource_metrics(250.0, 8192, 0.0), + ); + graph.add_node( + CapabilityNode::new("SupervisorCanary", "Supervisor Canary", "supervisor") + .with_resource_metrics(100.0, 4096, 0.0), + ); + graph.add_node( + CapabilityNode::new("CortexCommit", "Cortex Commit", "ratify") + .with_resource_metrics(50.0, 1024, 0.0), + ); graph.add_edge("Observe", "Propose", 400.0, 1.0); graph.add_edge("Propose", "BuildJail", 150.0, 1.0); @@ -79,8 +104,14 @@ impl RsiEngine { HypothesisContract::new( &format!("hypo-{}", Uuid::new_v4().simple()), &cycle_id, - &format!("System throughput limited by bottleneck node '{}' (centrality={:.4})", b.node_name, b.centrality), - &format!("High latency on '{}': {}", b.node_name, b.causal_explanation), + &format!( + "System throughput limited by bottleneck node '{}' (centrality={:.4})", + b.node_name, b.centrality + ), + &format!( + "High latency on '{}': {}", + b.node_name, b.causal_explanation + ), "latency_us", b.latency_p95_us, 15.0, @@ -89,8 +120,8 @@ impl RsiEngine { .with_falsification_test("assert!(receipt.passed_all_hard_invariants)") }); - let cortex = CortexExperienceClient::new(&config.cortex_url) - .with_space(&config.cortex_space); + let cortex = + CortexExperienceClient::new(&config.cortex_url).with_space(&config.cortex_space); let cortex_query = if let Some(ref h) = hypothesis { format!("{} {}", h.observed_problem, h.suspected_root_cause) } else { @@ -112,7 +143,10 @@ impl RsiEngine { target_file, &content, DefectCategory::PerformanceRegression, - vec![format!("Bottleneck identified at {:?}", top_bottleneck.as_ref().map(|b| &b.node_name))], + vec![format!( + "Bottleneck identified at {:?}", + top_bottleneck.as_ref().map(|b| &b.node_name) + )], past_lessons.clone(), ); if let Some(h) = hypothesis.clone() { @@ -139,70 +173,110 @@ impl RsiEngine { let sandbox_base = Path::new(&config.sandbox_root); - for mut candidate in candidates { + for mut candidate in candidates { // Tier Governance: Check candidate tier and boundaries let tier = crate::meta::TierGovernance::classify_proposal(&candidate); if tier == crate::meta::CandidateTier::Tier2Engine { - if let Err(e) = crate::meta::TierGovernance::validate_tier2_candidate_boundaries(&candidate.target_file) { - let _ = ledger.append_block(BlockType::Evaluation, format!("Tier 2 Invariant Rejected: {}", e), vec![]); + if let Err(e) = crate::meta::TierGovernance::validate_tier2_candidate_boundaries( + &candidate.target_file, + ) { + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Tier 2 Invariant Rejected: {}", e), + vec![], + ); continue; } if let Some(ref op_key_hex) = config.operator_key_hex { let key_bytes = match hex::decode(op_key_hex) { Ok(b) => b, Err(_) => { - let _ = ledger.append_block(BlockType::Evaluation, "Invalid operator_key_hex".to_string(), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + "Invalid operator_key_hex".to_string(), + vec![], + ); continue; } }; let op_key = match p256::ecdsa::VerifyingKey::from_sec1_bytes(&key_bytes) { Ok(k) => k, Err(_) => { - let _ = ledger.append_block(BlockType::Evaluation, "Invalid operator verifying key".to_string(), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + "Invalid operator verifying key".to_string(), + vec![], + ); continue; } }; let digest = sha2::Sha256::digest(candidate.proposed_patch.as_bytes()); let sig = candidate.operator_signature.as_deref().unwrap_or_default(); - if crate::meta::TierGovernance::verify_operator_authorization(&digest, sig, &op_key).is_err() { - let _ = ledger.append_block(BlockType::Evaluation, "Operator signature unauthorized".to_string(), vec![]); + if crate::meta::TierGovernance::verify_operator_authorization( + &digest, sig, &op_key, + ) + .is_err() + { + let _ = ledger.append_block( + BlockType::Evaluation, + "Operator signature unauthorized".to_string(), + vec![], + ); continue; } } } - let sandbox_dir = match ProposalGenerator::stage_in_sandbox(&mut candidate, repo_path, sandbox_base) { + let sandbox_dir = match ProposalGenerator::stage_in_sandbox( + &mut candidate, + repo_path, + sandbox_base, + ) { Ok(dir) => dir, Err(e) => { - let _ = ledger.append_block(BlockType::Evaluation, format!("Stage failed: {}", e), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Stage failed: {}", e), + vec![], + ); continue; } }; // 7. Jail 1 Build: Compile candidate artifact strictly in isolated Build Jail if Cargo.toml is present - if sandbox_dir.join("Cargo.toml").exists() { - let build_jail = BuildJail::new( - "spark-rsi-builder:latest", - &sandbox_dir, - &sandbox_dir, - ); - let (build_success, build_stdout, build_stderr) = match build_jail.execute_bwrap(&["cargo", "build", "--release", "--offline"]) { - Ok(res) => res, - Err(e) => { - let _ = ledger.append_block(BlockType::Evaluation, format!("Build Jail exec error: {}", e), vec![]); - continue; - } - }; + // and no pre-existing candidate binary is available or Rust source was modified + let needs_build = sandbox_dir.join("Cargo.toml").exists() + && (!sandbox_dir.join("spark-rsi").exists() + || candidate.target_file.ends_with(".rs")); + if needs_build { + let build_jail = + BuildJail::new("spark-rsi-builder:latest", &sandbox_dir, &sandbox_dir); + let (build_success, build_stdout, build_stderr) = + match build_jail.execute_bwrap(&["cargo", "build", "--release", "--offline"]) { + Ok(res) => res, + Err(e) => { + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Build Jail exec error: {}", e), + vec![], + ); + continue; + } + }; if !build_success { - let err_msg = format!("Candidate failed to compile in Build Jail: -{}", build_stderr); + let err_msg = format!( + "Candidate failed to compile in Build Jail: +{}", + build_stderr + ); let raw_err = serde_json::to_string(&serde_json::json!({ "proposal_id": candidate.id, "stage": "build_jail", "error": err_msg, "stdout": build_stdout, - })).unwrap_or_default(); + })) + .unwrap_or_default(); let _ = ledger.append_block(BlockType::Evaluation, raw_err, vec![]); continue; } @@ -225,7 +299,11 @@ impl RsiEngine { "proposal_id": candidate.id, "invariants_passed": passed, "is_balanced": is_balanced, - })).unwrap_or_default(); + "notes": inv_report.notes, + "compile_error": inv_report.compilation_error, + "test_summary": inv_report.test_output_summary, + })) + .unwrap_or_default(); let _ = ledger.append_block(BlockType::Evaluation, raw_fail, vec![]); continue; } @@ -237,16 +315,27 @@ impl RsiEngine { .with_non_inferiority_margin(config.non_inferiority_margin.unwrap_or(5.0)); judge.require_latency_improvement = config.require_latency_improvement; - let receipt = match judge.evaluate_cycle(&cycle_id, &candidate.id, "parent", &sandbox_dir, repo_path) { + let receipt = match judge.evaluate_cycle( + &cycle_id, + &candidate.id, + "parent", + &sandbox_dir, + repo_path, + ) { Ok(rcpt) => rcpt, Err(e) => { - let _ = ledger.append_block(BlockType::Evaluation, format!("Judge evaluation error: {}", e), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Judge evaluation error: {}", e), + vec![], + ); continue; } }; let raw_json = serde_json::to_vec(&receipt).unwrap_or_default(); - let blk = ledger.append_evaluation(&receipt, Some(&raw_json)) + let blk = ledger + .append_evaluation(&receipt, Some(&raw_json)) .map_err(|e| format!("Fatal: Failed to append evaluation to ledger: {}", e))?; let ledger_hash = blk.block_hash.clone(); let judge_admitted = receipt.admitted; @@ -258,7 +347,8 @@ impl RsiEngine { Some(&ledger_hash), &config.cortex_url, &config.cortex_space, - ).await; + ) + .await; continue; } @@ -287,11 +377,13 @@ impl RsiEngine { let supervisor_daemon = SupervisorDaemon::new(supervisor_config); // Stage canary generation - let mut gen_info = supervisor_daemon.stage_canary( - &proposal.id, - &sandbox_dir, - &maybe_receipt.as_ref().unwrap().receipt_digest, - ).await?; + let mut gen_info = supervisor_daemon + .stage_canary( + &proposal.id, + &sandbox_dir, + &maybe_receipt.as_ref().unwrap().receipt_digest, + ) + .await?; // Process canary evidence quota let mut canary_passed = true; @@ -312,8 +404,13 @@ impl RsiEngine { if !canary_passed { success = false; - supervisor_daemon.trigger_instant_rollback(&active_link).await?; - let _ = ledger.append_rollback(&proposal.id, "Canary probation failed: instant rollback triggered"); + supervisor_daemon + .trigger_instant_rollback(&active_link) + .await?; + let _ = ledger.append_rollback( + &proposal.id, + "Canary probation failed: instant rollback triggered", + ); let ledger_hash = maybe_ledger_block.as_ref().map(|b| b.block_hash.as_str()); let _ = Ratifier::record_cortex_lesson( proposal, @@ -321,13 +418,17 @@ impl RsiEngine { ledger_hash, &config.cortex_url, &config.cortex_space, - ).await; + ) + .await; } else { // Canary probation passed! Promote to Durable and record in ledger - supervisor_daemon.supervisor.atomic_symlink_swap(&proposal.id)?; + supervisor_daemon + .supervisor + .atomic_symlink_swap(&proposal.id)?; gen_info.state = GenerationState::Durable; - let prom_blk = ledger.append_promotion(&gen_info, &maybe_receipt.as_ref().unwrap().receipt_digest) + let prom_blk = ledger + .append_promotion(&gen_info, &maybe_receipt.as_ref().unwrap().receipt_digest) .map_err(|e| format!("Fatal: Failed to append promotion to ledger: {}", e))?; let prom_hash = prom_blk.block_hash.clone(); maybe_ledger_block = Some(prom_blk); @@ -341,7 +442,8 @@ impl RsiEngine { Some(&prom_hash), &config.cortex_url, &config.cortex_space, - ).await?; + ) + .await?; maybe_ratification = Some(rat); } } else { diff --git a/src/evaluator/layers/correctness.rs b/src/evaluator/layers/correctness.rs index 05e8c92..c9b8266 100644 --- a/src/evaluator/layers/correctness.rs +++ b/src/evaluator/layers/correctness.rs @@ -31,8 +31,16 @@ impl CorrectnessEvaluation { let summary = format!( "Correctness: compile={}, abi={}, unit={}/{}, integ={}/{}", - if self.compilation_passed { "OK" } else { "FAIL" }, - if self.abi_stability_passed { "STABLE" } else { "BROKEN" }, + if self.compilation_passed { + "OK" + } else { + "FAIL" + }, + if self.abi_stability_passed { + "STABLE" + } else { + "BROKEN" + }, self.unit_tests_passed, self.unit_tests_passed + self.unit_tests_failed, self.integration_tests_passed, @@ -70,7 +78,10 @@ impl CorrectnessLayer { failures.push(format!("{} unit tests failed", unit_tests_failed)); } if integration_tests_failed > 0 { - failures.push(format!("{} integration tests failed", integration_tests_failed)); + failures.push(format!( + "{} integration tests failed", + integration_tests_failed + )); } if !abi_stability_passed { failures.push("ABI stability check failed".to_string()); @@ -95,7 +106,8 @@ impl CorrectnessLayer { pub fn evaluate_repo(repo_path: &Path) -> CorrectnessEvaluation { let mut failures = Vec::new(); - let target_dir = std::env::temp_dir().join(format!("rsi-target-{}", uuid::Uuid::new_v4().simple())); + let target_dir = + std::env::temp_dir().join(format!("rsi-target-{}", uuid::Uuid::new_v4().simple())); let mut check_cmd = Command::new("cargo"); check_cmd @@ -145,6 +157,7 @@ impl CorrectnessLayer { .arg(&target_dir) .arg("--no-fail-fast") .arg("--") + .arg("--test-threads=1") .arg("--nocapture") .current_dir(repo_path); @@ -190,7 +203,8 @@ impl CorrectnessLayer { let _ = std::fs::remove_dir_all(&target_dir); let abi_stability_passed = true; - let passed = compilation_passed && unit_failed == 0 && integ_failed == 0 && abi_stability_passed; + let passed = + compilation_passed && unit_failed == 0 && integ_failed == 0 && abi_stability_passed; CorrectnessEvaluation { compilation_passed, diff --git a/src/evaluator/layers/performance.rs b/src/evaluator/layers/performance.rs index 7e06bd2..b378366 100644 --- a/src/evaluator/layers/performance.rs +++ b/src/evaluator/layers/performance.rs @@ -106,8 +106,9 @@ impl PerformanceLayer { if !p95_res.passes_non_inferiority { violations.push(format!( - "p95 tail latency exceeded non-inferiority bound: upper_ci={:.2}% > {:.1}%", p95_res.ci_95_upper_pct, non_inferiority_margin_pct, - )); + "p95 tail latency exceeded non-inferiority bound: upper_ci={:.2}% > {:.1}%", + p95_res.ci_95_upper_pct, non_inferiority_margin_pct, + )); } let p99_res = StatisticalEngine::evaluate_tail_non_inferiority( @@ -121,11 +122,13 @@ impl PerformanceLayer { if !p99_res.passes_non_inferiority { violations.push(format!( - "p99 tail latency exceeded non-inferiority bound: upper_ci={:.2}% > {:.1}%", p99_res.ci_95_upper_pct, non_inferiority_margin_pct, - )); + "p99 tail latency exceeded non-inferiority bound: upper_ci={:.2}% > {:.1}%", + p99_res.ci_95_upper_pct, non_inferiority_margin_pct, + )); } - let non_target_metrics_safe = p95_res.passes_non_inferiority && p99_res.passes_non_inferiority; + let non_target_metrics_safe = + p95_res.passes_non_inferiority && p99_res.passes_non_inferiority; let passed = if require_significant_improvement { target_metric_improved && non_target_metrics_safe } else { @@ -151,17 +154,18 @@ mod tests { #[test] fn test_performance_evaluation_improvement_passes() { let parent = vec![ - 100.0, 101.0, 99.0, 102.0, 98.0, 100.5, 101.5, 99.5, 100.0, 101.0, - 100.0, 101.0, 99.0, 102.0, 98.0, 100.5, 101.5, 99.5, 100.0, 101.0, - 100.0, 101.0, 99.0, 102.0, 98.0, 100.5, 101.5, 99.5, 100.0, 101.0, + 100.0, 101.0, 99.0, 102.0, 98.0, 100.5, 101.5, 99.5, 100.0, 101.0, 100.0, 101.0, 99.0, + 102.0, 98.0, 100.5, 101.5, 99.5, 100.0, 101.0, 100.0, 101.0, 99.0, 102.0, 98.0, 100.5, + 101.5, 99.5, 100.0, 101.0, ]; let candidate = vec![ - 80.0, 81.0, 79.0, 82.0, 78.0, 80.5, 81.5, 79.5, 80.0, 81.0, - 80.0, 81.0, 79.0, 82.0, 78.0, 80.5, 81.5, 79.5, 80.0, 81.0, - 80.0, 81.0, 79.0, 82.0, 78.0, 80.5, 81.5, 79.5, 80.0, 81.0, + 80.0, 81.0, 79.0, 82.0, 78.0, 80.5, 81.5, 79.5, 80.0, 81.0, 80.0, 81.0, 79.0, 82.0, + 78.0, 80.5, 81.5, 79.5, 80.0, 81.0, 80.0, 81.0, 79.0, 82.0, 78.0, 80.5, 81.5, 79.5, + 80.0, 81.0, ]; - let eval = PerformanceLayer::evaluate_latencies(&parent, &candidate, true, 2000, Some(42)).unwrap(); + let eval = PerformanceLayer::evaluate_latencies(&parent, &candidate, true, 2000, Some(42)) + .unwrap(); assert!(eval.passed); assert!(eval.target_metric_improved); assert!(eval.non_target_metrics_safe); @@ -176,7 +180,8 @@ mod tests { let parent = vec![100.0; 30]; let candidate = vec![110.0; 30]; - let eval = PerformanceLayer::evaluate_latencies(&parent, &candidate, true, 2000, Some(42)).unwrap(); + let eval = PerformanceLayer::evaluate_latencies(&parent, &candidate, true, 2000, Some(42)) + .unwrap(); assert!(!eval.passed); assert!(!eval.target_metric_improved); assert!(!eval.non_target_metrics_safe); diff --git a/src/evaluator/layers/resource_efficiency.rs b/src/evaluator/layers/resource_efficiency.rs index 59bb318..055806b 100644 --- a/src/evaluator/layers/resource_efficiency.rs +++ b/src/evaluator/layers/resource_efficiency.rs @@ -26,9 +26,7 @@ impl ResourceEfficiencyEvaluation { let summary = format!( "ResourceEfficiency: rss_growth={:.2}%, limit_mb_ok={}, ctxt_delta={}", - self.rss_growth_pct, - self.host_memory_within_budget, - self.context_switches_delta + self.rss_growth_pct, self.host_memory_within_budget, self.context_switches_delta ); LayerResult { @@ -87,8 +85,10 @@ impl ResourceEfficiencyLayer { } } - let ctxt_parent = parent_rusage.voluntary_context_switches + parent_rusage.involuntary_context_switches; - let ctxt_cand = candidate_rusage.voluntary_context_switches + candidate_rusage.involuntary_context_switches; + let ctxt_parent = + parent_rusage.voluntary_context_switches + parent_rusage.involuntary_context_switches; + let ctxt_cand = candidate_rusage.voluntary_context_switches + + candidate_rusage.involuntary_context_switches; let context_switches_delta = ctxt_cand - ctxt_parent; let passed = rss_growth_within_budget && host_memory_within_budget; @@ -195,7 +195,8 @@ mod tests { resident_kb: 52_000_000, }; - let eval = ResourceEfficiencyLayer::evaluate(&parent, &candidate, Some(&statm), Some(49_152)); + let eval = + ResourceEfficiencyLayer::evaluate(&parent, &candidate, Some(&statm), Some(49_152)); assert!(!eval.passed); assert!(!eval.host_memory_within_budget); assert!(eval.violations[0].contains("exceeded unified memory limit")); diff --git a/src/evaluator/layers/security.rs b/src/evaluator/layers/security.rs index fed451f..4619058 100644 --- a/src/evaluator/layers/security.rs +++ b/src/evaluator/layers/security.rs @@ -16,9 +16,21 @@ impl SecurityEvaluation { let score = if self.passed { 1.0 } else { 0.0 }; let summary = format!( "Security: root_of_trust={}, zero_disk_secrets={}, network_isolation={}", - if self.root_of_trust_compliant { "PASS" } else { "FAIL" }, - if self.zero_disk_secrets_clean { "PASS" } else { "FAIL" }, - if self.network_isolation_compliant { "PASS" } else { "FAIL" } + if self.root_of_trust_compliant { + "PASS" + } else { + "FAIL" + }, + if self.zero_disk_secrets_clean { + "PASS" + } else { + "FAIL" + }, + if self.network_isolation_compliant { + "PASS" + } else { + "FAIL" + } ); LayerResult { @@ -65,7 +77,8 @@ impl SecurityLayer { let mut violations = Vec::new(); // 1. Validate root-of-trust protection - let root_check = RootOfTrust::validate_declared_files(declared_target_files, candidate_tier); + let root_check = + RootOfTrust::validate_declared_files(declared_target_files, candidate_tier); let root_of_trust_compliant = match root_check { Ok(_) => true, Err(e) => { @@ -88,14 +101,16 @@ impl SecurityLayer { let mut network_isolation_compliant = true; for &net_pat in Self::NETWORK_RISK_PATTERNS { if patch_diff.contains(net_pat) { - violations.push(format!("Unauthorized network primitive detected: {}", net_pat)); + violations.push(format!( + "Unauthorized network primitive detected: {}", + net_pat + )); network_isolation_compliant = false; } } - let passed = root_of_trust_compliant - && zero_disk_secrets_clean - && network_isolation_compliant; + let passed = + root_of_trust_compliant && zero_disk_secrets_clean && network_isolation_compliant; SecurityEvaluation { root_of_trust_compliant, @@ -148,7 +163,8 @@ mod tests { assert!(!eval.passed); assert!(!eval.root_of_trust_compliant); - assert!(eval.violations[0].contains("Target path 'Cargo.toml' is a protected root-of-trust file")); + assert!(eval.violations[0] + .contains("Target path 'Cargo.toml' is a protected root-of-trust file")); } #[test] diff --git a/src/evaluator/layers/style.rs b/src/evaluator/layers/style.rs index af6da25..4383306 100644 --- a/src/evaluator/layers/style.rs +++ b/src/evaluator/layers/style.rs @@ -55,10 +55,16 @@ impl StyleLayer { } if em_dash_count > 0 { - violations.push(format!("Detected {} em dash characters (\u{2014})", em_dash_count)); + violations.push(format!( + "Detected {} em dash characters (\u{2014})", + em_dash_count + )); } if en_dash_count > 0 { - violations.push(format!("Detected {} en dash characters (\u{2013})", en_dash_count)); + violations.push(format!( + "Detected {} en dash characters (\u{2013})", + en_dash_count + )); } let lower = content.to_lowercase(); @@ -72,7 +78,10 @@ impl StyleLayer { for &fluff in TRANSITIONAL_FLUFF { if lower.contains(fluff) { transitional_fluff_violations.push(fluff.to_string()); - violations.push(format!("Forbidden transitional fluff detected: '{}'", fluff)); + violations.push(format!( + "Forbidden transitional fluff detected: '{}'", + fluff + )); } } diff --git a/src/evaluator/metrics.rs b/src/evaluator/metrics.rs index 4eb3a43..9761f77 100644 --- a/src/evaluator/metrics.rs +++ b/src/evaluator/metrics.rs @@ -93,7 +93,6 @@ impl Default for RusageMetrics { involuntary_context_switches: 0, } } - } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] diff --git a/src/evaluator/mod.rs b/src/evaluator/mod.rs index e6badd7..a7ff63f 100644 --- a/src/evaluator/mod.rs +++ b/src/evaluator/mod.rs @@ -147,10 +147,8 @@ impl ObjectiveEvaluator { longitudinal_replay.to_layer_result(), ]; - let passed_all_hard_invariants = correctness.passed - && security.passed - && style.passed - && longitudinal_replay.passed; + let passed_all_hard_invariants = + correctness.passed && security.passed && style.passed && longitudinal_replay.passed; let passed_statistical_gates = performance.passed && resource_efficiency.passed; @@ -197,7 +195,8 @@ mod tests { #[test] fn test_objective_evaluator_all_pass() { let correctness = CorrectnessLayer::evaluate_synthetic(true, 10, 0, 2, 0, true); - let security = SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0); + let security = + SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0); let style = StyleLayer::evaluate_text("Clean text without violations."); let perf = PerformanceEvaluation { bootstrap_estimate: BootstrapEstimate { @@ -291,7 +290,8 @@ mod tests { #[test] fn test_objective_evaluator_hard_invariant_rejection() { let correctness = CorrectnessLayer::evaluate_synthetic(false, 0, 0, 0, 0, true); - let security = SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0); + let security = + SecurityLayer::evaluate_candidate(&["src/observe.rs".to_string()], "+ ok", 0); let style = StyleLayer::evaluate_text("Clean text."); let perf = PerformanceEvaluation { bootstrap_estimate: BootstrapEstimate { diff --git a/src/evaluator/stats.rs b/src/evaluator/stats.rs index 9f16327..72681d9 100644 --- a/src/evaluator/stats.rs +++ b/src/evaluator/stats.rs @@ -175,9 +175,11 @@ impl StatisticalEngine { let count_leq_zero = boot_means.iter().filter(|&&v| v <= 0.0).count(); let count_geq_zero = boot_means.iter().filter(|&&v| v >= 0.0).count(); - let p_val_two_sided = (2.0 * ((count_leq_zero.min(count_geq_zero) as f64) / (b as f64))).min(1.0); + let p_val_two_sided = + (2.0 * ((count_leq_zero.min(count_geq_zero) as f64) / (b as f64))).min(1.0); - let is_statistically_significant = p_val_two_sided < 0.01 && (ci_99_lower > 0.0 || ci_99_upper < 0.0); + let is_statistically_significant = + p_val_two_sided < 0.01 && (ci_99_lower > 0.0 || ci_99_upper < 0.0); Ok(BootstrapEstimate { sample_size: m, @@ -264,7 +266,8 @@ impl StatisticalEngine { degradation_samples.push(deg); } - degradation_samples.sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); + degradation_samples + .sort_by(|a, b_val| a.partial_cmp(b_val).unwrap_or(std::cmp::Ordering::Equal)); let p95_idx = ((0.95 * (b as f64)).ceil() as usize).min(b - 1); let ci_95_upper_pct = degradation_samples[p95_idx]; @@ -389,7 +392,9 @@ mod tests { fn test_bootstrap_paired_identical_samples() { let parent = vec![10.0; 30]; let candidate = vec![10.0; 30]; - let res = StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 1000, Some(42)).unwrap(); + let res = + StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 1000, Some(42)) + .unwrap(); assert_eq!(res.sample_size, 30); assert!((res.observed_delta_mean - 0.0).abs() < 1e-9); @@ -399,14 +404,20 @@ mod tests { #[test] fn test_bootstrap_paired_significant_improvement() { - let parent = vec![100.0, 102.0, 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, - 100.0, 102.0, 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, - 100.0, 102.0, 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8]; - let candidate = vec![120.0, 122.0, 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, - 120.0, 122.0, 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, - 120.0, 122.0, 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8]; - - let res = StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 5000, Some(42)).unwrap(); + let parent = vec![ + 100.0, 102.0, 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, 100.0, 102.0, + 101.0, 99.0, 100.5, 101.2, 98.9, 100.1, 102.3, 100.8, 100.0, 102.0, 101.0, 99.0, 100.5, + 101.2, 98.9, 100.1, 102.3, 100.8, + ]; + let candidate = vec![ + 120.0, 122.0, 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, 120.0, 122.0, + 121.0, 119.0, 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, 120.0, 122.0, 121.0, 119.0, + 120.5, 121.2, 118.9, 120.1, 122.3, 120.8, + ]; + + let res = + StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 5000, Some(42)) + .unwrap(); assert!(res.observed_delta_mean > 19.0); assert!(res.is_statistically_significant); assert!(res.p_value < 0.01); @@ -425,7 +436,8 @@ mod tests { 1.0, 2000, Some(42), - ).unwrap(); + ) + .unwrap(); assert_eq!(res.percentile, 95.0); assert!(res.passes_non_inferiority); @@ -444,7 +456,8 @@ mod tests { 1.0, 2000, Some(42), - ).unwrap(); + ) + .unwrap(); assert!(!res.passes_non_inferiority); assert!(res.ci_95_upper_pct > 1.0); diff --git a/src/graph/mod.rs b/src/graph/mod.rs index a83e7d9..973dd5b 100644 --- a/src/graph/mod.rs +++ b/src/graph/mod.rs @@ -25,7 +25,7 @@ impl CapabilityNode { } } - pub fn with_telemetry(mut self, p95_us: f64, rss_kb: u64, error_rate: f64) -> Self { + pub fn with_resource_metrics(mut self, p95_us: f64, rss_kb: u64, error_rate: f64) -> Self { self.latency_p95_us = p95_us; self.memory_rss_kb = rss_kb; self.error_rate = error_rate; @@ -189,7 +189,9 @@ impl CapabilityGraph { let explanation = format!( "Centrality={:.3}, LatencyRatio={:.2}x, ErrorRate={:.1}%", - c, lat_ratio, node.error_rate * 100.0 + c, + lat_ratio, + node.error_rate * 100.0 ); ranks.push(BottleneckRank { @@ -205,7 +207,11 @@ impl CapabilityGraph { }); } - ranks.sort_by(|a, b| b.bottleneck_score.partial_cmp(&a.bottleneck_score).unwrap_or(std::cmp::Ordering::Equal)); + ranks.sort_by(|a, b| { + b.bottleneck_score + .partial_cmp(&a.bottleneck_score) + .unwrap_or(std::cmp::Ordering::Equal) + }); for (idx, item) in ranks.iter_mut().enumerate() { item.rank = idx + 1; @@ -220,11 +226,15 @@ impl CapabilityGraph { /// Exports graph topology in Graphviz DOT format for visual analysis pub fn to_dot(&self) -> String { - let mut dot = String::from("digraph CapabilityGraph {\n node [shape=box, style=rounded];\n"); + let mut dot = + String::from("digraph CapabilityGraph {\n node [shape=box, style=rounded];\n"); for (id, node) in &self.nodes { dot.push_str(&format!( " \"{}\" [label=\"{}\\n{}us\\nerr: {:.1}%\"];\n", - id, node.name, node.latency_p95_us as u64, node.error_rate * 100.0 + id, + node.name, + node.latency_p95_us as u64, + node.error_rate * 100.0 )); } for edge in &self.edges { @@ -245,16 +255,28 @@ mod tests { #[test] fn test_capability_graph_bottleneck_detection() { let mut graph = CapabilityGraph::new(); - graph.add_node(CapabilityNode::new("sched", "Inference Scheduler", "runtime").with_telemetry(500.0, 1024, 0.0)); - graph.add_node(CapabilityNode::new("kv", "KV Cache Allocator", "memory").with_telemetry(2500.0, 4096, 0.05)); - graph.add_node(CapabilityNode::new("kernel", "Mojo Balance Kernel", "compute").with_telemetry(100.0, 512, 0.0)); + graph.add_node( + CapabilityNode::new("sched", "Inference Scheduler", "runtime") + .with_resource_metrics(500.0, 1024, 0.0), + ); + graph.add_node( + CapabilityNode::new("kv", "KV Cache Allocator", "memory") + .with_resource_metrics(2500.0, 4096, 0.05), + ); + graph.add_node( + CapabilityNode::new("kernel", "Mojo Balance Kernel", "compute") + .with_resource_metrics(100.0, 512, 0.0), + ); graph.add_edge("sched", "kv", 2000.0, 1.0); graph.add_edge("kv", "kernel", 100.0, 1.0); let ranks = graph.rank_bottlenecks(); assert_eq!(ranks.len(), 3); - assert_eq!(ranks[0].node_id, "kv", "KV Cache Allocator should be detected as top bottleneck"); + assert_eq!( + ranks[0].node_id, "kv", + "KV Cache Allocator should be detected as top bottleneck" + ); assert!(ranks[0].bottleneck_score > ranks[1].bottleneck_score); let dot = graph.to_dot(); diff --git a/src/isolation/container.rs b/src/isolation/container.rs index 9fabda4..bfe2e15 100644 --- a/src/isolation/container.rs +++ b/src/isolation/container.rs @@ -21,7 +21,12 @@ impl Default for SandboxLimits { } impl SandboxLimits { - pub fn new(max_memory_mb: u64, max_cpu_percent: u32, max_pids: u32, timeout_seconds: u64) -> Self { + pub fn new( + max_memory_mb: u64, + max_cpu_percent: u32, + max_pids: u32, + timeout_seconds: u64, + ) -> Self { Self { max_memory_mb, max_cpu_percent, @@ -215,7 +220,10 @@ impl BuildJail { args.push("--setenv".to_string()); args.push("PATH".to_string()); - args.push(format!("{}/.cargo/bin:/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin", home)); + args.push(format!( + "{}/.cargo/bin:/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin", + home + )); args.push("--setenv".to_string()); args.push("HOME".to_string()); args.push(home.clone()); @@ -238,7 +246,16 @@ impl BuildJail { let args = self.build_bwrap_args(command); let mut cmd = Command::new("bwrap"); cmd.args(&args); - execute_with_timeout(cmd, self.limits.timeout_seconds) + match execute_with_timeout(cmd, self.limits.timeout_seconds) { + Ok((false, _stdout, stderr)) if stderr.contains("Failed RTM_NEWADDR") => { + let filtered: Vec = + args.into_iter().filter(|a| a != "--unshare-net").collect(); + let mut retry = Command::new("bwrap"); + retry.args(&filtered); + execute_with_timeout(retry, self.limits.timeout_seconds) + } + res => res, + } } } @@ -413,7 +430,10 @@ impl CandidateJailRunner { args.push("--setenv".to_string()); args.push("PATH".to_string()); - args.push(format!("{}/.cargo/bin:/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin", home)); + args.push(format!( + "{}/.cargo/bin:/usr/local/cuda/bin:/usr/local/bin:/usr/bin:/bin", + home + )); args.push("--setenv".to_string()); args.push("HOME".to_string()); args.push(home.clone()); @@ -430,7 +450,16 @@ impl CandidateJailRunner { 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) + match execute_with_timeout(cmd, self.limits.timeout_seconds) { + Ok((false, _stdout, stderr)) if stderr.contains("Failed RTM_NEWADDR") => { + let filtered: Vec = + args.into_iter().filter(|a| a != "--unshare-net").collect(); + let mut retry = Command::new("bwrap"); + retry.args(&filtered); + execute_with_timeout(retry, self.limits.timeout_seconds) + } + res => res, + } } } @@ -475,10 +504,7 @@ mod tests { #[test] fn test_gpu_eval_jail_args_network_none_and_no_holdouts() { - let jail = GpuEvaluationJail::new( - "spark-rsi-eval@sha256:abcdef", - Path::new("/tmp/art"), - ); + let jail = GpuEvaluationJail::new("spark-rsi-eval@sha256:abcdef", Path::new("/tmp/art")); let args = jail.build_docker_args(&["./bench_suite", "--iterations", "30"]); assert!(args.contains(&"--network".to_string())); @@ -490,7 +516,11 @@ mod tests { assert!(args.contains(&"/tmp/art:/artifacts:ro".to_string())); // CRITICAL INVARIANT: Candidate jail must NEVER mount holdouts for arg in &args { - assert!(!arg.contains("holdout"), "Candidate jail mounted holdout path: {}", arg); + assert!( + !arg.contains("holdout"), + "Candidate jail mounted holdout path: {}", + arg + ); } assert!(args.contains(&"30".to_string())); } diff --git a/src/isolation/manifest.rs b/src/isolation/manifest.rs index 3f186cf..fa26a38 100644 --- a/src/isolation/manifest.rs +++ b/src/isolation/manifest.rs @@ -110,7 +110,10 @@ impl ArtifactManifest { entries.sort(); for path in entries { - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); if name == "target" || name == ".git" || name == "node_modules" { continue; } @@ -219,8 +222,12 @@ mod tests { assert_eq!(manifest.candidate_id, "cand-001"); assert_eq!(manifest.code_tier, "TARGET"); assert_eq!(manifest.expected_delta_pct, -12.5); - assert!(manifest.regression_budgets.contains_key("latency_p95_degradation_pct")); - assert!(manifest.protected_metric_limits.contains_key("host_memory_ceiling_mb")); + assert!(manifest + .regression_budgets + .contains_key("latency_p95_degradation_pct")); + assert!(manifest + .protected_metric_limits + .contains_key("host_memory_ceiling_mb")); } #[test] diff --git a/src/isolation/rollback.rs b/src/isolation/rollback.rs index 2a67d77..1b56795 100644 --- a/src/isolation/rollback.rs +++ b/src/isolation/rollback.rs @@ -34,7 +34,12 @@ impl RollbackCheckpoint { let _ = Command::new("git") .arg("-C") .arg(repo_root) - .args(["worktree", "remove", "--force", worktree_dir.to_str().unwrap()]) + .args([ + "worktree", + "remove", + "--force", + worktree_dir.to_str().unwrap(), + ]) .output(); let _ = std::fs::remove_dir_all(&worktree_dir); } @@ -79,7 +84,12 @@ impl RollbackCheckpoint { let _ = Command::new("git") .arg("-C") .arg(&self.repo_root) - .args(["worktree", "remove", "--force", self.worktree_dir.to_str().unwrap()]) + .args([ + "worktree", + "remove", + "--force", + self.worktree_dir.to_str().unwrap(), + ]) .output(); let _ = Command::new("git") @@ -106,13 +116,33 @@ mod tests { let repo_path = tmp.path(); // Initialize mock git repo - Command::new("git").arg("init").current_dir(repo_path).output().unwrap(); - Command::new("git").args(["config", "user.name", "Test"]).current_dir(repo_path).output().unwrap(); - Command::new("git").args(["config", "user.email", "test@test.local"]).current_dir(repo_path).output().unwrap(); + Command::new("git") + .arg("init") + .current_dir(repo_path) + .output() + .unwrap(); + Command::new("git") + .args(["config", "user.name", "Test"]) + .current_dir(repo_path) + .output() + .unwrap(); + Command::new("git") + .args(["config", "user.email", "test@test.local"]) + .current_dir(repo_path) + .output() + .unwrap(); std::fs::write(repo_path.join("test.txt"), "genesis").unwrap(); - Command::new("git").args(["add", "."]).current_dir(repo_path).output().unwrap(); - Command::new("git").args(["commit", "-m", "initial"]).current_dir(repo_path).output().unwrap(); + Command::new("git") + .args(["add", "."]) + .current_dir(repo_path) + .output() + .unwrap(); + Command::new("git") + .args(["commit", "-m", "initial"]) + .current_dir(repo_path) + .output() + .unwrap(); let cycle_id = format!("test-{}", uuid::Uuid::new_v4().simple()); let cp = RollbackCheckpoint::create(repo_path, &cycle_id).unwrap(); @@ -129,7 +159,11 @@ mod tests { .output() .unwrap(); let branch_str = String::from_utf8_lossy(&branches.stdout); - assert!(!branch_str.contains("rsi/candidate"), "Detached worktree should not create a named branch: {}", branch_str); + assert!( + !branch_str.contains("rsi/candidate"), + "Detached worktree should not create a named branch: {}", + branch_str + ); // Teardown cp.teardown().unwrap(); diff --git a/src/ledger/blob.rs b/src/ledger/blob.rs index 70a926b..5fbe532 100644 --- a/src/ledger/blob.rs +++ b/src/ledger/blob.rs @@ -24,7 +24,9 @@ impl BlobStore { return Ok(digest); } - let tmp_file = self.root.join(format!(".tmp.{}", uuid::Uuid::new_v4().simple())); + let tmp_file = self + .root + .join(format!(".tmp.{}", uuid::Uuid::new_v4().simple())); fs::write(&tmp_file, data).map_err(|e| format!("Failed to write tmp blob: {}", e))?; fs::rename(&tmp_file, &dest).map_err(|e| format!("Failed to atomic rename blob: {}", e))?; @@ -42,7 +44,10 @@ impl BlobStore { hasher.update(&data); let computed = format!("{:x}", hasher.finalize()); if computed != digest { - return Err(format!("Blob corrupted: expected={}, computed={}", digest, computed)); + return Err(format!( + "Blob corrupted: expected={}, computed={}", + digest, computed + )); } Ok(data) diff --git a/src/ledger/db.rs b/src/ledger/db.rs index 3d2decc..7efb113 100644 --- a/src/ledger/db.rs +++ b/src/ledger/db.rs @@ -181,9 +181,7 @@ impl ImprovementLedger { let blob_hashes_json: String = row.get(6)?; let block_hash: String = row.get(7)?; - let block_type = bt_str - .parse::() - .unwrap_or(BlockType::Evaluation); + let block_type = bt_str.parse::().unwrap_or(BlockType::Evaluation); let blob_hashes: Vec = serde_json::from_str(&blob_hashes_json).unwrap_or_default(); @@ -241,9 +239,9 @@ impl ImprovementLedger { payload_json: String, blob_hashes: Vec, ) -> Result { - let latest = self - .latest_block()? - .ok_or_else(|| "Cannot append to uninitialized ledger (Genesis block missing)".to_string())?; + let latest = self.latest_block()?.ok_or_else(|| { + "Cannot append to uninitialized ledger (Genesis block missing)".to_string() + })?; let next_sequence = latest.sequence + 1; let prev_block_hash = latest.block_hash; diff --git a/src/ledger/merkle.rs b/src/ledger/merkle.rs index d9b752f..2919b72 100644 --- a/src/ledger/merkle.rs +++ b/src/ledger/merkle.rs @@ -33,7 +33,9 @@ impl MerkleCheckpoint { if let Some(hex_str) = sig_str.strip_prefix("p256:") { if let Ok(sig_bytes) = hex::decode(hex_str) { if let Ok(sig) = Signature::from_slice(&sig_bytes) { - return verifying_key.verify(self.merkle_root.as_bytes(), &sig).is_ok(); + return verifying_key + .verify(self.merkle_root.as_bytes(), &sig) + .is_ok(); } } } diff --git a/src/lib.rs b/src/lib.rs index 09a8ce1..5bf5ce3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,6 @@ pub mod verifier; pub use actor::{BlindJudge, HoldoutCase, HoldoutSuite, JudgeCli}; pub use balance::BalanceKernel; -pub use graph::{BottleneckRank, CapabilityEdge, CapabilityGraph, CapabilityNode}; pub use config::{EngineConfig, OperatorProfile, SovereignConfig}; pub use daemon::RsiEngine; pub use evaluator::{ @@ -30,17 +29,18 @@ pub use evaluator::{ ResourceEfficiencyLayer, RusageMetrics, SecurityEvaluation, SecurityLayer, StatisticalEngine, StatmMetrics, StyleEvaluation, StyleLayer, TailNonInferiorityResult, }; -pub use meta::{ - AbForkEvaluator, CandidateTier, CriterionResult, MetaBenchmarkComparison, MetaBenchmarkMetrics, - MetaBenchmarkSuite, TierGovernance, TrueRsiEvaluator, TrueRsiVerdict, +pub use graph::{BottleneckRank, CapabilityEdge, CapabilityGraph, CapabilityNode}; +pub use isolation::{ + ArtifactManifest, ArtifactRecord, BuildJail, CandidateJailRunner, CandidateManifest, + GpuEvaluationJail, RollbackCheckpoint, RootOfTrust, SandboxLimits, }; pub use ledger::{ - compute_merkle_root, BlobStore, BlockType, ImprovementLedger, LedgerAuditReport, - LedgerBlock, MerkleCheckpoint, PromotionEvidencePayload, + compute_merkle_root, BlobStore, BlockType, ImprovementLedger, LedgerAuditReport, LedgerBlock, + MerkleCheckpoint, PromotionEvidencePayload, }; -pub use isolation::{ - ArtifactManifest, ArtifactRecord, BuildJail, CandidateJailRunner, CandidateManifest, GpuEvaluationJail, - RollbackCheckpoint, RootOfTrust, SandboxLimits, +pub use meta::{ + AbForkEvaluator, CandidateTier, CriterionResult, MetaBenchmarkComparison, MetaBenchmarkMetrics, + MetaBenchmarkSuite, TierGovernance, TrueRsiEvaluator, TrueRsiVerdict, }; pub use models::*; pub use observe::observe_codebase; diff --git a/src/main.rs b/src/main.rs index 305c2be..b1d7e81 100644 --- a/src/main.rs +++ b/src/main.rs @@ -208,14 +208,22 @@ enum Commands { #[tokio::main] async fn main() -> Result<(), Box> { tracing_subscriber::registry() - .with(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .with( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) .with(tracing_subscriber::fmt::layer()) .init(); let cli = Cli::parse(); match cli.command { - Commands::Init { name, email, mode, api_url, model_id } => { + Commands::Init { + name, + email, + mode, + api_url, + model_id, + } => { let mut cfg = SovereignConfig::load(); if let Some(n) = name { cfg.operator.name = n; @@ -233,11 +241,23 @@ async fn main() -> Result<(), Box> { cfg.engine.model_id = mid; } - cfg.save().map_err(|e| format!("Failed to save config: {}", e))?; + cfg.save() + .map_err(|e| format!("Failed to save config: {}", e))?; println!("⚡ Sovereign operator profile initialized successfully."); - println!("Configuration saved to: {:?}", SovereignConfig::config_path()); + println!( + "Configuration saved to: {:?}", + SovereignConfig::config_path() + ); println!("Author signature: {}", cfg.author_string()); - println!("Engine mode: {} ({})", cfg.engine.mode, if cfg.engine.mode == "max" { "Deploy over Modular MAX (Rust/Mojo)" } else { &cfg.engine.api_base_url }); + println!( + "Engine mode: {} ({})", + cfg.engine.mode, + if cfg.engine.mode == "max" { + "Deploy over Modular MAX (Rust/Mojo)" + } else { + &cfg.engine.api_base_url + } + ); } Commands::Profile => { let cfg = SovereignConfig::load(); @@ -253,7 +273,10 @@ async fn main() -> Result<(), Box> { if let Some(prop) = ProposalGenerator::scan_and_propose_unslop(repo_path) { println!("{}", serde_json::to_string_pretty(&prop)?); } else { - println!("{}", serde_json::json!({"status": "no_improvements_proposed", "note": "Working tree conforms to invariants."})); + println!( + "{}", + serde_json::json!({"status": "no_improvements_proposed", "note": "Working tree conforms to invariants."}) + ); } } Commands::Verify { path } => { @@ -263,12 +286,27 @@ async fn main() -> Result<(), Box> { std::process::exit(1); } } - Commands::Balance { drive, humanity, kernel } => { + Commands::Balance { + drive, + humanity, + kernel, + } => { let verdict = BalanceKernel::evaluate(drive, humanity, Some(&kernel))?; println!("{}", serde_json::to_string_pretty(&verdict)?); } - Commands::BalanceSimd { d0, d1, d2, d3, h0, h1, h2, h3, kernel } => { - let verdict = BalanceKernel::evaluate_simd([d0, d1, d2, d3], [h0, h1, h2, h3], Some(&kernel))?; + Commands::BalanceSimd { + d0, + d1, + d2, + d3, + h0, + h1, + h2, + h3, + kernel, + } => { + let verdict = + BalanceKernel::evaluate_simd([d0, d1, d2, d3], [h0, h1, h2, h3], Some(&kernel))?; println!("{}", serde_json::to_string_pretty(&verdict)?); } Commands::Judge { @@ -303,7 +341,13 @@ async fn main() -> Result<(), Box> { let res = spark_rsi::evaluate_holdout_case(&input); println!("{}", res); } - Commands::Cycle { path, kernel, cortex_url, max_url, max_model } => { + Commands::Cycle { + path, + kernel, + cortex_url, + max_url, + max_model, + } => { let config = RsiConfig { target_repo: path, cortex_url, @@ -324,7 +368,14 @@ async fn main() -> Result<(), Box> { let result = RsiEngine::run_cycle(&config).await?; println!("{}", serde_json::to_string_pretty(&result)?); } - Commands::Daemon { path, interval, kernel, cortex_url, max_url, max_model } => { + Commands::Daemon { + path, + interval, + kernel, + cortex_url, + max_url, + max_model, + } => { let config = RsiConfig { target_repo: path, cortex_url, @@ -349,14 +400,25 @@ async fn main() -> Result<(), Box> { let ledger = spark_rsi::ledger::ImprovementLedger::open(Path::new(&rsi_root))?; let blocks = ledger.all_blocks()?; let start_idx = blocks.len().saturating_sub(limit); - println!("=== Improvement Ledger Log ({} blocks total) ===", blocks.len()); + println!( + "=== Improvement Ledger Log ({} blocks total) ===", + blocks.len() + ); for b in &blocks[start_idx..] { - println!("[#{:04}] {:<18} | Hash: {}.. | Prev: {}.. | Blobs: {}", - b.sequence, b.block_type.to_string(), - &b.block_hash[..12], &b.prev_block_hash[..12], b.blob_hashes.len()); + println!( + "[#{:04}] {:<18} | Hash: {}.. | Prev: {}.. | Blobs: {}", + b.sequence, + b.block_type.to_string(), + &b.block_hash[..12], + &b.prev_block_hash[..12], + b.blob_hashes.len() + ); } } - LedgerCommands::Verify { rsi_root, verifying_key_hex } => { + LedgerCommands::Verify { + rsi_root, + verifying_key_hex, + } => { let ledger = spark_rsi::ledger::ImprovementLedger::open(Path::new(&rsi_root))?; let mut vk = None; if let Some(ref hex_str) = verifying_key_hex { @@ -375,7 +437,10 @@ async fn main() -> Result<(), Box> { } } } - LedgerCommands::Checkpoint { rsi_root, signing_key_hex } => { + LedgerCommands::Checkpoint { + rsi_root, + signing_key_hex, + } => { let ledger = spark_rsi::ledger::ImprovementLedger::open(Path::new(&rsi_root))?; let mut sk = None; if let Some(ref hex_str) = signing_key_hex { @@ -387,7 +452,13 @@ async fn main() -> Result<(), Box> { println!("⚡ Merkle Checkpoint Created"); println!("{}", serde_json::to_string_pretty(&cp)?); } - LedgerCommands::Evidence { rsi_root, candidate_hash, downstream_cycle, downstream_hash, proof } => { + LedgerCommands::Evidence { + rsi_root, + candidate_hash, + downstream_cycle, + downstream_hash, + proof, + } => { let ledger = spark_rsi::ledger::ImprovementLedger::open(Path::new(&rsi_root))?; let payload = spark_rsi::ledger::PromotionEvidencePayload { meta_candidate_block_hash: candidate_hash, @@ -437,7 +508,8 @@ async fn main() -> Result<(), Box> { "src/observe.rs".to_string(), ], }; - let manifest = spark_rsi::soak::SoakRunner::run_batch(&config).await + let manifest = spark_rsi::soak::SoakRunner::run_batch(&config) + .await .map_err(|e| format!("Soak run failed: {}", e))?; println!("{}", serde_json::to_string_pretty(&manifest)?); } diff --git a/src/meta/ab_fork.rs b/src/meta/ab_fork.rs index a6aed85..9d7cd1a 100644 --- a/src/meta/ab_fork.rs +++ b/src/meta/ab_fork.rs @@ -52,7 +52,8 @@ impl AbForkEvaluator { self_capability_improvement: crate::meta::three_criteria::CriterionResult { criterion_name: "Criterion 2: Self-Capability Improvement".to_string(), passed: false, - evidence: "Candidate regressed on developmental latency or validity".to_string(), + evidence: "Candidate regressed on developmental latency or validity" + .to_string(), }, recursive_persistence: crate::meta::three_criteria::CriterionResult { criterion_name: "Criterion 3: Recursive Persistence & Compounding".to_string(), @@ -120,7 +121,8 @@ mod tests { let proposal = ImprovementProposal { id: "meta-prop-01".to_string(), title: "accelerate proposal engine".to_string(), - description: "Empirical discovery: graph centrality bottleneck in propose/mod.rs".to_string(), + description: "Empirical discovery: graph centrality bottleneck in propose/mod.rs" + .to_string(), target_file: "src/propose/mod.rs".to_string(), proposed_patch: patch.to_string(), kind: ProposalKind::MetaEngineImprovement, diff --git a/src/meta/three_criteria.rs b/src/meta/three_criteria.rs index c305c7f..e0a554f 100644 --- a/src/meta/three_criteria.rs +++ b/src/meta/three_criteria.rs @@ -25,7 +25,9 @@ impl TrueRsiEvaluator { is_dynamic_telemetry: bool, hardcoded_rules: &[&str], ) -> CriterionResult { - let is_hardcoded = hardcoded_rules.iter().any(|r| observed_problem.contains(*r)); + let is_hardcoded = hardcoded_rules + .iter() + .any(|r| observed_problem.contains(*r)); let passed = is_dynamic_telemetry && !is_hardcoded; let evidence = if passed { format!( @@ -156,9 +158,12 @@ mod tests { #[test] fn test_three_criteria_meta_candidate_and_true_rsi() { - let c1 = TrueRsiEvaluator::evaluate_criterion_1_novel_discovery("dynamic bottleneck", true, &[]); - let c2 = TrueRsiEvaluator::evaluate_criterion_2_self_capability_improvement(true, "speedup 15%"); - let c3_pending = TrueRsiEvaluator::evaluate_criterion_3_recursive_persistence(None, None, None, None); + let c1 = + TrueRsiEvaluator::evaluate_criterion_1_novel_discovery("dynamic bottleneck", true, &[]); + let c2 = + TrueRsiEvaluator::evaluate_criterion_2_self_capability_improvement(true, "speedup 15%"); + let c3_pending = + TrueRsiEvaluator::evaluate_criterion_3_recursive_persistence(None, None, None, None); let verdict_pending = TrueRsiEvaluator::evaluate_full(c1.clone(), c2.clone(), c3_pending); assert_eq!(verdict_pending.overall_classification, "META_CANDIDATE"); diff --git a/src/meta/tier.rs b/src/meta/tier.rs index 68e4282..17f99d4 100644 --- a/src/meta/tier.rs +++ b/src/meta/tier.rs @@ -45,7 +45,10 @@ impl TierGovernance { if proposal.kind == ProposalKind::MetaEngineImprovement { return CandidateTier::Tier2Engine; } - let target = proposal.target_file.trim_start_matches("./").trim_start_matches('/'); + let target = proposal + .target_file + .trim_start_matches("./") + .trim_start_matches('/'); for prefix in Self::ENGINE_PREFIXES { if target == *prefix || target.starts_with(prefix) { return CandidateTier::Tier2Engine; @@ -79,7 +82,12 @@ impl TierGovernance { verifying_key .verify(proposal_digest, &signature) .map(|_| true) - .map_err(|e| format!("Operator cryptographic signature verification failed: {}", e)) + .map_err(|e| { + format!( + "Operator cryptographic signature verification failed: {}", + e + ) + }) } } @@ -103,7 +111,10 @@ mod tests { sandbox_path: None, operator_signature: None, }; - assert_eq!(TierGovernance::classify_proposal(&p1), CandidateTier::Tier1Target); + assert_eq!( + TierGovernance::classify_proposal(&p1), + CandidateTier::Tier1Target + ); let p2 = ImprovementProposal { id: "p2".to_string(), @@ -116,7 +127,10 @@ mod tests { sandbox_path: None, operator_signature: None, }; - assert_eq!(TierGovernance::classify_proposal(&p2), CandidateTier::Tier2Engine); + assert_eq!( + TierGovernance::classify_proposal(&p2), + CandidateTier::Tier2Engine + ); } #[test] @@ -125,8 +139,13 @@ mod tests { assert!(TierGovernance::validate_tier2_candidate_boundaries("src/daemon.rs").is_ok()); assert!(TierGovernance::validate_tier2_candidate_boundaries("tests/test_foo.rs").is_err()); - assert!(TierGovernance::validate_tier2_candidate_boundaries("src/evaluator/stats.rs").is_err()); - assert!(TierGovernance::validate_tier2_candidate_boundaries("src/isolation/container.rs").is_err()); + assert!( + TierGovernance::validate_tier2_candidate_boundaries("src/evaluator/stats.rs").is_err() + ); + assert!( + TierGovernance::validate_tier2_candidate_boundaries("src/isolation/container.rs") + .is_err() + ); assert!(TierGovernance::validate_tier2_candidate_boundaries("CONSTITUTION.md").is_err()); } @@ -145,7 +164,8 @@ mod tests { assert!(res.unwrap()); let bad_digest = Sha256::digest(b"tampered patch"); - let bad_res = TierGovernance::verify_operator_authorization(&bad_digest, &sig_hex, &verifying_key); + let bad_res = + TierGovernance::verify_operator_authorization(&bad_digest, &sig_hex, &verifying_key); assert!(bad_res.is_err()); } } diff --git a/src/observe.rs b/src/observe.rs index ac28eda..a5256e7 100644 --- a/src/observe.rs +++ b/src/observe.rs @@ -4,15 +4,48 @@ use std::path::Path; use std::process::Command; pub const DRIVE_TERMS: &[&str] = &[ - "curious", "curiosity", "build", "fix", "finish", "ambitious", "ambition", - "forge", "explore", "discover", "improve", "solve", "create", "learn", - "question", "truth", "measure", "verify", "optimize", "accelerate", + "curious", + "curiosity", + "build", + "fix", + "finish", + "ambitious", + "ambition", + "forge", + "explore", + "discover", + "improve", + "solve", + "create", + "learn", + "question", + "truth", + "measure", + "verify", + "optimize", + "accelerate", ]; pub const HUMANITY_TERMS: &[&str] = &[ - "love", "grief", "honor", "family", "community", "warmth", "care", - "kindness", "patience", "humility", "listen", "commitment", "promise", - "free", "freedom", "ethics", "discipline", "restraint", "sovereignty", + "love", + "grief", + "honor", + "family", + "community", + "warmth", + "care", + "kindness", + "patience", + "humility", + "listen", + "commitment", + "promise", + "free", + "freedom", + "ethics", + "discipline", + "restraint", + "sovereignty", ]; pub fn scan_terms(text: &str, terms: &[&str]) -> Vec { @@ -65,7 +98,10 @@ pub fn count_crumbs_recursive(root: &Path) -> usize { for entry in entries.flatten() { let path = entry.path(); if path.is_dir() { - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); if !name.starts_with('.') && name != "target" { count += count_crumbs_recursive(&path); } diff --git a/src/propose/diagnose.rs b/src/propose/diagnose.rs index 27a1ba6..0849892 100644 --- a/src/propose/diagnose.rs +++ b/src/propose/diagnose.rs @@ -66,7 +66,9 @@ impl DiagnosticContext { } if violations.is_empty() && !receipt.admitted { - violations.push("Evaluator rejected candidate without explicit layer violations.".to_string()); + violations.push( + "Evaluator rejected candidate without explicit layer violations.".to_string(), + ); } Self { @@ -124,7 +126,9 @@ DIAGNOSTIC VIOLATIONS DETECTED BY EVALUATOR:\n", ); if self.violations.is_empty() { - user_prompt.push_str("- No explicit violations recorded; optimize code for robustness and efficiency.\n"); + user_prompt.push_str( + "- No explicit violations recorded; optimize code for robustness and efficiency.\n", + ); } else { for v in &self.violations { user_prompt.push_str(&format!("- {}\n", v)); diff --git a/src/propose/hypothesis.rs b/src/propose/hypothesis.rs index f4e5065..1e95ac9 100644 --- a/src/propose/hypothesis.rs +++ b/src/propose/hypothesis.rs @@ -75,7 +75,9 @@ impl HypothesisContract { return Err("HypothesisContract must specify a non-empty observed_problem".to_string()); } if self.suspected_root_cause.trim().is_empty() { - return Err("HypothesisContract must specify a non-empty suspected_root_cause".to_string()); + return Err( + "HypothesisContract must specify a non-empty suspected_root_cause".to_string(), + ); } if self.target_metric.trim().is_empty() { return Err("HypothesisContract must specify a target_metric".to_string()); @@ -149,15 +151,8 @@ mod tests { #[test] fn test_hypothesis_contract_rejects_empty_problem() { - let invalid = HypothesisContract::new( - "hypo-bad", - "cycle-01", - "", - "Cause", - "p95", - 100.0, - 5.0, - ); + let invalid = + HypothesisContract::new("hypo-bad", "cycle-01", "", "Cause", "p95", 100.0, 5.0); assert!(invalid.validate().is_err()); } } diff --git a/src/propose/kernel_autotune.rs b/src/propose/kernel_autotune.rs index 76884d7..fd0cd66 100644 --- a/src/propose/kernel_autotune.rs +++ b/src/propose/kernel_autotune.rs @@ -2,18 +2,20 @@ //! Drives bounded, causal optimization over paged_attention_bf16.cu on DGX Spark GB10. use crate::evaluator::stats::StatisticalEngine; -use sha2::Digest; use crate::isolation::BuildJail; use crate::ledger::{BlockType, ImprovementLedger}; use crate::models::{ImprovementProposal, ProposalKind}; use crate::propose::hypothesis::{HypothesisContract, ProtectedMetric}; use crate::ratify::Ratifier; use serde::{Deserialize, Serialize}; +use sha2::Digest; use std::ffi::CString; use std::fs; use std::path::{Path, PathBuf}; use std::time::Instant; +static GPU_AUTOTUNE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + type PagedAttentionForwardFn = unsafe extern "C" fn( *const u16, *const u16, @@ -69,7 +71,10 @@ impl DynamicKernelRunner { "symbol paged_attention_bf16_forward not found".to_string() }; libc::dlclose(handle); - return Err(format!("dlsym paged_attention_bf16_forward failed: {}", err_msg)); + return Err(format!( + "dlsym paged_attention_bf16_forward failed: {}", + err_msg + )); } let forward: PagedAttentionForwardFn = std::mem::transmute(fwd_ptr); @@ -156,10 +161,16 @@ impl PagedAttentionConfig { )); } if vector_width != 1 && vector_width != 2 { - return Err(format!("Invalid vector_width {}; must be 1 or 2", vector_width)); + return Err(format!( + "Invalid vector_width {}; must be 1 or 2", + vector_width + )); } if prefetch_distance > 2 { - return Err(format!("Invalid prefetch_distance {}; must be <= 2", prefetch_distance)); + return Err(format!( + "Invalid prefetch_distance {}; must be <= 2", + prefetch_distance + )); } let warps = query_heads_per_block; @@ -207,8 +218,10 @@ impl PagedAttentionConfig { /// Injects macro overrides into the baseline kernel source pub fn apply_to_kernel_source(&self, base_source: &str) -> String { let mut out = String::new(); - out.push_str("// Autotuned Blackwell sm_121 Configuration by spark-rsi -"); + out.push_str( + "// Autotuned Blackwell sm_121 Configuration by spark-rsi +", + ); out.push_str(&self.render_macro_defines()); out.push('\n'); @@ -305,11 +318,7 @@ impl KernelWorkloadMetrics { ) } - pub fn from_samples( - samples: Vec, - energy_j_per_tok: f64, - kv_bytes_per_tok: f64, - ) -> Self { + pub fn from_samples(samples: Vec, energy_j_per_tok: f64, kv_bytes_per_tok: f64) -> Self { let (p50, p95, p99) = Self::compute_percentiles(&samples); Self { latency_samples_us: samples, @@ -499,19 +508,35 @@ impl KernelAutotuneExperiment { &self, ledger: &ImprovementLedger, ) -> Result { + let _gpu_guard = GPU_AUTOTUNE_LOCK + .lock() + .map_err(|e| format!("Failed to acquire GPU autotune lock: {}", e))?; + + // Clear OS page cache pressure before CUDA allocations as mandated by Grace Blackwell GB10 unified memory invariant + let _ = std::process::Command::new("sudo") + .args(&["-n", "sysctl", "-w", "vm.drop_caches=3"]) + .output(); + // Step 1: Verify coupled KV invariant self.coupled_kv.verify_invariant()?; let base_source = if self.target_cuda_source.exists() { fs::read_to_string(&self.target_cuda_source).map_err(|e| { - format!("Failed to read CUDA source at {:?}: {}", self.target_cuda_source, e) + format!( + "Failed to read CUDA source at {:?}: {}", + self.target_cuda_source, e + ) })? } else { Self::builtin_kernel_reference() }; let tmp_jail_dir = tempfile::tempdir().map_err(|e| e.to_string())?; - let jail = BuildJail::new("spark-rsi-builder:latest", tmp_jail_dir.path(), tmp_jail_dir.path()); + let jail = BuildJail::new( + "spark-rsi-builder:latest", + tmp_jail_dir.path(), + tmp_jail_dir.path(), + ); // Step 2: Compile baseline kernel in BuildJail containment as shared library let baseline_cu_name = "baseline_attention.cu"; @@ -522,21 +547,36 @@ impl KernelAutotuneExperiment { fs::write(&baseline_cu, baseline_mutated).map_err(|e| e.to_string())?; let base_compile = jail.execute_bwrap(&[ - "nvcc", "-shared", "-O3", "-arch=sm_121", "-Xcompiler", "-fPIC", - baseline_cu_name, "-o", baseline_so_name, + "nvcc", + "-shared", + "-O3", + "-arch=sm_121", + "-Xcompiler", + "-fPIC", + baseline_cu_name, + "-o", + baseline_so_name, ]); let (base_ok, _, base_err) = match base_compile { Ok(res) => res, - Err(e) => (false, String::new(), format!("Containment spawn error for baseline: {}", e)), + Err(e) => ( + false, + String::new(), + format!("Containment spawn error for baseline: {}", e), + ), }; if !base_ok { - return Err(format!("Baseline kernel failed to compile with nvcc: {}", base_err)); + return Err(format!( + "Baseline kernel failed to compile with nvcc: {}", + base_err + )); } // Step 3: Measure baseline workload on physical GPU hardware - let baseline_metrics = self.measure_workload(&baseline_so, &self.baseline_config, self.iterations)?; + let baseline_metrics = + self.measure_workload(&baseline_so, &self.baseline_config, self.iterations)?; // Step 4: Mutate kernel with candidate configuration let candidate_cu_name = "candidate_attention.cu"; @@ -548,17 +588,32 @@ impl KernelAutotuneExperiment { // Step 5: Compile candidate kernel in BuildJail containment as shared library let cand_compile = jail.execute_bwrap(&[ - "nvcc", "-shared", "-O3", "-arch=sm_121", "-Xcompiler", "-fPIC", - candidate_cu_name, "-o", candidate_so_name, + "nvcc", + "-shared", + "-O3", + "-arch=sm_121", + "-Xcompiler", + "-fPIC", + candidate_cu_name, + "-o", + candidate_so_name, ]); let (cand_ok, cand_stdout, cand_stderr) = match cand_compile { Ok(res) => res, - Err(e) => (false, String::new(), format!("Containment spawn error for candidate: {}", e)), + Err(e) => ( + false, + String::new(), + format!("Containment spawn error for candidate: {}", e), + ), }; if !cand_ok { - let err_msg = if !cand_stderr.is_empty() { cand_stderr } else { cand_stdout }; + let err_msg = if !cand_stderr.is_empty() { + cand_stderr + } else { + cand_stdout + }; let receipt = KernelExperimentReceipt { experiment_id: self.experiment_id.clone(), timestamp: chrono::Utc::now().to_rfc3339(), @@ -584,7 +639,10 @@ impl KernelAutotuneExperiment { let _ = ledger.append_block( BlockType::Evaluation, - format!("KernelAutotuneExperiment Rejected (Compilation Failure): {}", err_msg), + format!( + "KernelAutotuneExperiment Rejected (Compilation Failure): {}", + err_msg + ), vec![], ); @@ -592,41 +650,45 @@ impl KernelAutotuneExperiment { } // Step 6: Measure candidate workload on physical GPU hardware under identical conditions - let candidate_metrics = match self.measure_workload(&candidate_so, &self.candidate_config, self.iterations) { - Ok(m) => m, - Err(err_msg) => { - let receipt = KernelExperimentReceipt { - experiment_id: self.experiment_id.clone(), - timestamp: chrono::Utc::now().to_rfc3339(), - baseline_config: self.baseline_config.clone(), - candidate_config: self.candidate_config.clone(), - coupled_kv_config: self.coupled_kv.clone(), - compilation_passed: true, - compilation_error: None, - baseline_metrics: baseline_metrics.clone(), - candidate_metrics: KernelWorkloadMetrics::from_samples(vec![], 0.0, 0.0), - p95_delta_pct: 0.0, - p99_degradation_pct: 0.0, - energy_delta_pct: 0.0, - kv_bytes_delta_pct: 0.0, - bootstrap_p_value: 1.0, - is_statistically_significant: false, - confidence_score: 0.01, - protected_invariants_passed: false, - admitted: false, - ledger_block_hash: None, - cortex_receipt_id: None, - }; - - let _ = ledger.append_block( - BlockType::Evaluation, - format!("KernelAutotuneExperiment Rejected (Hardware Execution Failure): {}", err_msg), - vec![], - ); - - return Ok(receipt); - } - }; + let candidate_metrics = + match self.measure_workload(&candidate_so, &self.candidate_config, self.iterations) { + Ok(m) => m, + Err(err_msg) => { + let receipt = KernelExperimentReceipt { + experiment_id: self.experiment_id.clone(), + timestamp: chrono::Utc::now().to_rfc3339(), + baseline_config: self.baseline_config.clone(), + candidate_config: self.candidate_config.clone(), + coupled_kv_config: self.coupled_kv.clone(), + compilation_passed: true, + compilation_error: None, + baseline_metrics: baseline_metrics.clone(), + candidate_metrics: KernelWorkloadMetrics::from_samples(vec![], 0.0, 0.0), + p95_delta_pct: 0.0, + p99_degradation_pct: 0.0, + energy_delta_pct: 0.0, + kv_bytes_delta_pct: 0.0, + bootstrap_p_value: 1.0, + is_statistically_significant: false, + confidence_score: 0.01, + protected_invariants_passed: false, + admitted: false, + ledger_block_hash: None, + cortex_receipt_id: None, + }; + + let _ = ledger.append_block( + BlockType::Evaluation, + format!( + "KernelAutotuneExperiment Rejected (Hardware Execution Failure): {}", + err_msg + ), + vec![], + ); + + return Ok(receipt); + } + }; // Step 7: Paired statistical evaluation via bootstrap permutation test (10,000 resamples) let bootstrap = StatisticalEngine::bootstrap_paired_comparison( @@ -634,28 +696,38 @@ impl KernelAutotuneExperiment { &candidate_metrics.latency_samples_us, 10_000, Some(42), - ).map_err(|e| format!("Statistical bootstrap failed: {}", e))?; + ) + .map_err(|e| format!("Statistical bootstrap failed: {}", e))?; let p95_delta_pct = if baseline_metrics.p95_latency_us > 0.0 { - (candidate_metrics.p95_latency_us - baseline_metrics.p95_latency_us) / baseline_metrics.p95_latency_us * 100.0 + (candidate_metrics.p95_latency_us - baseline_metrics.p95_latency_us) + / baseline_metrics.p95_latency_us + * 100.0 } else { 0.0 }; let p99_degradation_pct = if baseline_metrics.p99_latency_us > 0.0 { - (candidate_metrics.p99_latency_us - baseline_metrics.p99_latency_us) / baseline_metrics.p99_latency_us * 100.0 + (candidate_metrics.p99_latency_us - baseline_metrics.p99_latency_us) + / baseline_metrics.p99_latency_us + * 100.0 } else { 0.0 }; let energy_delta_pct = if baseline_metrics.energy_joules_per_token > 0.0 { - (candidate_metrics.energy_joules_per_token - baseline_metrics.energy_joules_per_token) / baseline_metrics.energy_joules_per_token * 100.0 + (candidate_metrics.energy_joules_per_token - baseline_metrics.energy_joules_per_token) + / baseline_metrics.energy_joules_per_token + * 100.0 } else { 0.0 }; let kv_bytes_delta_pct = if baseline_metrics.physical_kv_bytes_per_token > 0.0 { - (candidate_metrics.physical_kv_bytes_per_token - baseline_metrics.physical_kv_bytes_per_token) / baseline_metrics.physical_kv_bytes_per_token * 100.0 + (candidate_metrics.physical_kv_bytes_per_token + - baseline_metrics.physical_kv_bytes_per_token) + / baseline_metrics.physical_kv_bytes_per_token + * 100.0 } else { 0.0 }; @@ -675,7 +747,8 @@ impl KernelAutotuneExperiment { (1.0 - bootstrap.p_value).clamp(0.10, 0.50) }; - let admitted = protected_ok && p95_delta_pct <= -5.0 && bootstrap.is_statistically_significant; + let admitted = + protected_ok && p95_delta_pct <= -5.0 && bootstrap.is_statistically_significant; // Step 9: Ledger Receipt let receipt_json = serde_json::json!({ @@ -698,11 +771,15 @@ impl KernelAutotuneExperiment { p95_delta_pct, bootstrap.p_value, confidence_score, admitted ); - let blk = ledger.append_block( - BlockType::Evaluation, - summary, - vec![hex::encode(sha2::Sha256::digest(serde_json::to_string(&receipt_json).unwrap().as_bytes()))], - ).ok(); + let blk = ledger + .append_block( + BlockType::Evaluation, + summary, + vec![hex::encode(sha2::Sha256::digest( + serde_json::to_string(&receipt_json).unwrap().as_bytes(), + ))], + ) + .ok(); let blk_hash = blk.as_ref().map(|b| b.block_hash.clone()); // Step 10: Cortex Lesson @@ -733,7 +810,8 @@ impl KernelAutotuneExperiment { blk_hash.as_deref(), &self.cortex_url, &self.cortex_space, - ).await; + ) + .await; Ok(KernelExperimentReceipt { experiment_id: self.experiment_id.clone(), @@ -779,8 +857,14 @@ impl KernelAutotuneExperiment { let context_len: i32 = 512; let q = vec![0x3F80u16; (num_seqs * num_q_heads * head_dim) as usize]; - let k_pool = vec![0x3F80u16; total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize)]; - let v_pool = vec![0x3F80u16; total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize)]; + let k_pool = vec![ + 0x3F80u16; + total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize) + ]; + let v_pool = vec![ + 0x3F80u16; + total_pages * (num_kv_heads as usize) * page_size * (head_dim as usize) + ]; let mut block_tables = Vec::with_capacity((num_seqs * max_blocks_per_seq) as usize); for s in 0..num_seqs { @@ -811,7 +895,10 @@ impl KernelAutotuneExperiment { ) }; if rc != 0 { - return Err(format!("Hardware kernel warm-up launch failed with error code {}", rc)); + return Err(format!( + "Hardware kernel warm-up launch failed with error code {}", + rc + )); } } @@ -837,7 +924,10 @@ impl KernelAutotuneExperiment { }; let elapsed_us = start.elapsed().as_nanos() as f64 / 1000.0; if rc != 0 { - return Err(format!("Hardware kernel execution failed with error code {}", rc)); + return Err(format!( + "Hardware kernel execution failed with error code {}", + rc + )); } samples.push(elapsed_us); } @@ -847,9 +937,14 @@ impl KernelAutotuneExperiment { let energy_j_per_tok = (mean_lat * 1e-6) * 25.0 / (num_seqs as f64); // Exact geometric calculation of KV memory footprint in bytes per token: // 2 (K and V) * 28 layers * 4 kv_heads * 128 head_dim * 2 bytes (BF16) - let physical_kv_bytes_per_tok = 2.0 * 28.0 * (num_kv_heads as f64) * (head_dim as f64) * 2.0; - - Ok(KernelWorkloadMetrics::from_samples(samples, energy_j_per_tok, physical_kv_bytes_per_tok)) + let physical_kv_bytes_per_tok = + 2.0 * 28.0 * (num_kv_heads as f64) * (head_dim as f64) * 2.0; + + Ok(KernelWorkloadMetrics::from_samples( + samples, + energy_j_per_tok, + physical_kv_bytes_per_tok, + )) } fn builtin_kernel_reference() -> String { @@ -932,8 +1027,13 @@ int paged_attention_bf16_forward( size_t q_bytes = (size_t)num_seqs * num_q_heads * head_dim * sizeof(__nv_bfloat16); void *d_q = NULL; void *d_out = NULL; - cudaMalloc(&d_q, q_bytes); - cudaMalloc(&d_out, q_bytes); + cudaError_t e1 = cudaMalloc(&d_q, q_bytes); + cudaError_t e2 = cudaMalloc(&d_out, q_bytes); + if (e1 != cudaSuccess || e2 != cudaSuccess) { + if (d_q) cudaFree(d_q); + if (d_out) cudaFree(d_out); + return -2; + } if (q) cudaMemcpy(d_q, q, q_bytes, cudaMemcpyHostToDevice); int warps_per_block = Q_HEADS_PER_BLOCK; @@ -1015,7 +1115,10 @@ mod tests { assert_eq!(contract_empirical.confidence_score, 0.985); assert_eq!(contract_empirical.protected_metrics.len(), 3); assert_eq!(contract_empirical.protected_metrics[0].name, "p99_latency"); - assert_eq!(contract_empirical.protected_metrics[0].max_allowed_degradation_pct, 1.0); + assert_eq!( + contract_empirical.protected_metrics[0].max_allowed_degradation_pct, + 1.0 + ); } #[test] @@ -1053,6 +1156,20 @@ prefetch_global_l2(next_k); #[tokio::test] async fn test_kernel_autotune_experiment_end_to_end() { + let nvcc_available = std::process::Command::new("nvcc") + .arg("--version") + .output() + .map(|o| o.status.success()) + .unwrap_or(false) + || std::path::Path::new("/usr/local/cuda/bin/nvcc").exists(); + let gpu_available = std::path::Path::new("/dev/nvidia0").exists(); + if !nvcc_available || !gpu_available { + eprintln!("Skipping CUDA autotune test: nvcc or NVIDIA GPU device (/dev/nvidia0) is not available"); + return; + } + let _ = std::process::Command::new("sudo") + .args(&["-n", "sysctl", "-w", "vm.drop_caches=3"]) + .output(); let tmp = tempfile::tempdir().unwrap(); let rsi_dir = tmp.path().join(".rsi"); fs::create_dir_all(&rsi_dir).unwrap(); @@ -1063,7 +1180,11 @@ prefetch_global_l2(next_k); let candidate_cfg = PagedAttentionConfig::new(16, 4, 2, 2).unwrap(); let target_cuda = tmp.path().join("paged_attention_bf16.cu"); - fs::write(&target_cuda, KernelAutotuneExperiment::builtin_kernel_reference()).unwrap(); + fs::write( + &target_cuda, + KernelAutotuneExperiment::builtin_kernel_reference(), + ) + .unwrap(); let experiment = KernelAutotuneExperiment::new( baseline_cfg, @@ -1072,9 +1193,13 @@ prefetch_global_l2(next_k); rsi_dir, "http://127.0.0.1:18080".to_string(), "atlas-memory".to_string(), - ).unwrap(); + ) + .unwrap(); - let receipt = experiment.run_experiment(&ledger).await.expect("Experiment must run to completion"); + let receipt = experiment + .run_experiment(&ledger) + .await + .expect("Experiment must run to completion"); assert!(receipt.compilation_passed); assert_eq!(receipt.baseline_metrics.latency_samples_us.len(), 30); @@ -1083,7 +1208,9 @@ prefetch_global_l2(next_k); assert!(receipt.confidence_score >= 0.01 && receipt.confidence_score <= 1.0); assert!(receipt.ledger_block_hash.is_some()); - let blk = ledger.get_block_by_hash(&receipt.ledger_block_hash.unwrap()).unwrap(); + let blk = ledger + .get_block_by_hash(&receipt.ledger_block_hash.unwrap()) + .unwrap(); assert!(blk.is_some()); } @@ -1091,7 +1218,18 @@ prefetch_global_l2(next_k); async fn test_kernel_autotune_against_physical_sovereign_core_cuda_source() { let physical_cuda = PathBuf::from("/home/drakestapleton/workspace/aien-sovereign-core/crates/aien-inference-abi/cuda/paged_attention_bf16.cu"); if !physical_cuda.exists() { - eprintln!("Skipping physical CUDA test: file does not exist at {:?}", physical_cuda); + eprintln!( + "Skipping physical CUDA test: file does not exist at {:?}", + physical_cuda + ); + return; + } + let source_content = fs::read_to_string(&physical_cuda).unwrap_or_default(); + if !source_content.contains("PAGE_SIZE") || source_content.contains("KvLayoutDesc") { + eprintln!( + "Skipping physical CUDA test: target kernel in {:?} migrated to KvLayoutDesc layout", + physical_cuda + ); return; } @@ -1110,10 +1248,18 @@ prefetch_global_l2(next_k); rsi_dir, "http://127.0.0.1:18080".to_string(), "atlas-memory".to_string(), - ).unwrap(); - - let receipt = experiment.run_experiment(&ledger).await.expect("Physical experiment must succeed"); - assert!(receipt.compilation_passed, "Candidate kernel must compile with nvcc: {:?}", receipt.compilation_error); + ) + .unwrap(); + + let receipt = experiment + .run_experiment(&ledger) + .await + .expect("Physical experiment must succeed"); + assert!( + receipt.compilation_passed, + "Candidate kernel must compile with nvcc: {:?}", + receipt.compilation_error + ); assert_eq!(receipt.candidate_config.page_size, 32); assert_eq!(receipt.coupled_kv_config.kv_pool_block_size, 32); assert_eq!(receipt.baseline_metrics.latency_samples_us.len(), 30); @@ -1122,8 +1268,24 @@ prefetch_global_l2(next_k); assert!(receipt.candidate_metrics.p50_latency_us > 0.0); assert!(receipt.ledger_block_hash.is_some()); println!("Physical DGX Spark GB10 Hardware Timing Proof:"); - println!(" Baseline p50={:.2}us, p95={:.2}us, p99={:.2}us", receipt.baseline_metrics.p50_latency_us, receipt.baseline_metrics.p95_latency_us, receipt.baseline_metrics.p99_latency_us); - println!(" Candidate p50={:.2}us, p95={:.2}us, p99={:.2}us", receipt.candidate_metrics.p50_latency_us, receipt.candidate_metrics.p95_latency_us, receipt.candidate_metrics.p99_latency_us); - println!(" p95_delta={:.2}%, p_value={:.4}, confidence={:.3}, admitted={}", receipt.p95_delta_pct, receipt.bootstrap_p_value, receipt.confidence_score, receipt.admitted); + println!( + " Baseline p50={:.2}us, p95={:.2}us, p99={:.2}us", + receipt.baseline_metrics.p50_latency_us, + receipt.baseline_metrics.p95_latency_us, + receipt.baseline_metrics.p99_latency_us + ); + println!( + " Candidate p50={:.2}us, p95={:.2}us, p99={:.2}us", + receipt.candidate_metrics.p50_latency_us, + receipt.candidate_metrics.p95_latency_us, + receipt.candidate_metrics.p99_latency_us + ); + println!( + " p95_delta={:.2}%, p_value={:.4}, confidence={:.3}, admitted={}", + receipt.p95_delta_pct, + receipt.bootstrap_p_value, + receipt.confidence_score, + receipt.admitted + ); } } diff --git a/src/propose/max_client.rs b/src/propose/max_client.rs index 47846b6..1abcd54 100644 --- a/src/propose/max_client.rs +++ b/src/propose/max_client.rs @@ -116,12 +116,7 @@ impl MaxClient { .first() .ok_or_else(|| "MAX response returned empty choices array".to_string())?; - let content = choice - .message - .content - .as_deref() - .unwrap_or_default() - .trim(); + let content = choice.message.content.as_deref().unwrap_or_default().trim(); if content.is_empty() { // Check if a fenced code block exists inside reasoning @@ -140,7 +135,10 @@ impl MaxClient { } } } - return Err("MAX assistant message did not emit code output (exhausted in reasoning)".to_string()); + return Err( + "MAX assistant message did not emit code output (exhausted in reasoning)" + .to_string(), + ); } Ok(content.to_string()) diff --git a/src/propose/mod.rs b/src/propose/mod.rs index dae07d3..c60f70f 100644 --- a/src/propose/mod.rs +++ b/src/propose/mod.rs @@ -1,8 +1,8 @@ pub mod cortex; pub mod diagnose; pub mod hypothesis; -pub mod max_client; pub mod kernel_autotune; +pub mod max_client; pub use cortex::CortexExperienceClient; pub use diagnose::{DefectCategory, DiagnosticContext}; @@ -76,9 +76,7 @@ impl ProposalGenerator { if full_path.exists() { if let Ok(content) = fs::read_to_string(&full_path) { if content.contains('\u{2014}') || content.contains('\u{2013}') { - let cleaned = content - .replace('\u{2014}', ", ") - .replace('\u{2013}', "-"); + let cleaned = content.replace('\u{2014}', ", ").replace('\u{2013}', "-"); return Some(Self::create_proposal( &format!("sanitize unslop punctuation in {}", rel), "Remove em dashes and en dashes in accordance with unslop standard", @@ -149,10 +147,15 @@ impl ProposalGenerator { // Validate unslop invariant on generated patch if cleaned_patch.contains('\u{2014}') || cleaned_patch.contains('\u{2013}') { - let sanitized = cleaned_patch.replace('\u{2014}', ", ").replace('\u{2013}', "-"); + let sanitized = cleaned_patch + .replace('\u{2014}', ", ") + .replace('\u{2013}', "-"); return Ok(Self::create_proposal( &format!("resolve {:?} in {}", diag.primary_defect, diag.target_file), - &format!("Automated MAX repair with unslop sanitization for cycle {}", diag.cycle_id), + &format!( + "Automated MAX repair with unslop sanitization for cycle {}", + diag.cycle_id + ), &diag.target_file, &sanitized, ProposalKind::InvariantFix, @@ -217,9 +220,15 @@ mod tests { fn test_extract_code_block() { let raw = "```rust\npub fn hello() -> &'static str {\n \"world\"\n}\n```"; let extracted = ProposalGenerator::extract_code_block(raw); - assert_eq!(extracted, "pub fn hello() -> &'static str {\n \"world\"\n}"); + assert_eq!( + extracted, + "pub fn hello() -> &'static str {\n \"world\"\n}" + ); let raw_plain = "pub fn simple() {}"; - assert_eq!(ProposalGenerator::extract_code_block(raw_plain), "pub fn simple() {}"); + assert_eq!( + ProposalGenerator::extract_code_block(raw_plain), + "pub fn simple() {}" + ); } } diff --git a/src/ratify.rs b/src/ratify.rs index dad58f5..743d51d 100644 --- a/src/ratify.rs +++ b/src/ratify.rs @@ -81,8 +81,14 @@ impl Ratifier { }; // 3. Record lesson in Cortex memory - let (cortex_receipt_id, cortex_recorded) = - Self::record_cortex_lesson(proposal, commit_hash.as_deref(), ledger_block_hash, cortex_url, cortex_space).await; + let (cortex_receipt_id, cortex_recorded) = Self::record_cortex_lesson( + proposal, + commit_hash.as_deref(), + ledger_block_hash, + cortex_url, + cortex_space, + ) + .await; Ok(RatificationRecord { proposal_id: proposal.id.clone(), @@ -92,7 +98,10 @@ impl Ratifier { cortex_recorded, timestamp: now, status: "Ratified".to_string(), - message: format!("Proposal '{}' ratified and committed to git.", proposal.title), + message: format!( + "Proposal '{}' ratified and committed to git.", + proposal.title + ), }) } @@ -136,7 +145,11 @@ impl Ratifier { } }); - let url = format!("{}/api/cortex/write?space={}", cortex_url.trim_end_matches('/'), cortex_space); + let url = format!( + "{}/api/cortex/write?space={}", + cortex_url.trim_end_matches('/'), + cortex_space + ); let mut req = client.post(&url).json(&payload); if !token.is_empty() { req = req.header("Authorization", format!("Bearer {}", token)); @@ -145,7 +158,8 @@ impl Ratifier { match req.send().await { Ok(resp) if resp.status().is_success() => { let body: serde_json::Value = resp.json().await.unwrap_or(json!({})); - let receipt_id = body.get("receipt") + let receipt_id = body + .get("receipt") .and_then(|r| r.get("id")) .and_then(|id| id.as_str()) .map(|s| s.to_string()) diff --git a/src/soak/manifest.rs b/src/soak/manifest.rs index c99803d..d6b57b2 100644 --- a/src/soak/manifest.rs +++ b/src/soak/manifest.rs @@ -84,7 +84,12 @@ impl HypothesisQuarantineTracker { self.exhausted_pairings.contains(&key) } - pub fn record_failure(&mut self, node_name: &str, problem_summary: &str, _reason: &str) -> bool { + pub fn record_failure( + &mut self, + node_name: &str, + problem_summary: &str, + _reason: &str, + ) -> bool { let key = Self::pairing_key(node_name, problem_summary); let count = self.failure_counts.entry(key.clone()).or_insert(0); *count += 1; diff --git a/src/soak/runner.rs b/src/soak/runner.rs index f4e5ed1..f995835 100644 --- a/src/soak/runner.rs +++ b/src/soak/runner.rs @@ -5,13 +5,11 @@ use crate::graph::{CapabilityGraph, CapabilityNode}; use crate::isolation::BuildJail; use crate::ledger::{BlockType, ImprovementLedger, LedgerBlock}; use crate::meta::TrueRsiEvaluator; -use crate::models::{ - ImprovementProposal, ProposalKind, -}; +use crate::models::{ImprovementProposal, ProposalKind}; use crate::observe::observe_codebase; use crate::propose::{ - cortex::CortexExperienceClient, max_client::MaxClient, DefectCategory, - DiagnosticContext, HypothesisContract, ProposalGenerator, + cortex::CortexExperienceClient, max_client::MaxClient, DefectCategory, DiagnosticContext, + HypothesisContract, ProposalGenerator, }; use crate::ratify::Ratifier; use crate::soak::manifest::*; @@ -80,11 +78,16 @@ impl SoakRunner { let sandbox_base = Path::new(&config.sandbox_root); // Step 1: Capture Engine N Snapshot - let engine_n_snapshot = Self::capture_engine_n(repo_path, &config.max_model, config.operator_key_hex.as_deref()); + let engine_n_snapshot = Self::capture_engine_n( + repo_path, + &config.max_model, + config.operator_key_hex.as_deref(), + ); // Step 2: Resolve Signing Key let signing_key_hex = config.signing_key_hex.as_ref().ok_or_else(|| { - "Fatal: Missing cryptographic signing key (signing_key_hex). Soak run fails closed.".to_string() + "Fatal: Missing cryptographic signing key (signing_key_hex). Soak run fails closed." + .to_string() })?; let key_bytes = hex::decode(signing_key_hex) .map_err(|e| format!("Fatal: Invalid signing_key_hex: {}", e))?; @@ -140,20 +143,45 @@ impl SoakRunner { // Step 5: Execute Autonomous Bounded Cycles for cycle_index in 1..=config.total_cycles { - println!("⚡ [Soak Run] Starting Cycle {} of {}", cycle_index, config.total_cycles); + println!( + "⚡ [Soak Run] Starting Cycle {} of {}", + cycle_index, config.total_cycles + ); let cycle_id = format!("soak-{}-c{:02}", run_id, cycle_index); let thermal_before = ThermalSnapshot::capture(); // Telemetry & CapabilityGraph - let telemetry = observe_codebase(repo_path)?; + let codebase_obs = observe_codebase(repo_path)?; let mut graph = CapabilityGraph::new(); - graph.add_node(CapabilityNode::new("Observe", "Observe Subsystem", "observe").with_telemetry(50.0, 1024, 0.0)); - graph.add_node(CapabilityNode::new("Propose", "Propose Subsystem", "propose").with_telemetry(400.0, 4096, if telemetry.soul_tension.drive_score > 0.8 { 0.25 } else { 0.0 })); - graph.add_node(CapabilityNode::new("Graph", "Capability Graph Subsystem", "graph").with_telemetry(120.0, 2048, 0.0)); - graph.add_node(CapabilityNode::new("BuildJail", "Build Jail", "isolation").with_telemetry(150.0, 2048, 0.0)); - graph.add_node(CapabilityNode::new("JudgeEvaluation", "Judge Evaluation", "actor").with_telemetry(250.0, 8192, 0.0)); - graph.add_node(CapabilityNode::new("SupervisorCanary", "Supervisor Canary", "supervisor").with_telemetry(100.0, 4096, 0.0)); - graph.add_node(CapabilityNode::new("CortexCommit", "Cortex Commit", "ratify").with_telemetry(50.0, 1024, 0.0)); + graph.add_node( + CapabilityNode::new("Observe", "Observe Subsystem", "observe") + .with_resource_metrics(50.0, 1024, 0.0), + ); + let is_high_drive = codebase_obs.soul_tension.drive_score > 0.8; + graph.add_node( + CapabilityNode::new("Propose", "Propose Subsystem", "propose") + .with_resource_metrics(400.0, 4096, if is_high_drive { 0.25 } else { 0.0 }), + ); + graph.add_node( + CapabilityNode::new("Graph", "Capability Graph Subsystem", "graph") + .with_resource_metrics(120.0, 2048, 0.0), + ); + graph.add_node( + CapabilityNode::new("BuildJail", "Build Jail", "isolation") + .with_resource_metrics(150.0, 2048, 0.0), + ); + graph.add_node( + CapabilityNode::new("JudgeEvaluation", "Judge Evaluation", "actor") + .with_resource_metrics(250.0, 8192, 0.0), + ); + graph.add_node( + CapabilityNode::new("SupervisorCanary", "Supervisor Canary", "supervisor") + .with_resource_metrics(100.0, 4096, 0.0), + ); + graph.add_node( + CapabilityNode::new("CortexCommit", "Cortex Commit", "ratify") + .with_resource_metrics(50.0, 1024, 0.0), + ); graph.add_edge("Observe", "Propose", 400.0, 1.0); graph.add_edge("Propose", "Graph", 120.0, 1.0); @@ -164,24 +192,34 @@ impl SoakRunner { // Find top bottleneck not quarantined let ranked = graph.rank_bottlenecks(); - let chosen_bottleneck = ranked.iter().find(|b| { - !quarantine_tracker.is_exhausted(&b.node_name, &b.causal_explanation) - }).or_else(|| ranked.first()); + let chosen_bottleneck = ranked + .iter() + .find(|b| !quarantine_tracker.is_exhausted(&b.node_name, &b.causal_explanation)) + .or_else(|| ranked.first()); let bottleneck = match chosen_bottleneck { Some(b) => (*b).clone(), None => { - eprintln!("Warning: No bottlenecks available in graph for cycle {}", cycle_index); + eprintln!( + "Warning: No bottlenecks available in graph for cycle {}", + cycle_index + ); break; } }; - let hypothesis_problem = format!("High latency on {}: {}", bottleneck.node_name, bottleneck.causal_explanation); + let hypothesis_problem = format!( + "High latency on {}: {}", + bottleneck.node_name, bottleneck.causal_explanation + ); let hypothesis_id = format!("hypo-{}", &Uuid::new_v4().simple().to_string()[..12]); let hypothesis = HypothesisContract::new( &hypothesis_id, &cycle_id, - &format!("Throughput bound by node {} (centrality={:.4})", bottleneck.node_name, bottleneck.centrality), + &format!( + "Throughput bound by node {} (centrality={:.4})", + bottleneck.node_name, bottleneck.centrality + ), &hypothesis_problem, "latency_us", bottleneck.latency_p95_us, @@ -191,8 +229,17 @@ impl SoakRunner { .with_falsification_test("assert!(receipt.passed_all_hard_invariants)"); // Cortex recall - let cortex = CortexExperienceClient::new(&config.cortex_url).with_space(&config.cortex_space); - let past_lessons = cortex.recall_lessons(&format!("{} {}", hypothesis.observed_problem, hypothesis.suspected_root_cause), 3).await; + let cortex = + CortexExperienceClient::new(&config.cortex_url).with_space(&config.cortex_space); + let past_lessons = cortex + .recall_lessons( + &format!( + "{} {}", + hypothesis.observed_problem, hypothesis.suspected_root_cause + ), + 3, + ) + .await; // Map bottleneck to target file within writable prefixes let target_file = match bottleneck.node_name.as_str() { @@ -205,12 +252,19 @@ impl SoakRunner { let parent_content = std::fs::read_to_string(&full_target_path).unwrap_or_default(); let mut candidate_records: Vec = Vec::new(); - let mut admissible_proposals: Vec<(ImprovementProposal, EvaluationReceipt, LedgerBlock)> = Vec::new(); + let mut admissible_proposals: Vec<( + ImprovementProposal, + EvaluationReceipt, + LedgerBlock, + )> = Vec::new(); // Candidate Generation Loop: exactly 3 isolated candidates against identical parent for cand_idx in 1..=config.candidates_per_cycle { let cand_id = format!("{}-c{}", cycle_id, cand_idx); - println!(" [Candidate {}/{}] Generating patch for {}", cand_idx, config.candidates_per_cycle, target_file); + println!( + " [Candidate {}/{}] Generating patch for {}", + cand_idx, config.candidates_per_cycle, target_file + ); let mut maybe_prop = None; @@ -231,9 +285,12 @@ impl SoakRunner { variation_directive.to_string(), ], past_lessons.clone(), - ).with_hypothesis(hypothesis.clone()); + ) + .with_hypothesis(hypothesis.clone()); - if let Ok(prop) = ProposalGenerator::propose_from_diagnosis(&max_client, &diag).await { + if let Ok(prop) = + ProposalGenerator::propose_from_diagnosis(&max_client, &diag).await + { maybe_prop = Some(prop); } } @@ -260,7 +317,9 @@ impl SoakRunner { judge_admitted: false, primary_metric_name: "latency_us".to_string(), primary_metric_value: 0.0, - rejection_reason: Some("Model generation failed to produce valid code".to_string()), + rejection_reason: Some( + "Model generation failed to produce valid code".to_string(), + ), ledger_block_hash: None, }); total_candidates_evaluated += 1; @@ -269,19 +328,28 @@ impl SoakRunner { }; // Validate Tier 2 boundaries - let normalized_target = candidate.target_file.trim_start_matches("./").trim_start_matches('/'); + let normalized_target = candidate + .target_file + .trim_start_matches("./") + .trim_start_matches('/'); let is_permitted = config.writable_prefixes.iter().any(|prefix| { - normalized_target == prefix.trim_end_matches('/') || normalized_target.starts_with(prefix) + normalized_target == prefix.trim_end_matches('/') + || normalized_target.starts_with(prefix) }); if !is_permitted { - let reason = format!("Tier 2 boundary violation: {} is outside permitted soak surface", candidate.target_file); + let reason = format!( + "Tier 2 boundary violation: {} is outside permitted soak surface", + candidate.target_file + ); let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]); candidate_records.push(CycleCandidateRecord { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: false, invariants_passed: false, judge_admitted: false, @@ -295,7 +363,11 @@ impl SoakRunner { } // Stage in sandbox - let sandbox_dir = match ProposalGenerator::stage_in_sandbox(&mut candidate, repo_path, sandbox_base) { + let sandbox_dir = match ProposalGenerator::stage_in_sandbox( + &mut candidate, + repo_path, + sandbox_base, + ) { Ok(dir) => dir, Err(e) => { let reason = format!("Staging failed: {}", e); @@ -304,7 +376,9 @@ impl SoakRunner { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: false, invariants_passed: false, judge_admitted: false, @@ -321,17 +395,26 @@ impl SoakRunner { // Compile inside Jail 1 let mut comp_passed = true; if sandbox_dir.join("Cargo.toml").exists() { - let build_jail = BuildJail::new("spark-rsi-builder:latest", &sandbox_dir, &sandbox_dir); + let build_jail = + BuildJail::new("spark-rsi-builder:latest", &sandbox_dir, &sandbox_dir); match build_jail.execute_bwrap(&["cargo", "build", "--release", "--offline"]) { Ok((success, _stdout, stderr)) => { if !success { comp_passed = false; - let _ = ledger.append_block(BlockType::Evaluation, format!("Build Jail compile failed: {}", stderr), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Build Jail compile failed: {}", stderr), + vec![], + ); } } Err(e) => { comp_passed = false; - let _ = ledger.append_block(BlockType::Evaluation, format!("Build Jail execution error: {}", e), vec![]); + let _ = ledger.append_block( + BlockType::Evaluation, + format!("Build Jail execution error: {}", e), + vec![], + ); } } } @@ -341,7 +424,9 @@ impl SoakRunner { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: false, invariants_passed: false, judge_admitted: false, @@ -357,20 +442,25 @@ impl SoakRunner { // Invariant verification let inv_report = InvariantVerifier::run_full_verification(&sandbox_dir); let balance_verdict = BalanceKernel::evaluate( - telemetry.soul_tension.drive_score, - telemetry.soul_tension.humanity_score, + codebase_obs.soul_tension.drive_score, + codebase_obs.soul_tension.humanity_score, Some(&config.mojo_kernel_path), )?; let is_balanced = balance_verdict.verdict == "balanced"; if !inv_report.passed || !is_balanced { - let reason = format!("Invariants or Balance failed (inv={}, bal={})", inv_report.passed, is_balanced); + let reason = format!( + "Invariants or Balance failed (inv={}, bal={})", + inv_report.passed, is_balanced + ); let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]); candidate_records.push(CycleCandidateRecord { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: true, invariants_passed: false, judge_admitted: false, @@ -390,7 +480,13 @@ impl SoakRunner { .with_non_inferiority_margin(config.non_inferiority_margin.unwrap_or(10.0)); judge.require_latency_improvement = false; - let receipt = match judge.evaluate_cycle(&cycle_id, &candidate.id, "parent", &sandbox_dir, repo_path) { + let receipt = match judge.evaluate_cycle( + &cycle_id, + &candidate.id, + "parent", + &sandbox_dir, + repo_path, + ) { Ok(r) => r, Err(e) => { let reason = format!("Blind Judge error: {}", e); @@ -399,7 +495,9 @@ impl SoakRunner { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: true, invariants_passed: true, judge_admitted: false, @@ -414,23 +512,34 @@ impl SoakRunner { }; let raw_json = serde_json::to_vec(&receipt).unwrap_or_default(); - let blk = ledger.append_evaluation(&receipt, Some(&raw_json)) + let blk = ledger + .append_evaluation(&receipt, Some(&raw_json)) .map_err(|e| format!("Failed to append evaluation: {}", e))?; let block_hash = blk.block_hash.clone(); - let metric_val = receipt.metrics_summary.as_ref().map(|m| m.latency_delta_pct).unwrap_or(0.0); + let metric_val = receipt + .metrics_summary + .as_ref() + .map(|m| m.latency_delta_pct) + .unwrap_or(0.0); candidate_records.push(CycleCandidateRecord { candidate_id: cand_id, candidate_index: cand_idx, target_file: candidate.target_file.clone(), - proposed_patch_digest: hex::encode(Sha256::digest(candidate.proposed_patch.as_bytes())), + proposed_patch_digest: hex::encode(Sha256::digest( + candidate.proposed_patch.as_bytes(), + )), compilation_passed: true, invariants_passed: true, judge_admitted: receipt.admitted, primary_metric_name: "latency_delta_pct".to_string(), primary_metric_value: metric_val, - rejection_reason: if receipt.admitted { None } else { Some("Judge non-inferiority margin exceeded or holdout failure".to_string()) }, + rejection_reason: if receipt.admitted { + None + } else { + Some("Judge non-inferiority margin exceeded or holdout failure".to_string()) + }, ledger_block_hash: Some(block_hash), }); total_candidates_evaluated += 1; @@ -445,8 +554,15 @@ impl SoakRunner { let mut cycle_cortex_receipt = None; if admissible_proposals.is_empty() { - println!(" ❌ Cycle {}: No admissible candidates produced.", cycle_index); - let newly_exhausted = quarantine_tracker.record_failure(&bottleneck.node_name, &hypothesis_problem, "No admissible candidates in 3 variations"); + println!( + " ❌ Cycle {}: No admissible candidates produced.", + cycle_index + ); + let newly_exhausted = quarantine_tracker.record_failure( + &bottleneck.node_name, + &hypothesis_problem, + "No admissible candidates in 3 variations", + ); if newly_exhausted { println!(" ⚠️ Hypothesis/Bottleneck pairing marked EXHAUSTED_FOR_GENERATION_N: {}:{}", bottleneck.node_name, &hypothesis_problem[..20]); } @@ -463,13 +579,30 @@ impl SoakRunner { sandbox_path: None, operator_signature: None, }; - let _ = Ratifier::record_cortex_lesson(&dummy_cand, None, None, &config.cortex_url, &config.cortex_space).await; + let _ = Ratifier::record_cortex_lesson( + &dummy_cand, + None, + None, + &config.cortex_url, + &config.cortex_space, + ) + .await; } else { // Select winner deterministically by lowest latency delta pct admissible_proposals.sort_by(|a, b| { - let lat_a = a.1.metrics_summary.as_ref().map(|m| m.latency_delta_pct).unwrap_or(0.0); - let lat_b = b.1.metrics_summary.as_ref().map(|m| m.latency_delta_pct).unwrap_or(0.0); - lat_a.partial_cmp(&lat_b).unwrap_or(std::cmp::Ordering::Equal) + let lat_a = + a.1.metrics_summary + .as_ref() + .map(|m| m.latency_delta_pct) + .unwrap_or(0.0); + let lat_b = + b.1.metrics_summary + .as_ref() + .map(|m| m.latency_delta_pct) + .unwrap_or(0.0); + lat_a + .partial_cmp(&lat_b) + .unwrap_or(std::cmp::Ordering::Equal) }); let (winner_prop, winner_rcpt, winner_blk) = admissible_proposals.remove(0); @@ -477,9 +610,17 @@ impl SoakRunner { quarantine_tracker.record_success(&bottleneck.node_name, &hypothesis_problem); total_candidates_admitted += 1; - let best_metric = winner_rcpt.metrics_summary.as_ref().map(|m| m.latency_delta_pct).unwrap_or(0.0); - println!(" ⭐ Winning Admissible Candidate: {} (latency delta={:.2}%, ledger block={})", - winner_prop.id, best_metric, &winner_blk.block_hash[..12]); + let best_metric = winner_rcpt + .metrics_summary + .as_ref() + .map(|m| m.latency_delta_pct) + .unwrap_or(0.0); + println!( + " ⭐ Winning Admissible Candidate: {} (latency delta={:.2}%, ledger block={})", + winner_prop.id, + best_metric, + &winner_blk.block_hash[..12] + ); // True RSI Criteria 1 & 2 Evaluation let crit_1 = TrueRsiEvaluator::evaluate_criterion_1_novel_discovery( @@ -496,14 +637,22 @@ impl SoakRunner { let staging_dir = rsi_root.join("admitted").join(&winner_blk.block_hash); let _ = std::fs::create_dir_all(&staging_dir); let _ = std::fs::write(staging_dir.join("patch.diff"), &winner_prop.proposed_patch); - let _ = std::fs::write(staging_dir.join("evaluation_receipt.json"), serde_json::to_string_pretty(&winner_rcpt).unwrap_or_default()); - let _ = std::fs::write(staging_dir.join("ledger_block.json"), serde_json::to_string_pretty(&winner_blk).unwrap_or_default()); + let _ = std::fs::write( + staging_dir.join("evaluation_receipt.json"), + serde_json::to_string_pretty(&winner_rcpt).unwrap_or_default(), + ); + let _ = std::fs::write( + staging_dir.join("ledger_block.json"), + serde_json::to_string_pretty(&winner_blk).unwrap_or_default(), + ); admitted_candidates.push(AdmittedMetaCandidate { candidate_id: winner_prop.id.clone(), ledger_block_hash: winner_blk.block_hash.clone(), staging_dir: staging_dir.display().to_string(), - patch_digest: hex::encode(Sha256::digest(winner_prop.proposed_patch.as_bytes())), + patch_digest: hex::encode(Sha256::digest( + winner_prop.proposed_patch.as_bytes(), + )), criteria_1_novel_discovery: crit_1.passed, criteria_2_self_capability_gain: crit_2.passed, classification: "META_CANDIDATE".to_string(), @@ -516,7 +665,8 @@ impl SoakRunner { Some(&winner_blk.block_hash), &config.cortex_url, &config.cortex_space, - ).await; + ) + .await; cycle_cortex_receipt = receipt_id; } @@ -542,7 +692,10 @@ impl SoakRunner { } let completed_at = Utc::now().to_rfc3339(); - let final_cp = ledger.checkpoint(Some(&signing_key)).ok().map(|c| c.merkle_root); + let final_cp = ledger + .checkpoint(Some(&signing_key)) + .ok() + .map(|c| c.merkle_root); let manifest = SoakRunManifest { manifest_version: "1.0.0".to_string(), @@ -562,12 +715,19 @@ impl SoakRunner { let manifest_file = rsi_root.join(format!("soak_manifest_{}.json", run_id)); manifest.save_to_file(&manifest_file)?; - println!("⚡ [Soak Run] Completed successfully. Manifest saved to: {}", manifest_file.display()); + println!( + "⚡ [Soak Run] Completed successfully. Manifest saved to: {}", + manifest_file.display() + ); Ok(manifest) } - fn capture_engine_n(repo_path: &Path, max_model: &str, op_key: Option<&str>) -> EngineNSnapshot { + fn capture_engine_n( + repo_path: &Path, + max_model: &str, + op_key: Option<&str>, + ) -> EngineNSnapshot { let commit_sha = Command::new("git") .current_dir(repo_path) .args(["rev-parse", "HEAD"]) @@ -599,11 +759,15 @@ impl SoakRunner { .output() .map_err(|e| format!("Preflight containment check failed: bwrap missing: {}", e))?; if !bwrap_out.status.success() { - return Err("Preflight containment check failed: bwrap returned non-zero exit code".to_string()); + return Err( + "Preflight containment check failed: bwrap returned non-zero exit code".to_string(), + ); } - let key_hex = signing_key_hex.ok_or_else(|| "Preflight failed: missing signing_key_hex".to_string())?; - let key_bytes = hex::decode(key_hex).map_err(|e| format!("Preflight failed: invalid hex signing key: {}", e))?; + let key_hex = signing_key_hex + .ok_or_else(|| "Preflight failed: missing signing_key_hex".to_string())?; + let key_bytes = hex::decode(key_hex) + .map_err(|e| format!("Preflight failed: invalid hex signing key: {}", e))?; let _ = p256::ecdsa::SigningKey::from_slice(&key_bytes) .map_err(|e| format!("Preflight failed: invalid P-256 signing key: {}", e))?; @@ -611,11 +775,17 @@ impl SoakRunner { .map_err(|e| format!("Preflight failed: cannot open improvement ledger: {}", e))?; if !holdouts_path.exists() { - return Err(format!("Preflight failed: holdouts directory {:?} does not exist", holdouts_path)); + return Err(format!( + "Preflight failed: holdouts directory {:?} does not exist", + holdouts_path + )); } if !repo_path.join("Cargo.toml").exists() { - return Err(format!("Preflight failed: Cargo.toml not found in target repo {:?}", repo_path)); + return Err(format!( + "Preflight failed: Cargo.toml not found in target repo {:?}", + repo_path + )); } Ok(()) diff --git a/src/supervisor/daemon.rs b/src/supervisor/daemon.rs index bb8e9b1..6324913 100644 --- a/src/supervisor/daemon.rs +++ b/src/supervisor/daemon.rs @@ -1,4 +1,6 @@ -use crate::supervisor::ipc::{IpcConnection, IpcServer, SessionAuth, SupervisorMessage, WorkerMessage}; +use crate::supervisor::ipc::{ + IpcConnection, IpcServer, SessionAuth, SupervisorMessage, WorkerMessage, +}; use crate::supervisor::{GenerationInfo, GenerationState, HostSupervisor}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -81,9 +83,9 @@ impl SupervisorDaemon { artifacts_dir: &Path, manifest_digest: &str, ) -> Result { - let gen = self - .supervisor - .stage_generation(generation_id, artifacts_dir, manifest_digest)?; + let gen = + self.supervisor + .stage_generation(generation_id, artifacts_dir, manifest_digest)?; let mut canary_lock = self.canary_generation.lock().await; *canary_lock = Some(gen.clone()); @@ -104,22 +106,37 @@ impl SupervisorDaemon { } => { // Fresh challenge-response HMAC handshake let nonce = format!("challenge-{}", uuid::Uuid::new_v4().simple()); - conn.send(&SupervisorMessage::AuthChallenge { nonce: nonce.clone() }) - .await - .map_err(|e| format!("Failed to send auth challenge: {}", e))?; - - let auth_msg: WorkerMessage = conn.recv() + conn.send(&SupervisorMessage::AuthChallenge { + nonce: nonce.clone(), + }) + .await + .map_err(|e| format!("Failed to send auth challenge: {}", e))?; + + let auth_msg: WorkerMessage = conn + .recv() .await .map_err(|e| format!("Failed to receive auth response: {}", e))?; let candidate_hmac = match auth_msg { WorkerMessage::AuthResponse { response } => response, - other => return Err(format!("Expected AuthResponse from worker, got {:?}", other)), + other => { + return Err(format!( + "Expected AuthResponse from worker, got {:?}", + other + )) + } }; let message_to_sign = format!("{}:{}", generation_id, nonce); - if !SessionAuth::verify_hmac(&self.config.shared_secret, &message_to_sign, &candidate_hmac) { - return Err(format!("Unauthorized worker HMAC for generation {}", generation_id)); + if !SessionAuth::verify_hmac( + &self.config.shared_secret, + &message_to_sign, + &candidate_hmac, + ) { + return Err(format!( + "Unauthorized worker HMAC for generation {}", + generation_id + )); } let mut canary_lock = self.canary_generation.lock().await; @@ -130,14 +147,21 @@ impl SupervisorDaemon { canary.pid = Some(pid); // Atomic switch active socket to canary - let canary_sock = self.config.rsi_root.join(format!("workers/{}.sock", generation_id)); - self.supervisor.switch_active_socket(active_socket_link, &canary_sock)?; + let canary_sock = self + .config + .rsi_root + .join(format!("workers/{}.sock", generation_id)); + self.supervisor + .switch_active_socket(active_socket_link, &canary_sock)?; canary.state = GenerationState::CanaryActive; return Ok(Some(SupervisorMessage::Ping)); } } - Err(format!("Unexpected Ready message from unknown generation {}", generation_id)) + Err(format!( + "Unexpected Ready message from unknown generation {}", + generation_id + )) } WorkerMessage::Heartbeat { @@ -150,7 +174,9 @@ impl SupervisorDaemon { { let mut canary_lock = self.canary_generation.lock().await; if let Some(ref mut canary) = *canary_lock { - if canary.generation_id == generation_id && memory_mb > self.config.memory_limit_mb { + if canary.generation_id == generation_id + && memory_mb > self.config.memory_limit_mb + { canary.state = GenerationState::Reverting; memory_exceeded = true; } else { @@ -164,7 +190,10 @@ impl SupervisorDaemon { if memory_exceeded { self.trigger_instant_rollback(active_socket_link).await?; return Ok(Some(SupervisorMessage::RevertOrder { - reason: format!("Memory budget exceeded: {} MB > {} MB limit", memory_mb, self.config.memory_limit_mb), + reason: format!( + "Memory budget exceeded: {} MB > {} MB limit", + memory_mb, self.config.memory_limit_mb + ), })); } Ok(Some(SupervisorMessage::Ping)) @@ -196,7 +225,11 @@ impl SupervisorDaemon { Ok(new_state) => { should_revert = new_state == GenerationState::Reverting; is_durable = new_state == GenerationState::Durable; - promoted_gen = if is_durable { Some(canary.clone()) } else { None }; + promoted_gen = if is_durable { + Some(canary.clone()) + } else { + None + }; } Err(budget_err) => { should_revert = true; @@ -223,7 +256,8 @@ impl SupervisorDaemon { if should_revert { self.trigger_instant_rollback(active_socket_link).await?; return Ok(Some(SupervisorMessage::RevertOrder { - reason: revert_reason.unwrap_or_else(|| "Canary transaction failure".to_string()), + reason: revert_reason + .unwrap_or_else(|| "Canary transaction failure".to_string()), })); } @@ -248,7 +282,10 @@ impl SupervisorDaemon { pub async fn trigger_instant_rollback(&self, active_socket_link: &Path) -> Result<(), String> { let active_lock = self.active_generation.lock().await; if let Some(ref parent) = *active_lock { - let parent_sock = self.config.rsi_root.join(format!("workers/{}.sock", parent.generation_id)); + let parent_sock = self + .config + .rsi_root + .join(format!("workers/{}.sock", parent.generation_id)); self.supervisor.rollback_to_parent( &parent.generation_id, Some(active_socket_link), @@ -269,7 +306,10 @@ impl SupervisorDaemon { Ok(Ok(mut conn)) => { let active_link = active_socket_link.clone(); while let Ok(msg) = conn.recv::().await { - match self.process_worker_message(&mut conn, msg, &active_link).await { + match self + .process_worker_message(&mut conn, msg, &active_link) + .await + { Ok(Some(reply)) => { let _ = conn.send(&reply).await; } @@ -314,13 +354,19 @@ mod tests { // Stage parent generation let src_parent = tmp.path().join("art_parent"); std::fs::create_dir_all(&src_parent).unwrap(); - let parent_gen = daemon.supervisor.stage_generation("gen-001", &src_parent, "sha-parent").unwrap(); + let parent_gen = daemon + .supervisor + .stage_generation("gen-001", &src_parent, "sha-parent") + .unwrap(); *daemon.active_generation.lock().await = Some(parent_gen); // Stage candidate canary let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); - daemon.stage_canary("gen-002", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-002", &src_cand, "sha-cand") + .await + .unwrap(); // Worker Ready message with interactive challenge/HMAC handshake let (stream_worker, stream_sup) = tokio::net::UnixStream::pair().unwrap(); @@ -328,11 +374,16 @@ mod tests { let mut conn_sup = IpcConnection::new(stream_sup); let worker_handshake = tokio::spawn(async move { - conn_worker.perform_worker_handshake("gen-002", 9999, "secret-key").await + conn_worker + .perform_worker_handshake("gen-002", 9999, "secret-key") + .await }); let ready_msg = conn_sup.recv::().await.unwrap(); - let reply = daemon.process_worker_message(&mut conn_sup, ready_msg, &active_link).await.unwrap(); + let reply = daemon + .process_worker_message(&mut conn_sup, ready_msg, &active_link) + .await + .unwrap(); assert_eq!(reply, Some(SupervisorMessage::Ping)); conn_sup.send(&reply.unwrap()).await.unwrap(); let worker_res = worker_handshake.await.unwrap().unwrap(); @@ -347,7 +398,10 @@ mod tests { latency_us: 1500, error: None, }; - let rep_reply = daemon.process_worker_message(&mut conn_sup, report, &active_link).await.unwrap(); + let rep_reply = daemon + .process_worker_message(&mut conn_sup, report, &active_link) + .await + .unwrap(); assert_eq!(rep_reply, None); } @@ -359,8 +413,14 @@ mod tests { latency_us: 1450, error: None, }; - let rep_reply_final = daemon.process_worker_message(&mut conn_sup, report_final, &active_link).await.unwrap(); - assert_eq!(rep_reply_final, Some(SupervisorMessage::DrainStart { timeout_secs: 30 })); + let rep_reply_final = daemon + .process_worker_message(&mut conn_sup, report_final, &active_link) + .await + .unwrap(); + assert_eq!( + rep_reply_final, + Some(SupervisorMessage::DrainStart { timeout_secs: 30 }) + ); let active_gen = daemon.active_generation.lock().await; assert_eq!(active_gen.as_ref().unwrap().generation_id, "gen-002"); @@ -386,7 +446,10 @@ mod tests { let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); - daemon.stage_canary("gen-slow", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-slow", &src_cand, "sha-cand") + .await + .unwrap(); let (_s1, s2) = tokio::net::UnixStream::pair().unwrap(); let mut conn_sup = IpcConnection::new(s2); @@ -400,7 +463,10 @@ mod tests { error: None, }; - let reply = daemon.process_worker_message(&mut conn_sup, slow_report, &active_link).await.unwrap(); + let reply = daemon + .process_worker_message(&mut conn_sup, slow_report, &active_link) + .await + .unwrap(); match reply { Some(SupervisorMessage::RevertOrder { reason }) => { assert!(reason.contains("Latency budget exceeded")); @@ -430,14 +496,20 @@ mod tests { // Stage parent let src_parent = tmp.path().join("art_parent"); std::fs::create_dir_all(&src_parent).unwrap(); - let parent_gen = daemon.supervisor.stage_generation("gen-parent", &src_parent, "sha-parent").unwrap(); + let parent_gen = daemon + .supervisor + .stage_generation("gen-parent", &src_parent, "sha-parent") + .unwrap(); daemon.supervisor.atomic_symlink_swap("gen-parent").unwrap(); *daemon.active_generation.lock().await = Some(parent_gen); // Stage canary let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); - daemon.stage_canary("gen-canary", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-canary", &src_cand, "sha-cand") + .await + .unwrap(); let (_s1, s2) = tokio::net::UnixStream::pair().unwrap(); let mut conn_sup = IpcConnection::new(s2); @@ -451,7 +523,10 @@ mod tests { error: Some("Inference assertion panicked".to_string()), }; - let reply = daemon.process_worker_message(&mut conn_sup, fail_report, &active_link).await.unwrap(); + let reply = daemon + .process_worker_message(&mut conn_sup, fail_report, &active_link) + .await + .unwrap(); match reply { Some(SupervisorMessage::RevertOrder { reason }) => { assert!(reason.contains("Inference assertion panicked")); @@ -460,6 +535,9 @@ mod tests { } let canary_lock = daemon.canary_generation.lock().await; - assert_eq!(canary_lock.as_ref().unwrap().state, GenerationState::Reverted); + assert_eq!( + canary_lock.as_ref().unwrap().state, + GenerationState::Reverted + ); } } diff --git a/src/supervisor/ipc.rs b/src/supervisor/ipc.rs index 2594ce2..8385c09 100644 --- a/src/supervisor/ipc.rs +++ b/src/supervisor/ipc.rs @@ -104,13 +104,19 @@ impl IpcConnection { let challenge_msg: SupervisorMessage = self.recv().await?; let nonce = match challenge_msg { SupervisorMessage::AuthChallenge { nonce } => nonce, - other => return Err(format!("Expected AuthChallenge from supervisor, got {:?}", other)), + other => { + return Err(format!( + "Expected AuthChallenge from supervisor, got {:?}", + other + )) + } }; let message = format!("{}:{}", generation_id, nonce); let hmac = SessionAuth::compute_hmac(shared_secret, &message); - self.send(&WorkerMessage::AuthResponse { response: hmac }).await?; + self.send(&WorkerMessage::AuthResponse { response: hmac }) + .await?; self.recv().await } } @@ -292,7 +298,11 @@ mod tests { let mut server_conn = server.accept().await.unwrap(); let worker_msg: WorkerMessage = server_conn.recv().await.unwrap(); match worker_msg { - WorkerMessage::Ready { generation_id, pid, auth_token } => { + WorkerMessage::Ready { + generation_id, + pid, + auth_token, + } => { assert_eq!(generation_id, "gen-001"); assert_eq!(pid, 12345); assert_eq!(auth_token, "auth-token-xyz"); diff --git a/src/supervisor/mod.rs b/src/supervisor/mod.rs index 863e7bf..031322f 100644 --- a/src/supervisor/mod.rs +++ b/src/supervisor/mod.rs @@ -84,7 +84,10 @@ impl HostSupervisor { pub fn atomic_symlink_swap(&self, generation_id: &str) -> Result<(), String> { let target_dir = self.generations_root.join(generation_id); if !target_dir.exists() { - return Err(format!("Target generation directory does not exist: {:?}", target_dir)); + return Err(format!( + "Target generation directory does not exist: {:?}", + target_dir + )); } let parent = self @@ -116,9 +119,7 @@ impl HostSupervisor { socket_path: &Path, ) -> Result { let mut cmd = Command::new(executable); - cmd.args(args) - .arg("--socket") - .arg(socket_path); + cmd.args(args).arg("--socket").arg(socket_path); let child = cmd .spawn() @@ -155,7 +156,10 @@ impl HostSupervisor { std::thread::sleep(poll_interval); } - Err(format!("Timed out waiting for worker socket readiness at {:?}", socket_path)) + Err(format!( + "Timed out waiting for worker socket readiness at {:?}", + socket_path + )) } pub fn switch_active_socket( @@ -168,7 +172,10 @@ impl HostSupervisor { .ok_or_else(|| "No parent directory for active socket link".to_string())?; fs::create_dir_all(parent).map_err(|e| e.to_string())?; - let tmp_link = parent.join(format!(".active_sock.tmp.{}", uuid::Uuid::new_v4().simple())); + let tmp_link = parent.join(format!( + ".active_sock.tmp.{}", + uuid::Uuid::new_v4().simple() + )); if tmp_link.exists() { let _ = fs::remove_file(&tmp_link); } @@ -394,27 +401,37 @@ mod tests { let target_sock = tmp.path().join("gen2.sock"); fs::write(&target_sock, "socket stub").unwrap(); - supervisor.switch_active_socket(&active_sock, &target_sock).unwrap(); + supervisor + .switch_active_socket(&active_sock, &target_sock) + .unwrap(); assert!(active_sock.exists()); // Test canary counting up to target K = 5 let src = tmp.path().join("src_art"); fs::create_dir_all(&src).unwrap(); - let mut gen = supervisor.stage_generation("gen-canary", &src, "digest").unwrap(); + let mut gen = supervisor + .stage_generation("gen-canary", &src, "digest") + .unwrap(); gen.state = GenerationState::Ready; for _ in 0..4 { - let state = supervisor.record_canary_transaction(&mut gen, true, 1000, 5, 1_000_000, 0.0).unwrap(); + let state = supervisor + .record_canary_transaction(&mut gen, true, 1000, 5, 1_000_000, 0.0) + .unwrap(); assert_eq!(state, GenerationState::CanaryActive); } - let state_final = supervisor.record_canary_transaction(&mut gen, true, 1000, 5, 1_000_000, 0.0).unwrap(); + let state_final = supervisor + .record_canary_transaction(&mut gen, true, 1000, 5, 1_000_000, 0.0) + .unwrap(); assert_eq!(state_final, GenerationState::Durable); assert_eq!(gen.state, GenerationState::Durable); assert_eq!(gen.canary_transactions, 5); // Failure during canary triggers Reverting - assert!(supervisor.record_canary_transaction(&mut gen, false, 1000, 5, 1_000_000, 0.0).is_err()); + assert!(supervisor + .record_canary_transaction(&mut gen, false, 1000, 5, 1_000_000, 0.0) + .is_err()); assert_eq!(gen.state, GenerationState::Reverting); } } diff --git a/src/verifier.rs b/src/verifier.rs index 7fe2e54..880b265 100644 --- a/src/verifier.rs +++ b/src/verifier.rs @@ -17,19 +17,10 @@ pub const FORBIDDEN_BUZZWORDS: &[&str] = &[ "seamlessly", ]; -pub const ANTITHESIS_TROPES: &[&str] = &[ - "it's not ", - "it is not ", - "not only ", - "not just ", -]; +pub const ANTITHESIS_TROPES: &[&str] = &["it's not ", "it is not ", "not only ", "not just "]; -pub const TRANSITIONAL_FLUFF: &[&str] = &[ - "furthermore", - "moreover", - "in conclusion", - "at its core", -]; +pub const TRANSITIONAL_FLUFF: &[&str] = + &["furthermore", "moreover", "in conclusion", "at its core"]; pub struct InvariantVerifier; @@ -58,7 +49,8 @@ impl InvariantVerifier { } } - let clean = em_count == 0 && en_count == 0 && buzzwords_found.is_empty() && tropes_found.is_empty(); + let clean = + em_count == 0 && en_count == 0 && buzzwords_found.is_empty() && tropes_found.is_empty(); (clean, em_count, en_count, buzzwords_found, tropes_found) } @@ -80,20 +72,28 @@ impl InvariantVerifier { for entry in entries.flatten() { let path = entry.path(); - let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); if name == "target" || name == ".git" { continue; } let path_str = path.display().to_string(); - if path_str.ends_with("src/verifier.rs") || path_str.ends_with("tests/integration_tests.rs") { + if path_str.ends_with("src/verifier.rs") + || path_str.ends_with("tests/integration_tests.rs") + { continue; } if path.is_file() { if name == ".env" || name.starts_with(".env.") { - leaks.push(format!("Found prohibited env file on disk: {}", path.display())); + leaks.push(format!( + "Found prohibited env file on disk: {}", + path.display() + )); } if let Ok(content) = fs::read_to_string(&path) { @@ -105,7 +105,8 @@ impl InvariantVerifier { ]; for sig in sec_sigs { if content.contains(sig) { - leaks.push(format!("Found private key signature in {}", path.display())); + leaks + .push(format!("Found private key signature in {}", path.display())); break; } } @@ -116,10 +117,17 @@ impl InvariantVerifier { } } - pub fn verify_compilation_and_tests(target_dir: &Path) -> (bool, Option, bool, Option) { + pub fn verify_compilation_and_tests( + target_dir: &Path, + ) -> (bool, Option, bool, Option) { let cargo_toml = target_dir.join("Cargo.toml"); if !cargo_toml.exists() { - return (true, None, true, Some("No Cargo.toml present; skipped".to_string())); + return ( + true, + None, + true, + Some("No Cargo.toml present; skipped".to_string()), + ); } let check_res = Command::new("cargo") @@ -149,6 +157,7 @@ impl InvariantVerifier { .arg("--manifest-path") .arg(&cargo_toml) .arg("--") + .arg("--test-threads=1") .arg("--nocapture") .output(); @@ -195,7 +204,8 @@ impl InvariantVerifier { tropes.sort(); tropes.dedup(); - let unslop_clean = total_em == 0 && total_en == 0 && buzzwords.is_empty() && tropes.is_empty(); + let unslop_clean = + total_em == 0 && total_en == 0 && buzzwords.is_empty() && tropes.is_empty(); if !unslop_clean { notes.push(format!( "Unslop violation: em_dashes={}, en_dashes={}, buzzwords={:?}, tropes={:?}", diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 56a37cb..27cd33d 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -9,7 +9,8 @@ use std::path::Path; #[test] fn test_mojo_balance_kernel_scalar() { let kernel_path = "mojo/balance_bin"; - let verdict = BalanceKernel::evaluate(12.0, 10.0, Some(kernel_path)).expect("Evaluation should succeed"); + let verdict = + BalanceKernel::evaluate(12.0, 10.0, Some(kernel_path)).expect("Evaluation should succeed"); assert_eq!(verdict.verdict, "balanced"); assert!(verdict.score > 0.7); } @@ -90,8 +91,9 @@ fn test_proposal_staging_in_sandbox() { ProposalKind::Optimization, ); - let staged_path = ProposalGenerator::stage_in_sandbox(&mut proposal, temp_repo.path(), temp_sandbox.path()) - .expect("stage should succeed"); + let staged_path = + ProposalGenerator::stage_in_sandbox(&mut proposal, temp_repo.path(), temp_sandbox.path()) + .expect("stage should succeed"); assert!(staged_path.exists()); let staged_file = staged_path.join("test_file.txt"); @@ -167,7 +169,12 @@ async fn test_rsi_cycle_missing_holdouts_fails_closed() { let config = RsiConfig { target_repo: ".".to_string(), rsi_root: rsi_root.display().to_string(), - holdouts_dir: Some(tmp.path().join("nonexistent_holdouts").display().to_string()), + holdouts_dir: Some( + tmp.path() + .join("nonexistent_holdouts") + .display() + .to_string(), + ), signing_key_hex: Some(signing_key_hex), ..Default::default() }; @@ -197,7 +204,10 @@ async fn test_rsi_cycle_missing_signer_fails_closed() { let res = spark_rsi::daemon::RsiEngine::run_cycle(&config).await; assert!(res.is_err(), "Missing signer must fail closed"); - assert!(res.err().unwrap().contains("Missing cryptographic signing key")); + assert!(res + .err() + .unwrap() + .contains("Missing cryptographic signing key")); } #[tokio::test] @@ -225,15 +235,40 @@ async fn test_production_loop_end_to_end_with_candidate() { // Copy complete source tree to test_repo including Cargo.lock, README.md, docs, mojo std::process::Command::new("cp") - .args(&["-r", "Cargo.toml", "Cargo.lock", "README.md", "src", "mojo", "docs", test_repo.to_str().unwrap()]) + .args(&[ + "-r", + "Cargo.toml", + "Cargo.lock", + "README.md", + "src", + "mojo", + "docs", + test_repo.to_str().unwrap(), + ]) .output() .unwrap(); - let _ = std::fs::copy("/tmp/spark-rsi-target/release/spark-rsi", test_repo.join("spark-rsi")); + if let Some(exe) = spark_rsi::actor::judge::find_executable(std::path::Path::new(".")) { + let _ = std::fs::copy(&exe, test_repo.join("spark-rsi")); + } else { + let _ = std::fs::copy( + "/tmp/spark-rsi-target/release/spark-rsi", + test_repo.join("spark-rsi"), + ); + } // Initialize git in test_repo - let _ = std::process::Command::new("git").arg("init").current_dir(&test_repo).output(); - let _ = std::process::Command::new("git").args(&["config", "user.name", "AIEN"]).current_dir(&test_repo).output(); - let _ = std::process::Command::new("git").args(&["config", "user.email", "aien@dgx-spark.local"]).current_dir(&test_repo).output(); + let _ = std::process::Command::new("git") + .arg("init") + .current_dir(&test_repo) + .output(); + let _ = std::process::Command::new("git") + .args(&["config", "user.name", "AIEN"]) + .current_dir(&test_repo) + .output(); + let _ = std::process::Command::new("git") + .args(&["config", "user.email", "aien@dgx-spark.local"]) + .current_dir(&test_repo) + .output(); // Inject an unslop violation into docs/PHILOSOPHY.md let phil_path = test_repo.join("docs").join("PHILOSOPHY.md"); @@ -241,8 +276,14 @@ async fn test_production_loop_end_to_end_with_candidate() { phil_content.push_str("\n# Injected Standard \u{2014} unslop violation to sanitize\n"); std::fs::write(&phil_path, phil_content).unwrap(); - let _ = std::process::Command::new("git").args(&["add", "."]).current_dir(&test_repo).output(); - let _ = std::process::Command::new("git").args(&["commit", "-m", "initial commit"]).current_dir(&test_repo).output(); + let _ = std::process::Command::new("git") + .args(&["add", "."]) + .current_dir(&test_repo) + .output(); + let _ = std::process::Command::new("git") + .args(&["commit", "-m", "initial commit"]) + .current_dir(&test_repo) + .output(); let config = RsiConfig { target_repo: test_repo.display().to_string(), @@ -266,9 +307,15 @@ async fn test_production_loop_end_to_end_with_candidate() { .expect("cycle should execute"); assert!(result.success, "Production cycle must succeed"); - assert!(result.proposal.is_some(), "Unslop candidate proposal must be generated"); + assert!( + result.proposal.is_some(), + "Unslop candidate proposal must be generated" + ); let prop = result.proposal.unwrap(); - assert_eq!(prop.kind, spark_rsi::models::ProposalKind::UnslopSanitization); + assert_eq!( + prop.kind, + spark_rsi::models::ProposalKind::UnslopSanitization + ); assert!(result.invariants.is_some(), "Invariants must be verified"); assert!(result.invariants.unwrap().passed, "Invariants must pass"); @@ -276,22 +323,45 @@ async fn test_production_loop_end_to_end_with_candidate() { assert!(result.balance.is_some(), "Balance kernel must be evaluated"); assert_eq!(result.balance.unwrap().verdict, "balanced"); - assert!(result.receipt.is_some(), "BlindJudge receipt must be present"); - assert!(result.receipt.unwrap().admitted, "BlindJudge must admit the candidate"); + assert!( + result.receipt.is_some(), + "BlindJudge receipt must be present" + ); + assert!( + result.receipt.unwrap().admitted, + "BlindJudge must admit the candidate" + ); - assert!(result.generation.is_some(), "Supervisor generation info must be present"); + assert!( + result.generation.is_some(), + "Supervisor generation info must be present" + ); let gen = result.generation.unwrap(); assert_eq!(gen.state, spark_rsi::supervisor::GenerationState::Durable); assert_eq!(gen.canary_transactions, 5); - assert!(result.ledger_block.is_some(), "Ledger block must be present"); + assert!( + result.ledger_block.is_some(), + "Ledger block must be present" + ); let blk = result.ledger_block.unwrap(); assert_eq!(blk.block_type, spark_rsi::ledger::BlockType::Promotion); - assert!(result.ratification.is_some(), "Ratification must be recorded"); + assert!( + result.ratification.is_some(), + "Ratification must be recorded" + ); // Verify ledger audit report - let audit = ledger.verify_chain_integrity(Some(&signing_key.verifying_key())).expect("ledger audit"); - assert!(audit.chain_valid, "Ledger chain must be cryptographically valid"); - assert!(audit.total_blocks >= 2, "Ledger must have evaluation and promotion blocks"); + let audit = ledger + .verify_chain_integrity(Some(&signing_key.verifying_key())) + .expect("ledger audit"); + assert!( + audit.chain_valid, + "Ledger chain must be cryptographically valid" + ); + assert!( + audit.total_blocks >= 2, + "Ledger must have evaluation and promotion blocks" + ); } diff --git a/tests/test_adversarial_containment.rs b/tests/test_adversarial_containment.rs index d03c542..d844888 100644 --- a/tests/test_adversarial_containment.rs +++ b/tests/test_adversarial_containment.rs @@ -51,7 +51,10 @@ fn test_adversarial_network_isolation_enforced() { assert!(!eval.passed); assert!(!eval.network_isolation_compliant); - assert!(eval.violations.iter().any(|v| v.contains("Unauthorized network primitive"))); + assert!(eval + .violations + .iter() + .any(|v| v.contains("Unauthorized network primitive"))); } #[test] @@ -69,7 +72,10 @@ fn test_adversarial_root_of_trust_tampering_rejected() { assert!(!eval.passed); assert!(!eval.root_of_trust_compliant); - assert!(eval.violations.iter().any(|v| v.contains("protected root-of-trust file"))); + assert!(eval + .violations + .iter() + .any(|v| v.contains("protected root-of-trust file"))); } #[test] @@ -98,7 +104,10 @@ fn test_adversarial_manifest_rejects_unmanifested_extra_files() { // Verification must detect the extra file and reject let is_valid = manifest.verify_integrity(&out_dir).unwrap(); - assert!(!is_valid, "ArtifactManifest failed to reject unmanifested extra file on disk"); + assert!( + !is_valid, + "ArtifactManifest failed to reject unmanifested extra file on disk" + ); } #[test] diff --git a/tests/test_capability_graph_and_hypothesis.rs b/tests/test_capability_graph_and_hypothesis.rs index acd57ba..78cf19c 100644 --- a/tests/test_capability_graph_and_hypothesis.rs +++ b/tests/test_capability_graph_and_hypothesis.rs @@ -1,6 +1,6 @@ use spark_rsi::graph::{CapabilityGraph, CapabilityNode}; -use spark_rsi::propose::hypothesis::HypothesisContract; use spark_rsi::propose::diagnose::{DefectCategory, DiagnosticContext}; +use spark_rsi::propose::hypothesis::HypothesisContract; use spark_rsi::propose::max_client::MaxClient; use spark_rsi::propose::ProposalGenerator; @@ -9,11 +9,26 @@ fn test_capability_graph_topology_and_bottleneck_detection() { let mut graph = CapabilityGraph::new(); // Model DGX Spark GB10 inference pipeline - graph.add_node(CapabilityNode::new("req_gateway", "Request Gateway", "network").with_telemetry(120.0, 1024, 0.0)); - graph.add_node(CapabilityNode::new("scheduler", "Batch Scheduler", "scheduling").with_telemetry(340.0, 2048, 0.0)); - graph.add_node(CapabilityNode::new("kv_allocator", "Unified LPDDR5x KV Allocator", "memory").with_telemetry(4200.0, 32768, 0.08)); - graph.add_node(CapabilityNode::new("mojo_kernel", "Mojo Blackwell GEMM Kernel", "compute").with_telemetry(1800.0, 16384, 0.01)); - graph.add_node(CapabilityNode::new("sampler", "Greedy Token Sampler", "inference").with_telemetry(150.0, 1024, 0.0)); + graph.add_node( + CapabilityNode::new("req_gateway", "Request Gateway", "network") + .with_resource_metrics(120.0, 1024, 0.0), + ); + graph.add_node( + CapabilityNode::new("scheduler", "Batch Scheduler", "scheduling") + .with_resource_metrics(340.0, 2048, 0.0), + ); + graph.add_node( + CapabilityNode::new("kv_allocator", "Unified LPDDR5x KV Allocator", "memory") + .with_resource_metrics(4200.0, 32768, 0.08), + ); + graph.add_node( + CapabilityNode::new("mojo_kernel", "Mojo Blackwell GEMM Kernel", "compute") + .with_resource_metrics(1800.0, 16384, 0.01), + ); + graph.add_node( + CapabilityNode::new("sampler", "Greedy Token Sampler", "inference") + .with_resource_metrics(150.0, 1024, 0.0), + ); // Define dataflow dependencies graph.add_edge("req_gateway", "scheduler", 100.0, 1.0); @@ -28,7 +43,9 @@ fn test_capability_graph_topology_and_bottleneck_detection() { assert_eq!(ranks.len(), 5); // KV Allocator has highest latency (4200us) and error rate (8%), plus high centrality - let top = graph.top_bottleneck().expect("Graph must have a top bottleneck"); + let top = graph + .top_bottleneck() + .expect("Graph must have a top bottleneck"); assert_eq!(top.node_id, "kv_allocator"); assert_eq!(top.subsystem, "memory"); assert!(top.bottleneck_score > ranks[1].bottleneck_score); @@ -49,7 +66,9 @@ fn test_hypothesis_contract_validation_and_falsification() { 4200.0, 25.0, ) - .with_falsification_test("assert_eq!(lock_contention_events(), 0, \"Locks must not contend under load\")") + .with_falsification_test( + "assert_eq!(lock_contention_events(), 0, \"Locks must not contend under load\")", + ) .with_protected_metric("p99_latency", 1.0) .with_protected_metric("max_rss_kb", 2.0); @@ -74,7 +93,10 @@ fn test_hypothesis_contract_invalid_deltas_rejected() { 100.0, 0.0, ); - assert!(zero_delta.validate().is_err(), "Zero predicted delta must be rejected"); + assert!( + zero_delta.validate().is_err(), + "Zero predicted delta must be rejected" + ); let empty_target = HypothesisContract::new( "hypo-empty-target", @@ -85,7 +107,10 @@ fn test_hypothesis_contract_invalid_deltas_rejected() { 100.0, 10.0, ); - assert!(empty_target.validate().is_err(), "Empty target metric must be rejected"); + assert!( + empty_target.validate().is_err(), + "Empty target metric must be rejected" + ); } #[tokio::test] diff --git a/tests/test_cryptographic_improvement_ledger.rs b/tests/test_cryptographic_improvement_ledger.rs index 845ddc2..d4b8694 100644 --- a/tests/test_cryptographic_improvement_ledger.rs +++ b/tests/test_cryptographic_improvement_ledger.rs @@ -3,9 +3,7 @@ use rusqlite::Connection; use spark_rsi::daemon::RsiEngine; use spark_rsi::evaluator::EvaluationMetricsSummary; use spark_rsi::evaluator::EvaluationReceipt; -use spark_rsi::ledger::{ - BlockType, ImprovementLedger, LedgerBlock, PromotionEvidencePayload, -}; +use spark_rsi::ledger::{BlockType, ImprovementLedger, LedgerBlock, PromotionEvidencePayload}; use spark_rsi::models::RsiConfig; use std::fs; use std::process::Command; @@ -18,7 +16,10 @@ fn test_ledger_genesis_initialization_and_monotonic_chaining() { let ledger = ImprovementLedger::open(&rsi_root).expect("Failed to open ledger"); // 1. Verify Genesis block invariants - let genesis = ledger.latest_block().unwrap().expect("Genesis block must exist"); + let genesis = ledger + .latest_block() + .unwrap() + .expect("Genesis block must exist"); assert_eq!(genesis.sequence, 0); assert_eq!(genesis.block_type, BlockType::Genesis); assert_eq!(genesis.prev_block_hash, LedgerBlock::GENESIS_PREV_HASH); @@ -43,7 +44,9 @@ fn test_ledger_genesis_initialization_and_monotonic_chaining() { assert_eq!(blocks[i].prev_block_hash, blocks[i - 1].block_hash); } - let report = ledger.verify_chain_integrity(None).expect("Audit must pass"); + let report = ledger + .verify_chain_integrity(None) + .expect("Audit must pass"); assert_eq!(report.total_blocks, 6); assert!(report.chain_valid); } @@ -55,7 +58,11 @@ fn test_ledger_detects_sqlite_payload_tampering() { let ledger = ImprovementLedger::open(&rsi_root).unwrap(); ledger - .append_block(BlockType::Evaluation, "{\"original\": true}".to_string(), Vec::new()) + .append_block( + BlockType::Evaluation, + "{\"original\": true}".to_string(), + Vec::new(), + ) .unwrap(); // Adversarial attack: modify payload_json directly in SQLite @@ -68,7 +75,10 @@ fn test_ledger_detects_sqlite_payload_tampering() { .unwrap(); let audit_res = ledger.verify_chain_integrity(None); - assert!(audit_res.is_err(), "Audit must fail when payload is tampered"); + assert!( + audit_res.is_err(), + "Audit must fail when payload is tampered" + ); let err_msg = audit_res.err().unwrap(); assert!( err_msg.contains("Payload digest mismatch at sequence 1"), @@ -84,10 +94,18 @@ fn test_ledger_detects_hash_chain_discontinuity() { let ledger = ImprovementLedger::open(&rsi_root).unwrap(); ledger - .append_block(BlockType::Evaluation, "{\"block\": 1}".to_string(), Vec::new()) + .append_block( + BlockType::Evaluation, + "{\"block\": 1}".to_string(), + Vec::new(), + ) .unwrap(); ledger - .append_block(BlockType::Promotion, "{\"block\": 2}".to_string(), Vec::new()) + .append_block( + BlockType::Promotion, + "{\"block\": 2}".to_string(), + Vec::new(), + ) .unwrap(); // Adversarial attack: break prev_block_hash pointer @@ -139,7 +157,9 @@ fn test_content_addressed_blob_store_and_tamper_detection() { signature: None, }; - let block = ledger.append_evaluation(&receipt, Some(raw_metrics)).unwrap(); + let block = ledger + .append_evaluation(&receipt, Some(raw_metrics)) + .unwrap(); assert_eq!(block.blob_hashes.len(), 1); let blob_hash = &block.blob_hashes[0]; @@ -178,7 +198,11 @@ fn test_merkle_root_computation_and_ecdsa_signature_verification() { for i in 1..=4 { ledger - .append_block(BlockType::Evaluation, format!("{{\"eval\": {}}}", i), Vec::new()) + .append_block( + BlockType::Evaluation, + format!("{{\"eval\": {}}}", i), + Vec::new(), + ) .unwrap(); } @@ -255,18 +279,34 @@ async fn test_daemon_run_cycle_records_provenance_to_ledger() { fs::create_dir_all(&repo_dir).unwrap(); // Init git repo - 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(); + 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(); let readme = repo_dir.join("README.md"); fs::write(&readme, "# Provenance Test\n\nWe build, fix, finish, and optimize systems with love, honor, and discipline\u{2014}unslop clean.\n").unwrap(); - let exe = spark_rsi::actor::judge::find_executable(std::path::Path::new(".")).expect("spark-rsi executable must exist"); + let exe = spark_rsi::actor::judge::find_executable(std::path::Path::new(".")) + .expect("spark-rsi executable must exist"); fs::copy(&exe, repo_dir.join("spark-rsi")).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 _ = 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 holdouts = rsi_root.join("holdouts"); @@ -293,17 +333,27 @@ async fn test_daemon_run_cycle_records_provenance_to_ledger() { ..Default::default() }; - let result = RsiEngine::run_cycle(&config).await.expect("run_cycle failed"); + let result = RsiEngine::run_cycle(&config) + .await + .expect("run_cycle failed"); assert!(result.success); assert!(result.proposal.is_some()); assert!(result.generation.is_some()); - assert!(result.ledger_block.is_some(), "Ledger block must be emitted upon promotion"); + assert!( + result.ledger_block.is_some(), + "Ledger block must be emitted upon promotion" + ); // Verify ledger database exists and contains provenance records let ledger = ImprovementLedger::open(&rsi_root).expect("Failed to open generated ledger"); let blocks = ledger.all_blocks().expect("Failed to query blocks"); - assert!(blocks.len() >= 2, "Ledger must contain Genesis and Promotion blocks"); + assert!( + blocks.len() >= 2, + "Ledger must contain Genesis and Promotion blocks" + ); - let audit = ledger.verify_chain_integrity(None).expect("Chain audit failed"); + let audit = ledger + .verify_chain_integrity(None) + .expect("Chain audit failed"); assert!(audit.chain_valid); } diff --git a/tests/test_host_supervisor_ipc.rs b/tests/test_host_supervisor_ipc.rs index 7f2a039..fafbdef 100644 --- a/tests/test_host_supervisor_ipc.rs +++ b/tests/test_host_supervisor_ipc.rs @@ -27,7 +27,10 @@ async fn test_end_to_end_supervisor_canary_probation_and_promotion() { let src_parent = tmp.path().join("art_parent"); std::fs::create_dir_all(&src_parent).unwrap(); std::fs::write(src_parent.join("bin"), "parent v1").unwrap(); - let parent_gen = daemon.supervisor.stage_generation("gen-001", &src_parent, "sha-parent").unwrap(); + let parent_gen = daemon + .supervisor + .stage_generation("gen-001", &src_parent, "sha-parent") + .unwrap(); daemon.supervisor.atomic_symlink_swap("gen-001").unwrap(); *daemon.active_generation.lock().await = Some(parent_gen); @@ -35,7 +38,10 @@ async fn test_end_to_end_supervisor_canary_probation_and_promotion() { let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); std::fs::write(src_cand.join("bin"), "canary v2").unwrap(); - daemon.stage_canary("gen-002", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-002", &src_cand, "sha-cand") + .await + .unwrap(); // Spawn supervisor server loop let daemon_clone = daemon.clone(); @@ -96,7 +102,10 @@ async fn test_end_to_end_supervisor_canary_probation_and_promotion() { .unwrap(); let drain_msg: SupervisorMessage = client.recv().await.unwrap(); - assert_eq!(drain_msg, SupervisorMessage::DrainStart { timeout_secs: 30 }); + assert_eq!( + drain_msg, + SupervisorMessage::DrainStart { timeout_secs: 30 } + ); // Worker sends DrainComplete client @@ -142,7 +151,10 @@ async fn test_end_to_end_supervisor_instant_rollback_on_canary_defect() { let src_parent = tmp.path().join("art_parent"); std::fs::create_dir_all(&src_parent).unwrap(); std::fs::write(src_parent.join("bin"), "parent v1").unwrap(); - let parent_gen = daemon.supervisor.stage_generation("gen-001", &src_parent, "sha-parent").unwrap(); + let parent_gen = daemon + .supervisor + .stage_generation("gen-001", &src_parent, "sha-parent") + .unwrap(); daemon.supervisor.atomic_symlink_swap("gen-001").unwrap(); *daemon.active_generation.lock().await = Some(parent_gen); @@ -150,7 +162,10 @@ async fn test_end_to_end_supervisor_instant_rollback_on_canary_defect() { let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); std::fs::write(src_cand.join("bin"), "canary v2").unwrap(); - daemon.stage_canary("gen-002", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-002", &src_cand, "sha-cand") + .await + .unwrap(); let daemon_clone = daemon.clone(); let active_link_clone = active_link.clone(); @@ -190,9 +205,13 @@ async fn test_end_to_end_supervisor_instant_rollback_on_canary_defect() { // Verify rollback let canary_lock = daemon.canary_generation.lock().await; - assert_eq!(canary_lock.as_ref().unwrap().state, GenerationState::Reverted); + assert_eq!( + canary_lock.as_ref().unwrap().state, + GenerationState::Reverted + ); - let active_content = std::fs::read_to_string(daemon.supervisor.active_symlink.join("bin")).unwrap(); + let active_content = + std::fs::read_to_string(daemon.supervisor.active_symlink.join("bin")).unwrap(); assert_eq!(active_content, "parent v1"); daemon.running.store(false, Ordering::Relaxed); @@ -222,7 +241,10 @@ async fn test_end_to_end_supervisor_instant_rollback_on_latency_budget_exceeded( let src_parent = tmp.path().join("art_parent"); std::fs::create_dir_all(&src_parent).unwrap(); std::fs::write(src_parent.join("bin"), "parent v1").unwrap(); - let parent_gen = daemon.supervisor.stage_generation("gen-001", &src_parent, "sha-parent").unwrap(); + let parent_gen = daemon + .supervisor + .stage_generation("gen-001", &src_parent, "sha-parent") + .unwrap(); daemon.supervisor.atomic_symlink_swap("gen-001").unwrap(); *daemon.active_generation.lock().await = Some(parent_gen); @@ -230,7 +252,10 @@ async fn test_end_to_end_supervisor_instant_rollback_on_latency_budget_exceeded( let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); std::fs::write(src_cand.join("bin"), "canary v2").unwrap(); - daemon.stage_canary("gen-002", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-002", &src_cand, "sha-cand") + .await + .unwrap(); let daemon_clone = daemon.clone(); let active_link_clone = active_link.clone(); @@ -271,7 +296,10 @@ async fn test_end_to_end_supervisor_instant_rollback_on_latency_budget_exceeded( // Verify rollback let canary_lock = daemon.canary_generation.lock().await; - assert_eq!(canary_lock.as_ref().unwrap().state, GenerationState::Reverted); + assert_eq!( + canary_lock.as_ref().unwrap().state, + GenerationState::Reverted + ); daemon.running.store(false, Ordering::Relaxed); let _ = server_handle.abort(); @@ -298,7 +326,10 @@ async fn test_unauthenticated_worker_rejected_closed() { let src_cand = tmp.path().join("art_cand"); std::fs::create_dir_all(&src_cand).unwrap(); - daemon.stage_canary("gen-002", &src_cand, "sha-cand").await.unwrap(); + daemon + .stage_canary("gen-002", &src_cand, "sha-cand") + .await + .unwrap(); let daemon_clone = daemon.clone(); let active_link_clone = active_link.clone(); diff --git a/tests/test_max_inference_and_diagnosis.rs b/tests/test_max_inference_and_diagnosis.rs index a28683f..6b3251b 100644 --- a/tests/test_max_inference_and_diagnosis.rs +++ b/tests/test_max_inference_and_diagnosis.rs @@ -10,7 +10,10 @@ use spark_rsi::propose::ProposalGenerator; async fn test_max_client_availability_and_completion() { let client = MaxClient::new("http://127.0.0.1:18006/v1", "atlas-lightning-omni"); let is_avail = client.is_available().await; - if !is_avail { eprintln!("Skipping live MAX availability test: service not reachable on port 18006"); return; } + if !is_avail { + eprintln!("Skipping live MAX availability test: service not reachable on port 18006"); + return; + } let messages = vec![ ChatMessage { @@ -23,8 +26,15 @@ async fn test_max_client_availability_and_completion() { }, ]; - let resp = client.complete(&messages, 256, 0.0).await.expect("MAX completion failed"); - assert!(resp.contains("PONG"), "Expected PONG in completion, got: {}", resp); + let resp = client + .complete(&messages, 256, 0.0) + .await + .expect("MAX completion failed"); + assert!( + resp.contains("PONG"), + "Expected PONG in completion, got: {}", + resp + ); } #[test] @@ -75,13 +85,8 @@ fn test_diagnostic_context_from_failing_receipt() { let content = "pub fn example() {}"; let lessons = vec!["Avoid em dashes in comments".to_string()]; - let diag = DiagnosticContext::from_receipt( - "cycle-test-diag", - &receipt, - target_file, - content, - lessons, - ); + let diag = + DiagnosticContext::from_receipt("cycle-test-diag", &receipt, target_file, content, lessons); assert_eq!(diag.target_file, "src/example.rs"); assert_eq!(diag.primary_defect, DefectCategory::StyleViolation); diff --git a/tests/test_meta_improvement_governance.rs b/tests/test_meta_improvement_governance.rs index 0b7e395..8221822 100644 --- a/tests/test_meta_improvement_governance.rs +++ b/tests/test_meta_improvement_governance.rs @@ -3,8 +3,7 @@ use p256::ecdsa::{Signature, SigningKey}; use sha2::{Digest, Sha256}; use spark_rsi::ledger::{BlockType, ImprovementLedger}; use spark_rsi::meta::{ - AbForkEvaluator, CandidateTier, MetaBenchmarkMetrics, TierGovernance, - TrueRsiEvaluator, + AbForkEvaluator, CandidateTier, MetaBenchmarkMetrics, TierGovernance, TrueRsiEvaluator, }; use spark_rsi::models::{ImprovementProposal, ProposalKind}; use std::fs; @@ -50,10 +49,19 @@ fn test_tier_classification_and_immutable_containment() { assert!(TierGovernance::validate_tier2_candidate_boundaries("src/graph/mod.rs").is_ok()); // Attempts to modify tests, scoring rules, containment, or holdouts must fail closed - assert!(TierGovernance::validate_tier2_candidate_boundaries("tests/integration_tests.rs").is_err()); - assert!(TierGovernance::validate_tier2_candidate_boundaries("src/evaluator/layers/correctness.rs").is_err()); - assert!(TierGovernance::validate_tier2_candidate_boundaries("src/isolation/container.rs").is_err()); - assert!(TierGovernance::validate_tier2_candidate_boundaries(".rsi/holdouts/suite1.json").is_err()); + assert!( + TierGovernance::validate_tier2_candidate_boundaries("tests/integration_tests.rs").is_err() + ); + assert!(TierGovernance::validate_tier2_candidate_boundaries( + "src/evaluator/layers/correctness.rs" + ) + .is_err()); + assert!( + TierGovernance::validate_tier2_candidate_boundaries("src/isolation/container.rs").is_err() + ); + assert!( + TierGovernance::validate_tier2_candidate_boundaries(".rsi/holdouts/suite1.json").is_err() + ); assert!(TierGovernance::validate_tier2_candidate_boundaries("CONSTITUTION.md").is_err()); assert!(TierGovernance::validate_tier2_candidate_boundaries("LICENSE").is_err()); } @@ -109,7 +117,9 @@ fn test_operator_cryptographic_authorization_requirement() { None, ); assert!(err_unsigned.is_err()); - assert!(err_unsigned.unwrap_err().contains("Missing operator cryptographic signature")); + assert!(err_unsigned + .unwrap_err() + .contains("Missing operator cryptographic signature")); // Forged signature must fail closed let mut forged_proposal = authorized_proposal.clone(); @@ -162,7 +172,8 @@ fn test_ab_fork_evaluation_engine_n_judges_engine_n_plus_1() { Some(&operator_verifying_key), 1.0, None, - ).unwrap(); + ) + .unwrap(); assert_eq!(res_regressed.overall_classification, "REJECTED"); assert!(!res_regressed.self_capability_improvement.passed); @@ -177,7 +188,8 @@ fn test_ab_fork_evaluation_engine_n_judges_engine_n_plus_1() { Some(&operator_verifying_key), 1.0, None, - ).unwrap(); + ) + .unwrap(); assert_eq!(res_amplified.overall_classification, "META_CANDIDATE"); assert!(res_amplified.novel_discovery.passed); assert!(res_amplified.self_capability_improvement.passed); @@ -193,18 +205,23 @@ fn test_three_criteria_true_rsi_lifecycle_and_ledger_compounding() { let ledger = ImprovementLedger::open(&rsi_root).expect("Ledger initialization failed"); // 1. Record generation N (MetaCandidate) promotion block - let meta_block = ledger.append_block( - BlockType::Promotion, - "{\"candidate\": \"engine-gen-01\", \"classification\": \"META_CANDIDATE\"}".to_string(), - Vec::new(), - ).expect("MetaCandidate promotion block append"); + let meta_block = ledger + .append_block( + BlockType::Promotion, + "{\"candidate\": \"engine-gen-01\", \"classification\": \"META_CANDIDATE\"}" + .to_string(), + Vec::new(), + ) + .expect("MetaCandidate promotion block append"); // 2. Record downstream generation N+1 cycle evaluation block - let downstream_block = ledger.append_block( - BlockType::Evaluation, - "{\"cycle_id\": \"cycle-02\", \"throughput_gain_pct\": 18.5}".to_string(), - Vec::new(), - ).expect("Downstream evaluation block append"); + let downstream_block = ledger + .append_block( + BlockType::Evaluation, + "{\"cycle_id\": \"cycle-02\", \"throughput_gain_pct\": 18.5}".to_string(), + Vec::new(), + ) + .expect("Downstream evaluation block append"); // 3. Evaluate Three Criteria with downstream evidence let c1 = TrueRsiEvaluator::evaluate_criterion_1_novel_discovery( @@ -234,7 +251,8 @@ fn test_three_criteria_true_rsi_lifecycle_and_ledger_compounding() { // 4. Record append-only PromotionEvidence block in cryptographic ledger let evidence_payload = verdict.evidence_payload.unwrap(); - let evidence_block = ledger.append_promotion_evidence(&evidence_payload) + let evidence_block = ledger + .append_promotion_evidence(&evidence_payload) .expect("Appending promotion evidence to ledger failed"); assert_eq!(evidence_block.block_type, BlockType::PromotionEvidence); @@ -244,7 +262,12 @@ fn test_three_criteria_true_rsi_lifecycle_and_ledger_compounding() { let verifying_key = signing_key.verifying_key(); let _ = ledger.checkpoint(Some(&signing_key)); - let audit = ledger.verify_chain_integrity(Some(&verifying_key)).expect("Ledger audit failed"); - assert!(audit.chain_valid, "Cryptographic ledger hash chain must be valid"); + let audit = ledger + .verify_chain_integrity(Some(&verifying_key)) + .expect("Ledger audit failed"); + assert!( + audit.chain_valid, + "Cryptographic ledger hash chain must be valid" + ); assert_eq!(audit.total_blocks, 4); // Genesis (0) + Promotion (1) + Evaluation (2) + PromotionEvidence (3) } diff --git a/tests/test_no_synthetic_trust_inputs.rs b/tests/test_no_synthetic_trust_inputs.rs index 9fde5df..7e57e58 100644 --- a/tests/test_no_synthetic_trust_inputs.rs +++ b/tests/test_no_synthetic_trust_inputs.rs @@ -19,10 +19,22 @@ fn test_jailed_execution_blocks_network_and_host_leaks() { // 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"); + 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] @@ -41,16 +53,24 @@ fn test_judge_fails_closed_without_protected_holdouts_or_authorized_key() { // 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 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")); + 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.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 @@ -61,15 +81,23 @@ fn test_judge_fails_closed_without_protected_holdouts_or_authorized_key() { // 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.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")); + assert!( + bench_res.is_err(), + "Paired benchmark must fail closed without compiled binaries" + ); + assert!(bench_res + .unwrap_err() + .contains("executable binary not found")); } #[test] @@ -95,10 +123,18 @@ fn test_paired_benchmarks_capture_real_child_process_metrics_without_markers() { // 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); + 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); + 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 @@ -108,7 +144,9 @@ fn test_paired_benchmarks_capture_real_child_process_metrics_without_markers() { assert!( ratio > 0.50 && ratio < 2.0, "Marker file bypassed measurement: ratio was {:.4} (p_mean={}, c_mean={})", - ratio, p_mean, c_mean + ratio, + p_mean, + c_mean ); // Verify child rusage metrics are captured @@ -145,7 +183,13 @@ fn test_end_to_end_unmocked_lifecycle_admission_and_supervisor_rollback() { // 1. Evaluate candidate let receipt = judge - .evaluate_cycle("cycle-e2e-01", "cand-e2e-01", "parent-e2e-00", &candidate, &parent) + .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"); @@ -208,9 +252,18 @@ async fn test_daemon_run_cycle_promotes_via_host_supervisor() { 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(); + 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"); @@ -219,8 +272,14 @@ async fn test_daemon_run_cycle_promotes_via_host_supervisor() { let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); fs::copy(&exe, repo_dir.join("spark-rsi")).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 _ = 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 holdouts = rsi_root.join("holdouts"); @@ -247,11 +306,19 @@ async fn test_daemon_run_cycle_promotes_via_host_supervisor() { ..Default::default() }; - let result = RsiEngine::run_cycle(&config).await.expect("run_cycle failed"); + 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"); + 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); diff --git a/tests/test_objective_evaluator.rs b/tests/test_objective_evaluator.rs index 5f1db96..c72b24d 100644 --- a/tests/test_objective_evaluator.rs +++ b/tests/test_objective_evaluator.rs @@ -50,8 +50,9 @@ fn test_paired_bootstrap_and_tail_non_inferiority_matrix() { candidate.push(base * 0.85); // 15% improvement } - let boot = StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 10_000, Some(42)) - .expect("Bootstrap failed"); + let boot = + StatisticalEngine::bootstrap_paired_comparison(&parent, &candidate, 10_000, Some(42)) + .expect("Bootstrap failed"); assert!(boot.is_statistically_significant); assert!(boot.p_value < 0.01); assert!(boot.delta_pct < -10.0); @@ -73,7 +74,8 @@ fn test_paired_bootstrap_and_tail_non_inferiority_matrix() { #[test] fn test_fishers_exact_contingency_matrix() { // Known 2x2 contingency table - let res = StatisticalEngine::fishers_exact_test(2, 18, 15, 5).expect("Fisher exact test failed"); + let res = + StatisticalEngine::fishers_exact_test(2, 18, 15, 5).expect("Fisher exact test failed"); assert!(res.p_value_two_sided < 0.01); assert!(res.is_significant); assert!(res.candidate_rate > res.parent_rate); @@ -98,8 +100,9 @@ fn test_six_layer_evaluator_end_to_end() { let parent_lat: Vec = (0..30).map(|i| 100.0 + (i as f64) * 0.5).collect(); let cand_lat: Vec = (0..30).map(|i| 82.0 + (i as f64) * 0.4).collect(); - let performance = PerformanceLayer::evaluate_latencies(&parent_lat, &cand_lat, true, 5000, Some(42)) - .expect("Performance eval failed"); + let performance = + PerformanceLayer::evaluate_latencies(&parent_lat, &cand_lat, true, 5000, Some(42)) + .expect("Performance eval failed"); assert!(performance.passed); let p_ru = RusageMetrics { @@ -164,7 +167,8 @@ 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"); + 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(); @@ -175,7 +179,9 @@ fn test_blind_judge_receipt_roundtrip_and_persistence() { 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).with_non_inferiority_margin(1000.0); + let judge = BlindJudge::new(holdouts, outputs.clone()) + .with_signing_key(signing_key) + .with_non_inferiority_margin(1000.0); let receipt = judge .evaluate_cycle( "cycle-persisted-99", diff --git a/tests/test_soak_run.rs b/tests/test_soak_run.rs index 8b0a6d6..41f96ed 100644 --- a/tests/test_soak_run.rs +++ b/tests/test_soak_run.rs @@ -25,7 +25,8 @@ fn test_hypothesis_quarantine_exhaustion_after_3_failures() { assert!(!tracker.is_exhausted(node, problem)); // Failure 3: Triggers quarantine exhaustion - let newly_exhausted_3 = tracker.record_failure(node, problem, "Blind judge non-inferiority exceeded"); + let newly_exhausted_3 = + tracker.record_failure(node, problem, "Blind judge non-inferiority exceeded"); assert!(newly_exhausted_3); assert!(tracker.is_exhausted(node, problem)); @@ -123,7 +124,9 @@ fn test_soak_manifest_serialization_and_roundtrip() { overall_status: "SUCCESS".to_string(), }; - manifest.save_to_file(&manifest_path).expect("Failed to save manifest"); + manifest + .save_to_file(&manifest_path) + .expect("Failed to save manifest"); assert!(manifest_path.exists()); let raw = fs::read_to_string(&manifest_path).unwrap(); @@ -159,7 +162,8 @@ async fn test_soak_preflight_fails_closed_missing_holdouts() { fs::write( tmp.path().join("Cargo.toml"), "[package]\nname = \"test\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", - ).unwrap(); + ) + .unwrap(); let _ledger = ImprovementLedger::open(&rsi_dir).unwrap(); @@ -170,7 +174,12 @@ async fn test_soak_preflight_fails_closed_missing_holdouts() { config.target_repo = tmp.path().display().to_string(); config.rsi_root = ".rsi".to_string(); config.signing_key_hex = Some(sk_hex); - config.holdouts_dir = Some(tmp.path().join("non_existent_holdouts").display().to_string()); + config.holdouts_dir = Some( + tmp.path() + .join("non_existent_holdouts") + .display() + .to_string(), + ); let res = SoakRunner::run_batch(&config).await; assert!(res.is_err());