interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / crumbs / src / protocol.rs

411 lines · 12973 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//! The learner protocol (v1): the only channel between the sealed side and a learner.
17//!
18//! The learner runs as a separate operating-system process. It never shares an
19//! address space with sealed data; everything it can know arrives through the
20//! frames below, and every frame type is listed here. There is no frame that
21//! can carry a sealed field, a held-out example, a label or an explanation.
22//!
23//! Frame: `type u8 | len u32 | payload`.
24//!
25//! Sealed side -> learner:
26//! - `0x01 HELLO `: protocol u16, library_enabled u8, SearchConfig (6 x u32)
27//! - `0x02 CRUMB `: canonical Crumb v1 visible bytes
28//! - `0x03 VERDICT `: one byte (1 accept, 2 reject, 3 budget exhausted)
29//! - `0x04 ADMIT `: op_ref u32, scope_bits u8, CPG1 program
30//! - `0x05 SHUTDOWN`: empty
31//!
32//! Learner -> sealed side:
33//! - `0x81 READY `: protocol u16
34//! - `0x82 BANK `: n u32, n x (origin u8, op_ref u32, CPG1 program) (per crumb)
35//! - `0x83 SUBMIT `: node u32, flags u8, hypotheses u8, CPG1 program
36//! - `0x84 EVENTS `: n u32, n x 20-byte search event
37//! - `0x85 DONE `: outcome u8, solution_node u32, 12 x u32 counters, 2 x u64 counters
38//!
39//! Any other frame from the learner aborts the session; nothing is sent in reply.
40
41use crate::canon::{Dec, DecodeError, Enc};
42use crate::program::Program;
43use crate::verify::Verdict;
44use crate::visible::VisibleCrumb;
45use serde::{Deserialize, Serialize};
46use std::io::{Read, Write};
47use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
48
49pub const PROTOCOL_VERSION: u16 = 1;
50pub const MAX_FRAME: usize = 1 << 24;
51
52pub mod ft {
53 pub const HELLO: u8 = 0x01;
54 pub const CRUMB: u8 = 0x02;
55 pub const VERDICT: u8 = 0x03;
56 pub const ADMIT: u8 = 0x04;
57 pub const SHUTDOWN: u8 = 0x05;
58 pub const READY: u8 = 0x81;
59 pub const BANK: u8 = 0x82;
60 pub const SUBMIT: u8 = 0x83;
61 pub const EVENTS: u8 = 0x84;
62 pub const DONE: u8 = 0x85;
63}
64
65/// Search limits handed to the learner. Identical in every experimental condition.
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
67pub struct SearchConfig {
68 pub max_candidates: u32,
69 pub max_depth: u32,
70 pub frontier_cap: u32,
71 pub max_oracle_queries: u32,
72 pub ambiguity_scan: u32,
73 pub robust_min_pct: u32,
74}
75
76impl Default for SearchConfig {
77 fn default() -> Self {
78 SearchConfig {
79 max_candidates: 20_000,
80 max_depth: 6,
81 frontier_cap: 4_000,
82 max_oracle_queries: 4,
83 ambiguity_scan: 400,
84 robust_min_pct: 75,
85 }
86 }
87}
88
89/// Learner search-event kinds.
90pub mod ek {
91 pub const EXPAND: u8 = 1;
92 pub const SUBMIT: u8 = 2;
93}
94
95/// One observable search step, as reported by the learner. Numbers only.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
97pub struct LearnerEvent {
98 pub kind: u8,
99 pub prune: u8,
100 pub verify: u8,
101 pub fit: u8,
102 pub op_index: u16,
103 pub parent: u32,
104 pub child: u32,
105 pub exec_cost: u32,
106 pub oracle_index: u16,
107}
108
109pub const EVENT_BYTES: usize = 20;
110
111impl LearnerEvent {
112 fn decode(d: &mut Dec<'_>) -> Result<Self, DecodeError> {
113 Ok(LearnerEvent {
114 kind: d.u8()?,
115 prune: d.u8()?,
116 verify: d.u8()?,
117 fit: d.u8()?,
118 op_index: d.u16()?,
119 parent: d.u32()?,
120 child: d.u32()?,
121 exec_cost: d.u32()?,
122 oracle_index: d.u16()?,
123 })
124 }
125}
126
127#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
128pub struct BankEntry {
129 /// 0 = learner base vocabulary, 1 = admitted library operation.
130 pub origin: u8,
131 /// The ADMIT op_ref this entry came from (0 for base operations).
132 pub op_ref: u32,
133 pub program: Program,
134}
135
136#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
137pub struct Submission {
138 pub node: u32,
139 pub flags: u8,
140 pub hypotheses: u8,
141 pub program: Program,
142 pub verdict: Verdict,
143}
144
145pub const SUBMIT_ROBUST: u8 = 1;
146
147/// The learner's own end-of-crumb counters.
148#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
149pub struct LearnerStats {
150 pub outcome: u8,
151 pub solution_node: u32,
152 pub generated: u32,
153 pub evaluated: u32,
154 pub expansions: u32,
155 pub pruned_equiv: u32,
156 pub pruned_cost: u32,
157 pub pruned_cap: u32,
158 pub visible_fits: u32,
159 pub verify_failures: u32,
160 pub oracle_queries: u32,
161 pub oracle_rejections: u32,
162 pub candidates_to_solution: u32,
163 pub hypotheses_at_first_submit: u32,
164 pub exec_count: u64,
165 pub wall_ns: u64,
166}
167
168pub const OUTCOME_SOLVED: u8 = 1;
169pub const OUTCOME_UNSOLVED: u8 = 2;
170pub const OUTCOME_UNSUPPORTED: u8 = 3;
171
172/// Everything the learner produced for one crumb.
173#[derive(Clone, Debug, Default)]
174pub struct CrumbSession {
175 pub bank: Vec<BankEntry>,
176 pub events: Vec<LearnerEvent>,
177 pub submissions: Vec<Submission>,
178 pub stats: LearnerStats,
179}
180
181#[derive(Debug)]
182pub enum ProtocolError {
183 Io,
184 Malformed,
185 Violation,
186 Version,
187}
188
189impl std::fmt::Display for ProtocolError {
190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191 write!(f, "learner protocol error: {self:?}")
192 }
193}
194
195impl std::error::Error for ProtocolError {}
196
197impl From<std::io::Error> for ProtocolError {
198 fn from(_: std::io::Error) -> Self {
199 ProtocolError::Io
200 }
201}
202
203impl From<DecodeError> for ProtocolError {
204 fn from(_: DecodeError) -> Self {
205 ProtocolError::Malformed
206 }
207}
208
209pub fn write_frame(w: &mut dyn Write, t: u8, payload: &[u8]) -> std::io::Result<()> {
210 let mut hdr = [0u8; 5];
211 hdr[0] = t;
212 hdr[1..].copy_from_slice(&(payload.len() as u32).to_le_bytes());
213 w.write_all(&hdr)?;
214 w.write_all(payload)?;
215 w.flush()
216}
217
218pub fn read_frame(r: &mut dyn Read) -> Result<(u8, Vec<u8>), ProtocolError> {
219 let mut hdr = [0u8; 5];
220 r.read_exact(&mut hdr)?;
221 let len = u32::from_le_bytes(hdr[1..].try_into().unwrap()) as usize;
222 if len > MAX_FRAME {
223 return Err(ProtocolError::Malformed);
224 }
225 let mut buf = vec![0u8; len];
226 r.read_exact(&mut buf)?;
227 Ok((hdr[0], buf))
228}
229
230/// A learner running as a child process.
231pub struct LearnerProcess {
232 child: Child,
233 stdin: ChildStdin,
234 stdout: ChildStdout,
235 /// Every byte sent to the learner, kept for leak audits when enabled.
236 pub transcript: Option<Vec<u8>>,
237}
238
239impl LearnerProcess {
240 pub fn spawn(
241 path: &str,
242 args: &[&str],
243 record_transcript: bool,
244 ) -> Result<Self, ProtocolError> {
245 let mut child = Command::new(path)
246 .args(args)
247 .env_clear()
248 .stdin(Stdio::piped())
249 .stdout(Stdio::piped())
250 .stderr(Stdio::inherit())
251 .spawn()?;
252 let stdin = child.stdin.take().ok_or(ProtocolError::Io)?;
253 let stdout = child.stdout.take().ok_or(ProtocolError::Io)?;
254 Ok(LearnerProcess {
255 child,
256 stdin,
257 stdout,
258 transcript: record_transcript.then(Vec::new),
259 })
260 }
261
262 pub fn pid(&self) -> u32 {
263 self.child.id()
264 }
265
266 fn send(&mut self, t: u8, payload: &[u8]) -> Result<(), ProtocolError> {
267 if let Some(tr) = self.transcript.as_mut() {
268 tr.push(t);
269 tr.extend_from_slice(&(payload.len() as u32).to_le_bytes());
270 tr.extend_from_slice(payload);
271 }
272 write_frame(&mut self.stdin, t, payload)?;
273 Ok(())
274 }
275
276 pub fn hello(
277 &mut self,
278 cfg: &SearchConfig,
279 library_enabled: bool,
280 ) -> Result<(), ProtocolError> {
281 let mut e = Enc::new();
282 e.u16(PROTOCOL_VERSION).u8(library_enabled as u8);
283 for v in [
284 cfg.max_candidates,
285 cfg.max_depth,
286 cfg.frontier_cap,
287 cfg.max_oracle_queries,
288 cfg.ambiguity_scan,
289 cfg.robust_min_pct,
290 ] {
291 e.u32(v);
292 }
293 self.send(ft::HELLO, &e.finish())?;
294 let (t, p) = read_frame(&mut self.stdout)?;
295 if t != ft::READY {
296 return Err(ProtocolError::Violation);
297 }
298 let mut d = Dec::new(&p);
299 if d.u16()? != PROTOCOL_VERSION {
300 return Err(ProtocolError::Version);
301 }
302 Ok(())
303 }
304
305 /// Admit a verified library operation (sent only in conditions that allow reuse).
306 pub fn admit(
307 &mut self,
308 op_ref: u32,
309 scope_bits: u8,
310 program: &Program,
311 ) -> Result<(), ProtocolError> {
312 let mut e = Enc::new();
313 e.u32(op_ref).u8(scope_bits).bytes(&program.to_bytes());
314 self.send(ft::ADMIT, &e.finish())
315 }
316
317 /// Present one crumb. `oracle` is the sealed evaluator; it sees each
318 /// submission and returns the verdict byte the learner will receive.
319 pub fn run_crumb(
320 &mut self,
321 visible: &VisibleCrumb,
322 oracle: &mut dyn FnMut(&Submission) -> Verdict,
323 ) -> Result<CrumbSession, ProtocolError> {
324 self.send(ft::CRUMB, &visible.to_bytes())?;
325 let mut s = CrumbSession::default();
326 loop {
327 let (t, p) = read_frame(&mut self.stdout)?;
328 let mut d = Dec::new(&p);
329 match t {
330 ft::BANK => {
331 let n = d.u32()? as usize;
332 for _ in 0..n.min(4096) {
333 let origin = d.u8()?;
334 let op_ref = d.u32()?;
335 let program = Program::decode(&mut d)?;
336 s.bank.push(BankEntry {
337 origin,
338 op_ref,
339 program,
340 });
341 }
342 d.finish()?;
343 }
344 ft::EVENTS => {
345 let n = d.u32()? as usize;
346 if n * EVENT_BYTES + 4 != p.len() {
347 return Err(ProtocolError::Malformed);
348 }
349 for _ in 0..n {
350 s.events.push(LearnerEvent::decode(&mut d)?);
351 }
352 }
353 ft::SUBMIT => {
354 let node = d.u32()?;
355 let flags = d.u8()?;
356 let hypotheses = d.u8()?;
357 let program = Program::decode(&mut d)?;
358 d.finish()?;
359 let mut sub = Submission {
360 node,
361 flags,
362 hypotheses,
363 program,
364 verdict: Verdict::Reject,
365 };
366 sub.verdict = oracle(&sub);
367 self.send(ft::VERDICT, &[sub.verdict as u8])?;
368 s.submissions.push(sub);
369 }
370 ft::DONE => {
371 let st = &mut s.stats;
372 st.outcome = d.u8()?;
373 st.solution_node = d.u32()?;
374 for f in [
375 &mut st.generated,
376 &mut st.evaluated,
377 &mut st.expansions,
378 &mut st.pruned_equiv,
379 &mut st.pruned_cost,
380 &mut st.pruned_cap,
381 &mut st.visible_fits,
382 &mut st.verify_failures,
383 &mut st.oracle_queries,
384 &mut st.oracle_rejections,
385 &mut st.candidates_to_solution,
386 &mut st.hypotheses_at_first_submit,
387 ] {
388 *f = d.u32()?;
389 }
390 st.exec_count = d.u64()?;
391 st.wall_ns = d.u64()?;
392 d.finish()?;
393 return Ok(s);
394 }
395 _ => return Err(ProtocolError::Violation),
396 }
397 }
398 }
399
400 pub fn shutdown(mut self) -> Result<std::process::ExitStatus, ProtocolError> {
401 let _ = self.send(ft::SHUTDOWN, &[]);
402 drop(self.stdin);
403 Ok(self.child.wait()?)
404 }
405
406 /// Kill without ceremony (used after a protocol violation).
407 pub fn kill(mut self) {
408 let _ = self.child.kill();
409 let _ = self.child.wait();
410 }
411}