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 / examples / canary_qualification.rs

323 lines · 14067 bytes Raw Blame History
1//! Qualification run for the M1+M2 cut (docs/plans/2026-10-12-evidence-driven-rsi-cut.md,
2//! sections "Qualification fixture" and "Evidence package").
3//!
4//! Builds a target repository from `fixtures/canary-target`, runs one real RSI cycle through the
5//! build jail, the supervisor-driven canary and admission, and writes the evidence package to
6//! `--out`: the cycle result, the pinned workload and its digest, the adapter manifest, the
7//! sealed observation log and its verified summary, every ledger block and the chain audit, the
8//! stage samples, the environment, and a human-readable summary.
9//!
10//! Usage:
11//! cargo run --release --example canary_qualification -- --out <dir> [--mode <fixture mode>]
12//!
13//! `--mode` sets `RSI_CANARY_FIXTURE_MODE` for the worker (`correct` by default, or any mode the
14//! fixture understands, for example `wrong_answer`). The process exits 0 when the quota decision
15//! is the one the mode predicts (admitted for `correct`, refused otherwise) and 1 when it is not.
16//!
17//! A passing correct run qualifies the canary execution pipeline. It does not qualify RSI's
18//! ability to improve itself, and it does not qualify the safety envelope as a production
19//! evaluator: that evaluation runs through a reference backend and is recorded as such.
20
21use p256::ecdsa::SigningKey;
22use spark_rsi::actor::judge::{find_executable, HoldoutSuite};
23use spark_rsi::canary::{CanaryWorkloadManifest, SealedObservationLog};
24use spark_rsi::daemon::RsiEngine;
25use spark_rsi::ledger::ImprovementLedger;
26use spark_rsi::models::RsiConfig;
27use std::path::{Path, PathBuf};
28use std::process::Command;
29
30fn arg(name: &str) -> Option<String> {
31 let args: Vec<String> = std::env::args().collect();
32 args.iter()
33 .position(|a| a == name)
34 .and_then(|i| args.get(i + 1).cloned())
35}
36
37fn git(dir: &Path, args: &[&str]) -> Result<(), String> {
38 let out = Command::new("git")
39 .args(args)
40 .current_dir(dir)
41 .output()
42 .map_err(|e| format!("git {:?}: {}", args, e))?;
43 if !out.status.success() {
44 return Err(format!(
45 "git {:?} failed: {}",
46 args,
47 String::from_utf8_lossy(&out.stderr)
48 ));
49 }
50 Ok(())
51}
52
53fn capture(cmd: &str, args: &[&str], dir: &Path) -> String {
54 Command::new(cmd)
55 .args(args)
56 .current_dir(dir)
57 .output()
58 .ok()
59 .filter(|o| o.status.success())
60 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
61 .unwrap_or_else(|| "unknown".to_string())
62}
63
64fn write(path: &Path, bytes: &[u8]) -> Result<(), String> {
65 std::fs::write(path, bytes).map_err(|e| format!("cannot write {:?}: {}", path, e))
66}
67
68fn engine_executable(manifest_dir: &Path) -> Result<PathBuf, String> {
69 // Built alongside this example (target/<profile>/spark-rsi), else the judge's own finder.
70 if let Ok(me) = std::env::current_exe() {
71 if let Some(profile_dir) = me.parent().and_then(Path::parent) {
72 let sibling = profile_dir.join("spark-rsi");
73 if sibling.is_file() {
74 return Ok(sibling);
75 }
76 }
77 }
78 find_executable(manifest_dir)
79 .ok_or_else(|| "spark-rsi executable not found; build it first".to_string())
80}
81
82#[tokio::main]
83async fn main() -> Result<(), String> {
84 let out = PathBuf::from(arg("--out").ok_or("--out <dir> is required")?);
85 let mode = arg("--mode").unwrap_or_else(|| "correct".to_string());
86 std::env::set_var("RSI_CANARY_FIXTURE_MODE", &mode);
87 std::fs::create_dir_all(&out).map_err(|e| format!("cannot create {:?}: {}", out, e))?;
88
89 let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
90 let fixture = manifest_dir.join("fixtures/canary-target");
91 let engine = engine_executable(manifest_dir)?;
92 let started_at = chrono::Utc::now().to_rfc3339();
93
94 // The target repository: the fixture crate with its adapter manifest, a README whose em
95 // dash makes the unslop proposal, the engine executable the judge benchmarks, and the
96 // operator state: holdouts, the pinned workload, a test signing key.
97 let work = tempfile::tempdir().map_err(|e| e.to_string())?;
98 let repo = work.path().join("repo");
99 let sandbox = work.path().join("sandbox");
100 std::fs::create_dir_all(repo.join("src")).map_err(|e| e.to_string())?;
101 for f in ["Cargo.toml", "Cargo.lock", "canary-adapter.toml"] {
102 std::fs::copy(fixture.join(f), repo.join(f)).map_err(|e| format!("copy {}: {}", f, e))?;
103 }
104 std::fs::copy(fixture.join("src/main.rs"), repo.join("src/main.rs"))
105 .map_err(|e| e.to_string())?;
106 write(
107 &repo.join("README.md"),
108 "# Canary target\n\nWe build, fix, finish, and optimize systems with love, honor, and discipline\u{2014}with an em dash.\n".as_bytes(),
109 )?;
110 std::fs::copy(&engine, repo.join("spark-rsi")).map_err(|e| e.to_string())?;
111 write(&repo.join(".gitignore"), b"target\n")?;
112 git(&repo, &["init", "-b", "main"])?;
113 git(&repo, &["config", "user.name", "Qualification Operator"])?;
114 git(&repo, &["config", "user.email", "qualification@local"])?;
115 git(&repo, &["add", "."])?;
116 git(&repo, &["commit", "-q", "-m", "canary target"])?;
117
118 let rsi_root = repo.join(".rsi");
119 let holdouts = rsi_root.join("holdouts");
120 std::fs::create_dir_all(&holdouts).map_err(|e| e.to_string())?;
121 for suite in HoldoutSuite::builtin_suites() {
122 suite.save_to_dir(&holdouts)?;
123 }
124 let workload_path = rsi_root.join("canary/workload.json");
125 std::fs::create_dir_all(workload_path.parent().unwrap()).map_err(|e| e.to_string())?;
126 std::fs::copy(fixture.join("workload.json"), &workload_path).map_err(|e| e.to_string())?;
127 let workload = CanaryWorkloadManifest::load(&workload_path)?;
128
129 // A fixed test key: never production authority, kept fixed so the run is reproducible.
130 let signing_key = SigningKey::from_slice(&[0x51u8; 32]).map_err(|e| e.to_string())?;
131 let config = RsiConfig {
132 target_repo: repo.to_string_lossy().to_string(),
133 cortex_url: "http://127.0.0.1:9".to_string(),
134 cortex_space: "qualification".to_string(),
135 loop_interval_secs: 60,
136 sandbox_root: sandbox.to_string_lossy().to_string(),
137 rsi_root: ".rsi".to_string(),
138 holdouts_dir: None,
139 signing_key_hex: Some(hex::encode(signing_key.to_bytes())),
140 require_latency_improvement: false,
141 non_inferiority_margin: Some(250.0),
142 model_url: "http://127.0.0.1:9".to_string(),
143 canary_target: 10,
144 canary_workload_sha256: Some(workload.digest.clone()),
145 ..Default::default()
146 };
147
148 let result = RsiEngine::run_cycle(&config).await?;
149 let finished_at = chrono::Utc::now().to_rfc3339();
150
151 // Evidence package.
152 write(
153 &out.join("cycle-result.json"),
154 serde_json::to_string_pretty(&result)
155 .map_err(|e| e.to_string())?
156 .as_bytes(),
157 )?;
158 std::fs::copy(&workload_path, out.join("workload.json")).map_err(|e| e.to_string())?;
159 write(&out.join("workload.sha256"), workload.digest.as_bytes())?;
160 std::fs::copy(
161 fixture.join("canary-adapter.toml"),
162 out.join("canary-adapter.toml"),
163 )
164 .map_err(|e| e.to_string())?;
165 write(
166 &out.join("config.json"),
167 serde_json::to_string_pretty(&config)
168 .map_err(|e| e.to_string())?
169 .as_bytes(),
170 )?;
171
172 let canary = result.canary.clone().unwrap_or_default();
173 let mut sealed_summary = serde_json::json!({ "sealed_log": null });
174 if let Some(proposal) = &result.proposal {
175 let log = rsi_root.join(format!("canary/observations/{}.jsonl", proposal.id));
176 if log.is_file() {
177 std::fs::copy(&log, out.join("observations.jsonl")).map_err(|e| e.to_string())?;
178 let sealed = SealedObservationLog::load(&log)?;
179 sealed_summary = serde_json::json!({
180 "sealed_log": {
181 "verified": true,
182 "header": sealed.header,
183 "seal": sealed.seal,
184 "observations": sealed.observations.len(),
185 "qualifying": sealed.qualifying().count(),
186 "rejections": sealed.rejections.len(),
187 }
188 });
189 }
190 }
191 write(
192 &out.join("sealed-log.json"),
193 serde_json::to_string_pretty(&sealed_summary)
194 .map_err(|e| e.to_string())?
195 .as_bytes(),
196 )?;
197
198 let ledger = ImprovementLedger::open(&rsi_root)?;
199 let blocks = ledger.all_blocks()?;
200 write(
201 &out.join("ledger-blocks.json"),
202 serde_json::to_string_pretty(&blocks)
203 .map_err(|e| e.to_string())?
204 .as_bytes(),
205 )?;
206 let audit = ledger.verify_chain_integrity(Some(signing_key.verifying_key()))?;
207 write(
208 &out.join("ledger-audit.json"),
209 serde_json::to_string_pretty(&audit)
210 .map_err(|e| e.to_string())?
211 .as_bytes(),
212 )?;
213 for name in ["stage-samples.jsonl", "partial-cycles.jsonl"] {
214 let src = rsi_root.join("measure").join(name);
215 if src.is_file() {
216 std::fs::copy(&src, out.join(name)).map_err(|e| e.to_string())?;
217 }
218 }
219
220 let environment = serde_json::json!({
221 "spark_rsi_revision": capture("git", &["rev-parse", "HEAD"], manifest_dir),
222 "spark_rsi_branch": capture("git", &["rev-parse", "--abbrev-ref", "HEAD"], manifest_dir),
223 "rustc": capture("rustc", &["--version"], manifest_dir),
224 "cargo": capture("cargo", &["--version"], manifest_dir),
225 "host": capture("uname", &["-a"], manifest_dir),
226 "fixture_mode": mode,
227 "started_at": started_at,
228 "finished_at": finished_at,
229 "engine_executable": engine.display().to_string(),
230 });
231 write(
232 &out.join("environment.json"),
233 serde_json::to_string_pretty(&environment)
234 .map_err(|e| e.to_string())?
235 .as_bytes(),
236 )?;
237
238 let quota_admitted = canary.quota.as_ref().map(|q| q.admitted).unwrap_or(false);
239 let expected_admitted = mode == "correct";
240 let verdict = if quota_admitted == expected_admitted {
241 "AS PREDICTED"
242 } else {
243 "NOT AS PREDICTED"
244 };
245 let summary = format!(
246 "# Canary qualification run\n\n\
247 Mode: {mode}\n\
248 Revision: {rev}\n\
249 Verdict: {verdict} (quota admitted = {quota_admitted}, predicted = {expected_admitted})\n\n\
250 | Item | Value |\n|---|---|\n\
251 | cycle id | {cycle} |\n\
252 | proposal | {proposal} |\n\
253 | canary applicable / eligible | {applicable} / {eligible} |\n\
254 | refusal | {refusal} |\n\
255 | identity binding digest | {binding} |\n\
256 | executable digest | {exe} |\n\
257 | workload digest | {wl} |\n\
258 | sealed log digest | {log} |\n\
259 | commitment block hash | {commit} |\n\
260 | execution | {exec} |\n\
261 | quota | {quota} |\n\
262 | safety envelope | {env} |\n\
263 | envelope note | {note} |\n\
264 | promotion gate | {gate} |\n\
265 | cycle success | {success} |\n\
266 | durable generation | {durable} |\n\n\
267 A passing correct run qualifies the canary execution pipeline. It does not qualify RSI's \
268 ability to improve itself, and it does not qualify the safety envelope as a production \
269 evaluator.\n",
270 mode = mode,
271 rev = environment["spark_rsi_revision"].as_str().unwrap_or("unknown"),
272 verdict = verdict,
273 quota_admitted = quota_admitted,
274 expected_admitted = expected_admitted,
275 cycle = result.cycle_id,
276 proposal = result
277 .proposal
278 .as_ref()
279 .map(|p| format!("{} ({:?}, {})", p.id, p.kind, p.target_file))
280 .unwrap_or_else(|| "none".to_string()),
281 applicable = canary.applicable,
282 eligible = canary.eligible,
283 refusal = canary.refusal.clone().unwrap_or_else(|| "none".to_string()),
284 binding = canary.identity_binding_digest.clone().unwrap_or_else(|| "none".to_string()),
285 exe = canary.executable_digest.clone().unwrap_or_else(|| "none".to_string()),
286 wl = canary.workload_digest.clone().unwrap_or_else(|| "none".to_string()),
287 log = canary.log_digest.clone().unwrap_or_else(|| "none".to_string()),
288 commit = canary.commitment_block_hash.clone().unwrap_or_else(|| "none".to_string()),
289 exec = canary
290 .execution
291 .as_ref()
292 .map(|e| format!(
293 "planned {}, issued {}, verified {}, wrong {}, timeout {}, invalid {}, closed {}, rejections {}, ready {}, reverted {}, first failure {:?}",
294 e.requests_planned, e.issued, e.verified_success, e.wrong_result, e.timeout, e.invalid_response, e.connection_closed, e.rejections, e.ready, e.reverted, e.first_failure
295 ))
296 .unwrap_or_else(|| "none".to_string()),
297 quota = canary
298 .quota
299 .as_ref()
300 .map(|q| format!("admitted {} (counted {:?} of target {}){}", q.admitted, q.counted, q.target, q.refusal.as_ref().map(|r| format!(": {}", r)).unwrap_or_default()))
301 .unwrap_or_else(|| "not reached".to_string()),
302 env = canary
303 .envelope
304 .as_ref()
305 .map(|g| format!("passed {}: {}", g.passed, g.detail))
306 .unwrap_or_else(|| "not reached".to_string()),
307 note = canary.envelope_note.clone().unwrap_or_else(|| "none".to_string()),
308 gate = canary
309 .promotion_gate
310 .as_ref()
311 .map(|g| format!("passed {}: {}", g.passed, g.detail))
312 .unwrap_or_else(|| "not reached".to_string()),
313 success = result.success,
314 durable = result.generation.is_some(),
315 );
316 write(&out.join("summary.md"), summary.as_bytes())?;
317 println!("{}", summary);
318 println!("evidence written to {}", out.display());
319 if quota_admitted != expected_admitted {
320 std::process::exit(1);
321 }
322 Ok(())
323}