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 / aien-runtime / tests / headstart_ab.rs

1154 lines · 41955 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//! Headstart M6 (#538): the opt-in A/B qualification target for provisional
17//! preparation (crate::provisional, M3) on the M2 scheduler (spark-harness
18//! `scheduler`). Compiled only with `--features provisional-prep`; every test
19//! here is `#[ignore]`, so the default suites never run it.
20//!
21//! One driver, two arms. Both arms run the same driver, the same worker
22//! threads, the same `ResourceLimits::max_concurrency`, a journaled
23//! `PrepAdapter` over a fresh harness store and a fresh workspace. The only
24//! difference is `ProvisionalConfig::enabled`: `off` is the real sequential
25//! dispatch of M2 (`Core::eligible` needs every producer final), `on` lets a
26//! consumer start once its producers published a verified interface. No arm
27//! sets a prep hook, a sleep or any configured cost. The work units are the
28//! real code paths:
29//! - producer work: the M1 interface receipt (`publish_interface`) and the M1
30//! verified workflow completion (`complete_verified_workflow`);
31//! - preparation: `PrepAdapter::prepare`, the whitelisted compose plan
32//! preview over a seeded workspace;
33//! - commit: the fenced `PrepAdapter::submit_approved` (the real approved
34//! proposal path and World commit) in a LINKED build. The stub build
35//! refuses every commit (provisional_prep_test.rs `committed_or_stub`), so
36//! a STUB run passes the real fence around a no-op call instead and counts
37//! no World commit: STUB lines are overhead and correctness checks only,
38//! never a result.
39//!
40//! Shapes: `chain` (a narrow critical chain, the representative mechanism
41//! workload), `parallel` (independent tasks, an overhead and regression
42//! check: no gain is expected) and `failure` (a producer fails, another
43//! changes generation, while consumers may be preparing; descendants of the
44//! failed producer must never commit, and no commit may rest on the old
45//! generation).
46//!
47//! Output: one JSON line per sample, prefixed `HS-M6-AB `, also appended to
48//! `$HS_M6_OUT` when set. `scripts/bench/headstart-m6-ab.sh` runs one sample
49//! per process under `quietlock hold`. Ready queue depth is sampled with the
50//! existing read-only `Scheduler::queue` after every event this driver
51//! delivers, and blocked time comes from the existing
52//! `Scheduler::timing_trace` (journaled event times): no scheduler code was
53//! changed for this target.
54#![cfg(feature = "provisional-prep")]
55// The per-sample `json!` record is larger than the default macro recursion limit.
56#![recursion_limit = "256"]
57
58#[path = "support/home_guard.rs"]
59mod home_guard;
60
61use aien_omega_compose::hex;
62use aien_runtime::approved::{ApprovedProposal, ProposerHook};
63use aien_runtime::approved_auth::{desk_key_path, DeskKey};
64use aien_runtime::provisional::{
65 Delivered, FenceError, FenceProof, PrepAdapter, PrepError, ReadinessBinding,
66};
67use aien_runtime::{ComposeBridge, ComposeProposer};
68use serde_json::{json, Value};
69use sha2::{Digest, Sha256};
70use spark_harness::completion::CompletionSubmission;
71use spark_harness::execution::TaskState;
72use spark_harness::readiness::InterfaceSubmission;
73use spark_harness::scheduler::{
74 monotonic_clock, CommitResult, Effects, Event, EventKind, Outcome, ProvisionalConfig,
75 ResourceLimits, ResourceRequest, SchedError,
76};
77use spark_harness::{HarnessEngine, WorkflowState};
78use std::collections::{BTreeMap, BTreeSet, VecDeque};
79use std::path::{Path, PathBuf};
80use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
81use std::sync::{Arc, Condvar, Mutex};
82use std::time::{Duration, Instant};
83
84const SCHEMA: &str = "headstart-m6-ab/v1";
85const COMMIT: &str = "1111111111111111111111111111111111111111";
86/// A sample that has not settled after this long is reported as a deadlock.
87const SAMPLE_DEADLINE: Duration = Duration::from_secs(240);
88/// How long a failing or regenerating root waits for its consumers to
89/// prepare before it fails anyway (only the `on` arm dispatches them early).
90const FAIL_POINT_WAIT: Duration = Duration::from_secs(10);
91const DEFAULT_THREADS: usize = 4;
92const INBOX_FILES: usize = 8;
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum Arm {
96 Off,
97 On,
98}
99
100impl Arm {
101 fn parse(s: &str) -> Option<Self> {
102 match s {
103 "off" => Some(Arm::Off),
104 "on" => Some(Arm::On),
105 _ => None,
106 }
107 }
108 fn as_str(self) -> &'static str {
109 match self {
110 Arm::Off => "off",
111 Arm::On => "on",
112 }
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117enum Shape {
118 Chain,
119 Parallel,
120 Failure,
121}
122
123impl Shape {
124 const ALL: [Shape; 3] = [Shape::Chain, Shape::Parallel, Shape::Failure];
125 fn parse(s: &str) -> Option<Self> {
126 Shape::ALL.into_iter().find(|x| x.as_str() == s)
127 }
128 fn as_str(self) -> &'static str {
129 match self {
130 Shape::Chain => "chain",
131 Shape::Parallel => "parallel",
132 Shape::Failure => "failure",
133 }
134 }
135 fn class(self) -> &'static str {
136 match self {
137 Shape::Chain => "representative-mechanism",
138 Shape::Parallel => "overhead-regression",
139 Shape::Failure => "failure-cancellation",
140 }
141 }
142}
143
144/// The DAG of one shape: (task, producers) in registration order, and the
145/// roots the failure shape fails or moves to a new generation.
146struct Plan {
147 tasks: Vec<(String, Vec<String>)>,
148 fail_root: Option<String>,
149 regen_root: Option<String>,
150}
151
152fn plan(shape: Shape) -> Plan {
153 let t = |s: &str, p: &[&str]| (s.to_string(), p.iter().map(|x| x.to_string()).collect());
154 match shape {
155 Shape::Chain => {
156 let names: Vec<String> = (0..6).map(|i| format!("t{i:02}")).collect();
157 let mut tasks = Vec::new();
158 for (i, n) in names.iter().enumerate() {
159 let p = if i == 0 {
160 vec![]
161 } else {
162 vec![names[i - 1].clone()]
163 };
164 tasks.push((n.clone(), p));
165 }
166 Plan {
167 tasks,
168 fail_root: None,
169 regen_root: None,
170 }
171 }
172 Shape::Parallel => Plan {
173 tasks: (0..8).map(|i| (format!("p{i:02}"), vec![])).collect(),
174 fail_root: None,
175 regen_root: None,
176 },
177 Shape::Failure => Plan {
178 tasks: vec![
179 t("f", &[]),
180 t("g", &[]),
181 t("fc0", &["f"]),
182 t("fc1", &["f"]),
183 t("fcc0", &["fc0"]),
184 t("gc0", &["g"]),
185 t("gc1", &["g"]),
186 ],
187 fail_root: Some("f".into()),
188 regen_root: Some("g".into()),
189 },
190 }
191}
192
193fn cfg(arm: Arm, threads: usize) -> ProvisionalConfig {
194 ProvisionalConfig {
195 enabled: arm == Arm::On,
196 queue_capacity: 64,
197 limits: ResourceLimits {
198 cpu_slots: 64,
199 memory_bytes: 1 << 34,
200 max_concurrency: threads as u32,
201 },
202 // Nanosecond ticks (monotonic_clock): ten minutes.
203 lease_ttl: 600_000_000_000,
204 dedup_window: 4096,
205 }
206}
207
208fn copy_definitions(dir: &Path) {
209 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../spark-harness");
210 std::fs::create_dir_all(dir.join("schemas")).unwrap();
211 for f in ["workflows.json", "evals.json"] {
212 std::fs::copy(src.join(f), dir.join(f)).unwrap();
213 }
214 for e in std::fs::read_dir(src.join("schemas")).unwrap() {
215 let e = e.unwrap();
216 std::fs::copy(e.path(), dir.join("schemas").join(e.file_name())).unwrap();
217 }
218}
219
220/// Deterministic input notes the plan preview reads (`inbox/`), inside the
221/// compose input bounds (bridge.rs COMPOSE_INPUTS_MAX_FILES 16,
222/// COMPOSE_INPUTS_MAX_BYTES 16384).
223fn seed_workspace(ws: &Path) {
224 let inbox = ws.join("inbox");
225 std::fs::create_dir_all(&inbox).unwrap();
226 for i in 0..INBOX_FILES {
227 let mut s = String::new();
228 for line in 0..24 {
229 s.push_str(&format!(
230 "note {i} line {line}: the parser accepts token sequence {}\n",
231 (i * 31 + line * 7) % 97
232 ));
233 }
234 std::fs::write(inbox.join(format!("note-{i}.txt")), s).unwrap();
235 }
236}
237
238fn goal(task: &str) -> String {
239 format!("Read the text files in the inbox folder and write NOTES-{task}.md with a summary")
240}
241
242fn artifact(task: &str, generation: u64) -> Value {
243 json!({
244 "bug": format!("Parser rejects valid token sequence in {task} generation {generation}"),
245 "reproduction_steps": ["Run parser test"],
246 "failure_evidence": "thread panicked at line 42",
247 "regression_test": "tests::test_parser",
248 "diff_summary": "Fixed token parser logic",
249 "retest_evidence": "All tests passing cleanly"
250 })
251}
252
253fn model_never_called() -> ComposeProposer {
254 Arc::new(|_: &str, _: Duration| panic!("the model proposer ran on the approved path"))
255}
256
257fn sha(b: &[u8]) -> String {
258 hex(&Sha256::digest(b))
259}
260
261fn interplane_sha(path: &str, content: &str) -> String {
262 let s = format!(
263 "{{\"content\":{},\"path\":{}}}",
264 serde_json::to_string(content).unwrap(),
265 serde_json::to_string(path).unwrap()
266 );
267 sha(s.as_bytes())
268}
269
270/// Process CPU time and peak RSS (getrusage RUSAGE_SELF: every thread of
271/// this process; ru_maxrss is the process high-water mark in KiB).
272fn rusage() -> (f64, f64, i64) {
273 // SAFETY: getrusage only writes the struct we pass.
274 let mut ru: libc::rusage = unsafe { std::mem::zeroed() };
275 let rc = unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut ru) };
276 assert_eq!(rc, 0, "getrusage failed");
277 let ms = |t: libc::timeval| t.tv_sec as f64 * 1000.0 + t.tv_usec as f64 / 1000.0;
278 (ms(ru.ru_utime), ms(ru.ru_stime), ru.ru_maxrss)
279}
280
281fn loadavg_1m() -> Option<f64> {
282 std::fs::read_to_string("/proc/loadavg")
283 .ok()?
284 .split_whitespace()
285 .next()?
286 .parse()
287 .ok()
288}
289
290fn ms(d: Duration) -> f64 {
291 d.as_secs_f64() * 1000.0
292}
293
294/// The real World commit (LINKED) or nothing (STUB).
295struct Compose {
296 bridge: Arc<ComposeBridge>,
297 hook: ProposerHook,
298 desk: DeskKey,
299}
300
301#[derive(Default)]
302struct Queue {
303 jobs: VecDeque<(String, u64)>,
304 queued: BTreeSet<(String, u64)>,
305 active: usize,
306 changes: u64,
307 stop: bool,
308}
309
310#[derive(Default)]
311struct Metrics {
312 prep_ns: u128,
313 producer_ns: u128,
314 commit_ns: u128,
315 preparations: Vec<(String, u64, bool)>,
316 prep_refused: u64,
317 dispatches_abandoned: u64,
318 revoked: u64,
319 aborted: u64,
320 deferred: u64,
321 depth_samples: Vec<usize>,
322 interface_receipts: Vec<Value>,
323 completion_receipts: Vec<Value>,
324 commits: Vec<Value>,
325 committed: Vec<(String, u64)>,
326 world_commits: u64,
327 commit_refused: Vec<Value>,
328 commit_waits: u64,
329 fail_points: Vec<Value>,
330 driver_errors: Vec<String>,
331}
332
333struct Run<'a> {
334 adapter: Arc<PrepAdapter>,
335 engine: &'a HarnessEngine,
336 ws: PathBuf,
337 compose: Option<Compose>,
338 plan: &'a Plan,
339 q: Mutex<Queue>,
340 cv: Condvar,
341 ids: AtomicU64,
342 regen_done: AtomicBool,
343 m: Mutex<Metrics>,
344 deadline: Instant,
345}
346
347enum Stop {
348 /// The sample deadline passed (reported as a deadlock).
349 Deadline,
350}
351
352impl Run<'_> {
353 fn err(&self, e: String) {
354 self.m.lock().unwrap().driver_errors.push(e);
355 }
356
357 /// A step failed: a driver error while the task is still at
358 /// `generation`, an abandoned dispatch once M2 moved it on.
359 fn bail(&self, task: &str, generation: u64, e: String) {
360 if self.current(task, generation) {
361 self.err(e);
362 } else {
363 self.m.lock().unwrap().dispatches_abandoned += 1;
364 }
365 }
366
367 fn notify(&self) {
368 self.q.lock().unwrap().changes += 1;
369 self.cv.notify_all();
370 }
371
372 fn enqueue(&self, task: &str) {
373 let Some(generation) = self.adapter.generation(task) else {
374 return;
375 };
376 let mut q = self.q.lock().unwrap();
377 if q.queued.insert((task.to_string(), generation)) {
378 q.jobs.push_back((task.to_string(), generation));
379 }
380 }
381
382 /// Queue a job for every `Provisional` task without one (a dispatch
383 /// made inside the fence, whose effects the adapter does not return).
384 fn sweep(&self) {
385 for (t, _) in &self.plan.tasks {
386 if self.adapter.state(t) == Some(TaskState::Provisional) {
387 self.enqueue(t);
388 }
389 }
390 }
391
392 fn after(&self, fx: &Effects) {
393 for t in &fx.dispatched {
394 self.enqueue(t);
395 }
396 let depth = self.adapter.inspect(|s| s.queue().len());
397 {
398 let mut m = self.m.lock().unwrap();
399 m.revoked += fx.revoked.len() as u64;
400 m.aborted += fx.aborted.len() as u64;
401 m.depth_samples.push(depth);
402 }
403 self.notify();
404 }
405
406 fn send(&self, kind: EventKind) -> Result<Effects, String> {
407 let id = format!("m6-{}", self.ids.fetch_add(1, Ordering::SeqCst));
408 let what = format!("{kind:?}");
409 match self.adapter.deliver(Event { id, kind }) {
410 Ok(Delivered::Applied(Outcome::Applied(fx))) => {
411 self.after(&fx);
412 Ok(fx)
413 }
414 Ok(Delivered::Applied(Outcome::Duplicate)) => Err(format!("duplicate: {what}")),
415 Ok(Delivered::Deferred { committing, .. }) => {
416 self.m.lock().unwrap().deferred += 1;
417 Err(format!("deferred behind {committing}: {what}"))
418 }
419 Err(e) => Err(format!("{e}: {what}")),
420 }
421 }
422
423 /// Wait until `cond` returns Some. Re-checked after every change any
424 /// thread reports, so no wakeup is lost; bounded by the sample deadline.
425 fn wait_until<T>(
426 &self,
427 until: Instant,
428 mut cond: impl FnMut() -> Option<T>,
429 ) -> Result<T, Stop> {
430 loop {
431 let seen = self.q.lock().unwrap().changes;
432 if let Some(v) = cond() {
433 return Ok(v);
434 }
435 let mut q = self.q.lock().unwrap();
436 while q.changes == seen && !q.stop {
437 let now = Instant::now();
438 if now >= self.deadline {
439 q.stop = true;
440 self.cv.notify_all();
441 return Err(Stop::Deadline);
442 }
443 if now >= until {
444 return Err(Stop::Deadline);
445 }
446 let wait = until.min(self.deadline) - now;
447 q = self
448 .cv
449 .wait_timeout(q, wait.min(Duration::from_millis(500)))
450 .unwrap()
451 .0;
452 }
453 if q.stop {
454 return Err(Stop::Deadline);
455 }
456 }
457 }
458
459 fn current(&self, task: &str, generation: u64) -> bool {
460 self.adapter.generation(task) == Some(generation)
461 }
462
463 fn producers(&self, task: &str) -> &[String] {
464 &self
465 .plan
466 .tasks
467 .iter()
468 .find(|(t, _)| t == task)
469 .expect("planned task")
470 .1
471 }
472
473 fn consumers(&self, task: &str) -> Vec<String> {
474 self.plan
475 .tasks
476 .iter()
477 .filter(|(_, p)| p.iter().any(|x| x == task))
478 .map(|(t, _)| t.clone())
479 .collect()
480 }
481
482 fn worker(&self) {
483 loop {
484 let job = {
485 let mut q = self.q.lock().unwrap();
486 loop {
487 if q.stop {
488 break None;
489 }
490 if let Some(j) = q.jobs.pop_front() {
491 q.active += 1;
492 break Some(j);
493 }
494 if q.active == 0 {
495 break None;
496 }
497 if Instant::now() >= self.deadline {
498 q.stop = true;
499 break None;
500 }
501 q = self
502 .cv
503 .wait_timeout(q, Duration::from_millis(500))
504 .unwrap()
505 .0;
506 }
507 };
508 let Some((task, generation)) = job else {
509 self.cv.notify_all();
510 return;
511 };
512 self.job(&task, generation);
513 self.sweep();
514 self.q.lock().unwrap().active -= 1;
515 self.notify();
516 }
517 }
518
519 /// One dispatch of `task` at `generation`, start to commit. Abandoned
520 /// (and counted) as soon as the task leaves that generation.
521 fn job(&self, task: &str, generation: u64) {
522 if !self.current(task, generation)
523 || self.adapter.state(task) != Some(TaskState::Provisional)
524 {
525 self.m.lock().unwrap().dispatches_abandoned += 1;
526 return;
527 }
528 // Preparation: the whitelisted plan preview.
529 let t = Instant::now();
530 let r = self
531 .adapter
532 .prepare(task, generation, &goal(task), &self.ws);
533 let d = t.elapsed().as_nanos();
534 {
535 let mut m = self.m.lock().unwrap();
536 m.prep_ns += d;
537 match &r {
538 Ok(p) => m
539 .preparations
540 .push((task.to_string(), generation, p.is_provisional())),
541 Err(_) => m.prep_refused += 1,
542 }
543 }
544 match r {
545 Ok(_) => {}
546 Err(PrepError::StaleGeneration { .. } | PrepError::Revoked { .. }) => {
547 self.m.lock().unwrap().dispatches_abandoned += 1;
548 return;
549 }
550 Err(PrepError::Scheduler(_)) if !self.current(task, generation) => {
551 self.m.lock().unwrap().dispatches_abandoned += 1;
552 return;
553 }
554 Err(e) => return self.err(format!("prepare {task} g{generation}: {e}")),
555 }
556 // Producer work, part 1: the M1 interface receipt.
557 let t = Instant::now();
558 let rec = self.engine.publish_interface(&InterfaceSubmission {
559 task_id: task.into(),
560 generation,
561 source_commit: COMMIT.into(),
562 interface: json!({ "task": task, "api_version": generation }),
563 });
564 self.m.lock().unwrap().producer_ns += t.elapsed().as_nanos();
565 let claim = match rec {
566 Ok(r) => r.claim(),
567 Err(e) => return self.bail(task, generation, format!("publish_interface {task}: {e}")),
568 };
569 self.m.lock().unwrap().interface_receipts.push(json!({
570 "task": task, "generation": generation, "receipt_id": claim.receipt_id,
571 }));
572 if let Err(e) = self.send(EventKind::InterfacePublished {
573 task: task.into(),
574 generation,
575 claim,
576 }) {
577 return self.bail(task, generation, e);
578 }
579 if self.plan.fail_root.as_deref() == Some(task) {
580 self.fail_point(task, generation, true);
581 return;
582 }
583 if self.plan.regen_root.as_deref() == Some(task)
584 && !self.regen_done.swap(true, Ordering::SeqCst)
585 {
586 self.fail_point(task, generation, false);
587 return;
588 }
589 if let Err(e) = self.send(EventKind::WorkDone {
590 task: task.into(),
591 generation,
592 result_digest: format!("result-of-{task}-g{generation}"),
593 }) {
594 return self.bail(task, generation, e);
595 }
596 // Finalize needs every producer final (M1 completion accepted).
597 let producers = self.producers(task).to_vec();
598 let ready = self.wait_until(self.deadline, || {
599 if !self.current(task, generation) {
600 return Some(false);
601 }
602 let all = self.adapter.inspect(|s| {
603 producers.iter().all(|p| {
604 s.task(p)
605 .is_some_and(|t| t.state.is_final() && t.completion.is_some())
606 })
607 });
608 all.then_some(true)
609 });
610 match ready {
611 Ok(true) => {}
612 Ok(false) => {
613 self.m.lock().unwrap().dispatches_abandoned += 1;
614 return;
615 }
616 Err(Stop::Deadline) => return,
617 }
618 if let Err(e) = self.send(EventKind::Finalize {
619 task: task.into(),
620 generation,
621 }) {
622 if self.current(task, generation) {
623 self.err(e);
624 } else {
625 self.m.lock().unwrap().dispatches_abandoned += 1;
626 }
627 return;
628 }
629 // Producer work, part 2: the M1 verified workflow completion.
630 let mut wf = WorkflowState {
631 id: format!("wf-{task}-g{generation}"),
632 workflow_type: "engineering_fix".into(),
633 current_state: "review".into(),
634 history: Vec::new(),
635 created_at: "2026-10-16T00:00:00Z".into(),
636 };
637 let t = Instant::now();
638 let rec = self.engine.complete_verified_workflow(
639 &mut wf,
640 &CompletionSubmission {
641 task_id: task.into(),
642 generation,
643 source_commit: COMMIT.into(),
644 artifact: artifact(task, generation),
645 },
646 );
647 self.m.lock().unwrap().producer_ns += t.elapsed().as_nanos();
648 let rec = match rec {
649 Ok(r) => r,
650 Err(e) => {
651 return self.bail(
652 task,
653 generation,
654 format!("complete_verified_workflow {task}: {e}"),
655 )
656 }
657 };
658 self.m.lock().unwrap().completion_receipts.push(json!({
659 "task": task, "generation": generation, "receipt_id": rec.receipt_id,
660 "artifact_digest": rec.artifact_digest,
661 }));
662 if let Err(e) = self.send(EventKind::CompletionVerified {
663 task: task.into(),
664 generation,
665 claim: spark_harness::readiness::ProofClaim {
666 receipt_id: rec.receipt_id,
667 commit: rec.source_commit,
668 digest: rec.artifact_digest,
669 },
670 }) {
671 return self.bail(task, generation, e);
672 }
673 self.commit(task, generation);
674 }
675
676 /// The failure shape: wait (bounded) until every consumer prepared or
677 /// is `Blocked` and not queued for dispatch, then fail the producer or move it to a new
678 /// generation. Only the `on` arm can have consumers preparing here.
679 fn fail_point(&self, task: &str, generation: u64, fail: bool) {
680 let consumers = self.consumers(task);
681 let until = Instant::now() + FAIL_POINT_WAIT;
682 let reached = self
683 .wait_until(until, || {
684 consumers
685 .iter()
686 .all(|c| {
687 self.adapter.prepared(c).is_some()
688 || self.adapter.inspect(|s| {
689 s.task(c)
690 .is_some_and(|t| t.state == TaskState::Blocked && !t.queued)
691 })
692 })
693 .then_some(())
694 })
695 .is_ok();
696 let prepared: Vec<&String> = consumers
697 .iter()
698 .filter(|c| self.adapter.prepared(c).is_some())
699 .collect();
700 self.m.lock().unwrap().fail_points.push(json!({
701 "task": task, "generation": generation,
702 "action": if fail { "producer_failed" } else { "new_generation" },
703 "consumers_prepared": prepared, "wait_completed": reached,
704 }));
705 let r = if fail {
706 self.send(EventKind::ProducerFailed {
707 task: task.into(),
708 generation,
709 reason: "M6 failure shape".into(),
710 })
711 } else {
712 self.send(EventKind::NewGeneration {
713 task: task.into(),
714 generation: generation + 1,
715 })
716 };
717 if let Err(e) = r {
718 self.err(e);
719 }
720 }
721
722 fn approval(&self, c: &Compose, task: &str, generation: u64) -> ApprovedProposal {
723 let path = format!("NOTES-{task}.md");
724 let content =
725 format!("{task} generation {generation}: approved after the producers were final\n");
726 let request = format!("req-{task}-g{generation}");
727 let mut p = ApprovedProposal {
728 request_id: request.clone(),
729 trace_id: format!("trace-{request}"),
730 approval_id: format!("appr-{request}"),
731 approver: "interplane-host".into(),
732 path: path.clone(),
733 content: content.clone(),
734 approved_proposal_sha256: interplane_sha(&path, &content),
735 content_sha256: sha(content.as_bytes()),
736 approval_mac: String::new(),
737 requirements: Some(String::new()),
738 requirements_mac: String::new(),
739 requirements_base: None,
740 };
741 c.desk.seal(&mut p, &self.ws);
742 p
743 }
744
745 /// The fenced commit. LINKED: the real approved-proposal path. STUB: the
746 /// same fence around a no-op (no World commit). A commit refused because
747 /// another one runs in the same chain waits for a change and retries.
748 fn commit(&self, task: &str, generation: u64) {
749 let ws = self.ws.display().to_string();
750 loop {
751 // Read before submitting: a commit that ends between the refusal and
752 // this read would otherwise leave the retry waiting on an unrelated change.
753 let seen = self.q.lock().unwrap().changes;
754 let t = Instant::now();
755 let r: Result<(FenceProof, CommitResult, Option<Value>), FenceError> =
756 match &self.compose {
757 Some(c) => {
758 let p = self.approval(c, task, generation);
759 self.adapter
760 .submit_approved(task, generation, &c.hook, &p, &ws)
761 .map(|f| {
762 let rec = match &f.outcome {
763 Ok(rep) => json!({
764 "state": rep.state, "request_id": rep.request_id,
765 "trace_id": rep.trace_id, "replay_claim": rep.replay_claim,
766 "approved_grant": rep.approved_grant,
767 "compose_proposal_sha256": rep.compose_proposal_sha256,
768 "cx_promotion": rep.task.as_ref().map(|t| t.cx_promotion),
769 "cx_evidence": rep.task.as_ref().map(|t| t.cx_evidence),
770 "world_committed": rep.task.as_ref().map(|t| t.committed),
771 }),
772 Err(e) => json!({
773 "refused_by": e.refused_by, "name": e.name,
774 "trace_id": e.trace_id, "replay_claim": e.replay_claim,
775 }),
776 };
777 (f.proof, f.result, Some(rec))
778 })
779 }
780 None => self
781 .adapter
782 .fenced_for_tests(
783 task,
784 generation,
785 |_| (),
786 |_| CommitResult::Committed {
787 detail: "STUB no-op: no World commit".into(),
788 },
789 )
790 .map(|f| (f.proof, f.result, None)),
791 };
792 let d = t.elapsed().as_nanos();
793 self.m.lock().unwrap().commit_ns += d;
794 match r {
795 Ok((proof, result, rec)) => {
796 self.record_commit(task, generation, &proof, &result, rec);
797 self.notify();
798 return;
799 }
800 Err(FenceError::Scheduler(SchedError::CommitInProgress { .. })) => {
801 self.m.lock().unwrap().commit_waits += 1;
802 let waited = self.wait_until(self.deadline, || {
803 (self.q.lock().unwrap().changes != seen).then_some(())
804 });
805 if waited.is_err() {
806 return;
807 }
808 }
809 Err(e) => {
810 if self.current(task, generation) {
811 self.err(format!("fence {task} g{generation}: {e}"));
812 } else {
813 self.m.lock().unwrap().dispatches_abandoned += 1;
814 }
815 return;
816 }
817 }
818 }
819 }
820
821 fn record_commit(
822 &self,
823 task: &str,
824 generation: u64,
825 proof: &FenceProof,
826 result: &CommitResult,
827 rec: Option<Value>,
828 ) {
829 let binding = |b: &ReadinessBinding| {
830 json!({
831 "producer": b.producer_task, "generation": b.producer_generation,
832 "level": format!("{:?}", b.level), "receipt_id": b.receipt_id,
833 })
834 };
835 let mut m = self.m.lock().unwrap();
836 let world = rec
837 .as_ref()
838 .is_some_and(|r| r["state"] == "COMMITTED" && r["world_committed"] == true);
839 if world {
840 m.world_commits += 1;
841 }
842 let entry = json!({
843 "task": task, "generation": generation,
844 "result": result,
845 "own_completion": binding(&proof.completion),
846 "producers": proof.producers.iter().map(binding).collect::<Vec<_>>(),
847 "commit_receipt": rec,
848 });
849 if matches!(result, CommitResult::Committed { .. }) {
850 m.committed.push((task.to_string(), generation));
851 m.commits.push(entry);
852 } else {
853 m.commit_refused.push(entry);
854 }
855 }
856}
857
858/// One sample: a fresh store, workspace, journal and (LINKED) compose home;
859/// the shape's DAG driven to quiescence on `threads` workers.
860fn run_sample(arm: Arm, shape: Shape, threads: usize) -> Value {
861 let linked = aien_omega_compose::LINKED;
862 let tmp = tempfile::tempdir().unwrap();
863 let hd = tmp.path().join("harness");
864 copy_definitions(&hd);
865 let ws = tmp.path().join("ws");
866 seed_workspace(&ws);
867 let engine = HarnessEngine::load(&hd).expect("shipped definitions load");
868 let (adapter, revoked) = PrepAdapter::open(
869 cfg(arm, threads),
870 &engine.completion_store,
871 &tmp.path().join("journal.jsonl"),
872 monotonic_clock(),
873 )
874 .unwrap();
875 assert!(revoked.is_empty());
876 let compose = linked.then(|| {
877 let dir = tmp.path().join("compose");
878 let desk = DeskKey::create(&desk_key_path(&dir)).unwrap();
879 let bridge = Arc::new(ComposeBridge::new(
880 dir,
881 model_never_called(),
882 "test:model-never-called",
883 ));
884 let hook = ProposerHook::new(bridge.clone());
885 Compose { bridge, hook, desk }
886 });
887 let plan = plan(shape);
888 let run = Run {
889 adapter: Arc::new(adapter),
890 engine: &engine,
891 ws: ws.clone(),
892 compose,
893 plan: &plan,
894 q: Mutex::new(Queue::default()),
895 cv: Condvar::new(),
896 ids: AtomicU64::new(0),
897 regen_done: AtomicBool::new(false),
898 m: Mutex::new(Metrics::default()),
899 deadline: Instant::now() + SAMPLE_DEADLINE,
900 };
901 let load = loadavg_1m();
902 let (u0, s0, _) = rusage();
903 let t0 = Instant::now();
904 for (task, producers) in &plan.tasks {
905 if let Err(e) = run.send(EventKind::RegisterTask {
906 task: task.clone(),
907 resources: ResourceRequest {
908 cpu_slots: 1,
909 memory_bytes: 1 << 20,
910 },
911 producers: producers.clone(),
912 }) {
913 run.err(e);
914 }
915 }
916 std::thread::scope(|s| {
917 for _ in 0..threads {
918 s.spawn(|| run.worker());
919 }
920 });
921 let wall = t0.elapsed();
922 let (u1, s1, rss) = rusage();
923 let deadlock = run.q.lock().unwrap().stop;
924 if let Some(c) = &run.compose {
925 c.bridge.close();
926 }
927 let invariants = run.adapter.inspect(|s| s.check_invariants());
928 let trace = run.adapter.inspect(|s| s.timing_trace());
929 let final_states: BTreeMap<String, &'static str> = plan
930 .tasks
931 .iter()
932 .map(|(t, _)| {
933 (
934 t.clone(),
935 run.adapter.state(t).map_or("missing", |s| s.as_str()),
936 )
937 })
938 .collect();
939 let final_generations: BTreeMap<String, u64> = plan
940 .tasks
941 .iter()
942 .map(|(t, _)| (t.clone(), run.adapter.generation(t).unwrap_or(0)))
943 .collect();
944 let sum = |k: &str| -> f64 {
945 trace["tasks"]
946 .as_array()
947 .map(|a| a.iter().filter_map(|t| t[k].as_u64()).sum::<u64>())
948 .unwrap_or(0) as f64
949 / 1e6
950 };
951 let m = run.m.into_inner().unwrap();
952 let wall_ms = ms(wall);
953 let prep_ms = m.prep_ns as f64 / 1e6;
954 let producer_ms = m.producer_ns as f64 / 1e6;
955 let commit_ms = m.commit_ns as f64 / 1e6;
956 // Preparation results made at a generation the task did not commit at.
957 let discarded = m
958 .preparations
959 .iter()
960 .filter(|(t, g, _)| !m.committed.iter().any(|(ct, cg)| ct == t && cg == g))
961 .count();
962 let depth_peak = m.depth_samples.iter().copied().max().unwrap_or(0);
963 let depth_mean = if m.depth_samples.is_empty() {
964 0.0
965 } else {
966 m.depth_samples.iter().sum::<usize>() as f64 / m.depth_samples.len() as f64
967 };
968 let line = json!({
969 "schema": SCHEMA,
970 "arm": arm.as_str(),
971 "shape": shape.as_str(),
972 "shape_class": shape.class(),
973 "build": if linked { "LINKED" } else { "STUB" },
974 "result_class": if linked { "linked-sample" } else { "STUB: overhead and correctness only, not a result" },
975 "threads": threads,
976 "max_concurrency": threads,
977 "tasks": plan.tasks.len(),
978 "wall_ms": wall_ms,
979 "prep_ms": prep_ms,
980 "producer_ms": producer_ms,
981 "commit_ms": commit_ms,
982 "ceiling_estimate": prep_ms.min(producer_ms) / wall_ms,
983 "cpu_user_ms": u1 - u0,
984 "cpu_sys_ms": s1 - s0,
985 "max_rss_kb_process": rss,
986 "queue_depth_peak": depth_peak,
987 "queue_depth_mean": depth_mean,
988 "queue_depth_samples": m.depth_samples.len(),
989 "blocked_ms_total": sum("blocked"),
990 "provisional_ms_total": sum("provisional"),
991 "awaiting_final_proof_ms_total": sum("awaiting_final_proof"),
992 "preparations": m.preparations.len(),
993 "preparations_provisional": m.preparations.iter().filter(|p| p.2).count(),
994 "prep_refused": m.prep_refused,
995 "discards": {
996 "prep_results_discarded": discarded,
997 "dispatches_abandoned": m.dispatches_abandoned,
998 "revoked": m.revoked,
999 "aborted": m.aborted,
1000 },
1001 "deferred_events": m.deferred,
1002 "commit_waits_same_chain": m.commit_waits,
1003 "commits": m.committed.len(),
1004 "world_commits": m.world_commits,
1005 "commit_records": m.commits,
1006 "commit_refused": m.commit_refused,
1007 "interface_receipts": m.interface_receipts,
1008 "completion_receipts": m.completion_receipts,
1009 "fail_points": m.fail_points,
1010 "final_states": final_states,
1011 "final_generations": final_generations,
1012 "invariants": invariants.err(),
1013 "deadlock": deadlock,
1014 "driver_errors": m.driver_errors,
1015 "loadavg_1m_start": load,
1016 "arch": std::env::consts::ARCH,
1017 "os": std::env::consts::OS,
1018 "available_parallelism": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),
1019 });
1020 check_sample(&line, &plan);
1021 line
1022}
1023
1024/// The correctness gates every sample must pass, in both arms and builds.
1025fn check_sample(v: &Value, plan: &Plan) {
1026 assert_eq!(v["deadlock"], false, "deadlock: {v}");
1027 assert!(v["invariants"].is_null(), "M2 invariants: {v}");
1028 assert_eq!(
1029 v["driver_errors"].as_array().map(|a| a.len()),
1030 Some(0),
1031 "{v}"
1032 );
1033 assert_eq!(v["deferred_events"], 0, "{v}");
1034 let commits = v["commit_records"].as_array().unwrap();
1035 // No double commit: one commit per task at most.
1036 let mut seen = BTreeSet::new();
1037 for c in commits {
1038 let t = c["task"].as_str().unwrap();
1039 assert!(seen.insert(t.to_string()), "double commit of {t}: {v}");
1040 // Every commit rests on final proofs only.
1041 assert_eq!(c["own_completion"]["level"], "FinalVerified", "{v}");
1042 for p in c["producers"].as_array().unwrap() {
1043 assert_eq!(p["level"], "FinalVerified", "{v}");
1044 let pt = p["producer"].as_str().unwrap();
1045 assert_eq!(
1046 p["generation"], v["final_generations"][pt],
1047 "commit of {t} rests on a stale generation of {pt}: {v}"
1048 );
1049 }
1050 }
1051 if v["build"] == "LINKED" {
1052 assert_eq!(
1053 v["world_commits"].as_u64(),
1054 Some(commits.len() as u64),
1055 "every fenced commit is a World commit: {v}"
1056 );
1057 } else {
1058 assert_eq!(v["world_commits"], 0, "{v}");
1059 }
1060 if v["arm"] == "off" {
1061 assert_eq!(
1062 v["preparations_provisional"], 0,
1063 "flag off never prepares on an interface: {v}"
1064 );
1065 }
1066 match v["shape"].as_str().unwrap() {
1067 "chain" | "parallel" => {
1068 assert_eq!(commits.len(), plan.tasks.len(), "every task commits: {v}");
1069 for (t, _) in &plan.tasks {
1070 assert_eq!(v["final_states"][t], "committed", "{v}");
1071 }
1072 }
1073 "failure" => {
1074 for t in ["fc0", "fc1", "fcc0", "f"] {
1075 assert!(
1076 !seen.contains(t),
1077 "{t} committed after its producer failed: {v}"
1078 );
1079 }
1080 assert_eq!(v["final_states"]["f"], "aborted", "{v}");
1081 for t in ["g", "gc0", "gc1"] {
1082 assert_eq!(v["final_states"][t], "committed", "{v}");
1083 }
1084 assert_eq!(v["final_generations"]["g"], 2, "{v}");
1085 }
1086 other => panic!("unknown shape {other}"),
1087 }
1088}
1089
1090fn emit(mut line: Value, label: &str, tag: &str, sample: u64) {
1091 line["label"] = json!(label);
1092 line["tag"] = json!(tag);
1093 line["sample"] = json!(sample);
1094 let text = serde_json::to_string(&line).unwrap();
1095 println!("HS-M6-AB {text}");
1096 if let Ok(out) = std::env::var("HS_M6_OUT") {
1097 use std::io::Write;
1098 let mut f = std::fs::OpenOptions::new()
1099 .create(true)
1100 .append(true)
1101 .open(&out)
1102 .unwrap_or_else(|e| panic!("HS_M6_OUT {out}: {e}"));
1103 writeln!(f, "{text}").unwrap();
1104 }
1105}
1106
1107fn threads() -> usize {
1108 std::env::var("HS_M6_THREADS")
1109 .ok()
1110 .map(|s| s.parse().expect("HS_M6_THREADS is a number"))
1111 .unwrap_or(DEFAULT_THREADS)
1112}
1113
1114/// One sample, chosen by the environment (one per process, so the RSS
1115/// high-water mark is per sample): HS_M6_ARM (off|on), HS_M6_SHAPE
1116/// (chain|parallel|failure), HS_M6_SAMPLE (index), HS_M6_TAG (A, B, AA1,
1117/// AA2), HS_M6_THREADS (default 4), HS_M6_OUT (JSON lines file).
1118#[test]
1119#[ignore = "A/B qualification sample: run by scripts/bench/headstart-m6-ab.sh"]
1120fn headstart_ab_sample() {
1121 let _home = home_guard::home_slot();
1122 let arm = std::env::var("HS_M6_ARM").expect("HS_M6_ARM (off|on)");
1123 let shape = std::env::var("HS_M6_SHAPE").expect("HS_M6_SHAPE (chain|parallel|failure)");
1124 let arm = Arm::parse(&arm).expect("HS_M6_ARM is off or on");
1125 let shape = Shape::parse(&shape).expect("HS_M6_SHAPE is chain, parallel or failure");
1126 let sample = std::env::var("HS_M6_SAMPLE")
1127 .ok()
1128 .and_then(|s| s.parse().ok())
1129 .unwrap_or(0);
1130 let tag = std::env::var("HS_M6_TAG").unwrap_or_default();
1131 emit(run_sample(arm, shape, threads()), "SAMPLE", &tag, sample);
1132}
1133
1134/// One run per arm and shape in one process, labelled SMOKE: proves the
1135/// target works and that both arms end in the same task states (no state
1136/// divergence). Not a measurement.
1137#[test]
1138#[ignore = "A/B harness smoke run (not a measurement)"]
1139fn headstart_ab_smoke() {
1140 let _home = home_guard::home_slot();
1141 for shape in Shape::ALL {
1142 let off = run_sample(Arm::Off, shape, threads());
1143 let on = run_sample(Arm::On, shape, threads());
1144 assert_eq!(
1145 off["final_states"],
1146 on["final_states"],
1147 "flag on and off diverged on {}",
1148 shape.as_str()
1149 );
1150 assert_eq!(off["commits"], on["commits"], "{}", shape.as_str());
1151 emit(off, "SMOKE", "", 0);
1152 emit(on, "SMOKE", "", 0);
1153 }
1154}