interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / soak / runner.rs

784 lines · 34113 bytes Raw Blame History
1use crate::actor::BlindJudge;
2use crate::balance::BalanceKernel;
3use crate::evaluator::EvaluationReceipt;
4use crate::isolation::BuildJail;
5use crate::ledger::{BlockType, ImprovementLedger, LedgerBlock};
6use crate::measure::{build_capability_graph, measure_stages, MeasureContext, SampleLog};
7use crate::meta::TrueRsiEvaluator;
8use crate::models::{ImprovementProposal, ProposalKind, RsiConfig};
9use crate::observe::observe_codebase;
10use crate::propose::{
11 cortex::CortexExperienceClient, model_seat::ModelSeatClient, DefectCategory, DiagnosticContext,
12 HypothesisContract, ProposalGenerator,
13};
14use crate::ratify::Ratifier;
15use crate::soak::manifest::*;
16use crate::verifier::InvariantVerifier;
17use chrono::Utc;
18use sha2::{Digest, Sha256};
19use std::path::{Path, PathBuf};
20use std::process::Command;
21use uuid::Uuid;
22
23#[derive(Debug, Clone)]
24pub struct SoakConfig {
25 pub target_repo: String,
26 pub rsi_root: String,
27 pub sandbox_root: String,
28 pub holdouts_dir: Option<String>,
29 pub signing_key_hex: Option<String>,
30 pub operator_key_hex: Option<String>,
31 pub cortex_url: String,
32 pub cortex_space: String,
33 pub model_url: String,
34 pub model_id: String,
35 pub total_cycles: usize,
36 pub candidates_per_cycle: usize,
37 pub canary_target: usize,
38 pub non_inferiority_margin: Option<f64>,
39 pub writable_prefixes: Vec<String>,
40}
41
42impl Default for SoakConfig {
43 fn default() -> Self {
44 Self {
45 target_repo: ".".to_string(),
46 rsi_root: ".rsi".to_string(),
47 sandbox_root: "/tmp/spark-rsi-soak".to_string(),
48 holdouts_dir: None,
49 signing_key_hex: None,
50 operator_key_hex: None,
51 cortex_url: "http://127.0.0.1:18080".to_string(),
52 cortex_space: "atlas-memory".to_string(),
53 model_url: "http://127.0.0.1:18006/v1".to_string(),
54 model_id: "atlas-lightning-omni".to_string(),
55 total_cycles: 5,
56 candidates_per_cycle: 3,
57 canary_target: 5000,
58 non_inferiority_margin: Some(10.0),
59 writable_prefixes: vec![
60 "src/propose/".to_string(),
61 "src/graph/".to_string(),
62 "src/observe.rs".to_string(),
63 ],
64 }
65 }
66}
67
68pub struct SoakRunner;
69
70/// The measurement view of a soak configuration: the same workload key and execution-profile
71/// fingerprint fields the daemon uses, so soak cycles read the same stage-sample log.
72fn measure_config(config: &SoakConfig) -> RsiConfig {
73 RsiConfig {
74 target_repo: config.target_repo.clone(),
75 cortex_url: config.cortex_url.clone(),
76 cortex_space: config.cortex_space.clone(),
77 sandbox_root: config.sandbox_root.clone(),
78 rsi_root: config.rsi_root.clone(),
79 holdouts_dir: config.holdouts_dir.clone(),
80 model_url: config.model_url.clone(),
81 model_id: config.model_id.clone(),
82 canary_target: config.canary_target as u64,
83 non_inferiority_margin: config.non_inferiority_margin,
84 ..RsiConfig::default()
85 }
86}
87
88impl SoakRunner {
89 pub async fn run_batch(config: &SoakConfig) -> Result<SoakRunManifest, String> {
90 let run_id = format!("soak-{}", &Uuid::new_v4().simple().to_string()[..12]);
91 let started_at = Utc::now().to_rfc3339();
92 let repo_path = Path::new(&config.target_repo);
93 let rsi_root = repo_path.join(&config.rsi_root);
94 let sandbox_base = Path::new(&config.sandbox_root);
95
96 // Step 1: Capture Engine N Snapshot
97 let engine_n_snapshot = Self::capture_engine_n(
98 repo_path,
99 &config.model_id,
100 config.operator_key_hex.as_deref(),
101 );
102
103 // Step 2: Resolve Signing Key
104 let signing_key_hex = config.signing_key_hex.as_ref().ok_or_else(|| {
105 "Fatal: Missing cryptographic signing key (signing_key_hex). Soak run fails closed."
106 .to_string()
107 })?;
108 let key_bytes = hex::decode(signing_key_hex)
109 .map_err(|e| format!("Fatal: Invalid signing_key_hex: {}", e))?;
110 let signing_key = p256::ecdsa::SigningKey::from_slice(&key_bytes)
111 .map_err(|e| format!("Fatal: Invalid P-256 signing key: {}", e))?;
112
113 // Step 3: Resolve Holdouts Path
114 let holdouts_path = config
115 .holdouts_dir
116 .as_ref()
117 .map(PathBuf::from)
118 .unwrap_or_else(|| rsi_root.join("holdouts"));
119
120 // Step 4: Run Preflight Checks (Cycle 1 Gate)
121 let preflight_result = Self::run_preflight_checks(
122 repo_path,
123 &rsi_root,
124 &holdouts_path,
125 Some(signing_key_hex.as_str()),
126 );
127
128 if let Err(preflight_err) = preflight_result {
129 eprintln!("❌ Preflight check failed in Cycle 1: {}", preflight_err);
130 let manifest = SoakRunManifest {
131 manifest_version: "1.0.0".to_string(),
132 run_id: run_id.clone(),
133 started_at: started_at.clone(),
134 completed_at: Utc::now().to_rfc3339(),
135 engine_n_snapshot,
136 cycles: Vec::new(),
137 admitted_candidates: Vec::new(),
138 exhausted_hypotheses: Vec::new(),
139 final_merkle_checkpoint: None,
140 total_candidates_evaluated: 0,
141 total_candidates_admitted: 0,
142 preflight_passed: false,
143 overall_status: "PREFLIGHT_ABORTED".to_string(),
144 };
145 let manifest_path = rsi_root.join(format!("soak_manifest_{}.json", run_id));
146 let _ = manifest.save_to_file(&manifest_path);
147 return Err(format!("Preflight aborted: {}", preflight_err));
148 }
149
150 let ledger = ImprovementLedger::open(&rsi_root)
151 .map_err(|e| format!("Fatal: Failed to open ImprovementLedger: {}", e))?;
152
153 let mut quarantine_tracker = HypothesisQuarantineTracker::new();
154 let mut cycle_records = Vec::new();
155 let mut admitted_candidates = Vec::new();
156 let mut total_candidates_evaluated = 0;
157 let mut total_candidates_admitted = 0;
158 let model_seat = ModelSeatClient::new(&config.model_url, &config.model_id);
159
160 // Step 5: Execute Autonomous Bounded Cycles
161 for cycle_index in 1..=config.total_cycles {
162 println!(
163 "⚡ [Soak Run] Starting Cycle {} of {}",
164 cycle_index, config.total_cycles
165 );
166 let cycle_id = format!("soak-{}-c{:02}", run_id, cycle_index);
167 let thermal_before = ThermalSnapshot::capture();
168
169 // Observation and the pipeline graph: measured stage samples from completed prior cycles,
170 // never constants. Without enough compatible samples the ranking is structural.
171 let codebase_obs = observe_codebase(repo_path)?;
172 let measure_cfg = measure_config(config);
173 let measure_ctx = MeasureContext::for_config(&measure_cfg, repo_path);
174 let measurements = measure_stages(
175 SampleLog::new(&rsi_root).read_complete(),
176 &cycle_id,
177 &measure_ctx,
178 &measure_cfg,
179 );
180 let graph = build_capability_graph(&measurements)?;
181
182 // Find top bottleneck not quarantined
183 let ranked = graph.rank_bottlenecks();
184 let chosen_bottleneck = ranked
185 .iter()
186 .find(|b| !quarantine_tracker.is_exhausted(&b.node_name, &b.causal_explanation))
187 .or_else(|| ranked.first());
188
189 let bottleneck = match chosen_bottleneck {
190 Some(b) => (*b).clone(),
191 None => {
192 eprintln!(
193 "Warning: No bottlenecks available in graph for cycle {}",
194 cycle_index
195 );
196 break;
197 }
198 };
199
200 let hypothesis_problem = format!(
201 "High latency on {}: {}",
202 bottleneck.node_name, bottleneck.causal_explanation
203 );
204 let hypothesis_id = format!("hypo-{}", &Uuid::new_v4().simple().to_string()[..12]);
205 // A numeric latency target only when the stage's latency is measured; otherwise an
206 // exploratory hypothesis with no performance claim.
207 let hypothesis = HypothesisContract::from_bottleneck(
208 &hypothesis_id,
209 &cycle_id,
210 &bottleneck,
211 measure_cfg.measure_target_improvement_pct,
212 )
213 .with_protected_metric("correctness", 0.0)
214 .with_falsification_test("assert!(receipt.passed_all_hard_invariants)");
215
216 // Cortex recall
217 let cortex =
218 CortexExperienceClient::new(&config.cortex_url).with_space(&config.cortex_space);
219 let past_lessons = cortex
220 .recall_lessons(
221 &format!(
222 "{} {}",
223 hypothesis.observed_problem, hypothesis.suspected_root_cause
224 ),
225 3,
226 )
227 .await;
228
229 // Map bottleneck to target file within writable prefixes
230 let target_file = match bottleneck.node_name.as_str() {
231 "Propose" => "src/propose/hypothesis.rs",
232 _ => "src/observe.rs",
233 };
234
235 let full_target_path = repo_path.join(target_file);
236 let parent_content = std::fs::read_to_string(&full_target_path).unwrap_or_default();
237
238 let mut candidate_records: Vec<CycleCandidateRecord> = Vec::new();
239 let mut admissible_proposals: Vec<(
240 ImprovementProposal,
241 EvaluationReceipt,
242 LedgerBlock,
243 )> = Vec::new();
244
245 // Candidate Generation Loop: exactly 3 isolated candidates against identical parent
246 for cand_idx in 1..=config.candidates_per_cycle {
247 let cand_id = format!("{}-c{}", cycle_id, cand_idx);
248 println!(
249 " [Candidate {}/{}] Generating patch for {}",
250 cand_idx, config.candidates_per_cycle, target_file
251 );
252
253 let mut maybe_prop = None;
254
255 if model_seat.is_available().await {
256 let variation_directive = match cand_idx {
257 1 => "Candidate variation 1 of 3: Focus on algorithmic simplification and data locality.",
258 2 => "Candidate variation 2 of 3: Focus on loop unrolling and branch prediction efficiency.",
259 _ => "Candidate variation 3 of 3: Focus on memory allocation reduction and cache line alignment.",
260 };
261
262 let diag = DiagnosticContext::from_violations(
263 &cycle_id,
264 target_file,
265 &parent_content,
266 DefectCategory::PerformanceRegression,
267 vec![
268 format!("Bottleneck: {}", bottleneck.node_name),
269 variation_directive.to_string(),
270 ],
271 past_lessons.clone(),
272 )
273 .with_hypothesis(hypothesis.clone());
274
275 if let Ok(prop) =
276 ProposalGenerator::propose_from_diagnosis(&model_seat, &diag).await
277 {
278 maybe_prop = Some(prop);
279 }
280 }
281
282 if maybe_prop.is_none() && cand_idx == 1 {
283 if let Some(prop) = ProposalGenerator::scan_and_propose_unslop(repo_path) {
284 maybe_prop = Some(prop);
285 }
286 }
287
288 let mut candidate = match maybe_prop {
289 Some(mut p) => {
290 p.id = cand_id.clone();
291 p
292 }
293 None => {
294 candidate_records.push(CycleCandidateRecord {
295 candidate_id: cand_id,
296 candidate_index: cand_idx,
297 target_file: target_file.to_string(),
298 proposed_patch_digest: "none".to_string(),
299 compilation_passed: false,
300 invariants_passed: false,
301 judge_admitted: false,
302 primary_metric_name: "latency_us".to_string(),
303 primary_metric_value: 0.0,
304 rejection_reason: Some(
305 "Model generation failed to produce valid code".to_string(),
306 ),
307 ledger_block_hash: None,
308 });
309 total_candidates_evaluated += 1;
310 continue;
311 }
312 };
313
314 // Validate Tier 2 boundaries
315 let normalized_target = candidate
316 .target_file
317 .trim_start_matches("./")
318 .trim_start_matches('/');
319 let is_permitted = config.writable_prefixes.iter().any(|prefix| {
320 normalized_target == prefix.trim_end_matches('/')
321 || normalized_target.starts_with(prefix)
322 });
323
324 if !is_permitted {
325 let reason = format!(
326 "Tier 2 boundary violation: {} is outside permitted soak surface",
327 candidate.target_file
328 );
329 let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]);
330 candidate_records.push(CycleCandidateRecord {
331 candidate_id: cand_id,
332 candidate_index: cand_idx,
333 target_file: candidate.target_file.clone(),
334 proposed_patch_digest: hex::encode(Sha256::digest(
335 candidate.proposed_patch.as_bytes(),
336 )),
337 compilation_passed: false,
338 invariants_passed: false,
339 judge_admitted: false,
340 primary_metric_name: "latency_us".to_string(),
341 primary_metric_value: 0.0,
342 rejection_reason: Some(reason),
343 ledger_block_hash: None,
344 });
345 total_candidates_evaluated += 1;
346 continue;
347 }
348
349 // Stage in sandbox
350 let sandbox_dir = match ProposalGenerator::stage_in_sandbox(
351 &mut candidate,
352 repo_path,
353 sandbox_base,
354 ) {
355 Ok(dir) => dir,
356 Err(e) => {
357 let reason = format!("Staging failed: {}", e);
358 let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]);
359 candidate_records.push(CycleCandidateRecord {
360 candidate_id: cand_id,
361 candidate_index: cand_idx,
362 target_file: candidate.target_file.clone(),
363 proposed_patch_digest: hex::encode(Sha256::digest(
364 candidate.proposed_patch.as_bytes(),
365 )),
366 compilation_passed: false,
367 invariants_passed: false,
368 judge_admitted: false,
369 primary_metric_name: "latency_us".to_string(),
370 primary_metric_value: 0.0,
371 rejection_reason: Some(reason),
372 ledger_block_hash: None,
373 });
374 total_candidates_evaluated += 1;
375 continue;
376 }
377 };
378 let build_output = tempfile::tempdir()
379 .map_err(|e| format!("Cannot create private build output: {}", e))?;
380
381 // Compile inside Jail 1
382 let mut comp_passed = true;
383 if sandbox_dir.join("Cargo.toml").exists() {
384 let build_jail = BuildJail::new(
385 "spark-rsi-builder:latest",
386 &sandbox_dir,
387 build_output.path(),
388 );
389 match build_jail.execute_bwrap(&[
390 "cargo",
391 "build",
392 "--release",
393 "--offline",
394 "--locked",
395 "-j2",
396 ]) {
397 Ok((success, _stdout, stderr)) => {
398 if !success {
399 comp_passed = false;
400 let _ = ledger.append_block(
401 BlockType::Evaluation,
402 format!("Build Jail compile failed: {}", stderr),
403 vec![],
404 );
405 }
406 }
407 Err(e) => {
408 comp_passed = false;
409 let _ = ledger.append_block(
410 BlockType::Evaluation,
411 format!("Build Jail execution error: {}", e),
412 vec![],
413 );
414 }
415 }
416 }
417
418 if !comp_passed {
419 candidate_records.push(CycleCandidateRecord {
420 candidate_id: cand_id,
421 candidate_index: cand_idx,
422 target_file: candidate.target_file.clone(),
423 proposed_patch_digest: hex::encode(Sha256::digest(
424 candidate.proposed_patch.as_bytes(),
425 )),
426 compilation_passed: false,
427 invariants_passed: false,
428 judge_admitted: false,
429 primary_metric_name: "latency_us".to_string(),
430 primary_metric_value: 0.0,
431 rejection_reason: Some("Failed to compile in Jail 1".to_string()),
432 ledger_block_hash: None,
433 });
434 total_candidates_evaluated += 1;
435 continue;
436 }
437
438 // Invariant verification
439 let inv_report = InvariantVerifier::run_full_verification(&sandbox_dir);
440 let balance_verdict = BalanceKernel::evaluate(
441 codebase_obs.soul_tension.drive_score,
442 codebase_obs.soul_tension.humanity_score,
443 );
444 let is_balanced = balance_verdict.verdict == "balanced";
445
446 if !inv_report.passed || !is_balanced {
447 let reason = format!(
448 "Invariants or Balance failed (inv={}, bal={})",
449 inv_report.passed, is_balanced
450 );
451 let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]);
452 candidate_records.push(CycleCandidateRecord {
453 candidate_id: cand_id,
454 candidate_index: cand_idx,
455 target_file: candidate.target_file.clone(),
456 proposed_patch_digest: hex::encode(Sha256::digest(
457 candidate.proposed_patch.as_bytes(),
458 )),
459 compilation_passed: true,
460 invariants_passed: false,
461 judge_admitted: false,
462 primary_metric_name: "latency_us".to_string(),
463 primary_metric_value: 0.0,
464 rejection_reason: Some(reason),
465 ledger_block_hash: None,
466 });
467 total_candidates_evaluated += 1;
468 continue;
469 }
470
471 // Blind Judge Evaluation in Jail 2
472 let output_dir = sandbox_base.join("eval_outputs");
473 let mut judge = BlindJudge::new(holdouts_path.clone(), output_dir)
474 .with_signing_key(signing_key.clone())
475 .with_non_inferiority_margin(config.non_inferiority_margin.unwrap_or(10.0));
476 judge.require_latency_improvement = false;
477
478 let receipt = match judge.evaluate_cycle(
479 &cycle_id,
480 &candidate.id,
481 "parent",
482 &sandbox_dir,
483 repo_path,
484 ) {
485 Ok(r) => r,
486 Err(e) => {
487 let reason = format!("Blind Judge error: {}", e);
488 let _ = ledger.append_block(BlockType::Evaluation, reason.clone(), vec![]);
489 candidate_records.push(CycleCandidateRecord {
490 candidate_id: cand_id,
491 candidate_index: cand_idx,
492 target_file: candidate.target_file.clone(),
493 proposed_patch_digest: hex::encode(Sha256::digest(
494 candidate.proposed_patch.as_bytes(),
495 )),
496 compilation_passed: true,
497 invariants_passed: true,
498 judge_admitted: false,
499 primary_metric_name: "latency_us".to_string(),
500 primary_metric_value: 0.0,
501 rejection_reason: Some(reason),
502 ledger_block_hash: None,
503 });
504 total_candidates_evaluated += 1;
505 continue;
506 }
507 };
508
509 let raw_json = serde_json::to_vec(&receipt).unwrap_or_default();
510 let blk = ledger
511 .append_evaluation(&receipt, Some(&raw_json))
512 .map_err(|e| format!("Failed to append evaluation: {}", e))?;
513 let block_hash = blk.block_hash.clone();
514
515 let metric_val = receipt
516 .metrics_summary
517 .as_ref()
518 .map(|m| m.latency_delta_pct)
519 .unwrap_or(0.0);
520
521 candidate_records.push(CycleCandidateRecord {
522 candidate_id: cand_id,
523 candidate_index: cand_idx,
524 target_file: candidate.target_file.clone(),
525 proposed_patch_digest: hex::encode(Sha256::digest(
526 candidate.proposed_patch.as_bytes(),
527 )),
528 compilation_passed: true,
529 invariants_passed: true,
530 judge_admitted: receipt.admitted,
531 primary_metric_name: "latency_delta_pct".to_string(),
532 primary_metric_value: metric_val,
533 rejection_reason: if receipt.admitted {
534 None
535 } else {
536 Some("Judge non-inferiority margin exceeded or holdout failure".to_string())
537 },
538 ledger_block_hash: Some(block_hash),
539 });
540 total_candidates_evaluated += 1;
541
542 if receipt.admitted {
543 admissible_proposals.push((candidate, receipt, blk));
544 }
545 }
546
547 // Multi-comparison candidate selection among admissible proposals
548 let mut winning_cand_id = None;
549 let mut cycle_cortex_receipt = None;
550
551 if admissible_proposals.is_empty() {
552 println!(
553 " ❌ Cycle {}: No admissible candidates produced.",
554 cycle_index
555 );
556 let newly_exhausted = quarantine_tracker.record_failure(
557 &bottleneck.node_name,
558 &hypothesis_problem,
559 "No admissible candidates in 3 variations",
560 );
561 if newly_exhausted {
562 println!(" ⚠️ Hypothesis/Bottleneck pairing marked EXHAUSTED_FOR_GENERATION_N: {}:{}", bottleneck.node_name, &hypothesis_problem[..20]);
563 }
564
565 // Record negative experience in Cortex
566 let dummy_cand = ImprovementProposal {
567 id: format!("{}-c0", cycle_id),
568 title: "Performance Optimization Attempt".to_string(),
569 description: "Automated candidate variation".to_string(),
570 target_file: target_file.to_string(),
571 proposed_patch: String::new(),
572 kind: ProposalKind::Optimization,
573 created_at: Utc::now().to_rfc3339(),
574 sandbox_path: None,
575 operator_signature: None,
576 };
577 let _ = Ratifier::record_cortex_lesson(
578 &dummy_cand,
579 None,
580 None,
581 &config.cortex_url,
582 &config.cortex_space,
583 )
584 .await;
585 } else {
586 // Select winner deterministically by lowest latency delta pct
587 admissible_proposals.sort_by(|a, b| {
588 let lat_a =
589 a.1.metrics_summary
590 .as_ref()
591 .map(|m| m.latency_delta_pct)
592 .unwrap_or(0.0);
593 let lat_b =
594 b.1.metrics_summary
595 .as_ref()
596 .map(|m| m.latency_delta_pct)
597 .unwrap_or(0.0);
598 lat_a
599 .partial_cmp(&lat_b)
600 .unwrap_or(std::cmp::Ordering::Equal)
601 });
602
603 let (winner_prop, winner_rcpt, winner_blk) = admissible_proposals.remove(0);
604 winning_cand_id = Some(winner_prop.id.clone());
605 quarantine_tracker.record_success(&bottleneck.node_name, &hypothesis_problem);
606 total_candidates_admitted += 1;
607
608 let best_metric = winner_rcpt
609 .metrics_summary
610 .as_ref()
611 .map(|m| m.latency_delta_pct)
612 .unwrap_or(0.0);
613 println!(
614 " ⭐ Winning Admissible Candidate: {} (latency delta={:.2}%, ledger block={})",
615 winner_prop.id,
616 best_metric,
617 &winner_blk.block_hash[..12]
618 );
619
620 // True RSI Criteria 1 & 2 Evaluation
621 let crit_1 = TrueRsiEvaluator::evaluate_criterion_1_novel_discovery(
622 &hypothesis.observed_problem,
623 true,
624 &["hardcoded", "static_rule"],
625 );
626 let crit_2 = TrueRsiEvaluator::evaluate_criterion_2_self_capability_improvement(
627 true,
628 &format!("latency improved by {:.2}% ", best_metric),
629 );
630
631 // Stage into .rsi/admitted/<ledger_block_hash>/
632 let staging_dir = rsi_root.join("admitted").join(&winner_blk.block_hash);
633 let _ = std::fs::create_dir_all(&staging_dir);
634 let _ = std::fs::write(staging_dir.join("patch.diff"), &winner_prop.proposed_patch);
635 let _ = std::fs::write(
636 staging_dir.join("evaluation_receipt.json"),
637 serde_json::to_string_pretty(&winner_rcpt).unwrap_or_default(),
638 );
639 let _ = std::fs::write(
640 staging_dir.join("ledger_block.json"),
641 serde_json::to_string_pretty(&winner_blk).unwrap_or_default(),
642 );
643
644 admitted_candidates.push(AdmittedMetaCandidate {
645 candidate_id: winner_prop.id.clone(),
646 ledger_block_hash: winner_blk.block_hash.clone(),
647 staging_dir: staging_dir.display().to_string(),
648 patch_digest: hex::encode(Sha256::digest(
649 winner_prop.proposed_patch.as_bytes(),
650 )),
651 criteria_1_novel_discovery: crit_1.passed,
652 criteria_2_self_capability_gain: crit_2.passed,
653 classification: "META_CANDIDATE".to_string(),
654 });
655
656 // Record positive outcome to Cortex citing ledger hash
657 let (receipt_id, _success) = Ratifier::record_cortex_lesson(
658 &winner_prop,
659 None,
660 Some(&winner_blk.block_hash),
661 &config.cortex_url,
662 &config.cortex_space,
663 )
664 .await;
665 cycle_cortex_receipt = receipt_id;
666 }
667
668 // Merkle Checkpoint after each cycle
669 let checkpoint = ledger.checkpoint(Some(&signing_key)).ok();
670 let cp_hash = checkpoint.as_ref().map(|c| c.merkle_root.clone());
671 let thermal_after = ThermalSnapshot::capture();
672
673 cycle_records.push(CycleRecord {
674 cycle_index,
675 cycle_id,
676 bottleneck_node: bottleneck.node_name.clone(),
677 hypothesis_id: hypothesis.id.clone(),
678 hypothesis_problem: hypothesis.observed_problem.clone(),
679 candidates: candidate_records,
680 winning_candidate_id: winning_cand_id,
681 merkle_checkpoint_hash: cp_hash,
682 thermal_before,
683 thermal_after,
684 cortex_receipt_id: cycle_cortex_receipt,
685 status: "COMPLETED".to_string(),
686 });
687 }
688
689 let completed_at = Utc::now().to_rfc3339();
690 let final_cp = ledger
691 .checkpoint(Some(&signing_key))
692 .ok()
693 .map(|c| c.merkle_root);
694
695 let manifest = SoakRunManifest {
696 manifest_version: "1.0.0".to_string(),
697 run_id: run_id.clone(),
698 started_at,
699 completed_at,
700 engine_n_snapshot,
701 cycles: cycle_records,
702 admitted_candidates,
703 exhausted_hypotheses: quarantine_tracker.exhausted_list(),
704 final_merkle_checkpoint: final_cp,
705 total_candidates_evaluated,
706 total_candidates_admitted,
707 preflight_passed: true,
708 overall_status: "SUCCESS".to_string(),
709 };
710
711 let manifest_file = rsi_root.join(format!("soak_manifest_{}.json", run_id));
712 manifest.save_to_file(&manifest_file)?;
713 println!(
714 "⚡ [Soak Run] Completed successfully. Manifest saved to: {}",
715 manifest_file.display()
716 );
717
718 Ok(manifest)
719 }
720
721 fn capture_engine_n(repo_path: &Path, model_id: &str, op_key: Option<&str>) -> EngineNSnapshot {
722 let commit_sha = Command::new("git")
723 .current_dir(repo_path)
724 .args(["rev-parse", "HEAD"])
725 .output()
726 .ok()
727 .and_then(|o| String::from_utf8(o.stdout).ok())
728 .map(|s| s.trim().to_string())
729 .unwrap_or_else(|| "unknown_sha".to_string());
730
731 EngineNSnapshot {
732 commit_sha,
733 evaluator_version: spark_rsi::version().to_string(),
734 holdout_bundle_digest: "sha256:holdouts-bundle-authoritative".to_string(),
735 builder_digest: "sha256:spark-rsi-builder-pinned".to_string(),
736 model_id: model_id.to_string(),
737 cortex_snapshot_ref: Utc::now().to_rfc3339(),
738 operator_verifying_key: op_key.map(|s| s.to_string()),
739 }
740 }
741
742 fn run_preflight_checks(
743 repo_path: &Path,
744 rsi_root: &Path,
745 holdouts_path: &Path,
746 signing_key_hex: Option<&str>,
747 ) -> Result<(), String> {
748 let bwrap_out = Command::new("bwrap")
749 .arg("--version")
750 .output()
751 .map_err(|e| format!("Preflight containment check failed: bwrap missing: {}", e))?;
752 if !bwrap_out.status.success() {
753 return Err(
754 "Preflight containment check failed: bwrap returned non-zero exit code".to_string(),
755 );
756 }
757
758 let key_hex = signing_key_hex
759 .ok_or_else(|| "Preflight failed: missing signing_key_hex".to_string())?;
760 let key_bytes = hex::decode(key_hex)
761 .map_err(|e| format!("Preflight failed: invalid hex signing key: {}", e))?;
762 let _ = p256::ecdsa::SigningKey::from_slice(&key_bytes)
763 .map_err(|e| format!("Preflight failed: invalid P-256 signing key: {}", e))?;
764
765 let _ = ImprovementLedger::open(rsi_root)
766 .map_err(|e| format!("Preflight failed: cannot open improvement ledger: {}", e))?;
767
768 if !holdouts_path.exists() {
769 return Err(format!(
770 "Preflight failed: holdouts directory {:?} does not exist",
771 holdouts_path
772 ));
773 }
774
775 if !repo_path.join("Cargo.toml").exists() {
776 return Err(format!(
777 "Preflight failed: Cargo.toml not found in target repo {:?}",
778 repo_path
779 ));
780 }
781
782 Ok(())
783 }
784}