Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/crumbs/src/trace.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / crumbs / src / trace.rs` 537 lines ยท 18758 bytes Raw Blame History 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 //! Search-trace corpus (the M23-style training data for AIEN_0). 17 //! 18 //! The learner reports bare search events (which operation it applied to which 19 //! node, how it pruned, what it submitted). The sealed side reconstructs every 20 //! candidate program from those events and the declared operation bank, and 21 //! derives everything else itself from the *visible* examples: state digests, 22 //! remaining-mismatch vectors, improvement flags. Held-out results enter a 23 //! record only on SUBMIT events, and only as the verdict the learner received. 24 //! 25 //! No record has a free-text field. Nothing resembling reasoning prose can be 26 //! stored; records hold operations, states, measurements and outcomes. 27 //! 28 //! `CTR1` trace record (fixed 247 bytes incl. chain digest) and `CTS1` 29 //! training sample (fixed 268 bytes incl. chain digest) are hash-chained with 30 //! BLAKE3 so a corpus file cannot be edited without detection. 31 32 use crate::canon::Enc; 33 use crate::digest::{digest, Digest, Domain, Hasher}; 34 use crate::program::Program; 35 use crate::protocol::{ek, CrumbSession}; 36 use crate::verify::Verdict; 37 use crate::visible::{lane_mask, Encoding, VisibleCrumb}; 38 use serde::{Deserialize, Serialize}; 39 use std::collections::{HashMap, HashSet}; 40 41 pub const TRACE_RECORD_BYTES: usize = 247; 42 pub const SAMPLE_RECORD_BYTES: usize = 268; 43 pub const SAMPLE_MAX_OPS: usize = 128; 44 pub const RESIDUALS: usize = 4; 45 46 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] 47 #[repr(u8)] 48 pub enum ResultClass { 49 /// Generated but pruned (equivalent, over cost, frontier cap). 50 Pruned = 1, 51 /// Evaluated; mismatch did not shrink. 52 Failed = 2, 53 /// Evaluated; some examples matched but no improvement on the parent. 54 Partial = 3, 55 /// Evaluated; mismatch shrank relative to the parent. 56 Improved = 4, 57 /// Submitted and accepted by the sealed verifier. 58 Verified = 5, 59 /// Submitted, explained the visible examples, rejected by held-outs. 60 RejectedHidden = 6, 61 /// A robust (best partial fit) submission that was rejected. 62 RejectedRobust = 7, 63 } 64 65 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 66 pub struct TraceRecord { 67 pub event_index: u32, 68 pub kind: u8, 69 pub result_class: ResultClass, 70 pub parent: u32, 71 pub child: u32, 72 pub op_index: u16, 73 pub op_id: Digest, 74 pub op_origin: u8, 75 pub depth: u16, 76 pub prune: u8, 77 pub verify: u8, 78 pub fit: u8, 79 /// 0 unless this is a SUBMIT record; then the verdict byte the learner got. 80 pub hidden: u8, 81 pub improved: bool, 82 pub contributed: bool, 83 pub state_digest: Digest, 84 pub child_state_digest: Digest, 85 pub program_digest: Digest, 86 pub mismatch_before: u16, 87 pub mismatch_after: u16, 88 pub hamming_before: u32, 89 pub hamming_after: u32, 90 pub exec_cost: u32, 91 pub search_cost: u32, 92 pub program_steps: u16, 93 pub oracle_index: u16, 94 pub residual: [u64; RESIDUALS], 95 } 96 97 /// One decision state on a verified solution path, with the operations that 98 /// were tried there and which of them led onward (equivalence-aware). 99 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 100 pub struct TrainingSample { 101 pub bank_digest: Digest, 102 pub state_digest: Digest, 103 pub depth: u8, 104 pub solution_depth: u8, 105 pub n_examples: u8, 106 pub n_ops: u16, 107 pub values: [u64; 8], 108 pub targets: [u64; 8], 109 pub positive_bits: [u8; SAMPLE_MAX_OPS / 8], 110 pub tried_bits: [u8; SAMPLE_MAX_OPS / 8], 111 } 112 113 /// Per-crumb summary (the `final:` block of the trace). 114 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] 115 pub struct TraceSummary { 116 pub bank_digest: Digest, 117 pub bank_op_ids: Vec, 118 pub solved: bool, 119 pub solution_digest: Option, 120 pub verified_on_heldout: bool, 121 pub records: u32, 122 pub samples: u32, 123 pub stream_digest: Digest, 124 /// Library operations (by op_ref) used in the accepted solution. 125 pub library_refs_in_solution: Vec, 126 /// A submitted program disagreed with the program reconstructed from events. 127 pub integrity_violations: u32, 128 } 129 130 #[derive(Clone, Debug, Default)] 131 pub struct CrumbTrace { 132 pub records: Vec, 133 pub samples: Vec, 134 pub summary: Option, 135 } 136 137 struct Node { 138 parent: u32, 139 op: u16, 140 depth: u16, 141 vals: Vec, 142 program: Program, 143 } 144 145 fn state_digest(vals: &[u64]) -> Digest { 146 let mut e = Enc::new(); 147 for v in vals { 148 e.u64(*v); 149 } 150 digest(Domain::SearchState, &e.finish()) 151 } 152 153 pub fn bank_digest(bank: &[crate::protocol::BankEntry]) -> Digest { 154 let mut h = Hasher::new(Domain::LearnerBank); 155 for b in bank { 156 h.update(&[b.origin]).update(&b.program.digest().0); 157 } 158 h.finish() 159 } 160 161 /// Derive the canonical trace for one crumb session. 162 pub fn derive(visible: &VisibleCrumb, session: &CrumbSession) -> CrumbTrace { 163 let mut out = CrumbTrace::default(); 164 let vals_in: Vec<(u64, u64)> = visible 165 .values() 166 .into_iter() 167 .map(|(i, o)| (i[0], o[0])) 168 .collect(); 169 let mask = match visible.encoding { 170 Encoding::DecimalUtf8 => u64::MAX, 171 Encoding::RawLe => lane_mask(visible.out_lane_bytes), 172 }; 173 let targets: Vec = vals_in.iter().map(|p| p.1).collect(); 174 let bank_ids: Vec = session.bank.iter().map(|b| b.program.digest()).collect(); 175 let bdig = bank_digest(&session.bank); 176 177 let measure = |vals: &[u64]| -> (u16, u32, [u64; RESIDUALS]) { 178 let mut mism = 0u16; 179 let mut ham = 0u32; 180 let mut res = [0u64; RESIDUALS]; 181 for (i, (v, t)) in vals.iter().zip(&targets).enumerate() { 182 let v = v & mask; 183 if v != *t { 184 mism += 1; 185 } 186 ham += (v ^ t).count_ones(); 187 if i < RESIDUALS { 188 res[i] = t.wrapping_sub(v); 189 } 190 } 191 (mism, ham, res) 192 }; 193 194 let mut nodes: HashMap = HashMap::new(); 195 nodes.insert( 196 0, 197 Node { 198 parent: u32::MAX, 199 op: u16::MAX, 200 depth: 0, 201 vals: vals_in.iter().map(|p| p.0).collect(), 202 program: Program::default(), 203 }, 204 ); 205 206 // Oracle verdicts by node, from the actual submissions. 207 let mut verdict_of: HashMap = HashMap::new(); 208 let mut integrity_violations = 0; 209 for s in &session.submissions { 210 verdict_of.insert(s.node, s.verdict); 211 } 212 213 for (idx, ev) in session.events.iter().enumerate() { 214 let mut r = TraceRecord { 215 event_index: idx as u32, 216 kind: ev.kind, 217 result_class: ResultClass::Failed, 218 parent: ev.parent, 219 child: ev.child, 220 op_index: ev.op_index, 221 op_id: Digest::ZERO, 222 op_origin: 0, 223 depth: 0, 224 prune: ev.prune, 225 verify: ev.verify, 226 fit: ev.fit, 227 hidden: 0, 228 improved: false, 229 contributed: false, 230 state_digest: Digest::ZERO, 231 child_state_digest: Digest::ZERO, 232 program_digest: Digest::ZERO, 233 mismatch_before: 0, 234 mismatch_after: 0, 235 hamming_before: 0, 236 hamming_after: 0, 237 exec_cost: ev.exec_cost, 238 search_cost: idx as u32, 239 program_steps: 0, 240 oracle_index: ev.oracle_index, 241 residual: [0; RESIDUALS], 242 }; 243 match ev.kind { 244 ek::EXPAND => { 245 let Some(parent) = nodes.get(&ev.parent) else { 246 continue; 247 }; 248 let Some(op) = session.bank.get(ev.op_index as usize) else { 249 continue; 250 }; 251 let vals: Vec = parent.vals.iter().map(|&x| op.program.run(x)).collect(); 252 let program = parent.program.then(&op.program); 253 let (mb, hb, _) = measure(&parent.vals); 254 let (ma, ha, res) = measure(&vals); 255 r.op_id = bank_ids[ev.op_index as usize]; 256 r.op_origin = op.origin; 257 r.depth = parent.depth + 1; 258 r.state_digest = state_digest(&parent.vals); 259 r.child_state_digest = state_digest(&vals); 260 r.program_digest = program.digest(); 261 r.mismatch_before = mb; 262 r.mismatch_after = ma; 263 r.hamming_before = hb; 264 r.hamming_after = ha; 265 r.program_steps = program.len() as u16; 266 r.residual = res; 267 r.improved = ev.prune == 0 && (ma < mb || (ma == mb && ha < hb)); 268 r.result_class = if ev.prune != 0 { 269 ResultClass::Pruned 270 } else if r.improved { 271 ResultClass::Improved 272 } else if (ma as usize) < targets.len() { 273 ResultClass::Partial 274 } else { 275 ResultClass::Failed 276 }; 277 let depth = r.depth; 278 nodes.insert( 279 ev.child, 280 Node { 281 parent: ev.parent, 282 op: ev.op_index, 283 depth, 284 vals, 285 program, 286 }, 287 ); 288 } 289 ek::SUBMIT => { 290 let Some(node) = nodes.get(&ev.parent) else { 291 continue; 292 }; 293 let (m, h, res) = measure(&node.vals); 294 r.depth = node.depth; 295 r.state_digest = state_digest(&node.vals); 296 r.child_state_digest = r.state_digest; 297 r.program_digest = node.program.digest(); 298 r.mismatch_before = m; 299 r.mismatch_after = m; 300 r.hamming_before = h; 301 r.hamming_after = h; 302 r.program_steps = node.program.len() as u16; 303 r.residual = res; 304 let v = verdict_of.get(&ev.parent).copied(); 305 r.hidden = v.map_or(0, |v| v as u8); 306 r.result_class = match v { 307 Some(Verdict::Accept) => ResultClass::Verified, 308 _ if ev.fit == 2 => ResultClass::RejectedRobust, 309 _ => ResultClass::RejectedHidden, 310 }; 311 if let Some(sub) = session.submissions.iter().find(|s| s.node == ev.parent) { 312 if sub.program.run_all_eq(&node.program) == Some(false) { 313 integrity_violations += 1; 314 } 315 } 316 } 317 _ => continue, 318 } 319 out.records.push(r); 320 } 321 322 // Backfill: which transitions contributed to the accepted solution? 323 let accepted = session 324 .submissions 325 .iter() 326 .find(|s| s.verdict == Verdict::Accept); 327 let mut library_refs = Vec::new(); 328 let mut path_states: HashSet<(u16, Digest)> = HashSet::new(); 329 let mut path_nodes: Vec = Vec::new(); 330 if let Some(acc) = accepted { 331 let mut n = acc.node; 332 while let Some(node) = nodes.get(&n) { 333 path_nodes.push(n); 334 path_states.insert((node.depth, state_digest(&node.vals))); 335 if node.op != u16::MAX { 336 let b = &session.bank[node.op as usize]; 337 if b.origin == 1 { 338 library_refs.push(b.op_ref); 339 } 340 } 341 if node.parent == u32::MAX { 342 break; 343 } 344 n = node.parent; 345 } 346 library_refs.sort_unstable(); 347 for r in out.records.iter_mut() { 348 if r.kind == ek::EXPAND && path_states.contains(&(r.depth, r.child_state_digest)) { 349 r.contributed = true; 350 } 351 if r.kind == ek::SUBMIT && r.parent == acc.node { 352 r.contributed = true; 353 } 354 } 355 // Training samples: one per decision state on the path. A submission 356 // whose node was never reported in the event stream yields none. 357 path_nodes.reverse(); // root first 358 let solution_depth = path_nodes.len().saturating_sub(1) as u8; 359 for &pn in path_nodes.iter().take(path_nodes.len().saturating_sub(1)) { 360 let node = &nodes[&pn]; 361 let sd = state_digest(&node.vals); 362 let mut s = TrainingSample { 363 bank_digest: bdig, 364 state_digest: sd, 365 depth: node.depth as u8, 366 solution_depth, 367 n_examples: targets.len().min(255) as u8, 368 n_ops: session.bank.len() as u16, 369 values: [0; 8], 370 targets: [0; 8], 371 positive_bits: [0; SAMPLE_MAX_OPS / 8], 372 tried_bits: [0; SAMPLE_MAX_OPS / 8], 373 }; 374 let k = 8.min(targets.len()); 375 s.values[..k].copy_from_slice(&node.vals[..k]); 376 s.targets[..k].copy_from_slice(&targets[..k]); 377 for r in out 378 .records 379 .iter() 380 .filter(|r| r.kind == ek::EXPAND && r.parent == pn) 381 { 382 let i = r.op_index as usize; 383 if i < SAMPLE_MAX_OPS { 384 s.tried_bits[i / 8] |= 1 << (i % 8); 385 if r.contributed { 386 s.positive_bits[i / 8] |= 1 << (i % 8); 387 } 388 } 389 } 390 out.samples.push(s); 391 } 392 } 393 394 let stream = stream_digest(&out.records, &out.samples); 395 out.summary = Some(TraceSummary { 396 bank_digest: bdig, 397 bank_op_ids: bank_ids, 398 solved: accepted.is_some(), 399 solution_digest: accepted.map(|a| a.program.digest()), 400 verified_on_heldout: accepted.is_some(), 401 records: out.records.len() as u32, 402 samples: out.samples.len() as u32, 403 stream_digest: stream, 404 library_refs_in_solution: library_refs, 405 integrity_violations, 406 }); 407 out 408 } 409 410 impl Program { 411 /// Compare behaviour on the public probes (None if either is empty). 412 pub fn run_all_eq(&self, other: &Program) -> Option { 413 if self.is_empty() || other.is_empty() { 414 return None; 415 } 416 Some(self.behavior() == other.behavior()) 417 } 418 } 419 420 impl TraceRecord { 421 pub fn encode_body(&self, e: &mut Enc) { 422 e.bytes(b"CTR1") 423 .u16(1) 424 .u8(self.kind) 425 .u8(self.result_class as u8); 426 e.u32(self.event_index) 427 .u32(self.parent) 428 .u32(self.child) 429 .u16(self.op_index) 430 .u8(self.op_origin); 431 e.u8(self.prune) 432 .u8(self.verify) 433 .u8(self.fit) 434 .u8(self.hidden); 435 e.u8(self.improved as u8) 436 .u8(self.contributed as u8) 437 .u16(self.depth); 438 e.digest(&self.op_id) 439 .digest(&self.state_digest) 440 .digest(&self.child_state_digest) 441 .digest(&self.program_digest); 442 e.u16(self.mismatch_before) 443 .u16(self.mismatch_after) 444 .u32(self.hamming_before) 445 .u32(self.hamming_after); 446 e.u32(self.exec_cost) 447 .u32(self.search_cost) 448 .u16(self.program_steps) 449 .u16(self.oracle_index); 450 for r in self.residual { 451 e.u64(r); 452 } 453 } 454 } 455 456 impl TrainingSample { 457 pub fn encode_body(&self, e: &mut Enc) { 458 e.bytes(b"CTS1").u16(1).u16(self.n_ops); 459 e.digest(&self.bank_digest).digest(&self.state_digest); 460 e.u8(self.depth) 461 .u8(self.solution_depth) 462 .u8(self.n_examples) 463 .u8(0); 464 for v in self.values { 465 e.u64(v); 466 } 467 for v in self.targets { 468 e.u64(v); 469 } 470 e.bytes(&self.positive_bits).bytes(&self.tried_bits); 471 } 472 } 473 474 /// Encode records with a BLAKE3 chain; `chain` carries the previous digest. 475 pub fn encode_records(records: &[TraceRecord], chain: &mut Digest) -> Vec { 476 let mut out = Vec::with_capacity(records.len() * TRACE_RECORD_BYTES); 477 for r in records { 478 let mut e = Enc::new(); 479 r.encode_body(&mut e); 480 let body = e.finish(); 481 debug_assert_eq!(body.len(), TRACE_RECORD_BYTES - 32); 482 let d = Hasher::new(Domain::TraceRecord) 483 .update(&chain.0) 484 .update(&body) 485 .finish(); 486 out.extend_from_slice(&body); 487 out.extend_from_slice(&d.0); 488 *chain = d; 489 } 490 out 491 } 492 493 pub fn encode_samples(samples: &[TrainingSample], chain: &mut Digest) -> Vec { 494 let mut out = Vec::with_capacity(samples.len() * SAMPLE_RECORD_BYTES); 495 for s in samples { 496 let mut e = Enc::new(); 497 s.encode_body(&mut e); 498 let body = e.finish(); 499 debug_assert_eq!(body.len(), SAMPLE_RECORD_BYTES - 32); 500 let d = Hasher::new(Domain::TrainingSample) 501 .update(&chain.0) 502 .update(&body) 503 .finish(); 504 out.extend_from_slice(&body); 505 out.extend_from_slice(&d.0); 506 *chain = d; 507 } 508 out 509 } 510 511 fn stream_digest(records: &[TraceRecord], samples: &[TrainingSample]) -> Digest { 512 let mut c1 = Digest::ZERO; 513 let a = encode_records(records, &mut c1); 514 let mut c2 = Digest::ZERO; 515 let b = encode_samples(samples, &mut c2); 516 let _ = (a, b); 517 let mut e = Enc::new(); 518 e.digest(&c1).digest(&c2); 519 digest(Domain::TraceStream, &e.finish()) 520 } 521 522 /// Re-verify a chained record file. Returns the number of records or None. 523 pub fn verify_chain(bytes: &[u8], record_len: usize, domain: Domain) -> Option { 524 if !bytes.len().is_multiple_of(record_len) { 525 return None; 526 } 527 let mut chain = Digest::ZERO; 528 for rec in bytes.chunks(record_len) { 529 let (body, d) = rec.split_at(record_len - 32); 530 let want = Hasher::new(domain).update(&chain.0).update(body).finish(); 531 if want.0 != d { 532 return None; 533 } 534 chain = want; 535 } 536 Some(bytes.len() / record_len) 537 }