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 / spark-harness / src / readiness.rs

581 lines · 20791 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//! Artifact readiness and operation classes (Headstart M2, issue #535).
17//!
18//! A producer task can make its output ready for consumers at two levels:
19//!
20//! - [`ReadinessLevel::InterfaceVerified`]: the producer published an
21//! immutable interface artifact through [`HarnessEngine::publish_interface`].
22//! The harness recomputes the digest itself, mints an aien-proof receipt of
23//! kind [`INTERFACE_KIND`] (distinct from the M1 completion kind) and records
24//! it as the task's current interface. Consumers may only run the reversible,
25//! sandboxed [`OperationClass`] entries against it.
26//! - [`ReadinessLevel::FinalVerified`]: M1 [`verify_completion`] passes for the
27//! producer's current generation.
28//!
29//! [`ReadinessLevel::Revoked`] permits nothing.
30//!
31//! An [`ArtifactReadiness`] can only be built by [`verify_interface`] or
32//! [`verify_final`], which re-read the receipt from the harness store. It has
33//! no public constructor and no `Deserialize`, so a caller cannot hand the
34//! scheduler a readiness value, a receipt or a pass flag.
35//!
36//! The same trust limits as M1 apply (see `completion.rs` module docs):
37//! receipts are unsigned, so authenticity rests on ownership of the store
38//! plus recomputation of the receipt identity and every binding.
39
40use crate::completion::{
41 artifact_digest, check_identifier, host_identity, require, single_ref, task_key,
42 verify_completion, write_atomic, CompletionError,
43};
44use crate::HarnessEngine;
45use aien_proof::evidence::{self, Assertion, Mutation, Receipt, Tier, Verdict};
46use aien_proof::lock::FileLock;
47use serde::{Deserialize, Deserializer, Serialize, Serializer};
48use serde_json::Value;
49use std::fmt;
50use std::fs;
51use std::path::Path;
52
53/// Receipt `kind` for published interface artifacts.
54pub const INTERFACE_KIND: &str = "spark-harness-interface";
55/// Honest tier: host-executed deterministic checks.
56pub const INTERFACE_TIER: Tier = Tier::HostTest;
57/// Subdirectory of the harness store holding current interface records.
58pub const INTERFACE_DIR: &str = "interfaces";
59const ASSERTION_SOURCE: &str = "spark-harness";
60
61/// Closed set of operation classes a scheduled task may ask to run.
62///
63/// Only [`OperationClass::is_reversible_preparation`] classes may run while a
64/// dependency is merely interface-verified. Every match on this enum is
65/// exhaustive on purpose: a new class must be classified explicitly.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
67pub enum OperationClass {
68 /// Reading sources and artifacts, no writes outside scratch space.
69 ReadOnlyAnalysis,
70 /// Builds or tests in a throwaway sandbox whose output is discarded on
71 /// revocation.
72 SandboxedCheck,
73 /// Committing work (World commit). Irreversible.
74 Commit,
75 /// Publishing an artifact others may consume. Irreversible.
76 Publish,
77 /// Mutating persistent state. Irreversible.
78 PersistentMutation,
79 /// Any effect outside the host (network, devices, people). Irreversible.
80 ExternalEffect,
81}
82
83impl OperationClass {
84 pub const ALL: [OperationClass; 6] = [
85 OperationClass::ReadOnlyAnalysis,
86 OperationClass::SandboxedCheck,
87 OperationClass::Commit,
88 OperationClass::Publish,
89 OperationClass::PersistentMutation,
90 OperationClass::ExternalEffect,
91 ];
92
93 pub fn as_str(self) -> &'static str {
94 match self {
95 OperationClass::ReadOnlyAnalysis => "read_only_analysis",
96 OperationClass::SandboxedCheck => "sandboxed_check",
97 OperationClass::Commit => "commit",
98 OperationClass::Publish => "publish",
99 OperationClass::PersistentMutation => "persistent_mutation",
100 OperationClass::ExternalEffect => "external_effect",
101 }
102 }
103
104 /// Exact, case-sensitive match. Anything else is unknown and refused.
105 pub fn parse(s: &str) -> Result<Self, UnknownOperation> {
106 OperationClass::ALL
107 .into_iter()
108 .find(|op| op.as_str() == s)
109 .ok_or_else(|| UnknownOperation(s.to_string()))
110 }
111
112 /// True only for classes whose effects stay inside a sandbox and can be
113 /// thrown away when the interface they used is revoked.
114 pub fn is_reversible_preparation(self) -> bool {
115 match self {
116 OperationClass::ReadOnlyAnalysis | OperationClass::SandboxedCheck => true,
117 OperationClass::Commit
118 | OperationClass::Publish
119 | OperationClass::PersistentMutation
120 | OperationClass::ExternalEffect => false,
121 }
122 }
123}
124
125/// An operation name that is not in [`OperationClass`].
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct UnknownOperation(pub String);
128
129impl fmt::Display for UnknownOperation {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 write!(f, "unknown operation class {:?}, refused", self.0)
132 }
133}
134
135impl std::error::Error for UnknownOperation {}
136
137impl Serialize for OperationClass {
138 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
139 s.serialize_str(self.as_str())
140 }
141}
142
143impl<'de> Deserialize<'de> for OperationClass {
144 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
145 let s = String::deserialize(d)?;
146 OperationClass::parse(&s).map_err(serde::de::Error::custom)
147 }
148}
149
150/// How far a producer's output may be trusted by its consumers.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
152pub enum ReadinessLevel {
153 InterfaceVerified,
154 FinalVerified,
155 Revoked,
156}
157
158impl ReadinessLevel {
159 /// The single place that decides which operations a level allows.
160 pub fn permits(self, op: OperationClass) -> bool {
161 match self {
162 ReadinessLevel::FinalVerified => true,
163 ReadinessLevel::InterfaceVerified => op.is_reversible_preparation(),
164 ReadinessLevel::Revoked => false,
165 }
166 }
167}
168
169/// Proof pointer carried by scheduler events: which harness receipt, for
170/// which source commit and artifact digest. It is only a claim; the store is
171/// re-read and every field re-checked before it is believed.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(deny_unknown_fields)]
174pub struct ProofClaim {
175 pub receipt_id: String,
176 pub commit: String,
177 pub digest: String,
178}
179
180/// Verified readiness of one producer artifact. Built only by
181/// [`verify_interface`] and [`verify_final`].
182#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
183pub struct ArtifactReadiness {
184 producer_task: String,
185 source_commit: String,
186 producer_generation: u64,
187 artifact_digest: String,
188 receipt_id: String,
189 level: ReadinessLevel,
190}
191
192impl ArtifactReadiness {
193 pub fn producer_task(&self) -> &str {
194 &self.producer_task
195 }
196 pub fn source_commit(&self) -> &str {
197 &self.source_commit
198 }
199 pub fn producer_generation(&self) -> u64 {
200 self.producer_generation
201 }
202 pub fn artifact_digest(&self) -> &str {
203 &self.artifact_digest
204 }
205 pub fn receipt_id(&self) -> &str {
206 &self.receipt_id
207 }
208 pub fn level(&self) -> ReadinessLevel {
209 self.level
210 }
211 pub fn permits(&self, op: OperationClass) -> bool {
212 self.level.permits(op)
213 }
214 /// The same bindings, downgraded to [`ReadinessLevel::Revoked`].
215 pub fn revoked(mut self) -> Self {
216 self.level = ReadinessLevel::Revoked;
217 self
218 }
219}
220
221/// What a producer submits to publish an interface. No receipt, digest or
222/// flag field exists; unknown fields are rejected.
223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
224#[serde(deny_unknown_fields)]
225pub struct InterfaceSubmission {
226 pub task_id: String,
227 pub generation: u64,
228 /// 40 or 64 lowercase hex, checked by aien-proof `check_commit`.
229 pub source_commit: String,
230 /// The interface artifact. Must be a non-empty JSON object.
231 pub interface: Value,
232}
233
234/// Durable record naming the task's current interface receipt.
235#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(deny_unknown_fields)]
237pub struct InterfaceRecord {
238 pub task_id: String,
239 pub generation: u64,
240 pub receipt_id: String,
241 pub source_commit: String,
242 pub artifact_digest: String,
243}
244
245impl InterfaceRecord {
246 pub fn claim(&self) -> ProofClaim {
247 ProofClaim {
248 receipt_id: self.receipt_id.clone(),
249 commit: self.source_commit.clone(),
250 digest: self.artifact_digest.clone(),
251 }
252 }
253}
254
255fn record_path(store: &Path, task_id: &str) -> std::path::PathBuf {
256 store
257 .join(INTERFACE_DIR)
258 .join(format!("{}.json", task_key(task_id)))
259}
260
261fn read_record(path: &Path, task_id: &str) -> Result<Option<InterfaceRecord>, CompletionError> {
262 let bytes = match fs::read(path) {
263 Ok(b) => b,
264 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
265 Err(e) => {
266 return Err(CompletionError::Store(format!(
267 "cannot read interface record {}: {e}",
268 path.display()
269 )))
270 }
271 };
272 let rec: InterfaceRecord = serde_json::from_slice(&bytes).map_err(|e| {
273 CompletionError::Store(format!(
274 "interface record {} is malformed, refusing: {e}",
275 path.display()
276 ))
277 })?;
278 if rec.task_id != task_id {
279 return Err(CompletionError::Store(format!(
280 "interface record {} belongs to task '{}', not '{task_id}'",
281 path.display(),
282 rec.task_id
283 )));
284 }
285 Ok(Some(rec))
286}
287
288fn pass(id: &str, expected: &str, observed: String) -> Assertion {
289 Assertion {
290 id: id.to_string(),
291 expected: expected.to_string(),
292 observed,
293 pass: true,
294 source: ASSERTION_SOURCE.to_string(),
295 note: String::new(),
296 }
297}
298
299impl HarnessEngine {
300 fn mint_interface_receipt(
301 &self,
302 sub: &InterfaceSubmission,
303 digest: &str,
304 keys: usize,
305 ) -> Result<Receipt, CompletionError> {
306 let assertions = vec![
307 pass(
308 "interface:shape",
309 "interface is a non-empty JSON object",
310 format!("object with {keys} key(s)"),
311 ),
312 pass(
313 "interface:digest",
314 "digest recomputed by the harness",
315 format!("blake3:{digest}"),
316 ),
317 ];
318 let assertion_bytes =
319 serde_json::to_vec(&assertions).map_err(|e| CompletionError::Store(e.to_string()))?;
320 let repo = if self.completion_repo.trim().is_empty() {
321 crate::UNSPECIFIED_REPO.to_string()
322 } else {
323 self.completion_repo.clone()
324 };
325 let mut r = Receipt {
326 schema: evidence::SCHEMA.to_string(),
327 version: evidence::SCHEMA_VERSION,
328 id: String::new(),
329 kind: INTERFACE_KIND.to_string(),
330 tier: INTERFACE_TIER,
331 result: Verdict::Pass,
332 timestamp: (self.completion_clock)(),
333 repo,
334 commit: sub.source_commit.clone(),
335 dirty: false,
336 toolchain: format!("spark-harness {}", env!("CARGO_PKG_VERSION")),
337 procedure: "spark-harness publish_interface".to_string(),
338 machine: host_identity(),
339 env_class: INTERFACE_TIER.as_str().to_string(),
340 input_artifacts: Vec::new(),
341 output_artifacts: vec![format!("blake3:{digest}")],
342 assertions,
343 dependencies: Vec::new(),
344 declared_mutation: Mutation::None,
345 observed_mutation: Mutation::None,
346 authority: String::new(),
347 output_digest: blake3::hash(&assertion_bytes).to_hex().to_string(),
348 external_refs: vec![
349 format!("task:{}", sub.task_id),
350 format!("generation:{}", sub.generation),
351 ],
352 ledger: None,
353 lease: None,
354 required_features: Vec::new(),
355 reserved: String::new(),
356 };
357 r.id = evidence::receipt_id(&r).map_err(CompletionError::Store)?;
358 Ok(r)
359 }
360
361 /// Publish an immutable interface artifact for `sub.task_id` at
362 /// `sub.generation`. The harness computes the digest, mints and stores a
363 /// receipt of kind [`INTERFACE_KIND`], and records it as the task's
364 /// current interface.
365 ///
366 /// - A lower generation than the recorded one is refused as stale.
367 /// - The same generation and digest returns the existing record and
368 /// mints nothing (idempotent).
369 /// - The same generation with a different digest is an interface change:
370 /// a new receipt replaces the record, and the old receipt stops
371 /// verifying. The scheduler revokes consumers bound to the old one.
372 pub fn publish_interface(
373 &self,
374 sub: &InterfaceSubmission,
375 ) -> Result<InterfaceRecord, CompletionError> {
376 check_identifier("task_id", &sub.task_id)?;
377 evidence::check_commit(&sub.source_commit).map_err(CompletionError::InvalidSubmission)?;
378 let keys = match &sub.interface {
379 Value::Object(m) if !m.is_empty() => m.len(),
380 _ => {
381 return Err(CompletionError::InvalidSubmission(
382 "interface must be a non-empty JSON object".to_string(),
383 ))
384 }
385 };
386 let digest = artifact_digest(&sub.interface);
387 let dir = self.completion_store.join(INTERFACE_DIR);
388 fs::create_dir_all(&dir)
389 .map_err(|e| CompletionError::Store(format!("cannot create {}: {e}", dir.display())))?;
390 let _lock = FileLock::acquire(&dir.join(".lock"))
391 .map_err(|e| CompletionError::Store(format!("cannot lock interface store: {e}")))?;
392 let path = record_path(&self.completion_store, &sub.task_id);
393 if let Some(prev) = read_record(&path, &sub.task_id)? {
394 if sub.generation < prev.generation {
395 return Err(CompletionError::StaleGeneration {
396 task_id: sub.task_id.clone(),
397 submitted: sub.generation,
398 recorded: prev.generation,
399 });
400 }
401 if sub.generation == prev.generation
402 && prev.artifact_digest == digest
403 && prev.source_commit == sub.source_commit
404 {
405 return Ok(prev);
406 }
407 }
408 let receipt = self.mint_interface_receipt(sub, &digest, keys)?;
409 let receipt_id = evidence::store_receipt(&self.completion_store, &receipt)
410 .map_err(CompletionError::Store)?;
411 let rec = InterfaceRecord {
412 task_id: sub.task_id.clone(),
413 generation: sub.generation,
414 receipt_id,
415 source_commit: sub.source_commit.clone(),
416 artifact_digest: digest,
417 };
418 let text =
419 serde_json::to_vec_pretty(&rec).map_err(|e| CompletionError::Store(e.to_string()))?;
420 write_atomic(&path, &text).map_err(|e| {
421 CompletionError::Store(format!(
422 "cannot write interface record {}: {e}",
423 path.display()
424 ))
425 })?;
426 Ok(rec)
427 }
428}
429
430/// Read the task's current interface record from the store, if any.
431pub fn current_interface(
432 store: &Path,
433 task_id: &str,
434) -> Result<Option<InterfaceRecord>, CompletionError> {
435 read_record(&record_path(store, task_id), task_id)
436}
437
438/// Re-read and check an interface receipt: identity recomputes, PASS,
439/// kind [`INTERFACE_KIND`], tier, commit, digest, task and generation all
440/// match, and the task's interface record names exactly this receipt.
441pub fn verify_interface(
442 store: &Path,
443 task_id: &str,
444 generation: u64,
445 claim: &ProofClaim,
446) -> Result<ArtifactReadiness, CompletionError> {
447 let receipt = evidence::load_receipt(store, &claim.receipt_id)
448 .map_err(CompletionError::ReceiptInvalid)?;
449 let path = store
450 .join(evidence::RECEIPT_DIR)
451 .join(format!("{}.json", receipt.id));
452 let bytes = fs::read(&path)
453 .map_err(|e| CompletionError::ReceiptInvalid(format!("{}: {e}", path.display())))?;
454 let (again, report) =
455 evidence::verify_bytes(&bytes).map_err(CompletionError::ReceiptInvalid)?;
456 if again != receipt {
457 return Err(CompletionError::ReceiptInvalid(
458 "receipt file changed while being verified".to_string(),
459 ));
460 }
461 if receipt.result != Verdict::Pass || !report.ok() {
462 return Err(CompletionError::NotPass(format!(
463 "{} ({})",
464 receipt.result.as_str(),
465 report.reasons.join("; ")
466 )));
467 }
468 require("kind", INTERFACE_KIND, &receipt.kind)?;
469 require("tier", INTERFACE_TIER.as_str(), receipt.tier.as_str())?;
470 require("commit", &claim.commit, &receipt.commit)?;
471 let digest_hex = claim
472 .digest
473 .strip_prefix("blake3:")
474 .unwrap_or(&claim.digest)
475 .to_ascii_lowercase();
476 require(
477 "artifact_digest",
478 &format!("blake3:{digest_hex}"),
479 &receipt.output_artifacts.join(","),
480 )?;
481 require(
482 "task",
483 task_id,
484 single_ref(&receipt.external_refs, "task:")?,
485 )?;
486 require(
487 "generation",
488 &generation.to_string(),
489 single_ref(&receipt.external_refs, "generation:")?,
490 )?;
491 let current = current_interface(store, task_id)?.ok_or_else(|| {
492 CompletionError::NotCurrentCompletion(format!(
493 "no interface record for task '{task_id}'; receipt {} is an orphan",
494 receipt.id
495 ))
496 })?;
497 if current.receipt_id != receipt.id
498 || current.generation != generation
499 || current.artifact_digest != digest_hex
500 {
501 return Err(CompletionError::NotCurrentCompletion(format!(
502 "task '{task_id}' current interface is generation {} receipt {}; receipt {} is not it",
503 current.generation, current.receipt_id, receipt.id
504 )));
505 }
506 Ok(ArtifactReadiness {
507 producer_task: task_id.to_string(),
508 source_commit: receipt.commit,
509 producer_generation: generation,
510 artifact_digest: digest_hex,
511 receipt_id: receipt.id,
512 level: ReadinessLevel::InterfaceVerified,
513 })
514}
515
516/// M1 [`verify_completion`] for the producer's generation, as readiness.
517pub fn verify_final(
518 store: &Path,
519 task_id: &str,
520 generation: u64,
521 claim: &ProofClaim,
522) -> Result<ArtifactReadiness, CompletionError> {
523 let v = verify_completion(
524 store,
525 &claim.receipt_id,
526 task_id,
527 generation,
528 &claim.commit,
529 &claim.digest,
530 )?;
531 Ok(ArtifactReadiness {
532 producer_task: v.task_id,
533 source_commit: v.source_commit,
534 producer_generation: v.generation,
535 artifact_digest: v.artifact_digest,
536 receipt_id: v.receipt_id,
537 level: ReadinessLevel::FinalVerified,
538 })
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
544
545 #[test]
546 fn parse_is_exact_and_closed() {
547 for op in OperationClass::ALL {
548 assert_eq!(OperationClass::parse(op.as_str()), Ok(op));
549 }
550 for bad in [
551 "",
552 "Commit",
553 "read-only-analysis",
554 " commit",
555 "sandboxed_check ",
556 "rm",
557 ] {
558 assert!(
559 OperationClass::parse(bad).is_err(),
560 "{bad:?} must be unknown"
561 );
562 }
563 let err = serde_json::from_str::<OperationClass>("\"deploy\"");
564 assert!(err.is_err());
565 }
566
567 #[test]
568 fn levels_permit_only_what_they_should() {
569 for op in OperationClass::ALL {
570 assert!(ReadinessLevel::FinalVerified.permits(op));
571 assert!(!ReadinessLevel::Revoked.permits(op));
572 assert_eq!(
573 ReadinessLevel::InterfaceVerified.permits(op),
574 matches!(
575 op,
576 OperationClass::ReadOnlyAnalysis | OperationClass::SandboxedCheck
577 )
578 );
579 }
580 }
581}