interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / allen-reflex / src / tower.rs

512 lines · 19450 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//! ALLEN Tower: scheduling core for a Pi 5 bare-metal AIENOS test and verification orchestrator.
17//!
18//! Intended pairing: the persistent 8 GB Raspberry Pi 5 (bare-metal AIENOS + ALLEN REFLEX)
19//! with the DGX Spark. Status: library only. Nothing links this module into the Pi kernel or
20//! any test runner yet, and no Pi or Spark run has exercised it.
21//!
22//! Rules this core enforces:
23//! - A PASS receipt is reused only for the exact `(gate, tier, input_digest)` it was recorded
24//! for, and only for gates marked cacheable. A receipt from one tier (for example the
25//! labelled Pi test tier) never stands in for another tier.
26//! - `input_digest` is meant to come from [`combine_mneme_digest`]: SHA-256 over the declared
27//! inputs, the sibling pins and every observed Mneme (`libmneme.so`) file-read digest.
28//! - Concurrent identical cacheable requests join the run already in flight (`JoinInflight`).
29//! Uncacheable gates always run on their own.
30//! - Routing: `Portable` and `Pi5Host` gates run on the Pi 5 (`RunPi5Local`), `SparkHost` and
31//! `SparkQemu` gates go to the Spark host pool (`DispatchSparkHost`), and `SparkGb10` /
32//! `SparkNvrm` gates go to the Spark's one-at-a-time GPU queue (`QueueSparkGb10`).
33
34use aienos_crypto::sha256::Sha256;
35use alloc::string::String;
36use alloc::vec;
37use alloc::vec::Vec;
38
39/// Execution tier for a verification gate.
40#[derive(Clone, Copy, PartialEq, Eq, Debug)]
41pub enum GateTier {
42 /// Pure tree/receipt check with no hardware or host tool assumptions.
43 Portable,
44 /// Lightweight C or Rust check runnable directly on the persistent 8 GB Pi 5.
45 Pi5Host,
46 /// Multi-core compilation or mutation sweep dispatched to Spark's 20 Grace cores.
47 SparkHost,
48 /// Full-system AArch64 QEMU emulation dispatched to Spark's host pool.
49 SparkQemu,
50 /// Exclusive Grace Blackwell GB10 silicon gate (serialized 1-at-a-time).
51 SparkGb10,
52 /// Exclusive NVRM kernel-driver lifecycle gate (serialized 1-at-a-time).
53 SparkNvrm,
54}
55
56/// Gate scheduling request evaluated by ALLEN Tower.
57#[derive(Clone, PartialEq, Eq, Debug)]
58pub struct GateSpec {
59 pub gate: String,
60 pub tier: GateTier,
61 pub input_digest: [u8; 32],
62 pub cacheable: bool,
63}
64
65/// Orchestrator action emitted by ALLEN Tower.
66#[derive(Clone, PartialEq, Eq, Debug)]
67pub enum TowerAction {
68 /// Exact `(gate, tier, input_digest)` already has a verified PASS receipt.
69 ReuseReceipt { receipt_digest: [u8; 32] },
70 /// Identical `(gate, tier, input_digest)` is running in slot `slot`; join its result.
71 /// The slot number stays the same until that run is completed.
72 JoinInflight { slot: usize },
73 /// Execute locally on the persistent Pi 5 orchestrator node.
74 RunPi5Local,
75 /// Dispatch to DGX Spark's parallel host/QEMU worker pool.
76 DispatchSparkHost,
77 /// Enqueue on DGX Spark's serialized GB10/NVRM hardware lock queue.
78 QueueSparkGb10,
79}
80
81impl TowerAction {
82 /// Canonical wire name for the tower action.
83 pub fn name(&self) -> &'static str {
84 match self {
85 TowerAction::ReuseReceipt { .. } => "reuse_receipt",
86 TowerAction::JoinInflight { .. } => "join_inflight",
87 TowerAction::RunPi5Local => "run_pi5_local",
88 TowerAction::DispatchSparkHost => "dispatch_spark_host",
89 TowerAction::QueueSparkGb10 => "queue_spark_gb10",
90 }
91 }
92}
93
94/// Machine-checkable reason for a [`TowerDecision`].
95#[derive(Clone, Copy, PartialEq, Eq, Debug)]
96pub enum TowerWhy {
97 CachedPassReceipt,
98 InflightDuplicate,
99 TierLocalPi5,
100 TierSparkHostPool,
101 TierSparkGpuSerial,
102 UncacheableGate,
103}
104
105impl TowerWhy {
106 pub fn name(self) -> &'static str {
107 match self {
108 TowerWhy::CachedPassReceipt => "cached_pass_receipt",
109 TowerWhy::InflightDuplicate => "inflight_duplicate",
110 TowerWhy::TierLocalPi5 => "tier_local_pi5",
111 TowerWhy::TierSparkHostPool => "tier_spark_host_pool",
112 TowerWhy::TierSparkGpuSerial => "tier_spark_gpu_serial",
113 TowerWhy::UncacheableGate => "uncacheable_gate",
114 }
115 }
116}
117
118/// Deterministic scheduling decision from ALLEN Tower.
119#[derive(Clone, PartialEq, Eq, Debug)]
120pub struct TowerDecision {
121 pub gate: String,
122 pub action: TowerAction,
123 pub why: TowerWhy,
124}
125
126impl TowerDecision {
127 /// Format as a single-line JSON decision record. The gate name is JSON-escaped.
128 pub fn to_json(&self) -> String {
129 let mut out = String::from(r#"{"tower_action":""#);
130 out.push_str(self.action.name());
131 out.push_str(r#"","gate":""#);
132 push_json_escaped(&mut out, &self.gate);
133 out.push_str(r#"","why":""#);
134 out.push_str(self.why.name());
135 out.push_str(r#""}"#);
136 out
137 }
138}
139
140fn push_json_escaped(out: &mut String, s: &str) {
141 const HEX: &[u8; 16] = b"0123456789abcdef";
142 for c in s.chars() {
143 match c {
144 '"' => out.push_str("\\\""),
145 '\\' => out.push_str("\\\\"),
146 '\n' => out.push_str("\\n"),
147 '\r' => out.push_str("\\r"),
148 '\t' => out.push_str("\\t"),
149 c if (c as u32) < 0x20 => {
150 let b = c as u32 as u8;
151 out.push_str("\\u00");
152 out.push(HEX[(b >> 4) as usize] as char);
153 out.push(HEX[(b & 0xf) as usize] as char);
154 }
155 c => out.push(c),
156 }
157 }
158}
159
160/// Domain tag that starts every cache-key encoding (NUL-terminated).
161const INPUT_DOMAIN: &[u8] = b"ALLEN-TOWER-INPUT-V1\0";
162
163/// Combine the declared input digest, the sibling pin digest and the Mneme observed
164/// read-set digests into one 32-byte cache key.
165///
166/// Key = SHA-256(`"ALLEN-TOWER-INPUT-V1\0"` || declared || pins || read count as u64 LE ||
167/// each read digest in order). Every field has a fixed size and the count is explicit, so two
168/// different inputs never share an encoding; the order of the reads matters.
169pub fn combine_mneme_digest(
170 declared_inputs: &[u8; 32],
171 sibling_pins: &[u8; 32],
172 mneme_reads: &[[u8; 32]],
173) -> [u8; 32] {
174 let mut h = Sha256::new();
175 h.update(INPUT_DOMAIN);
176 h.update(declared_inputs);
177 h.update(sibling_pins);
178 h.update(&(mneme_reads.len() as u64).to_le_bytes());
179 for r in mneme_reads {
180 h.update(r);
181 }
182 h.finalize()
183}
184
185/// One recorded PASS receipt: `(gate, tier, input_digest, receipt_digest)`.
186type ReceiptEntry = (String, GateTier, [u8; 32], [u8; 32]);
187/// One occupied in-flight slot: `(gate, tier, input_digest)`.
188type InflightEntry = (String, GateTier, [u8; 32]);
189
190/// Bounded, `no_std` orchestrator state machine for the Pi 5 ALLEN Tower.
191pub struct TowerOrchestrator {
192 max_receipts: usize,
193 receipts: Vec<ReceiptEntry>,
194 /// Fixed table of `max_inflight` slots; a run keeps its slot index until completed.
195 inflight: Vec<Option<InflightEntry>>,
196}
197
198impl TowerOrchestrator {
199 pub fn new(max_receipts: usize, max_inflight: usize) -> Self {
200 Self {
201 max_receipts,
202 receipts: Vec::new(),
203 inflight: vec![None; max_inflight],
204 }
205 }
206
207 /// Maximum number of PASS receipts kept (oldest evicted first).
208 pub fn max_receipts(&self) -> usize {
209 self.max_receipts
210 }
211
212 /// Number of in-flight slots.
213 pub fn max_inflight(&self) -> usize {
214 self.inflight.len()
215 }
216
217 /// Record a verified PASS receipt for `(gate, tier, input_digest)` and free its in-flight slot.
218 pub fn record_pass_receipt(
219 &mut self,
220 gate: &str,
221 tier: GateTier,
222 input_digest: [u8; 32],
223 receipt_digest: [u8; 32],
224 ) {
225 self.complete_inflight(gate, tier, &input_digest);
226 for entry in &mut self.receipts {
227 if entry.0 == gate && entry.1 == tier && entry.2 == input_digest {
228 entry.3 = receipt_digest;
229 return;
230 }
231 }
232 if self.max_receipts == 0 {
233 return;
234 }
235 if self.receipts.len() >= self.max_receipts {
236 self.receipts.remove(0);
237 }
238 self.receipts
239 .push((String::from(gate), tier, input_digest, receipt_digest));
240 }
241
242 /// Free the in-flight slot of a finished run. Returns false if no slot held it.
243 pub fn complete_inflight(
244 &mut self,
245 gate: &str,
246 tier: GateTier,
247 input_digest: &[u8; 32],
248 ) -> bool {
249 for slot in &mut self.inflight {
250 if matches!(slot, Some((g, t, d)) if g == gate && *t == tier && d == input_digest) {
251 *slot = None;
252 return true;
253 }
254 }
255 false
256 }
257
258 /// Decide how to handle `spec` without dropping or weakening any gate check.
259 ///
260 /// A cacheable request that finds every in-flight slot taken is dispatched without being
261 /// tracked, so a duplicate of it runs again instead of joining (never skipped).
262 pub fn schedule_gate(&mut self, spec: &GateSpec) -> TowerDecision {
263 let (action, tier_why) = match spec.tier {
264 GateTier::Portable | GateTier::Pi5Host => {
265 (TowerAction::RunPi5Local, TowerWhy::TierLocalPi5)
266 }
267 GateTier::SparkHost | GateTier::SparkQemu => {
268 (TowerAction::DispatchSparkHost, TowerWhy::TierSparkHostPool)
269 }
270 GateTier::SparkGb10 | GateTier::SparkNvrm => {
271 (TowerAction::QueueSparkGb10, TowerWhy::TierSparkGpuSerial)
272 }
273 };
274
275 if !spec.cacheable {
276 return TowerDecision {
277 gate: spec.gate.clone(),
278 action,
279 why: TowerWhy::UncacheableGate,
280 };
281 }
282
283 for (g, t, din, drcpt) in &self.receipts {
284 if *g == spec.gate && *t == spec.tier && *din == spec.input_digest {
285 return TowerDecision {
286 gate: spec.gate.clone(),
287 action: TowerAction::ReuseReceipt {
288 receipt_digest: *drcpt,
289 },
290 why: TowerWhy::CachedPassReceipt,
291 };
292 }
293 }
294
295 let same = |e: &Option<InflightEntry>| matches!(e, Some((g, t, d)) if *g == spec.gate && *t == spec.tier && *d == spec.input_digest);
296 if let Some(slot) = self.inflight.iter().position(same) {
297 return TowerDecision {
298 gate: spec.gate.clone(),
299 action: TowerAction::JoinInflight { slot },
300 why: TowerWhy::InflightDuplicate,
301 };
302 }
303 if let Some(free) = self.inflight.iter_mut().find(|e| e.is_none()) {
304 *free = Some((spec.gate.clone(), spec.tier, spec.input_digest));
305 }
306
307 TowerDecision {
308 gate: spec.gate.clone(),
309 action,
310 why: tier_why,
311 }
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn tower_reuses_receipt_and_deduplicates_inflight_and_routes_tiers() {
321 let mut tower = TowerOrchestrator::new(64, 16);
322 let d_decl = [0x11u8; 32];
323 let d_pins = [0x22u8; 32];
324 let d_read1 = [0x33u8; 32];
325 let d_in = combine_mneme_digest(&d_decl, &d_pins, &[d_read1]);
326 let d_rcpt = [0x99u8; 32];
327
328 tower.record_pass_receipt("OMEGA-ALGEBRA", GateTier::SparkHost, d_in, d_rcpt);
329
330 let spec = GateSpec {
331 gate: String::from("OMEGA-ALGEBRA"),
332 tier: GateTier::SparkHost,
333 input_digest: d_in,
334 cacheable: true,
335 };
336 let dec = tower.schedule_gate(&spec);
337 assert_eq!(
338 dec.action,
339 TowerAction::ReuseReceipt {
340 receipt_digest: d_rcpt
341 }
342 );
343 assert_eq!(dec.why, TowerWhy::CachedPassReceipt);
344 assert_eq!(
345 dec.to_json(),
346 r#"{"tower_action":"reuse_receipt","gate":"OMEGA-ALGEBRA","why":"cached_pass_receipt"}"#
347 );
348
349 // Changing a Mneme observed read-set file invalidates the receipt and dispatches to Spark.
350 let d_in_changed = combine_mneme_digest(&d_decl, &d_pins, &[[0x34u8; 32]]);
351 assert_ne!(d_in, d_in_changed);
352 let spec_changed = GateSpec {
353 gate: String::from("OMEGA-ALGEBRA"),
354 tier: GateTier::SparkHost,
355 input_digest: d_in_changed,
356 cacheable: true,
357 };
358 let dec1 = tower.schedule_gate(&spec_changed);
359 assert_eq!(dec1.action, TowerAction::DispatchSparkHost);
360 assert_eq!(dec1.why, TowerWhy::TierSparkHostPool);
361
362 // A second concurrent request for the same (gate, input_digest) joins the in-flight run.
363 let dec2 = tower.schedule_gate(&spec_changed);
364 assert_eq!(dec2.action, TowerAction::JoinInflight { slot: 0 });
365 assert_eq!(dec2.why, TowerWhy::InflightDuplicate);
366
367 // Portable/Pi5Host routes locally to Pi 5; SparkGb10 queues on Spark GPU lock.
368 let pi_spec = GateSpec {
369 gate: String::from("AIENOS-ZERO-DISK-SECRETS"),
370 tier: GateTier::Portable,
371 input_digest: [0x55u8; 32],
372 cacheable: true,
373 };
374 assert_eq!(
375 tower.schedule_gate(&pi_spec).action,
376 TowerAction::RunPi5Local
377 );
378
379 let gpu_spec = GateSpec {
380 gate: String::from("OMEGA-DIVSQRT-CHIP"),
381 tier: GateTier::SparkGb10,
382 input_digest: [0x66u8; 32],
383 cacheable: false,
384 };
385 let gpu_dec = tower.schedule_gate(&gpu_spec);
386 assert_eq!(gpu_dec.action, TowerAction::QueueSparkGb10);
387 assert_eq!(gpu_dec.why, TowerWhy::UncacheableGate);
388 }
389
390 fn spec(gate: &str, tier: GateTier, d: u8, cacheable: bool) -> GateSpec {
391 GateSpec {
392 gate: String::from(gate),
393 tier,
394 input_digest: [d; 32],
395 cacheable,
396 }
397 }
398
399 #[test]
400 fn join_slot_stays_stable_after_an_earlier_run_completes() {
401 let mut tower = TowerOrchestrator::new(8, 4);
402 let a = spec("GATE-A", GateTier::SparkHost, 1, true);
403 let b = spec("GATE-B", GateTier::SparkHost, 2, true);
404 assert_eq!(
405 tower.schedule_gate(&a).action,
406 TowerAction::DispatchSparkHost
407 );
408 assert_eq!(
409 tower.schedule_gate(&b).action,
410 TowerAction::DispatchSparkHost
411 );
412 assert_eq!(
413 tower.schedule_gate(&b).action,
414 TowerAction::JoinInflight { slot: 1 }
415 );
416 assert!(tower.complete_inflight("GATE-A", GateTier::SparkHost, &[1; 32]));
417 // B is still the run in slot 1; a joiner must keep pointing at it.
418 assert_eq!(
419 tower.schedule_gate(&b).action,
420 TowerAction::JoinInflight { slot: 1 }
421 );
422 }
423
424 #[test]
425 fn receipt_from_one_tier_is_not_reused_for_another_tier() {
426 let mut tower = TowerOrchestrator::new(8, 4);
427 tower.record_pass_receipt("AIENOS-STORE", GateTier::Pi5Host, [7; 32], [0xaa; 32]);
428 // Same gate and inputs, but asked for on the Spark host tier: must run there.
429 let spark = spec("AIENOS-STORE", GateTier::SparkHost, 7, true);
430 let dec = tower.schedule_gate(&spark);
431 assert_eq!(dec.action, TowerAction::DispatchSparkHost);
432 assert_eq!(dec.why, TowerWhy::TierSparkHostPool);
433 // The Pi tier still reuses its own receipt.
434 let pi = spec("AIENOS-STORE", GateTier::Pi5Host, 7, true);
435 assert_eq!(
436 tower.schedule_gate(&pi).action,
437 TowerAction::ReuseReceipt {
438 receipt_digest: [0xaa; 32]
439 }
440 );
441 // An in-flight run on one tier is not joined by a request for another tier.
442 let qemu = spec("AIENOS-STORE", GateTier::SparkQemu, 7, true);
443 assert_eq!(
444 tower.schedule_gate(&qemu).action,
445 TowerAction::DispatchSparkHost
446 );
447 }
448
449 #[test]
450 fn full_slot_table_dispatches_every_request_and_pass_frees_the_slot() {
451 let mut tower = TowerOrchestrator::new(8, 1);
452 let a = spec("GATE-A", GateTier::Pi5Host, 1, true);
453 let b = spec("GATE-B", GateTier::Pi5Host, 2, true);
454 assert_eq!(tower.schedule_gate(&a).action, TowerAction::RunPi5Local);
455 // No free slot: B runs untracked, so a duplicate of B runs again (never skipped).
456 assert_eq!(tower.schedule_gate(&b).action, TowerAction::RunPi5Local);
457 assert_eq!(tower.schedule_gate(&b).action, TowerAction::RunPi5Local);
458 // Recording A's PASS frees slot 0 for the next run.
459 tower.record_pass_receipt("GATE-A", GateTier::Pi5Host, [1; 32], [0xbb; 32]);
460 assert_eq!(tower.schedule_gate(&b).action, TowerAction::RunPi5Local);
461 assert_eq!(
462 tower.schedule_gate(&b).action,
463 TowerAction::JoinInflight { slot: 0 }
464 );
465 assert_eq!(tower.max_inflight(), 1);
466 }
467
468 #[test]
469 fn uncacheable_gate_is_never_joined_to_another_run() {
470 let mut tower = TowerOrchestrator::new(8, 4);
471 let g = spec("OMEGA-DIVSQRT-CHIP", GateTier::SparkGb10, 6, false);
472 assert_eq!(tower.schedule_gate(&g).action, TowerAction::QueueSparkGb10);
473 let again = tower.schedule_gate(&g);
474 assert_eq!(again.action, TowerAction::QueueSparkGb10);
475 assert_eq!(again.why, TowerWhy::UncacheableGate);
476 }
477
478 #[test]
479 fn decision_json_escapes_the_gate_name() {
480 let dec = TowerDecision {
481 gate: String::from("a\"b\\c\nd\u{1}"),
482 action: TowerAction::RunPi5Local,
483 why: TowerWhy::TierLocalPi5,
484 };
485 assert_eq!(
486 dec.to_json(),
487 r#"{"tower_action":"run_pi5_local","gate":"a\"b\\c\nd\u0001","why":"tier_local_pi5"}"#
488 );
489 }
490
491 #[test]
492 fn cache_key_is_sha256_of_the_domain_separated_encoding() {
493 // Expected value computed outside Rust with coreutils sha256sum over
494 // "ALLEN-TOWER-INPUT-V1\0" || [0x11;32] || [0x22;32] || 2u64 LE || [0x33;32] || [0x34;32].
495 let got = combine_mneme_digest(&[0x11; 32], &[0x22; 32], &[[0x33; 32], [0x34; 32]]);
496 let want = [
497 0x37, 0x6b, 0xdf, 0x72, 0xe9, 0xfb, 0xa8, 0xe7, 0xca, 0xf8, 0x23, 0x76, 0xb2, 0xc5,
498 0x3d, 0xb5, 0x54, 0xca, 0xda, 0x99, 0xb8, 0xbb, 0x40, 0x1d, 0x54, 0x34, 0xf0, 0xc2,
499 0xd9, 0x09, 0x83, 0x93,
500 ];
501 assert_eq!(got, want);
502 // Order of the observed reads and their count both change the key.
503 assert_ne!(
504 got,
505 combine_mneme_digest(&[0x11; 32], &[0x22; 32], &[[0x34; 32], [0x33; 32]])
506 );
507 assert_ne!(
508 combine_mneme_digest(&[0x11; 32], &[0x22; 32], &[]),
509 combine_mneme_digest(&[0x11; 32], &[0x22; 32], &[[0; 32]])
510 );
511 }
512}