aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / crumbs / src / gates.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Learner-dependent qualification gates, run against a real learner binary |
| 17 | //! (for v1: Omega's `crumbline-learner`). |
| 18 | //! |
| 19 | //! crumbs gates --learner PATH [--out DIR] |
| 20 | //! |
| 21 | //! Prints one `GATE_NAME PASS|FAIL detail` line per gate and writes gates.json |
| 22 | //! plus an aien-proof assertion file (`aien-proof receipt import --assert ...`). |
| 23 | |
| 24 | use crate::audit::{find_labels, read_process_writable_memory, sealed_specific_labels}; |
| 25 | use crate::digest::Domain; |
| 26 | use crate::gen::{self, registry, rng::Rng}; |
| 27 | use crate::program::{Op, Program}; |
| 28 | use crate::promotion::{PromotionConfig, Stage}; |
| 29 | use crate::protocol::{LearnerProcess, SearchConfig, Submission}; |
| 30 | use crate::sealed::{HeldoutTier, KnownSolution, LaneExample, Population}; |
| 31 | use crate::session::{CrumbOutcome, Session, SessionConfig}; |
| 32 | use crate::trace::{verify_chain, ResultClass, SAMPLE_RECORD_BYTES, TRACE_RECORD_BYTES}; |
| 33 | use crate::verify::{EvalClass, Verdict}; |
| 34 | use crate::visible::{Encoding, VisibleCrumb}; |
| 35 | use serde::Serialize; |
| 36 | use std::path::{Path, PathBuf}; |
| 37 | |
| 38 | #[derive(Serialize, Clone)] |
| 39 | pub struct GateResult { |
| 40 | pub id: String, |
| 41 | pub pass: bool, |
| 42 | pub observed: String, |
| 43 | } |
| 44 | |
| 45 | fn gate(id: &str, pass: bool, observed: String) -> GateResult { |
| 46 | println!("{id} {} {observed}", if pass { "PASS" } else { "FAIL" }); |
| 47 | GateResult { |
| 48 | id: id.to_string(), |
| 49 | pass, |
| 50 | observed, |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | fn session(learner: &str, cond: &str, library: bool, dir: &Path) -> Session { |
| 55 | Session::start(SessionConfig { |
| 56 | condition: cond.into(), |
| 57 | learner: learner.into(), |
| 58 | run_id: format!("gates-{cond}"), |
| 59 | search: SearchConfig::default(), |
| 60 | library_enabled: library, |
| 61 | promotion: PromotionConfig::default(), |
| 62 | record_transcript: true, |
| 63 | out_dir: Some(dir.join(cond)), |
| 64 | }) |
| 65 | .expect("learner starts") |
| 66 | } |
| 67 | |
| 68 | fn present(s: &mut Session, key: &str, seed: u64) -> CrumbOutcome { |
| 69 | let f = registry() |
| 70 | .by_key(key) |
| 71 | .unwrap_or_else(|| panic!("family {key}")); |
| 72 | s.present(f, seed, Population::Fundamental, "gates") |
| 73 | .expect("session") |
| 74 | } |
| 75 | |
| 76 | pub fn run_gates(learner: &str, out: &Path) -> Vec<GateResult> { |
| 77 | let _ = std::fs::remove_dir_all(out); |
| 78 | std::fs::create_dir_all(out).unwrap(); |
| 79 | let mut gates = Vec::new(); |
| 80 | |
| 81 | // CRUMB_OMEGA_VISIBLE_PASS: the learner synthesizes programs that explain |
| 82 | // the visible examples, and never submits one that does not. |
| 83 | let mut s = session(learner, "visible", false, out); |
| 84 | let (mut fits, mut bad_visible, mut n) = (0u32, 0usize, 0u32); |
| 85 | let (mut expressible, mut expressible_found) = (0u32, 0u32); |
| 86 | for key in [ |
| 87 | "chain-basic-l1-w16", |
| 88 | "chain-basic-l2-w16", |
| 89 | "chain-basic-l3-w16", |
| 90 | "latent-offset-w16", |
| 91 | "mod-affine-w12", |
| 92 | ] { |
| 93 | for seed in 1..=8 { |
| 94 | let f = registry().by_key(key).unwrap(); |
| 95 | let g = gen::generate(f, seed); |
| 96 | let o = s |
| 97 | .present(f, seed, Population::Fundamental, "gates") |
| 98 | .expect("session"); |
| 99 | n += 1; |
| 100 | let found = o.stats.visible_fits > 0; |
| 101 | fits += found as u32; |
| 102 | bad_visible += o |
| 103 | .evaluations |
| 104 | .iter() |
| 105 | .filter(|e| e.class == EvalClass::FalsifiedVisible && !e.robust_submission) |
| 106 | .count(); |
| 107 | // Truth expressible as <= 3 single-step operations the learner itself |
| 108 | // declared: an exhaustive depth-3 search must find a visible fit. |
| 109 | if let KnownSolution::Known(t) = &g.sealed.known_solution { |
| 110 | let in_bank = t.steps.iter().all(|st| { |
| 111 | o.declared_bank |
| 112 | .iter() |
| 113 | .any(|b| b.steps.len() == 1 && b.steps[0] == *st) |
| 114 | }); |
| 115 | if in_bank && t.len() <= 3 { |
| 116 | expressible += 1; |
| 117 | expressible_found += found as u32; |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | gates.push(gate( |
| 123 | "CRUMB_OMEGA_VISIBLE_PASS", |
| 124 | expressible > 0 && expressible_found == expressible && bad_visible == 0, |
| 125 | format!("visible fit found on {expressible_found}/{expressible} crumbs whose truth is <= 3 of the learner's declared operations ({fits}/{n} overall); {bad_visible} exact submissions that failed the visible examples"), |
| 126 | )); |
| 127 | let (_, visible_outs, _) = s.finish().unwrap(); |
| 128 | |
| 129 | // CRUMB_HIDDEN_VERIFY_PASS: visible fits that fail held-outs are recorded |
| 130 | // as useful failures and search continues; acceptance needs held-outs. |
| 131 | let mut s = session(learner, "hidden", false, out); |
| 132 | let (mut useful_failures, mut continued, mut accepted_not_verified) = (0usize, 0u32, 0usize); |
| 133 | for key in [ |
| 134 | "decoy-simple-rule-w12", |
| 135 | "decoy-simple-rule-w16", |
| 136 | "multi-fit-w12", |
| 137 | "multi-fit-w16", |
| 138 | "insufficient-evidence-n3", |
| 139 | "prefix-diverges-k8", |
| 140 | ] { |
| 141 | for seed in 1..=4 { |
| 142 | let o = present(&mut s, key, seed); |
| 143 | let fh = o.falsified_hidden(); |
| 144 | useful_failures += fh; |
| 145 | if fh > 0 |
| 146 | && (o.evaluations.len() > 1 || o.stats.generated > o.stats.candidates_to_solution) |
| 147 | { |
| 148 | continued += 1; |
| 149 | } |
| 150 | accepted_not_verified += o |
| 151 | .evaluations |
| 152 | .iter() |
| 153 | .filter(|e| { |
| 154 | e.verdict == Verdict::Accept |
| 155 | && !matches!( |
| 156 | e.class, |
| 157 | EvalClass::Verified | EvalClass::AmbiguousUnderdetermined |
| 158 | ) |
| 159 | }) |
| 160 | .count(); |
| 161 | } |
| 162 | } |
| 163 | let (_, hidden_outs, _) = s.finish().unwrap(); |
| 164 | let rejected_records = count_records( |
| 165 | &out.join("hidden").join("trace.ctr"), |
| 166 | ResultClass::RejectedHidden, |
| 167 | ); |
| 168 | gates.push(gate( |
| 169 | "CRUMB_HIDDEN_VERIFY_PASS", |
| 170 | useful_failures > 0 && continued > 0 && accepted_not_verified == 0 && rejected_records == useful_failures, |
| 171 | format!("{useful_failures} visible-fit candidates falsified by held-outs, all recorded ({rejected_records} REJECTED_HIDDEN trace records); search continued after a rejection in {continued} crumbs; {accepted_not_verified} acceptances without held-out verification"), |
| 172 | )); |
| 173 | |
| 174 | gates.push(no_hidden_access(learner, out)); |
| 175 | |
| 176 | // Trace corpus gates over the real Omega sessions above. |
| 177 | let (mut chains_ok, mut total_records, mut total_samples, mut label_hits) = |
| 178 | (true, 0usize, 0usize, 0usize); |
| 179 | for d in ["visible", "hidden"] { |
| 180 | let tr = std::fs::read(out.join(d).join("trace.ctr")).unwrap_or_default(); |
| 181 | let smp = std::fs::read(out.join(d).join("samples.cts")).unwrap_or_default(); |
| 182 | chains_ok &= verify_chain(&tr, TRACE_RECORD_BYTES, Domain::TraceRecord).is_some(); |
| 183 | chains_ok &= verify_chain(&smp, SAMPLE_RECORD_BYTES, Domain::TrainingSample).is_some(); |
| 184 | total_records += tr.len() / TRACE_RECORD_BYTES; |
| 185 | total_samples += smp.len() / SAMPLE_RECORD_BYTES; |
| 186 | label_hits += find_labels(&tr).len() + find_labels(&smp).len(); |
| 187 | } |
| 188 | let all: Vec<&CrumbOutcome> = visible_outs.iter().chain(hidden_outs.iter()).collect(); |
| 189 | let integrity: u32 = all.iter().map(|o| o.trace.integrity_violations).sum(); |
| 190 | let samples_for_solved = all |
| 191 | .iter() |
| 192 | .filter(|o| o.accepted && o.stats.generated > 0) |
| 193 | .all(|o| o.trace.samples > 0); |
| 194 | gates.push(gate( |
| 195 | "CRUMB_TRACE_PASS", |
| 196 | chains_ok && total_records > 0 && integrity == 0, |
| 197 | format!("{total_records} hash-chained CTR1 records re-verified from disk; {integrity} submitted-vs-reconstructed program mismatches"), |
| 198 | )); |
| 199 | let consistent = check_samples(&out.join("visible").join("samples.cts")) |
| 200 | && check_samples(&out.join("hidden").join("samples.cts")); |
| 201 | gates.push(gate( |
| 202 | "CRUMB_TRAINING_SAMPLE_PASS", |
| 203 | total_samples > 0 && samples_for_solved && consistent, |
| 204 | format!("{total_samples} CTS1 samples; every solved crumb produced samples; every sample's positives are a non-empty subset of the operations tried"), |
| 205 | )); |
| 206 | gates.push(gate( |
| 207 | "NO_COT_STORAGE_PASS", |
| 208 | label_hits == 0 && chains_ok, |
| 209 | format!("fixed-size numeric records ({TRACE_RECORD_BYTES} B / {SAMPLE_RECORD_BYTES} B) with no text fields; {label_hits} label strings in the corpus"), |
| 210 | )); |
| 211 | |
| 212 | gates.extend(promotion_and_reuse(learner, out)); |
| 213 | gates.push(scope_enforcement(learner)); |
| 214 | |
| 215 | let _ = std::fs::write( |
| 216 | out.join("gates.json"), |
| 217 | serde_json::to_string_pretty(&gates).unwrap(), |
| 218 | ); |
| 219 | let assertions: Vec<serde_json::Value> = gates |
| 220 | .iter() |
| 221 | .map(|g| { |
| 222 | serde_json::json!({"id": g.id, "expected": "PASS", "observed": g.observed, |
| 223 | "result": if g.pass {"pass"} else {"fail"}, "source": "crumbs gates", "note": ""}) |
| 224 | }) |
| 225 | .collect(); |
| 226 | let _ = std::fs::write( |
| 227 | out.join("aien-proof-assertions.json"), |
| 228 | serde_json::to_string_pretty(&serde_json::json!({ "assertions": assertions })).unwrap(), |
| 229 | ); |
| 230 | gates |
| 231 | } |
| 232 | |
| 233 | fn count_records(path: &Path, class: ResultClass) -> usize { |
| 234 | let tr = std::fs::read(path).unwrap_or_default(); |
| 235 | // byte 7 of a CTR1 record is its result class |
| 236 | tr.chunks(TRACE_RECORD_BYTES) |
| 237 | .filter(|r| r.len() == TRACE_RECORD_BYTES && r[7] == class as u8) |
| 238 | .count() |
| 239 | } |
| 240 | |
| 241 | /// Positive bits must be a non-empty subset of tried bits in every sample. |
| 242 | fn check_samples(path: &Path) -> bool { |
| 243 | let b = std::fs::read(path).unwrap_or_default(); |
| 244 | b.chunks(SAMPLE_RECORD_BYTES).all(|r| { |
| 245 | // body: magic 4, version 2, n_ops 2, digests 64, 4 bytes, values 64, targets 64 => 204 |
| 246 | let pos = &r[204..220]; |
| 247 | let tried = &r[220..236]; |
| 248 | pos.iter().zip(tried).all(|(p, t)| p & !t == 0) && pos.iter().any(|p| *p != 0) |
| 249 | }) |
| 250 | } |
| 251 | |
| 252 | fn no_hidden_access(learner: &str, out: &Path) -> GateResult { |
| 253 | // Canary crumbs: the visible examples come from a known chain, and the |
| 254 | // held-outs are random 64-bit inputs the learner never sees. Neither those |
| 255 | // inputs nor their outputs can appear in the learner's memory unless the |
| 256 | // boundary leaks. |
| 257 | let mut s = session(learner, "canary", false, out); |
| 258 | let mut needles: Vec<Vec<u8>> = Vec::new(); |
| 259 | let mut rng = Rng::named("canary", &[1]); |
| 260 | let mut accepted = 0u32; |
| 261 | for seed in 1..=4u64 { |
| 262 | let f = registry().by_key("chain-basic-l2-w16").unwrap(); |
| 263 | let mut g = gen::generate(f, seed); |
| 264 | let KnownSolution::Known(p) = g.sealed.known_solution.clone() else { |
| 265 | unreachable!() |
| 266 | }; |
| 267 | let mut mk = || -> Vec<LaneExample> { |
| 268 | (0..16) |
| 269 | .map(|_| { |
| 270 | let x = rng.next_u64() | (1 << 63); |
| 271 | LaneExample { |
| 272 | input: vec![x], |
| 273 | output: vec![p.run(x)], |
| 274 | } |
| 275 | }) |
| 276 | .collect() |
| 277 | }; |
| 278 | g.sealed.heldouts.interpolation = mk(); |
| 279 | g.sealed.heldouts.extrapolation = mk(); |
| 280 | g.sealed.heldouts.adversarial = mk(); |
| 281 | for t in HeldoutTier::ALL { |
| 282 | for ex in g.sealed.heldouts.tier(t) { |
| 283 | for v in [ex.input[0], ex.output[0]] { |
| 284 | if v.to_le_bytes().iter().filter(|b| **b != 0).count() >= 6 { |
| 285 | needles.push(v.to_le_bytes().to_vec()); |
| 286 | needles.push(v.to_string().into_bytes()); |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | needles.push(g.sealed.digest().0.to_vec()); |
| 292 | needles.push(g.sealed.generator_instance_digest.0.to_vec()); |
| 293 | if let Ok(o) = s.present_with(&g.visible, &g.sealed) { |
| 294 | accepted += o.accepted as u32; |
| 295 | } |
| 296 | } |
| 297 | let pid = s.learner_pid().unwrap(); |
| 298 | let mem = read_process_writable_memory(pid).unwrap_or_default(); |
| 299 | let mem_hits = needles |
| 300 | .iter() |
| 301 | .filter(|n| crate::audit::contains(&mem, n)) |
| 302 | .count(); |
| 303 | let label_hits_mem = find_labels(&mem); |
| 304 | let transcript = s.transcript().map(|t| t.to_vec()).unwrap_or_default(); |
| 305 | let tr_hits = needles |
| 306 | .iter() |
| 307 | .filter(|n| crate::audit::contains(&transcript, n)) |
| 308 | .count(); |
| 309 | s.finish().unwrap(); |
| 310 | let bin = std::fs::read(learner).unwrap_or_default(); |
| 311 | let bin_hits: Vec<String> = sealed_specific_labels() |
| 312 | .into_iter() |
| 313 | .filter(|l| crate::audit::contains(&bin, l.as_bytes())) |
| 314 | .collect(); |
| 315 | gate( |
| 316 | "CRUMB_NO_HIDDEN_ACCESS_PASS", |
| 317 | !mem.is_empty() && mem_hits == 0 && label_hits_mem.is_empty() && tr_hits == 0 && bin_hits.is_empty() && accepted > 0, |
| 318 | format!( |
| 319 | "read {} KiB of the live learner's writable memory: {mem_hits} of {} canary held-out values/digests found; labels in memory {:?}; canary bytes in transcript {tr_hits}; sealed labels in learner binary {:?}; canary crumbs verified {accepted}/4", |
| 320 | mem.len() >> 10, |
| 321 | needles.len(), |
| 322 | label_hits_mem, |
| 323 | bin_hits |
| 324 | ), |
| 325 | ) |
| 326 | } |
| 327 | |
| 328 | fn promotion_and_reuse(learner: &str, out: &Path) -> Vec<GateResult> { |
| 329 | // A short trail: two capabilities, each shown twice, then their composition. |
| 330 | let script: [(&str, u64); 5] = [ |
| 331 | ("capability-03", 1), |
| 332 | ("capability-05", 1), |
| 333 | ("capability-03", 2), |
| 334 | ("capability-05", 2), |
| 335 | ("compose-03-05", 9), |
| 336 | ]; |
| 337 | let mut runs = Vec::new(); |
| 338 | for (cond, lib) in [("control-trail", false), ("learning-trail", true)] { |
| 339 | let mut s = session(learner, cond, lib, out); |
| 340 | let outs: Vec<CrumbOutcome> = script |
| 341 | .iter() |
| 342 | .map(|(k, seed)| present(&mut s, k, *seed)) |
| 343 | .collect(); |
| 344 | let (_, _, ladder) = s.finish().unwrap(); |
| 345 | runs.push((outs, ladder)); |
| 346 | } |
| 347 | let (learn_outs, ladder) = &runs[1]; |
| 348 | let admitted: Vec<_> = ladder |
| 349 | .ops |
| 350 | .values() |
| 351 | .filter(|r| r.stage == Stage::Admitted) |
| 352 | .collect(); |
| 353 | let evidence_ok = admitted.iter().all(|r| { |
| 354 | r.distinct_crumbs() >= 2 |
| 355 | && r.supports |
| 356 | .iter() |
| 357 | .all(|s| s.adversarial_total > 0 && s.extrapolation_total > 0) |
| 358 | && r.history |
| 359 | .windows(2) |
| 360 | .all(|w| w[0].0 < w[1].0 && w[0].1 <= w[1].1) |
| 361 | && r.scope_bits > 0 |
| 362 | }); |
| 363 | let mut res = vec![gate( |
| 364 | "CRUMB_OPERATION_PROMOTION_PASS", |
| 365 | !admitted.is_empty() && evidence_ok, |
| 366 | format!( |
| 367 | "{} operations admitted, each with >= 2 distinct held-out-verified crumbs, adversarial and extrapolation evidence, ordered ladder history and a recorded scope; {} tracked candidates not admitted", |
| 368 | admitted.len(), |
| 369 | ladder.ops.len() - admitted.len() |
| 370 | ), |
| 371 | )]; |
| 372 | let (cl, cc) = (&learn_outs[4], &runs[0].0[4]); |
| 373 | res.push(gate( |
| 374 | "CRUMB_LIBRARY_REUSE_PASS", |
| 375 | cl.accepted && cl.verified && cl.reused_library(), |
| 376 | format!( |
| 377 | "composition crumb: learning verified using admitted ops {:?} after {} candidates; control verified={} after {} candidates", |
| 378 | cl.trace.library_refs_in_solution, cl.stats.candidates_to_solution, cc.verified, cc.stats.candidates_to_solution |
| 379 | ), |
| 380 | )); |
| 381 | res |
| 382 | } |
| 383 | |
| 384 | fn scope_enforcement(learner: &str) -> GateResult { |
| 385 | let mut lp = LearnerProcess::spawn(learner, &[], false).expect("learner"); |
| 386 | lp.hello( |
| 387 | &SearchConfig { |
| 388 | max_candidates: 2000, |
| 389 | ..SearchConfig::default() |
| 390 | }, |
| 391 | true, |
| 392 | ) |
| 393 | .unwrap(); |
| 394 | let op = Program::of(&[(Op::Mul, 3), (Op::Add, 2)]); |
| 395 | lp.admit(1, 4, &op).unwrap(); // verified only for inputs below 2^4 |
| 396 | let small: Vec<(Vec<u64>, Vec<u64>)> = |
| 397 | (1..9u64).map(|x| (vec![x], vec![op.run(x) * 2])).collect(); |
| 398 | let wide: Vec<(Vec<u64>, Vec<u64>)> = [3u64, 700, 40_000, 9, 12_345, 60_001] |
| 399 | .iter() |
| 400 | .map(|&x| (vec![x], vec![op.run(x) * 2])) |
| 401 | .collect(); |
| 402 | let mut reject = |_: &Submission| Verdict::Reject; |
| 403 | let vs = VisibleCrumb::from_values(Encoding::DecimalUtf8, 0, 0, &small, None).unwrap(); |
| 404 | let vw = VisibleCrumb::from_values(Encoding::DecimalUtf8, 0, 0, &wide, None).unwrap(); |
| 405 | let in_scope = lp.run_crumb(&vs, &mut reject).unwrap(); |
| 406 | let out_scope = lp.run_crumb(&vw, &mut reject).unwrap(); |
| 407 | let _ = lp.shutdown(); |
| 408 | let lib_in = in_scope.bank.iter().filter(|b| b.origin == 1).count(); |
| 409 | let lib_out = out_scope.bank.iter().filter(|b| b.origin == 1).count(); |
| 410 | gate( |
| 411 | "CRUMB_SCOPE_ENFORCEMENT_PASS", |
| 412 | lib_in == 1 && lib_out == 0, |
| 413 | format!("operation admitted with a 4-bit scope: offered on a crumb with inputs below 2^4 ({lib_in}), withheld on a crumb with 16-bit inputs ({lib_out})"), |
| 414 | ) |
| 415 | } |
| 416 | |
| 417 | pub fn main(args: &[String]) -> i32 { |
| 418 | let get = |n: &str| { |
| 419 | args.iter() |
| 420 | .position(|a| a == n) |
| 421 | .and_then(|i| args.get(i + 1).cloned()) |
| 422 | }; |
| 423 | let learner = get("--learner").expect("--learner PATH"); |
| 424 | let out = get("--out") |
| 425 | .map(PathBuf::from) |
| 426 | .unwrap_or_else(|| std::env::temp_dir().join("crumbs-gates")); |
| 427 | let g = run_gates(&learner, &out); |
| 428 | let passed = g.iter().filter(|x| x.pass).count(); |
| 429 | println!( |
| 430 | "GATES {passed}/{} PASS (evidence: {})", |
| 431 | g.len(), |
| 432 | out.display() |
| 433 | ); |
| 434 | i32::from(passed != g.len()) |
| 435 | } |