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 / session.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 | //! A curriculum session: the sealed side driving one learner process. |
| 17 | //! |
| 18 | //! For every crumb: generate (visible + sealed), present the visible bytes, |
| 19 | //! evaluate each submission against the sealed held-outs, derive the trace, |
| 20 | //! climb the promotion ladder, admit operations to the learner (only when the |
| 21 | //! condition allows reuse), and append a Crumbline ledger record. |
| 22 | |
| 23 | use crate::digest::{digest, CrumbOccurrenceId, Digest, Domain}; |
| 24 | use crate::gen::{self, FamilySpec}; |
| 25 | use crate::ledger::{CrumblineRecord, Ledger}; |
| 26 | use crate::promotion::{Admission, Ladder, PromotionConfig}; |
| 27 | use crate::protocol::{LearnerProcess, LearnerStats, ProtocolError, SearchConfig, SUBMIT_ROBUST}; |
| 28 | use crate::provenance::Lane; |
| 29 | use crate::sealed::{DecoyStatus, Population, SealedCrumb}; |
| 30 | use crate::trace::{self, TraceSummary}; |
| 31 | use crate::verify::{evaluate, verifier_digest, EvalClass, SealedEvaluation, Verdict}; |
| 32 | use serde::{Deserialize, Serialize}; |
| 33 | use std::io::Write; |
| 34 | use std::path::PathBuf; |
| 35 | |
| 36 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 37 | pub struct SessionConfig { |
| 38 | pub condition: String, |
| 39 | pub learner: String, |
| 40 | pub run_id: String, |
| 41 | pub search: SearchConfig, |
| 42 | /// Admitted operations are sent to the learner only when true. |
| 43 | pub library_enabled: bool, |
| 44 | pub promotion: PromotionConfig, |
| 45 | pub record_transcript: bool, |
| 46 | /// Directory for the trace corpus, ledger and evidence (None = in memory only). |
| 47 | pub out_dir: Option<PathBuf>, |
| 48 | } |
| 49 | |
| 50 | /// Per-crumb outcome (sealed-side bookkeeping; never sent to a learner). |
| 51 | #[derive(Clone, Debug, Serialize, Deserialize)] |
| 52 | pub struct CrumbOutcome { |
| 53 | pub seq: u64, |
| 54 | pub phase: String, |
| 55 | pub family_id: u32, |
| 56 | pub family_key: String, |
| 57 | pub mechanism: String, |
| 58 | pub population: Population, |
| 59 | pub decoy: DecoyStatus, |
| 60 | pub crumb_digest: Digest, |
| 61 | pub supported: bool, |
| 62 | pub accepted: bool, |
| 63 | pub verified: bool, |
| 64 | pub ambiguous_accept: bool, |
| 65 | pub evaluations: Vec<SealedEvaluation>, |
| 66 | pub stats: LearnerStats, |
| 67 | pub trace: TraceSummary, |
| 68 | pub library_ops_available: u32, |
| 69 | /// The operation bank the learner declared for this crumb (learner-neutral CPG1). |
| 70 | pub declared_bank: Vec<crate::program::Program>, |
| 71 | pub admissions_after: Vec<Admission>, |
| 72 | pub ledger_root: Digest, |
| 73 | } |
| 74 | |
| 75 | impl CrumbOutcome { |
| 76 | pub fn falsified_hidden(&self) -> usize { |
| 77 | self.evaluations |
| 78 | .iter() |
| 79 | .filter(|e| e.class == EvalClass::FalsifiedHidden) |
| 80 | .count() |
| 81 | } |
| 82 | pub fn first_class(&self) -> Option<EvalClass> { |
| 83 | self.evaluations.first().map(|e| e.class) |
| 84 | } |
| 85 | pub fn reused_library(&self) -> bool { |
| 86 | self.accepted && !self.trace.library_refs_in_solution.is_empty() |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub struct Session { |
| 91 | pub cfg: SessionConfig, |
| 92 | learner: Option<LearnerProcess>, |
| 93 | pub ladder: Ladder, |
| 94 | pub ledger: Ledger, |
| 95 | pub outcomes: Vec<CrumbOutcome>, |
| 96 | pub learner_digest: Digest, |
| 97 | seq: u64, |
| 98 | admissions_frozen: bool, |
| 99 | trace_chain: Digest, |
| 100 | sample_chain: Digest, |
| 101 | } |
| 102 | |
| 103 | fn file_digest(path: &str) -> Digest { |
| 104 | std::fs::read(path) |
| 105 | .map(|b| digest(Domain::Config, &b)) |
| 106 | .unwrap_or(Digest::ZERO) |
| 107 | } |
| 108 | |
| 109 | impl Session { |
| 110 | pub fn start(cfg: SessionConfig) -> Result<Self, ProtocolError> { |
| 111 | let mut learner = LearnerProcess::spawn(&cfg.learner, &[], cfg.record_transcript)?; |
| 112 | learner.hello(&cfg.search, cfg.library_enabled)?; |
| 113 | if let Some(d) = &cfg.out_dir { |
| 114 | std::fs::create_dir_all(d).map_err(|_| ProtocolError::Io)?; |
| 115 | } |
| 116 | Ok(Session { |
| 117 | learner_digest: file_digest(&cfg.learner), |
| 118 | ladder: Ladder::new(cfg.promotion.clone()), |
| 119 | ledger: Ledger::new(Lane::Main, &cfg.run_id), |
| 120 | learner: Some(learner), |
| 121 | cfg, |
| 122 | outcomes: vec![], |
| 123 | seq: 0, |
| 124 | admissions_frozen: false, |
| 125 | trace_chain: Digest::ZERO, |
| 126 | sample_chain: Digest::ZERO, |
| 127 | }) |
| 128 | } |
| 129 | |
| 130 | pub fn learner_pid(&self) -> Option<u32> { |
| 131 | self.learner.as_ref().map(|l| l.pid()) |
| 132 | } |
| 133 | |
| 134 | pub fn transcript(&self) -> Option<&[u8]> { |
| 135 | self.learner.as_ref().and_then(|l| l.transcript.as_deref()) |
| 136 | } |
| 137 | |
| 138 | /// Stop admitting operations (used to freeze the library for evaluation). |
| 139 | pub fn freeze_admissions(&mut self) { |
| 140 | self.admissions_frozen = true; |
| 141 | } |
| 142 | |
| 143 | fn append_file(&self, name: &str, bytes: &[u8]) { |
| 144 | if let Some(d) = &self.cfg.out_dir { |
| 145 | if let Ok(mut f) = std::fs::OpenOptions::new() |
| 146 | .create(true) |
| 147 | .append(true) |
| 148 | .open(d.join(name)) |
| 149 | { |
| 150 | let _ = f.write_all(bytes); |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | pub fn present( |
| 156 | &mut self, |
| 157 | fam: &FamilySpec, |
| 158 | seed: u64, |
| 159 | population: Population, |
| 160 | phase: &str, |
| 161 | ) -> Result<CrumbOutcome, ProtocolError> { |
| 162 | let g = gen::generate(fam, seed); |
| 163 | self.present_sealed(&g.visible, &g.sealed, population, phase) |
| 164 | } |
| 165 | |
| 166 | /// Present a crumb from an explicit visible/sealed pair (used by gates that |
| 167 | /// construct canary sealed records). |
| 168 | pub fn present_with( |
| 169 | &mut self, |
| 170 | visible: &crate::visible::VisibleCrumb, |
| 171 | sealed: &SealedCrumb, |
| 172 | ) -> Result<CrumbOutcome, ProtocolError> { |
| 173 | self.present_sealed(visible, sealed, Population::Fundamental, "gates") |
| 174 | } |
| 175 | |
| 176 | fn present_sealed( |
| 177 | &mut self, |
| 178 | visible: &crate::visible::VisibleCrumb, |
| 179 | sealed: &SealedCrumb, |
| 180 | population: Population, |
| 181 | phase: &str, |
| 182 | ) -> Result<CrumbOutcome, ProtocolError> { |
| 183 | let seq = self.seq; |
| 184 | self.seq += 1; |
| 185 | let max_q = self.cfg.search.max_oracle_queries as usize; |
| 186 | let mut evaluations: Vec<SealedEvaluation> = Vec::new(); |
| 187 | let learner = self.learner.as_mut().ok_or(ProtocolError::Io)?; |
| 188 | let ladder = &mut self.ladder; |
| 189 | let session = learner.run_crumb(visible, &mut |sub| { |
| 190 | if evaluations.len() >= max_q { |
| 191 | return Verdict::BudgetExhausted; |
| 192 | } |
| 193 | let ev = evaluate( |
| 194 | visible, |
| 195 | sealed, |
| 196 | &sub.program, |
| 197 | sub.hypotheses, |
| 198 | sub.flags & SUBMIT_ROBUST != 0, |
| 199 | ); |
| 200 | match ev.class { |
| 201 | EvalClass::Verified => ladder.observe_accept(seq, sealed, &ev, &sub.program), |
| 202 | EvalClass::FalsifiedHidden => ladder.observe_reject(&ev, &sub.program), |
| 203 | _ => {} |
| 204 | } |
| 205 | let v = ev.verdict; |
| 206 | evaluations.push(ev); |
| 207 | v |
| 208 | })?; |
| 209 | |
| 210 | let tr = trace::derive(visible, &session); |
| 211 | let mut rec_chain = self.trace_chain; |
| 212 | let tbytes = trace::encode_records(&tr.records, &mut rec_chain); |
| 213 | let mut s_chain = self.sample_chain; |
| 214 | let sbytes = trace::encode_samples(&tr.samples, &mut s_chain); |
| 215 | self.trace_chain = rec_chain; |
| 216 | self.sample_chain = s_chain; |
| 217 | self.append_file("trace.ctr", &tbytes); |
| 218 | self.append_file("samples.cts", &sbytes); |
| 219 | |
| 220 | let admissions = if self.admissions_frozen { |
| 221 | vec![] |
| 222 | } else { |
| 223 | self.ladder.advance(seq) |
| 224 | }; |
| 225 | if self.cfg.library_enabled { |
| 226 | let learner = self.learner.as_mut().ok_or(ProtocolError::Io)?; |
| 227 | for a in &admissions { |
| 228 | learner.admit(a.op_ref, a.scope_bits, &a.program)?; |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | let summary = tr.summary.clone().expect("derive always summarizes"); |
| 233 | let rec = CrumblineRecord { |
| 234 | seq, |
| 235 | lane: Lane::Main, |
| 236 | occurrence: CrumbOccurrenceId::new(), |
| 237 | condition: self.cfg.condition.clone(), |
| 238 | population, |
| 239 | crumb_digest: visible.digest(), |
| 240 | generator_instance_digest: sealed.generator_instance_digest, |
| 241 | sealed_digest: sealed.digest(), |
| 242 | verifier_digest: verifier_digest(), |
| 243 | learner_digest: self.learner_digest, |
| 244 | evaluations: evaluations.iter().map(|e| e.digest()).collect(), |
| 245 | trace_stream_digest: summary.stream_digest, |
| 246 | promotions: admissions.iter().map(|a| a.promotion_digest).collect(), |
| 247 | prev_root: Digest::ZERO, |
| 248 | root: Digest::ZERO, |
| 249 | }; |
| 250 | let root = self |
| 251 | .ledger |
| 252 | .append(rec, &sealed.provenance) |
| 253 | .expect("main lane accepts every provenance"); |
| 254 | if let Some(r) = self.ledger.records.last() { |
| 255 | self.append_file( |
| 256 | "ledger.jsonl", |
| 257 | format!("{}\n", serde_json::to_string(r).unwrap()).as_bytes(), |
| 258 | ); |
| 259 | } |
| 260 | for e in &evaluations { |
| 261 | self.append_file( |
| 262 | "evaluations.jsonl", |
| 263 | format!("{}\n", serde_json::to_string(e).unwrap()).as_bytes(), |
| 264 | ); |
| 265 | } |
| 266 | |
| 267 | let accepted = evaluations.iter().any(|e| e.verdict == Verdict::Accept); |
| 268 | let out = CrumbOutcome { |
| 269 | seq, |
| 270 | phase: phase.to_string(), |
| 271 | family_id: sealed.family_id, |
| 272 | family_key: sealed.family_key.clone(), |
| 273 | mechanism: sealed.mechanism.clone(), |
| 274 | population, |
| 275 | decoy: sealed.decoy_status, |
| 276 | crumb_digest: visible.digest(), |
| 277 | supported: session.stats.outcome != crate::protocol::OUTCOME_UNSUPPORTED, |
| 278 | accepted, |
| 279 | verified: evaluations.iter().any(|e| e.class == EvalClass::Verified), |
| 280 | ambiguous_accept: evaluations |
| 281 | .iter() |
| 282 | .any(|e| e.class == EvalClass::AmbiguousUnderdetermined), |
| 283 | library_ops_available: session.bank.iter().filter(|b| b.origin == 1).count() as u32, |
| 284 | declared_bank: session.bank.iter().map(|b| b.program.clone()).collect(), |
| 285 | evaluations, |
| 286 | stats: session.stats, |
| 287 | trace: summary, |
| 288 | admissions_after: admissions, |
| 289 | ledger_root: root, |
| 290 | }; |
| 291 | self.outcomes.push(out.clone()); |
| 292 | Ok(out) |
| 293 | } |
| 294 | |
| 295 | pub fn finish(mut self) -> Result<(Ledger, Vec<CrumbOutcome>, Ladder), ProtocolError> { |
| 296 | if let Some(l) = self.learner.take() { |
| 297 | l.shutdown()?; |
| 298 | } |
| 299 | if let Some(d) = &self.cfg.out_dir { |
| 300 | let _ = std::fs::write( |
| 301 | d.join("promotion.json"), |
| 302 | serde_json::to_string_pretty(&self.ladder.ops.values().collect::<Vec<_>>()) |
| 303 | .unwrap(), |
| 304 | ); |
| 305 | } |
| 306 | Ok((self.ledger, self.outcomes, self.ladder)) |
| 307 | } |
| 308 | } |