spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
spark-rsi-mv / tests / test_no_synthetic_trust_inputs.rs
| 1 | use p256::ecdsa::{SigningKey, VerifyingKey}; |
| 2 | use spark_rsi::actor::judge::{find_executable, run_paired_benchmarks, BlindJudge, HoldoutSuite}; |
| 3 | use spark_rsi::canary::{CanaryWorkloadManifest, SealedObservationLog}; |
| 4 | use spark_rsi::daemon::RsiEngine; |
| 5 | use spark_rsi::isolation::CandidateJailRunner; |
| 6 | use spark_rsi::ledger::ImprovementLedger; |
| 7 | use spark_rsi::models::{ProposalKind, RsiConfig}; |
| 8 | use spark_rsi::supervisor::{GenerationState, HostSupervisor}; |
| 9 | use std::fs; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | |
| 13 | #[allow(dead_code)] |
| 14 | mod canary_fixture; |
| 15 | |
| 16 | #[test] |
| 17 | fn test_jailed_execution_blocks_network_and_host_leaks() { |
| 18 | let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); |
| 19 | let runner = CandidateJailRunner::new(&exe); |
| 20 | |
| 21 | // 1. Verify candidate execution inside jail returns valid deterministic response |
| 22 | let (success, stdout, _) = runner |
| 23 | .execute(&["holdout", "check_unicode_dashes"]) |
| 24 | .expect("Jail execution failed"); |
| 25 | assert!(success); |
| 26 | assert_eq!(stdout.trim(), "DASHES_PROHIBITED"); |
| 27 | |
| 28 | // 2. Verify Bubblewrap args contain mandatory isolation parameters |
| 29 | let args = runner.build_bwrap_args(&["holdout", ""]); |
| 30 | assert!( |
| 31 | args.contains(&"--unshare-net".to_string()), |
| 32 | "Jail missing --unshare-net" |
| 33 | ); |
| 34 | assert!( |
| 35 | args.contains(&"--unshare-user".to_string()), |
| 36 | "Jail missing --unshare-user" |
| 37 | ); |
| 38 | assert!( |
| 39 | args.contains(&"--unshare-pid".to_string()), |
| 40 | "Jail missing --unshare-pid" |
| 41 | ); |
| 42 | assert!( |
| 43 | args.contains(&"--die-with-parent".to_string()), |
| 44 | "Jail missing --die-with-parent" |
| 45 | ); |
| 46 | } |
| 47 | |
| 48 | #[test] |
| 49 | fn test_judge_fails_closed_without_protected_holdouts_or_authorized_key() { |
| 50 | let tmp = tempfile::tempdir().unwrap(); |
| 51 | let holdouts = tmp.path().join("holdouts"); |
| 52 | let outputs = tmp.path().join("eval_outputs"); |
| 53 | let candidate = tmp.path().join("cand"); |
| 54 | let parent = tmp.path().join("parent"); |
| 55 | fs::create_dir_all(&candidate).unwrap(); |
| 56 | fs::create_dir_all(&parent).unwrap(); |
| 57 | |
| 58 | let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); |
| 59 | fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); |
| 60 | fs::copy(&exe, parent.join("spark-rsi")).unwrap(); |
| 61 | |
| 62 | // Failure Case 1: Missing holdouts directory fails closed |
| 63 | let signing_key = SigningKey::from_bytes(&[44u8; 32].into()).unwrap(); |
| 64 | let judge_no_holdouts = |
| 65 | BlindJudge::new(holdouts.clone(), outputs.clone()).with_signing_key(signing_key.clone()); |
| 66 | let res1 = judge_no_holdouts.evaluate_cycle("c1", "cand1", "parent0", &candidate, &parent); |
| 67 | assert!( |
| 68 | res1.is_err(), |
| 69 | "Judge must fail closed when holdouts dir does not exist" |
| 70 | ); |
| 71 | assert!(res1 |
| 72 | .unwrap_err() |
| 73 | .contains("Holdouts directory does not exist")); |
| 74 | |
| 75 | // Failure Case 2: Empty holdouts directory fails closed |
| 76 | fs::create_dir_all(&holdouts).unwrap(); |
| 77 | let res2 = judge_no_holdouts.evaluate_cycle("c2", "cand2", "parent0", &candidate, &parent); |
| 78 | assert!( |
| 79 | res2.is_err(), |
| 80 | "Judge must fail closed when holdouts dir is empty" |
| 81 | ); |
| 82 | assert!(res2.unwrap_err().contains("No valid holdout suites found")); |
| 83 | |
| 84 | // Populate valid holdout suites |
| 85 | for suite in HoldoutSuite::builtin_suites() { |
| 86 | suite.save_to_dir(&holdouts).unwrap(); |
| 87 | } |
| 88 | |
| 89 | // Failure Case 3: Missing signing key fails closed (zero fallback to static seed) |
| 90 | let judge_no_key = BlindJudge::new(holdouts.clone(), outputs.clone()); |
| 91 | let res3 = judge_no_key.evaluate_cycle("c3", "cand3", "parent0", &candidate, &parent); |
| 92 | assert!( |
| 93 | res3.is_err(), |
| 94 | "Judge must fail closed without authorized signing key" |
| 95 | ); |
| 96 | assert!(res3.unwrap_err().contains("signing key")); |
| 97 | |
| 98 | // Failure Case 4: Missing candidate binary in paired benchmarks fails closed (zero fallback to synthetic hash loop) |
| 99 | let empty_dir = tmp.path().join("empty_binary_dir"); |
| 100 | fs::create_dir_all(&empty_dir).unwrap(); |
| 101 | let bench_res = run_paired_benchmarks(&empty_dir, &candidate, 10); |
| 102 | assert!( |
| 103 | bench_res.is_err(), |
| 104 | "Paired benchmark must fail closed without compiled binaries" |
| 105 | ); |
| 106 | assert!(bench_res |
| 107 | .unwrap_err() |
| 108 | .contains("executable binary not found")); |
| 109 | } |
| 110 | |
| 111 | #[test] |
| 112 | fn test_paired_benchmarks_capture_real_child_process_metrics_without_markers() { |
| 113 | let tmp = tempfile::tempdir().unwrap(); |
| 114 | let candidate = tmp.path().join("cand"); |
| 115 | let parent = tmp.path().join("parent"); |
| 116 | fs::create_dir_all(&candidate).unwrap(); |
| 117 | fs::create_dir_all(&parent).unwrap(); |
| 118 | |
| 119 | let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); |
| 120 | fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); |
| 121 | fs::copy(&exe, parent.join("spark-rsi")).unwrap(); |
| 122 | |
| 123 | // Plant synthetic speedup marker in candidate |
| 124 | fs::write(candidate.join(".rsi_speedup"), "0.10").unwrap(); |
| 125 | |
| 126 | let (p_lats, c_lats, p_ru, c_ru) = run_paired_benchmarks(&parent, &candidate, 30) |
| 127 | .expect("Paired benchmark must execute real child processes"); |
| 128 | |
| 129 | assert_eq!(p_lats.len(), 30); |
| 130 | assert_eq!(c_lats.len(), 30); |
| 131 | |
| 132 | // Verify latencies are genuine measured positive non-zero numbers |
| 133 | for lat in &p_lats { |
| 134 | assert!( |
| 135 | *lat > 50.0, |
| 136 | "Latency must be real elapsed microseconds: {}", |
| 137 | lat |
| 138 | ); |
| 139 | } |
| 140 | for lat in &c_lats { |
| 141 | assert!( |
| 142 | *lat > 50.0, |
| 143 | "Latency must be real elapsed microseconds: {}", |
| 144 | lat |
| 145 | ); |
| 146 | } |
| 147 | |
| 148 | // Core invariant: .rsi_speedup (0.10) must NOT artificially scale candidate latency by 10x |
| 149 | let p_mean: f64 = p_lats.iter().sum::<f64>() / 30.0; |
| 150 | let c_mean: f64 = c_lats.iter().sum::<f64>() / 30.0; |
| 151 | let ratio = c_mean / p_mean; |
| 152 | assert!( |
| 153 | ratio > 0.50 && ratio < 2.0, |
| 154 | "Marker file bypassed measurement: ratio was {:.4} (p_mean={}, c_mean={})", |
| 155 | ratio, |
| 156 | p_mean, |
| 157 | c_mean |
| 158 | ); |
| 159 | |
| 160 | // Verify child rusage metrics are captured |
| 161 | assert!(p_ru.max_rss_kb > 0, "Parent RSS must be non-zero"); |
| 162 | assert!(c_ru.max_rss_kb > 0, "Candidate RSS must be non-zero"); |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn test_end_to_end_unmocked_lifecycle_admission_and_supervisor_rollback() { |
| 167 | let tmp = tempfile::tempdir().unwrap(); |
| 168 | let rsi_root = tmp.path().join(".rsi"); |
| 169 | let holdouts = rsi_root.join("holdouts"); |
| 170 | let outputs = rsi_root.join("eval_outputs"); |
| 171 | let candidate = tmp.path().join("cand"); |
| 172 | let parent = tmp.path().join("parent"); |
| 173 | fs::create_dir_all(&candidate).unwrap(); |
| 174 | fs::create_dir_all(&parent).unwrap(); |
| 175 | |
| 176 | let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); |
| 177 | fs::copy(&exe, candidate.join("spark-rsi")).unwrap(); |
| 178 | fs::copy(&exe, parent.join("spark-rsi")).unwrap(); |
| 179 | |
| 180 | // Seed protected holdouts |
| 181 | for suite in HoldoutSuite::builtin_suites() { |
| 182 | suite.save_to_dir(&holdouts).unwrap(); |
| 183 | } |
| 184 | |
| 185 | let signing_key = SigningKey::from_bytes(&[55u8; 32].into()).unwrap(); |
| 186 | let verifying_key = VerifyingKey::from(&signing_key); |
| 187 | |
| 188 | let judge = BlindJudge::new(holdouts, outputs.clone()) |
| 189 | .with_signing_key(signing_key) |
| 190 | .with_non_inferiority_margin(500.0); |
| 191 | |
| 192 | // 1. Evaluate candidate |
| 193 | let receipt = judge |
| 194 | .evaluate_cycle( |
| 195 | "cycle-e2e-01", |
| 196 | "cand-e2e-01", |
| 197 | "parent-e2e-00", |
| 198 | &candidate, |
| 199 | &parent, |
| 200 | ) |
| 201 | .expect("Evaluation cycle failed"); |
| 202 | |
| 203 | assert!(receipt.admitted, "Clean candidate must be admitted"); |
| 204 | assert!(receipt.passed_all_hard_invariants); |
| 205 | assert!(receipt.passed_statistical_gates); |
| 206 | assert!(receipt.verify_digest()); |
| 207 | assert!(receipt.signature.is_some()); |
| 208 | assert!(receipt.verify_signature(&verifying_key)); |
| 209 | |
| 210 | // 2. Route admitted candidate into HostSupervisor |
| 211 | let supervisor = HostSupervisor::new(&rsi_root, 49_152); |
| 212 | |
| 213 | // Stage parent generation first |
| 214 | supervisor |
| 215 | .stage_generation("gen-parent-00", &parent, "parent-digest-00") |
| 216 | .expect("Parent staging failed"); |
| 217 | supervisor |
| 218 | .atomic_symlink_swap("gen-parent-00") |
| 219 | .expect("Initial parent symlink swap failed"); |
| 220 | |
| 221 | // Stage admitted candidate generation |
| 222 | let mut gen_info = supervisor |
| 223 | .stage_generation("gen-e2e-01", &candidate, &receipt.receipt_digest) |
| 224 | .expect("Candidate staging failed"); |
| 225 | assert_eq!(gen_info.state, GenerationState::Staged); |
| 226 | |
| 227 | // Atomic symlink swap to point to candidate |
| 228 | supervisor |
| 229 | .atomic_symlink_swap("gen-e2e-01") |
| 230 | .expect("Candidate symlink swap failed"); |
| 231 | let active_link = fs::read_link(rsi_root.join("active")).unwrap(); |
| 232 | assert!(active_link.to_string_lossy().contains("gen-e2e-01")); |
| 233 | |
| 234 | // Worker self-reports are diagnostics: however many clean ones arrive, the generation stays |
| 235 | // on probation. Only a sealed supervisor-driven observation log can reach admission. |
| 236 | for _ in 0..25 { |
| 237 | let state = supervisor |
| 238 | .record_canary_transaction(&mut gen_info, true, 1000, 1_000_000, 0.0) |
| 239 | .expect("Canary update failed"); |
| 240 | assert_eq!(state, GenerationState::CanaryActive); |
| 241 | } |
| 242 | assert_ne!(gen_info.state, GenerationState::Durable); |
| 243 | |
| 244 | // A reported failure still triggers the early safety revert |
| 245 | let failed = supervisor.record_canary_transaction(&mut gen_info, false, 1000, 1_000_000, 0.0); |
| 246 | assert!(failed.is_err()); |
| 247 | assert_eq!(gen_info.state, GenerationState::Reverting); |
| 248 | |
| 249 | // Supervisor executes atomic rollback to parent |
| 250 | let rollback_res = supervisor.rollback_to_parent("gen-parent-00", None, None); |
| 251 | assert!(rollback_res.is_ok(), "Supervisor rollback failed"); |
| 252 | let reverted_link = fs::read_link(rsi_root.join("active")).unwrap(); |
| 253 | assert!(reverted_link.to_string_lossy().contains("gen-parent-00")); |
| 254 | } |
| 255 | |
| 256 | // --------------------------------------------------------------------------------------------- |
| 257 | // Daemon-level canary admission. The target repository is built from fixtures/canary-target and |
| 258 | // the daemon drives the real fixture executable through the supervisor. No test here lets a |
| 259 | // worker self-report success into admission. |
| 260 | // --------------------------------------------------------------------------------------------- |
| 261 | |
| 262 | static FIXTURE_ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); |
| 263 | |
| 264 | /// The build jail is the only thing that builds the candidate. Without bubblewrap there is no |
| 265 | /// jail, so the daemon tests cannot run and say so. Set RSI_REQUIRE_BUILD_JAIL=1 to make a |
| 266 | /// missing jail a failure instead of a skip. |
| 267 | fn build_jail_available() -> bool { |
| 268 | let ok = Command::new("bwrap") |
| 269 | .args([ |
| 270 | "--unshare-user", |
| 271 | "--unshare-pid", |
| 272 | "--unshare-net", |
| 273 | "--ro-bind", |
| 274 | "/usr", |
| 275 | "/usr", |
| 276 | "--ro-bind", |
| 277 | "/lib", |
| 278 | "/lib", |
| 279 | "--proc", |
| 280 | "/proc", |
| 281 | "--dev", |
| 282 | "/dev", |
| 283 | "/usr/bin/true", |
| 284 | ]) |
| 285 | .output() |
| 286 | .map(|o| o.status.success()) |
| 287 | .unwrap_or(false); |
| 288 | if !ok { |
| 289 | assert!( |
| 290 | std::env::var_os("RSI_REQUIRE_BUILD_JAIL").is_none(), |
| 291 | "RSI_REQUIRE_BUILD_JAIL is set but bubblewrap cannot run here" |
| 292 | ); |
| 293 | eprintln!( |
| 294 | "SKIPPED: bubblewrap cannot run in this environment, so the build jail is unavailable" |
| 295 | ); |
| 296 | } |
| 297 | ok |
| 298 | } |
| 299 | |
| 300 | fn git(dir: &Path, args: &[&str]) { |
| 301 | let out = Command::new("git") |
| 302 | .args(args) |
| 303 | .current_dir(dir) |
| 304 | .output() |
| 305 | .expect("git runs"); |
| 306 | assert!(out.status.success(), "git {:?} failed", args); |
| 307 | } |
| 308 | |
| 309 | /// A target repository: the fixture crate, a README with an em dash so the unslop proposal |
| 310 | /// exists, the pinned workload under `.rsi/canary`, holdouts and a signing key. With |
| 311 | /// `with_adapter` false the adapter manifest is left out. |
| 312 | struct Target { |
| 313 | _tmp: tempfile::TempDir, |
| 314 | repo: PathBuf, |
| 315 | config: RsiConfig, |
| 316 | } |
| 317 | |
| 318 | fn make_target(with_adapter: bool, pin: Option<&str>) -> Target { |
| 319 | let tmp = tempfile::tempdir().unwrap(); |
| 320 | let repo = tmp.path().join("repo"); |
| 321 | let sandbox = tmp.path().join("sandbox"); |
| 322 | let fx = canary_fixture::fixture_dir(); |
| 323 | fs::create_dir_all(repo.join("src")).unwrap(); |
| 324 | for f in ["Cargo.toml", "Cargo.lock"] { |
| 325 | fs::copy(fx.join(f), repo.join(f)).unwrap(); |
| 326 | } |
| 327 | fs::copy(fx.join("src/main.rs"), repo.join("src/main.rs")).unwrap(); |
| 328 | if with_adapter { |
| 329 | fs::copy( |
| 330 | fx.join("canary-adapter.toml"), |
| 331 | repo.join("canary-adapter.toml"), |
| 332 | ) |
| 333 | .unwrap(); |
| 334 | } |
| 335 | fs::write( |
| 336 | repo.join("README.md"), |
| 337 | "# Target\n\nWe build, fix, finish, and optimize systems with love, honor, and discipline\u{2014}with an em dash.\n", |
| 338 | ) |
| 339 | .unwrap(); |
| 340 | // The judge's paired benchmarks need the engine executable in the tree. |
| 341 | let exe = find_executable(Path::new(".")).expect("spark-rsi executable must exist"); |
| 342 | fs::copy(&exe, repo.join("spark-rsi")).unwrap(); |
| 343 | fs::write(repo.join(".gitignore"), "target\n").unwrap(); |
| 344 | git(&repo, &["init", "-b", "main"]); |
| 345 | git(&repo, &["config", "user.name", "Test Operator"]); |
| 346 | git(&repo, &["config", "user.email", "operator@test.local"]); |
| 347 | git(&repo, &["add", "."]); |
| 348 | git(&repo, &["commit", "-m", "initial commit"]); |
| 349 | |
| 350 | let rsi_root = repo.join(".rsi"); |
| 351 | let holdouts = rsi_root.join("holdouts"); |
| 352 | fs::create_dir_all(&holdouts).unwrap(); |
| 353 | for s in HoldoutSuite::builtin_suites() { |
| 354 | s.save_to_dir(&holdouts).unwrap(); |
| 355 | } |
| 356 | let workload = rsi_root.join("canary/workload.json"); |
| 357 | fs::create_dir_all(workload.parent().unwrap()).unwrap(); |
| 358 | fs::copy(fx.join("workload.json"), &workload).unwrap(); |
| 359 | let digest = CanaryWorkloadManifest::load(&workload).unwrap().digest; |
| 360 | |
| 361 | let signing_key = SigningKey::from_bytes(&[88u8; 32].into()).unwrap(); |
| 362 | let config = RsiConfig { |
| 363 | target_repo: repo.to_str().unwrap().to_string(), |
| 364 | cortex_url: "http://127.0.0.1:18080".to_string(), |
| 365 | cortex_space: "atlas-memory".to_string(), |
| 366 | loop_interval_secs: 60, |
| 367 | sandbox_root: sandbox.to_str().unwrap().to_string(), |
| 368 | rsi_root: ".rsi".to_string(), |
| 369 | holdouts_dir: None, |
| 370 | signing_key_hex: Some(hex::encode(signing_key.to_bytes())), |
| 371 | require_latency_improvement: false, |
| 372 | non_inferiority_margin: Some(250.0), |
| 373 | model_url: "http://127.0.0.1:9".to_string(), |
| 374 | canary_target: 10, |
| 375 | canary_workload_sha256: Some(pin.map(str::to_string).unwrap_or(digest)), |
| 376 | ..Default::default() |
| 377 | }; |
| 378 | Target { |
| 379 | _tmp: tmp, |
| 380 | repo, |
| 381 | config, |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | fn ledger_payloads(repo: &Path) -> Vec<String> { |
| 386 | ImprovementLedger::open(&repo.join(".rsi")) |
| 387 | .unwrap() |
| 388 | .all_blocks() |
| 389 | .unwrap() |
| 390 | .into_iter() |
| 391 | .map(|b| b.payload_json) |
| 392 | .collect() |
| 393 | } |
| 394 | |
| 395 | fn commitment(payloads: &[String]) -> Option<serde_json::Value> { |
| 396 | payloads.iter().find_map(|p| { |
| 397 | let v: serde_json::Value = serde_json::from_str(p).ok()?; |
| 398 | v.get("canary_commitment").cloned() |
| 399 | }) |
| 400 | } |
| 401 | |
| 402 | #[tokio::test] |
| 403 | async fn daemon_cycle_with_a_correct_fixture_reaches_the_later_gates() { |
| 404 | if !build_jail_available() |
| 405 | || !spark_rsi::not_run::user_scope_or_not_run( |
| 406 | "daemon_cycle_with_a_correct_fixture_reaches_the_later_gates", |
| 407 | ) |
| 408 | { |
| 409 | return; |
| 410 | } |
| 411 | let _guard = FIXTURE_ENV_LOCK.lock().await; |
| 412 | std::env::remove_var("RSI_CANARY_FIXTURE_MODE"); |
| 413 | let t = make_target(true, None); |
| 414 | |
| 415 | let result = RsiEngine::run_cycle(&t.config).await.expect("run_cycle"); |
| 416 | assert!(result.proposal.is_some(), "the em dash makes a proposal"); |
| 417 | let canary = result.canary.expect("canary summary"); |
| 418 | assert!(canary.applicable && canary.eligible, "{:?}", canary); |
| 419 | let binding = canary.identity_binding_digest.clone().expect("identity"); |
| 420 | assert_eq!(binding.len(), 64); |
| 421 | |
| 422 | // The sealed log: ten supervisor-verified observations, all qualifying. |
| 423 | let log_path = t.repo.join(format!( |
| 424 | ".rsi/canary/observations/{}.jsonl", |
| 425 | result.proposal.as_ref().unwrap().id |
| 426 | )); |
| 427 | let sealed = SealedObservationLog::load(&log_path).expect("sealed log verifies"); |
| 428 | assert_eq!(sealed.seal.observation_count, 10); |
| 429 | assert_eq!(sealed.seal.qualifying_count, 10); |
| 430 | assert_eq!( |
| 431 | canary.log_digest.as_deref(), |
| 432 | Some(sealed.seal.log_digest.as_str()) |
| 433 | ); |
| 434 | |
| 435 | // The ledger holds the commitment, bound to the identity and the sealed log. |
| 436 | let payloads = ledger_payloads(&t.repo); |
| 437 | let c = commitment(&payloads).expect("canary_commitment block in the ledger"); |
| 438 | assert_eq!(c["identity_binding_digest"], binding.as_str()); |
| 439 | assert_eq!(c["log_digest"], sealed.seal.log_digest.as_str()); |
| 440 | assert_eq!(c["qualifying_count"], 10); |
| 441 | assert_eq!(c["observation_count"], 10); |
| 442 | assert_eq!(c["rejection_count"], 0); |
| 443 | assert_eq!( |
| 444 | c["workload_digest"], |
| 445 | canary.workload_digest.as_deref().unwrap() |
| 446 | ); |
| 447 | assert!(c["adapter_manifest_digest"].as_str().unwrap().len() == 64); |
| 448 | assert!(canary.commitment_block_hash.is_some()); |
| 449 | |
| 450 | // Quota admission passed, the envelope ran and is recorded as a reference evaluation, and |
| 451 | // the promotion gate decided. |
| 452 | let quota = canary.quota.expect("quota decision"); |
| 453 | assert!(quota.admitted, "{:?}", quota); |
| 454 | assert_eq!(quota.counted, Some(10)); |
| 455 | assert_eq!(quota.target, 10); |
| 456 | assert!(canary.envelope.expect("envelope decision").passed); |
| 457 | assert!(canary |
| 458 | .envelope_note |
| 459 | .expect("envelope note") |
| 460 | .contains("DeterministicReferenceBackend")); |
| 461 | let gate = canary.promotion_gate.expect("promotion gate decision"); |
| 462 | // The in-process judge signs with the daemon's own key and binds no version 2 receipt, so |
| 463 | // the gate refuses in this cut (issue #35). Nothing becomes durable. |
| 464 | assert!(!gate.passed, "{:?}", gate); |
| 465 | assert!(!result.success); |
| 466 | assert!(result.generation.is_none()); |
| 467 | assert!(fs::read_link(t.repo.join(".rsi/active")).is_err()); |
| 468 | assert!(payloads |
| 469 | .iter() |
| 470 | .any(|p| p.contains("DeterministicReferenceBackend"))); |
| 471 | } |
| 472 | |
| 473 | #[tokio::test] |
| 474 | async fn daemon_cycle_with_a_wrong_answering_fixture_is_refused_and_rolled_back() { |
| 475 | if !build_jail_available() |
| 476 | || !spark_rsi::not_run::user_scope_or_not_run( |
| 477 | "daemon_cycle_with_a_wrong_answering_fixture_is_refused_and_rolled_back", |
| 478 | ) |
| 479 | { |
| 480 | return; |
| 481 | } |
| 482 | let _guard = FIXTURE_ENV_LOCK.lock().await; |
| 483 | std::env::set_var("RSI_CANARY_FIXTURE_MODE", "wrong_answer"); |
| 484 | let t = make_target(true, None); |
| 485 | let outcome = RsiEngine::run_cycle(&t.config).await; |
| 486 | std::env::remove_var("RSI_CANARY_FIXTURE_MODE"); |
| 487 | let result = outcome.expect("run_cycle"); |
| 488 | |
| 489 | let canary = result.canary.expect("canary summary"); |
| 490 | let quota = canary.quota.expect("quota decision"); |
| 491 | assert!(!quota.admitted, "{:?}", quota); |
| 492 | assert!(quota.refusal.is_some()); |
| 493 | assert!( |
| 494 | canary.envelope.is_none(), |
| 495 | "the envelope runs only after the quota" |
| 496 | ); |
| 497 | assert!(canary.promotion_gate.is_none()); |
| 498 | assert!(!result.success); |
| 499 | assert!(result.generation.is_none(), "nothing becomes durable"); |
| 500 | assert!(fs::read_link(t.repo.join(".rsi/active")).is_err()); |
| 501 | assert!(fs::read_link(t.repo.join(".rsi/active.sock")).is_err()); |
| 502 | |
| 503 | let payloads = ledger_payloads(&t.repo); |
| 504 | assert!( |
| 505 | commitment(&payloads).is_some(), |
| 506 | "the commitment precedes admission" |
| 507 | ); |
| 508 | assert!( |
| 509 | payloads |
| 510 | .iter() |
| 511 | .any(|p| p.contains("\"reason\"") && p.contains("rolled_back_at")), |
| 512 | "a rollback block records the reason" |
| 513 | ); |
| 514 | } |
| 515 | |
| 516 | #[tokio::test] |
| 517 | async fn daemon_cycle_refuses_a_target_without_an_adapter_before_any_worker_starts() { |
| 518 | let _guard = FIXTURE_ENV_LOCK.lock().await; |
| 519 | let t = make_target(false, None); |
| 520 | let result = RsiEngine::run_cycle(&t.config).await.expect("run_cycle"); |
| 521 | |
| 522 | let canary = result.canary.expect("canary summary"); |
| 523 | assert!(canary.applicable); |
| 524 | assert!(!canary.eligible); |
| 525 | assert!(canary.refusal.unwrap().contains("not eligible for canary")); |
| 526 | assert!( |
| 527 | result.proposal.is_some(), |
| 528 | "the judge ran, the canary refused" |
| 529 | ); |
| 530 | assert!(!result.success); |
| 531 | assert!(canary.quota.is_none() && canary.log_digest.is_none()); |
| 532 | assert!(result.generation.is_none()); |
| 533 | assert!( |
| 534 | !t.repo.join(".rsi/canary/observations").exists(), |
| 535 | "no worker started, so no observation log exists" |
| 536 | ); |
| 537 | assert!(!t.repo.join(".rsi/workers").exists()); |
| 538 | assert!(ledger_payloads(&t.repo) |
| 539 | .iter() |
| 540 | .any(|p| p.contains("not eligible for canary"))); |
| 541 | } |
| 542 | |
| 543 | #[tokio::test] |
| 544 | async fn daemon_cycle_refuses_a_mismatched_or_missing_workload_pin() { |
| 545 | let _guard = FIXTURE_ENV_LOCK.lock().await; |
| 546 | let wrong = "0".repeat(64); |
| 547 | let t = make_target(true, Some(&wrong)); |
| 548 | let err = RsiEngine::run_cycle(&t.config).await.unwrap_err(); |
| 549 | assert!(err.contains("canary workload refused"), "{}", err); |
| 550 | assert!(err.contains("pinned digest"), "{}", err); |
| 551 | assert!(!t.repo.join(".rsi/canary/observations").exists()); |
| 552 | |
| 553 | // Unpinned fails closed in production mode. |
| 554 | let mut unpinned = make_target(true, None); |
| 555 | unpinned.config.canary_workload_sha256 = None; |
| 556 | let err = RsiEngine::run_cycle(&unpinned.config).await.unwrap_err(); |
| 557 | assert!(err.contains("must pin the canary workload"), "{}", err); |
| 558 | } |
| 559 | |
| 560 | #[tokio::test] |
| 561 | async fn exemption_is_explicit_configuration_and_never_covers_executable_changes() { |
| 562 | // Default policy: nothing is exempt, so a documentation-like proposal in a tree that ships |
| 563 | // an adapter is still canary-applicable. |
| 564 | let _guard = FIXTURE_ENV_LOCK.lock().await; |
| 565 | let t = make_target(false, None); |
| 566 | assert!(t.config.canary_exempt_kinds.is_empty()); |
| 567 | let result = RsiEngine::run_cycle(&t.config).await.expect("run_cycle"); |
| 568 | assert!(result.canary.expect("summary").applicable); |
| 569 | |
| 570 | // Listing the kind exempts it only when nothing executable is involved. This tree ships no |
| 571 | // adapter and its engine executable is already present, so the change is exempt by |
| 572 | // configuration. The exemption skips the canary only: the envelope and the promotion gate |
| 573 | // still decide, and the gate still refuses. |
| 574 | let mut listed = make_target(false, None); |
| 575 | listed.config.canary_exempt_kinds = vec![ProposalKind::UnslopSanitization]; |
| 576 | let result = RsiEngine::run_cycle(&listed.config) |
| 577 | .await |
| 578 | .expect("run_cycle"); |
| 579 | let canary = result.canary.expect("summary"); |
| 580 | assert!(!canary.applicable); |
| 581 | assert!(canary.exemption.is_some()); |
| 582 | assert!(canary.quota.is_none() && canary.log_digest.is_none()); |
| 583 | assert!(canary.envelope.expect("envelope still runs").passed); |
| 584 | assert!(!canary.promotion_gate.expect("gate still decides").passed); |
| 585 | assert!(!result.success && result.generation.is_none()); |
| 586 | assert!(!listed.repo.join(".rsi/canary/observations").exists()); |
| 587 | |
| 588 | // A tree that declares an adapter is executable: listing the kind exempts nothing. The |
| 589 | // unpinned workload stops the cycle, which proves canary admission was required. |
| 590 | let mut executable = make_target(true, None); |
| 591 | executable.config.canary_exempt_kinds = vec![ProposalKind::UnslopSanitization]; |
| 592 | executable.config.canary_workload_sha256 = None; |
| 593 | let err = RsiEngine::run_cycle(&executable.config).await.unwrap_err(); |
| 594 | assert!(err.contains("must pin the canary workload"), "{}", err); |
| 595 | } |