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/patches/a092125ecdf3deae # 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 ## GitHub aien-dev/aien-sovereign-core-mv#446 (code only) closed derived `a092125ecdf3deae` #446 Imported from GitHub aien-dev/aien-sovereign-core-mv#446 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `bba027d3138e7c0de8181bc87c2b83551e64fde1` · Head `0f13a305bbfaa58dce8a6d5162efb76a9781b82f` ### Apply it ``` git checkout -b patch-a092125ecdf3deae bba027d3138e7c0de8181bc87c2b83551e64fde1 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/a092125ecdf3deae.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 446 0f13a305bbfaa58dce8a6d5162efb76a9781b82f ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":446,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/446","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:12Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 85e92e1e..651c2575 100644 --- a/.crumb +++ b/.crumb @@ -100,8 +100,8 @@ "purpose": "" }, { - "digest": "6c97a5cb9d0f05465df81a036e54d7113433b64dcbf9f67bc6453032a1d4cb3f", - "last_commit": "c26f4d7", + "digest": "07f19c8d7013a03659eb514ccf94dd7ff76f2ff3ce3736cc3bb11c156ed30e1c", + "last_commit": "2a1b901", "name": "scripts", "purpose": "" }, @@ -113,20 +113,20 @@ }, { "digest": "ccfbfd158c2d059c0a7dd3101068244f27805b828e44ae695b652ae18e726795", - "last_commit": "cd88714", + "last_commit": "bba027d", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], - "children_root": "sha256:f1eac180509183a13d4eabf04f7a8073c4add305cd76c09e07c1f86988c6cdaf", - "compiled_at": "2026-10-11T20:00:36Z", + "children_root": "sha256:51934dfd49549a190cb949b997750b0a98ff7bd0edbfdb204d24b56f6bd6f1e5", + "compiled_at": "2026-10-11T20:24:07Z", "compiler": "crumb-compile/1", - "digest": "sha256:33f7cba7d0076cbd5172151ec6784aca22f40413adf71771df982d299458d599", + "digest": "sha256:6584c0907c65c1f3afc50c0650ec4fa0e281c1f2bb31bb3fd0d2815476f5b399", "evidence_files": 187, "evidence_root": "sha256:27ee0353cb4d4aae2b7dbce2bfe0d9f4ef2a94cd7a4555b84684d59372503280", - "files": 3836, - "generated_at_commit": "cd88714f9b3c7127278ba7beb9c1046dbd09c0d1", - "source_tree": "sha256:32d18adb65af5605fa4805c38afb3f61eb13378fb6702efdebcfd53fb5d9ecc0" + "files": 3856, + "generated_at_commit": "cc3fd4f0794c49f5f311e407a290d873bc1417fd", + "source_tree": "sha256:1f494efee52692167ba79c9ed196e9d7087842b483b092fd320b5dfbc86061e9" } }, "history": [], diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 986c8dc0..d7f98368 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -48,6 +48,9 @@ jobs: - name: Pin materializer self-test (scripts/pins.sh, offline) run: bash scripts/test-pins.sh + - name: Native library identity refusals (scripts/test-native-identity.sh, no omega needed) + run: bash scripts/test-native-identity.sh + - name: Verify Piped Installer Bootstrap run: bash scripts/test-install.sh diff --git a/Cargo.lock b/Cargo.lock index c66d8e20..1dcc2900 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -25,6 +25,10 @@ dependencies = [ "memchr", ] +[[package]] +name = "aien-abi-conformance" +version = "0.1.0" + [[package]] name = "aien-abi-core" version = "0.1.0" @@ -245,6 +249,7 @@ dependencies = [ name = "aien-omega-compose" version = "0.1.0" dependencies = [ + "aien-abi-conformance", "sha2 0.10.9", "tempfile", ] @@ -252,6 +257,9 @@ dependencies = [ [[package]] name = "aien-omega-gpu" version = "0.1.0" +dependencies = [ + "aien-abi-conformance", +] [[package]] name = "aien-platform" diff --git a/Cargo.toml b/Cargo.toml index 2b458394..ef1d3f07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -33,6 +33,7 @@ members = [ "crates/aien-inference-service", "crates/aien-inference-runtime", "crates/cortex-path-m1", + "crates/aien-abi-conformance", "crates/aien-omega-gpu", "crates/aien-omega-compose", "crates/aien-campaign-verifier", diff --git a/crates/aien-abi-conformance/Cargo.toml b/crates/aien-abi-conformance/Cargo.toml new file mode 100644 index 00000000..c014c17f --- /dev/null +++ b/crates/aien-abi-conformance/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "aien-abi-conformance" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton "] +description = "Checks the hand-written Rust mirrors of omega's C ABI against the pinned C headers and the linked archive (layouts, constants, signatures, symbols, artifact identity). No dependencies." +license.workspace = true + +[dependencies] diff --git a/crates/aien-abi-conformance/src/build.rs b/crates/aien-abi-conformance/src/build.rs new file mode 100644 index 00000000..c084af5a --- /dev/null +++ b/crates/aien-abi-conformance/src/build.rs @@ -0,0 +1,260 @@ +//! Shared `build.rs` steps for the crates that link an omega archive: the C-side ABI check, +//! the archive identity check, and the `cargo:rustc-env` identity record the crate exposes at +//! run time (`native_identity()`), so a binary can say what it linked. + +use crate::identity::{self, Digest}; +use crate::probe::{check_c, defined_symbols, CCheck}; +use crate::Manifest; +use std::path::{Path, PathBuf}; + +/// How the archive was obtained. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Link { + /// no native library (every native call returns Unavailable) + Stub, + /// built from an omega checkout at the commit `omega.lock` pins + PinnedSource, + /// built from an omega checkout at a developer-override commit (not qualifiable) + DevOverride, + /// a prebuilt archive given by path and expected digest (not qualifiable) + Prebuilt, +} + +impl Link { + pub fn as_str(self) -> &'static str { + match self { + Link::Stub => "stub", + Link::PinnedSource => "pinned-source", + Link::DevOverride => "dev-override", + Link::Prebuilt => "prebuilt", + } + } +} + +/// What `build.rs` established; [`Identity::emit`] records it for the crate. +#[derive(Debug, Clone)] +pub struct Identity { + pub link: Link, + /// "pass" (headers + probe + symbols), "symbols-only" (prebuilt: no headers), "none" (stub) + pub abi: &'static str, + /// "locked" | "unrecorded" | "prebuilt-match" | "none" + pub digest: &'static str, + pub archive_sha256: String, + pub omega_sha: String, + pub aienos_lock: String, + pub physics_lock: String, + pub target: String, + pub cc: String, +} + +impl Identity { + pub fn stub(omega_sha: &str) -> Identity { + Identity { + link: Link::Stub, + abi: "none", + digest: "none", + archive_sha256: String::new(), + omega_sha: omega_sha.into(), + aienos_lock: String::new(), + physics_lock: String::new(), + target: env_or("TARGET", ""), + cc: String::new(), + } + } + + /// `cargo:rustc-env={prefix}_{KEY}=value` for every field. + pub fn emit(&self, prefix: &str) { + let kv = [ + ("LINK", self.link.as_str().to_string()), + ("ABI", self.abi.to_string()), + ("DIGEST", self.digest.to_string()), + ("ARCHIVE_SHA256", self.archive_sha256.clone()), + ("SOURCE_SHA", self.omega_sha.clone()), + ("AIENOS_LOCK", self.aienos_lock.clone()), + ("PHYSICS_LOCK", self.physics_lock.clone()), + ("TARGET", self.target.clone()), + ("CC", self.cc.replace(['\n', '\r'], " ")), + ]; + for (k, v) in kv { + println!("cargo:rustc-env={prefix}_{k}={v}"); + } + } +} + +fn env_or(k: &str, d: &str) -> String { + std::env::var(k).unwrap_or_else(|_| d.to_string()) +} + +/// `true` when `AIEN_REQUIRE_NATIVE_LIBS=1` (release and qualification builds). +pub fn require_native() -> bool { + std::env::var("AIEN_REQUIRE_NATIVE_LIBS").as_deref() == Ok("1") +} + +/// Refuse `AIEN_FORCE_CPU_STUB=1` together with `AIEN_REQUIRE_NATIVE_LIBS=1`: a build that +/// requires the native library must never quietly become a stub. +pub fn refuse_stub_if_required(krate: &str) { + if require_native() { + panic!( + "{krate}: AIEN_FORCE_CPU_STUB=1 and AIEN_REQUIRE_NATIVE_LIBS=1 contradict each other: \ + a required-native build cannot be a stub (unset one of them)" + ); + } +} + +fn read_trim(p: &Path) -> String { + std::fs::read_to_string(p) + .map(|s| s.trim().to_string()) + .unwrap_or_default() +} + +fn load_manifest(path: &Path) -> Manifest { + println!("cargo:rerun-if-changed={}", path.display()); + let text = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("cannot read ABI manifest {}: {e}", path.display())); + Manifest::parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())) +} + +fn load_lock(path: &Path) -> Vec { + println!("cargo:rerun-if-changed={}", path.display()); + match std::fs::read_to_string(path) { + Ok(t) => identity::parse_lock(&t).unwrap_or_else(|e| panic!("{e}")), + Err(_) => Vec::new(), + } +} + +/// Checks for an archive built from an omega checkout. Panics (fails the build) on any ABI +/// mismatch, missing symbol or digest that differs from `native-artifacts.lock`. +#[allow(clippy::too_many_arguments)] +pub fn qualify_built( + krate: &str, + manifest: &Path, + lock: &Path, + omega: &Path, + physics: &Path, + archive: &Path, + omega_sha: &str, + pinned: bool, +) -> Identity { + let m = load_manifest(manifest); + for h in &m.headers { + println!("cargo:rerun-if-changed={}", omega.join(h).display()); + } + let cc = env_or("CC", "cc"); + let target = env_or("TARGET", ""); + let host = env_or("HOST", ""); + let abi = if target == host { + let work = PathBuf::from(env_or("OUT_DIR", ".")).join("abi-probe"); + let includes = vec![ + omega.join("src"), + omega.join("src/runtime"), + physics.join("m16"), + physics.join("nvrm"), + ]; + match check_c(&CCheck { + manifest: &m, + root: omega, + includes, + archive: Some(archive), + work: &work, + cc: cc.clone(), + }) { + Ok(report) => { + let _ = std::fs::write(work.join("report.txt"), &report); + "pass" + } + Err(errs) => panic!( + "{krate}: omega {omega_sha} does not match {} ({} problem(s)); nothing was linked:\n - {}", + manifest.display(), + errs.len(), + errs.join("\n - ") + ), + } + } else if require_native() { + panic!("{krate}: cross build ({host} -> {target}): the ABI layout probe cannot run, and AIEN_REQUIRE_NATIVE_LIBS=1 needs it"); + } else { + println!("cargo:warning={krate}: cross build ({host} -> {target}): C ABI layout probe skipped (not qualifiable)"); + "unchecked" + }; + let sha = identity::sha256_file(archive).unwrap_or_else(|e| panic!("{krate}: {e}")); + let ccv = identity::cc_version(&cc); + let name = archive + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_default(); + let digest = match identity::check_built( + &load_lock(lock), + &name, + omega_sha, + &target, + &ccv, + &sha, + ) { + Ok(Digest::Locked) => "locked", + Ok(Digest::Unrecorded) => { + println!( + "cargo:warning={krate}: {name} sha256 {sha} (omega {omega_sha}, {target}, `{ccv}`) is not recorded in native-artifacts.lock: builds, but does not qualify" + ); + "unrecorded" + } + Err(e) => panic!("{krate}: {e}"), + }; + Identity { + link: if pinned { + Link::PinnedSource + } else { + Link::DevOverride + }, + abi, + digest, + archive_sha256: sha, + omega_sha: omega_sha.into(), + aienos_lock: read_trim(&omega.join("aienos.lock")), + physics_lock: read_trim(&omega.join("physics.lock")), + target, + cc: ccv, + } +} + +/// Checks for a prebuilt archive: its digest must equal `$sha_var`, and it must define every +/// function the manifest names (no headers are available, so layouts are not re-probed; the +/// identity says so and qualification does not accept it). +pub fn qualify_prebuilt( + krate: &str, + manifest: &Path, + archive: &Path, + sha_var: &str, + omega_sha: &str, +) -> Identity { + println!("cargo:rerun-if-env-changed={sha_var}"); + let want = std::env::var(sha_var).ok(); + let sha = identity::check_prebuilt(archive, want.as_deref(), sha_var) + .unwrap_or_else(|e| panic!("{krate}: {e}")); + let m = load_manifest(manifest); + let syms = defined_symbols(archive).unwrap_or_else(|e| panic!("{krate}: {e}")); + let missing: Vec<&str> = m + .fns + .iter() + .map(|(n, _)| n.as_str()) + .filter(|n| !syms.iter().any(|s| s == n)) + .collect(); + assert!( + missing.is_empty(), + "{krate}: prebuilt {} does not define {missing:?}", + archive.display() + ); + println!( + "cargo:warning={krate}: linking prebuilt {} (sha256 {sha}): a development override, not a qualified build", + archive.display() + ); + Identity { + link: Link::Prebuilt, + abi: "symbols-only", + digest: "prebuilt-match", + archive_sha256: sha, + omega_sha: omega_sha.into(), + aienos_lock: String::new(), + physics_lock: String::new(), + target: env_or("TARGET", ""), + cc: String::new(), + } +} diff --git a/crates/aien-abi-conformance/src/header.rs b/crates/aien-abi-conformance/src/header.rs new file mode 100644 index 00000000..e3adf3da --- /dev/null +++ b/crates/aien-abi-conformance/src/header.rs @@ -0,0 +1,325 @@ +//! Just enough C header reading for omega's plain ABI headers: comments and preprocessor +//! lines removed, then top-level declarations split on `;`. It reads +//! `typedef struct [Tag] { ... } Name;` (field names in order), prototypes and +//! `typedef R (*Name)(...);` callback types. Types come back in canonical Rust spelling. + +use crate::manifest::{make_sig, split_top}; +use std::collections::BTreeMap; + +#[derive(Debug, Default)] +pub struct Header { + /// struct typedef name -> field names in declaration order + pub structs: BTreeMap>, + /// function name -> canonical signature + pub fns: BTreeMap, + /// callback typedef name -> canonical signature + pub fnptrs: BTreeMap, +} + +/// Remove comments, string-free preprocessor lines (with `\` continuations) and +/// `extern "C" {` / `}` wrappers. +pub fn strip(src: &str) -> String { + let mut out = String::with_capacity(src.len()); + let b = src.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'*' { + i += 2; + while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { + i += 1; + } + i += 2; + out.push(' '); + } else if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'/' { + while i < b.len() && b[i] != b'\n' { + i += 1; + } + } else { + out.push(b[i] as char); + i += 1; + } + } + let mut kept = String::new(); + let mut cont = false; + for line in out.lines() { + let t = line.trim(); + if cont || t.starts_with('#') { + cont = t.ends_with('\\'); + continue; + } + kept.push_str(line); + kept.push('\n'); + } + kept.replace("extern \"C\" {", " ") +} + +/// Split at top-level `;` (braces tracked) into whitespace-normalised statements. +fn statements(src: &str) -> Vec { + let mut v = Vec::new(); + let mut depth = 0i32; + let mut cur = String::new(); + for c in src.chars() { + match c { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth < 0 { + // the closing brace of an extern "C" block + depth = 0; + continue; + } + } + ';' if depth == 0 => { + let s = cur.split_whitespace().collect::>().join(" "); + if !s.is_empty() { + v.push(s); + } + cur.clear(); + continue; + } + _ => {} + } + cur.push(c); + } + v +} + +fn tokens(s: &str) -> Vec { + let mut t = Vec::new(); + let mut cur = String::new(); + for c in s.chars() { + if c.is_alphanumeric() || c == '_' { + cur.push(c); + } else { + if !cur.is_empty() { + t.push(std::mem::take(&mut cur)); + } + if !c.is_whitespace() { + t.push(c.to_string()); + } + } + } + if !cur.is_empty() { + t.push(cur); + } + t +} + +const BUILTIN: &[&str] = &[ + "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "_Bool", + "bool", +]; + +/// One C declaration (parameter, field or return type) -> (canonical Rust type, name). +pub fn c_decl(decl: &str) -> (String, Option) { + let toks = tokens(decl); + let mut base_const = false; + let mut words: Vec = Vec::new(); + let mut i = 0; + while i < toks.len() && toks[i] != "*" && toks[i] != "[" { + match toks[i].as_str() { + "const" => base_const = true, + "volatile" | "struct" | "enum" | "restrict" | "__restrict" => {} + w => words.push(w.to_string()), + } + i += 1; + } + // Pointer levels: each `*` may be followed by `const` (the pointer itself, ABI-irrelevant). + let mut stars = 0; + let mut name = None; + while i < toks.len() { + match toks[i].as_str() { + "*" => stars += 1, + "const" | "restrict" | "__restrict" => {} + "[" => { + // array parameter: decays to a pointer + stars += 1; + while i < toks.len() && toks[i] != "]" { + i += 1; + } + } + w if w.chars().all(|c| c.is_alphanumeric() || c == '_') => name = Some(w.to_string()), + _ => {} + } + i += 1; + } + let builtin: Vec<&str> = words + .iter() + .map(String::as_str) + .filter(|w| BUILTIN.contains(w)) + .collect(); + let (base, rest_name) = if builtin.is_empty() { + ( + words.first().cloned().unwrap_or_default(), + words.get(1).cloned(), + ) + } else { + let others: Vec<&String> = words + .iter() + .filter(|w| !BUILTIN.contains(&w.as_str())) + .collect(); + (builtin.join(" "), others.first().map(|s| s.to_string())) + }; + let name = name.or(rest_name); + let rust_base = match base.as_str() { + "int" | "signed" | "signed int" | "int32_t" => "i32", + "unsigned" | "unsigned int" | "uint32_t" => "u32", + "long" | "long int" | "long long" | "int64_t" => "i64", + "unsigned long" | "unsigned long long" | "uint64_t" => "u64", + "short" | "int16_t" => "i16", + "unsigned short" | "uint16_t" => "u16", + "signed char" | "int8_t" => "i8", + "unsigned char" | "uint8_t" => "u8", + "char" => "c_char", + "size_t" => "usize", + "ssize_t" | "ptrdiff_t" => "isize", + "float" => "f32", + "double" => "f64", + "bool" | "_Bool" => "bool", + "void" if stars > 0 => "c_void", + "void" => "()", + other => other, + } + .to_string(); + let mut ty = String::new(); + for level in 0..stars { + // The innermost pointer points at the (possibly const) base; outer ones point at + // pointers whose own constness the C declaration placed after their `*`. + let innermost = level == stars - 1; + ty.push_str(if innermost && base_const { + "*const " + } else { + "*mut " + }); + } + ty.push_str(&rust_base); + (ty, name) +} + +fn params(list: &str) -> Vec { + let l = list.trim(); + if l.is_empty() || l == "void" { + return Vec::new(); + } + split_top(l).iter().map(|p| c_decl(p).0).collect() +} + +/// Parse the declarations of one header. +pub fn parse(src: &str) -> Header { + let mut h = Header::default(); + for st in statements(&strip(src)) { + if let Some(rest) = st.strip_prefix("typedef ") { + if rest.starts_with("struct") && rest.contains('{') { + let (Some(open), Some(close)) = (rest.find('{'), rest.rfind('}')) else { + continue; + }; + let name = rest[close + 1..].trim().to_string(); + let mut fields = Vec::new(); + for decl in rest[open + 1..close].split(';') { + let d = decl.trim(); + if d.is_empty() { + continue; + } + let parts = split_top(d); + // first declarator carries the base type; the rest are bare declarators + if let Some((_, Some(n))) = parts.first().map(|p| c_decl(p)) { + fields.push(n); + } + for p in parts.iter().skip(1) { + let t = tokens(p); + if let Some(n) = t + .iter() + .find(|w| w.chars().all(|c| c.is_alphanumeric() || c == '_')) + { + fields.push(n.clone()); + } + } + } + h.structs.insert(name, fields); + } else if let Some(p) = rest.find("(*") { + // typedef R (*Name)(params) + let ret = c_decl(&rest[..p]).0; + let after = &rest[p + 2..]; + let Some(close) = after.find(')') else { + continue; + }; + let name = after[..close].trim().to_string(); + let plist = after[close + 1..].trim(); + if let Some(inner) = plist.strip_prefix('(').and_then(|s| s.strip_suffix(')')) { + h.fnptrs.insert(name, make_sig(¶ms(inner), &ret)); + } + } + continue; + } + // prototype: R name(params) + let Some(open) = st.find('(') else { continue }; + if !st.ends_with(')') || st.contains('{') || st.contains('=') { + continue; + } + let (ret, name) = c_decl(&st[..open]); + let Some(name) = name else { continue }; + let inner = &st[open + 1..st.len() - 1]; + h.fns.insert(name, make_sig(¶ms(inner), &ret)); + } + h +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn declarations() { + assert_eq!(c_decl("const char *dir").0, "*const c_char"); + assert_eq!(c_decl("RxcHost **out").0, "*mut *mut RxcHost"); + assert_eq!(c_decl("const uint64_t links[4]").0, "*const u64"); + assert_eq!(c_decl("uint32_t out[4]").0, "*mut u32"); + assert_eq!(c_decl("size_t").0, "usize"); + assert_eq!(c_decl("unsigned int x").0, "u32"); + assert_eq!(c_decl("const OmegaGpuTensor *t").0, "*const OmegaGpuTensor"); + assert_eq!(c_decl("void").0, "()"); + assert_eq!(c_decl("int").1, None); + assert_eq!(c_decl("uint32_t m").1.as_deref(), Some("m")); + } + + #[test] + fn header_parts() { + let src = r#" +/* comment with ; inside */ +#ifndef X +#define X 1u /* abi */ +#define LONG(a) \ + ((a) + 1) +#ifdef __cplusplus +extern "C" { +#endif +typedef struct Foo Foo; +typedef int (*CbFn)(void *ctx, uint64_t task, uint64_t *result); +typedef struct { + uint32_t a, b; // two + char name[64]; + bool ok; +} Info; +int open_it(const char *dir, uint32_t n, Foo **out, Info *info); +void close_it(Foo *h); +uint32_t layout(uint32_t out[4]); +int set_cb(Foo *h, CbFn fn, void *ctx); +const char *rc_name(int rc); +#ifdef __cplusplus +} +#endif +#endif +"#; + let h = parse(src); + assert_eq!(h.structs["Info"], ["a", "b", "name", "ok"]); + assert_eq!( + h.fns["open_it"], + "fn(*const c_char, u32, *mut *mut Foo, *mut Info) -> i32" + ); + assert_eq!(h.fns["close_it"], "fn(*mut Foo) -> ()"); + assert_eq!(h.fns["layout"], "fn(*mut u32) -> u32"); + assert_eq!(h.fns["set_cb"], "fn(*mut Foo, CbFn, *mut c_void) -> i32"); + assert_eq!(h.fns["rc_name"], "fn(i32) -> *const c_char"); + assert_eq!(h.fnptrs["CbFn"], "fn(*mut c_void, u64, *mut u64) -> i32"); + } +} diff --git a/crates/aien-abi-conformance/src/identity.rs b/crates/aien-abi-conformance/src/identity.rs new file mode 100644 index 00000000..7216c8d6 --- /dev/null +++ b/crates/aien-abi-conformance/src/identity.rs @@ -0,0 +1,196 @@ +//! Native archive identity (used from `build.rs`). +//! +//! `native-artifacts.lock` (repository root) records the expected sha256 of each archive built +//! from the pinned omega source, per target triple and C compiler, one line each: +//! +//! ```text +//! +//! ``` +//! +//! omega's archives are byte-reproducible for a given source, compiler and target (the build +//! writes no paths or times into them), so an entry is a real expectation: a built archive that +//! differs from its entry fails the build. A combination with no entry builds, and is reported +//! as `digest unrecorded`, which the qualification entry point does not accept as PASS. +//! A prebuilt archive (`*_LIB`) must come with its expected digest (`*_LIB_SHA256`). + +use std::path::Path; +use std::process::Command; + +pub fn sha256_file(path: &Path) -> Result { + let out = Command::new("sha256sum") + .arg(path) + .output() + .map_err(|e| format!("cannot run sha256sum on {}: {e}", path.display()))?; + if !out.status.success() { + return Err(format!("sha256sum failed on {}", path.display())); + } + let text = String::from_utf8_lossy(&out.stdout); + let d = text.split_whitespace().next().unwrap_or("").to_string(); + if is_sha256(&d) { + Ok(d) + } else { + Err(format!( + "sha256sum printed no digest for {}", + path.display() + )) + } +} + +pub fn is_sha256(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) +} + +/// First line of ` --version` (the compiler identity recorded with each digest). +pub fn cc_version(cc: &str) -> String { + Command::new(cc) + .arg("--version") + .output() + .ok() + .and_then(|o| { + String::from_utf8_lossy(&o.stdout) + .lines() + .next() + .map(|l| l.trim().to_string()) + }) + .unwrap_or_else(|| "unknown".into()) +} + +/// One `native-artifacts.lock` entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockEntry { + pub archive: String, + pub omega: String, + pub target: String, + pub sha256: String, + pub cc: String, +} + +pub fn parse_lock(text: &str) -> Result, String> { + let mut v = Vec::new(); + for (i, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let w: Vec<&str> = line.splitn(5, ' ').collect(); + if w.len() != 5 || !is_sha256(w[3]) || w[1].len() != 40 { + return Err(format!( + "native-artifacts.lock line {}: want ` `: {raw}", + i + 1 + )); + } + v.push(LockEntry { + archive: w[0].into(), + omega: w[1].into(), + target: w[2].into(), + sha256: w[3].into(), + cc: w[4].trim().into(), + }); + } + Ok(v) +} + +/// The recorded digest for this archive, omega commit, target and compiler, if any. +pub fn expected<'a>( + lock: &'a [LockEntry], + archive: &str, + omega: &str, + target: &str, + cc: &str, +) -> Option<&'a LockEntry> { + lock.iter() + .find(|e| e.archive == archive && e.omega == omega && e.target == target && e.cc == cc) +} + +/// Outcome of the digest check for an archive built from source. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Digest { + /// matches its `native-artifacts.lock` entry + Locked, + /// no entry for this (archive, omega, target, compiler) + Unrecorded, +} + +/// Compare a built archive's digest with the lock. `Err` = a recorded digest that differs. +pub fn check_built( + lock: &[LockEntry], + archive: &str, + omega: &str, + target: &str, + cc: &str, + actual: &str, +) -> Result { + match expected(lock, archive, omega, target, cc) { + Some(e) if e.sha256 == actual => Ok(Digest::Locked), + Some(e) => Err(format!( + "{archive} built from omega {omega} for {target} with `{cc}` has sha256 {actual}, native-artifacts.lock expects {}", + e.sha256 + )), + None => Ok(Digest::Unrecorded), + } +} + +/// A prebuilt archive must name its expected digest, and match it. +pub fn check_prebuilt(path: &Path, expected: Option<&str>, var: &str) -> Result { + let Some(want) = expected else { + return Err(format!( + "{} is a prebuilt archive with no expected digest: set {var}= (sha256sum {})", + path.display(), + path.display() + )); + }; + let want = want.trim().to_ascii_lowercase(); + if !is_sha256(&want) { + return Err(format!("{var} must be 64 lowercase hex characters")); + } + let got = sha256_file(path)?; + if got != want { + return Err(format!( + "{} has sha256 {got}, {var} expects {want} (wrong, rebuilt, truncated or corrupted archive)", + path.display() + )); + } + Ok(got) +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: &str = "3eb20f5ec60b465413320000000000000000000000000000000000000000abcd"; + + #[test] + fn lock_lookup_and_mismatch() { + let o = "6c6180cf378075b61291f4565d226eba38b4decd"; + let text = format!("# c\nlibx.a {o} aarch64-unknown-linux-gnu {A} cc (X) 1.2\n"); + let l = parse_lock(&text).unwrap(); + let t = "aarch64-unknown-linux-gnu"; + assert_eq!( + check_built(&l, "libx.a", o, t, "cc (X) 1.2", A), + Ok(Digest::Locked) + ); + assert_eq!( + check_built(&l, "libx.a", o, t, "cc (X) 1.3", A), + Ok(Digest::Unrecorded) + ); + let bad = A.replace('a', "b"); + assert!(check_built(&l, "libx.a", o, t, "cc (X) 1.2", &bad).is_err()); + assert!(parse_lock("libx.a short aarch64 abc cc\n").is_err()); + } + + #[test] + fn prebuilt_needs_and_checks_a_digest() { + let dir = std::env::temp_dir().join(format!("abi-id-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let f = dir.join("lib.a"); + std::fs::write(&f, b"!\n").unwrap(); + let real = sha256_file(&f).unwrap(); + assert!(check_prebuilt(&f, None, "X_SHA256").is_err()); + assert_eq!(check_prebuilt(&f, Some(&real), "X_SHA256").unwrap(), real); + // truncated / corrupted: same name, different bytes + std::fs::write(&f, b"! i32 +//! fn rxc_host_open fn(*const c_char, u32, ...) -> i32 +//! ``` +//! +//! Kinds: `bool c_char i8 u8 i16 u16 i32 u32 i64 u64 f32 f64` (`size_t` is `u64` on the +//! LP64 targets this code runs on). Types in signatures use Rust spelling, canonicalised by +//! [`canon_type`] so `c_int`, `int` and `int32_t` all read `i32`. + +use std::collections::BTreeSet; + +#[derive(Debug, Default, Clone)] +pub struct Manifest { + pub abi: Option<(String, String)>, + pub headers: Vec, + /// (name, size, align) + pub structs: Vec<(String, usize, usize)>, + /// (struct, field, offset, size, kind, count), in declaration order per struct. + pub fields: Vec<(String, String, usize, usize, String, usize)>, + pub consts: Vec<(String, i128)>, + pub fnptrs: Vec<(String, String)>, + pub fns: Vec<(String, String)>, +} + +impl Manifest { + pub fn parse(text: &str) -> Result { + let mut m = Manifest::default(); + for (i, raw) in text.lines().enumerate() { + let line = raw.split('#').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + let bad = |why: &str| format!("manifest line {}: {why}: {raw}", i + 1); + let w: Vec<&str> = line.split_whitespace().collect(); + let num = |s: &str| s.parse::().map_err(|_| bad("not a number")); + match w[0] { + "abi" if w.len() == 3 => m.abi = Some((w[1].into(), w[2].into())), + "header" if w.len() == 2 => m.headers.push(w[1].into()), + "struct" if w.len() == 4 => m.structs.push((w[1].into(), num(w[2])?, num(w[3])?)), + "field" if w.len() == 7 => m.fields.push(( + w[1].into(), + w[2].into(), + num(w[3])?, + num(w[4])?, + w[5].into(), + num(w[6])?, + )), + "const" if w.len() == 3 => m.consts.push(( + w[1].into(), + w[2].parse::().map_err(|_| bad("not an integer"))?, + )), + "fnptr" | "fn" if w.len() >= 3 => { + let rest = line[w[0].len()..].trim_start()[w[1].len()..].trim(); + let sig = canon_sig(rest).ok_or_else(|| bad("bad signature"))?; + if w[0] == "fn" { + m.fns.push((w[1].into(), sig)); + } else { + m.fnptrs.push((w[1].into(), sig)); + } + } + _ => return Err(bad("unknown or malformed line")), + } + } + let mut seen = BTreeSet::new(); + for (s, ..) in &m.structs { + if !seen.insert(s.clone()) { + return Err(format!("manifest: struct {s} listed twice")); + } + } + for (s, f, ..) in &m.fields { + if !seen.contains(s) { + return Err(format!("manifest: field {s}.{f} of an unlisted struct")); + } + } + Ok(m) + } + + /// The comparable facts (everything but `abi` and `header`), one canonical line each, + /// in file order. + pub fn fact_lines(&self) -> Vec { + let mut v = Vec::new(); + for (s, size, align) in &self.structs { + v.push(format!("struct {s} {size} {align}")); + for (fs, f, off, sz, kind, n) in &self.fields { + if fs == s { + v.push(format!("field {s} {f} {off} {sz} {kind} {n}")); + } + } + } + for (n, val) in &self.consts { + v.push(format!("const {n} {val}")); + } + for (n, sig) in &self.fnptrs { + v.push(format!("fnptr {n} {sig}")); + } + for (n, sig) in &self.fns { + v.push(format!("fn {n} {sig}")); + } + v + } + + pub fn field_names(&self, s: &str) -> Vec { + self.fields + .iter() + .filter(|f| f.0 == s) + .map(|f| f.1.clone()) + .collect() + } +} + +/// Canonical spelling of one Rust-syntax type: whitespace removed, `Option<..>` (a nullable +/// function pointer has the same ABI as the bare one) and `std::os::raw::` paths dropped, +/// C-alias integers mapped to their fixed-width names, then `*const `/`*mut ` re-spaced. +pub fn canon_type(t: &str) -> String { + let mut s: String = t.chars().filter(|c| !c.is_whitespace()).collect(); + for p in [ + "std::os::raw::", + "core::ffi::", + "std::ffi::", + "::std::os::raw::", + ] { + s = s.replace(p, ""); + } + while let Some(inner) = s.strip_prefix("Option<").and_then(|r| r.strip_suffix('>')) { + s = inner.to_string(); + } + let mut out = String::new(); + let mut rest = s.as_str(); + loop { + if let Some(r) = rest.strip_prefix("*const") { + out.push_str("*const "); + rest = r; + } else if let Some(r) = rest.strip_prefix("*mut") { + out.push_str("*mut "); + rest = r; + } else { + break; + } + } + let base = match rest { + "c_int" => "i32", + "c_uint" => "u32", + "c_long" | "c_longlong" => "i64", + "c_ulong" | "c_ulonglong" => "u64", + "c_short" => "i16", + "c_ushort" => "u16", + "c_float" => "f32", + "c_double" => "f64", + "c_schar" => "i8", + "c_uchar" => "u8", + "" | "()" => "()", + other => other, + }; + out.push_str(base); + out +} + +/// Canonical signature `fn(a, b) -> r` from either `fn(a, b) -> r`, `(a, b) -> r` or a +/// parameter list plus return type assembled by the callers. +pub fn canon_sig(s: &str) -> Option { + let s = s.trim(); + let s = s.strip_prefix("fn").unwrap_or(s).trim(); + let open = s.find('(')?; + let mut depth = 0i32; + let mut close = None; + for (i, c) in s.char_indices().skip(open) { + match c { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 { + close = Some(i); + break; + } + } + _ => {} + } + } + let close = close?; + let params = split_top(&s[open + 1..close]); + let ret = s[close + 1..].trim(); + let ret = ret.strip_prefix("->").map(str::trim).unwrap_or("()"); + Some(make_sig(¶ms, ret)) +} + +pub(crate) fn make_sig>(params: &[S], ret: &str) -> String { + let ps: Vec = params + .iter() + .map(|p| canon_type(p.as_ref())) + .filter(|p| p != "()") + .collect(); + format!("fn({}) -> {}", ps.join(", "), canon_type(ret)) +} + +/// Split on commas that are not inside `<>`, `()` or `[]`. +pub(crate) fn split_top(s: &str) -> Vec { + let mut out = Vec::new(); + let mut depth = 0i32; + let mut cur = String::new(); + for c in s.chars() { + match c { + '<' | '(' | '[' => depth += 1, + '>' | ')' | ']' => depth -= 1, + ',' if depth == 0 => { + out.push(cur.trim().to_string()); + cur.clear(); + continue; + } + _ => {} + } + cur.push(c); + } + if !cur.trim().is_empty() { + out.push(cur.trim().to_string()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_types() { + assert_eq!(canon_type("* const c_char"), "*const c_char"); + assert_eq!(canon_type("*mut *mut RxcHost"), "*mut *mut RxcHost"); + assert_eq!(canon_type("Option"), "RxcHostVerifyFn"); + assert_eq!(canon_type("c_int"), "i32"); + assert_eq!(canon_type(""), "()"); + assert_eq!( + canon_sig("fn(*mut c_void,u64, * mut u64)->c_int").unwrap(), + "fn(*mut c_void, u64, *mut u64) -> i32" + ); + assert_eq!(canon_sig("fn()").unwrap(), "fn() -> ()"); + } + + #[test] + fn parse_round_trip_and_refusals() { + let t = "abi x 2\nheader a.h\nstruct S 8 4\nfield S a 0 4 u32 1\nfield S b 4 4 i32 1\nconst K -3\nfn f fn(u32) -> i32\n"; + let m = Manifest::parse(t).unwrap(); + assert_eq!(m.fact_lines().len(), 5); + assert_eq!(m.field_names("S"), ["a", "b"]); + assert!(Manifest::parse("field T a 0 4 u32 1\n").is_err()); + assert!(Manifest::parse("struct S 8\n").is_err()); + assert!(Manifest::parse("struct S 8 4\nstruct S 8 4\n").is_err()); + } +} diff --git a/crates/aien-abi-conformance/src/native.rs b/crates/aien-abi-conformance/src/native.rs new file mode 100644 index 00000000..06322426 --- /dev/null +++ b/crates/aien-abi-conformance/src/native.rs @@ -0,0 +1,113 @@ +//! Run-time view of what a binary linked (filled from the `build.rs` identity record). + +/// One native component as linked into this binary. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NativeIdentity { + pub component: &'static str, + /// stub | pinned-source | dev-override | prebuilt + pub link: &'static str, + /// pass | symbols-only | unchecked | none + pub abi: &'static str, + /// locked | unrecorded | prebuilt-match | none + pub digest: &'static str, + pub archive_sha256: &'static str, + pub source_sha: &'static str, + pub aienos_lock: &'static str, + pub physics_lock: &'static str, + pub target: &'static str, + pub cc: &'static str, +} + +impl NativeIdentity { + /// Release-grade: built from the pinned omega source, C ABI checked, digest recorded + /// and matched. A stub, a developer override or a prebuilt archive never qualifies. + pub fn qualifies(&self) -> bool { + self.link == "pinned-source" && self.abi == "pass" && self.digest == "locked" + } + + /// Why [`Self::qualifies`] is false (empty when it is true). + pub fn gaps(&self) -> Vec<&'static str> { + let mut v = Vec::new(); + if self.link != "pinned-source" { + v.push("not built from the pinned omega source"); + } + if self.abi != "pass" { + v.push("C ABI not checked against the manifest"); + } + if self.digest != "locked" { + v.push("archive digest not matched against native-artifacts.lock"); + } + v + } + + /// One JSON object (no dependencies; every value is a plain ASCII token). + pub fn to_json(&self) -> String { + let esc = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\""); + format!( + "{{\"component\":\"{}\",\"link\":\"{}\",\"abi\":\"{}\",\"digest\":\"{}\",\"archive_sha256\":\"{}\",\"source_sha\":\"{}\",\"aienos_lock\":\"{}\",\"physics_lock\":\"{}\",\"target\":\"{}\",\"cc\":\"{}\",\"qualifies\":{}}}", + esc(self.component), + esc(self.link), + esc(self.abi), + esc(self.digest), + esc(self.archive_sha256), + esc(self.source_sha), + esc(self.aienos_lock), + esc(self.physics_lock), + esc(self.target), + esc(self.cc), + self.qualifies() + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_a_pinned_checked_locked_build_qualifies() { + let ok = NativeIdentity { + component: "x", + link: "pinned-source", + abi: "pass", + digest: "locked", + archive_sha256: "a", + source_sha: "b", + aienos_lock: "", + physics_lock: "", + target: "t", + cc: "cc \"q\"", + }; + assert!(ok.qualifies() && ok.gaps().is_empty()); + assert!(ok.to_json().contains("\"qualifies\":true")); + assert!(ok.to_json().contains("cc \\\"q\\\"")); + for bad in [ + NativeIdentity { + link: "stub", + abi: "none", + digest: "none", + ..ok + }, + NativeIdentity { + link: "prebuilt", + abi: "symbols-only", + digest: "prebuilt-match", + ..ok + }, + NativeIdentity { + link: "dev-override", + ..ok + }, + NativeIdentity { + digest: "unrecorded", + ..ok + }, + NativeIdentity { + abi: "unchecked", + ..ok + }, + ] { + assert!(!bad.qualifies() && !bad.gaps().is_empty(), "{bad:?}"); + } + } +} diff --git a/crates/aien-abi-conformance/src/probe.rs b/crates/aien-abi-conformance/src/probe.rs new file mode 100644 index 00000000..f3d23fed --- /dev/null +++ b/crates/aien-abi-conformance/src/probe.rs @@ -0,0 +1,239 @@ +//! C side of the check (used from `build.rs`): headers, a compiled layout probe, and `nm`. + +use crate::header; +use crate::manifest::Manifest; +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Inputs for [`check_c`]. +pub struct CCheck<'a> { + pub manifest: &'a Manifest, + /// Directory the manifest's `header` paths are relative to (the omega checkout). + pub root: &'a Path, + /// Extra `-I` directories the headers need (omega `src`, physics `m16`, ...). + pub includes: Vec, + /// The archive that will be linked; every manifest `fn` must be a defined global symbol. + /// `None` skips the symbol check (header-only use in tests). + pub archive: Option<&'a Path>, + /// Scratch directory for the probe source and binary. + pub work: &'a Path, + /// C compiler (`$CC` or `cc`). + pub cc: String, +} + +/// Run every C-side check. `Ok(report)` lists what was checked; `Err` lists every mismatch. +pub fn check_c(c: &CCheck) -> Result> { + let m = c.manifest; + let mut errs = Vec::new(); + let mut report = String::new(); + + // 1. Headers: field names and order, prototypes, callback typedefs. + let mut parsed = header::Header::default(); + for h in &m.headers { + let p = c.root.join(h); + match std::fs::read_to_string(&p) { + Ok(src) => { + let one = header::parse(&src); + parsed.structs.extend(one.structs); + parsed.fns.extend(one.fns); + parsed.fnptrs.extend(one.fnptrs); + } + Err(e) => errs.push(format!("cannot read header {}: {e}", p.display())), + } + } + for (s, ..) in &m.structs { + let want = m.field_names(s); + match parsed.structs.get(s) { + None => errs.push(format!("struct {s}: not declared in the headers")), + Some(got) if *got != want => errs.push(format!( + "struct {s}: C fields {got:?} != manifest fields {want:?} (added, removed, renamed or reordered)" + )), + Some(_) => {} + } + } + for (n, sig) in &m.fns { + match parsed.fns.get(n) { + None => errs.push(format!("fn {n}: no prototype in the headers")), + Some(got) if got != sig => { + errs.push(format!("fn {n}: C signature `{got}` != manifest `{sig}`")) + } + Some(_) => {} + } + } + for (n, sig) in &m.fnptrs { + match parsed.fnptrs.get(n) { + None => errs.push(format!("fnptr {n}: no typedef in the headers")), + Some(got) if got != sig => errs.push(format!( + "fnptr {n}: C signature `{got}` != manifest `{sig}`" + )), + Some(_) => {} + } + } + let _ = writeln!( + report, + "headers: {} structs, {} functions, {} callback types", + m.structs.len(), + m.fns.len(), + m.fnptrs.len() + ); + + // 2. Probe: compiled against the same headers, prints the layout facts. + match run_probe(c) { + Ok(lines) => { + let want: Vec = m + .fact_lines() + .into_iter() + .filter(|l| !l.starts_with("fn") && !l.starts_with("fnptr")) + .collect(); + for w in &want { + if !lines.contains(w) { + let n = if w.starts_with("field ") { 3 } else { 2 }; + let key: Vec<&str> = w.split_whitespace().take(n).collect(); + let key = key.join(" "); + let got = lines + .iter() + .find(|l| l.starts_with(&format!("{key} "))) + .cloned() + .unwrap_or_else(|| "(absent)".into()); + errs.push(format!("layout: C `{got}` != manifest `{w}`")); + } + } + let _ = writeln!(report, "probe: {} layout/constant facts match", want.len()); + } + Err(e) => errs.push(e), + } + + // 3. Symbols: every declared function is defined by the archive. + if let Some(a) = c.archive { + match defined_symbols(a) { + Ok(syms) => { + for (n, _) in &m.fns { + if !syms.iter().any(|s| s == n) { + errs.push(format!("symbol {n}: not defined in {}", a.display())); + } + } + let _ = writeln!(report, "nm: {} functions defined", m.fns.len()); + } + Err(e) => errs.push(e), + } + } + if errs.is_empty() { + Ok(report) + } else { + Err(errs) + } +} + +/// The probe's C source for a manifest (public for tests and for the evidence record). +pub fn probe_source(m: &Manifest) -> String { + let mut s = String::from( + "#include \n#include \n#include \n#include \n", + ); + for h in &m.headers { + let _ = writeln!(s, "#include \"{h}\""); + } + s.push_str( + "_Static_assert(sizeof(long) == 8 && sizeof(void *) == 8, \"LP64 only\");\n\ + #define K(x) _Generic((x), _Bool: \"bool\", char: \"c_char\", signed char: \"i8\", \ + unsigned char: \"u8\", short: \"i16\", unsigned short: \"u16\", int: \"i32\", \ + unsigned int: \"u32\", long: \"i64\", unsigned long: \"u64\", long long: \"i64\", \ + unsigned long long: \"u64\", float: \"f32\", double: \"f64\", default: \"other\")\n\ + int main(void) {\n", + ); + for (st, size, align) in &m.structs { + let _ = (size, align); + let _ = writeln!( + s, + " printf(\"struct {st} %zu %zu\\n\", sizeof({st}), _Alignof({st}));" + ); + for (fs, f, _, _, _, n) in &m.fields { + if fs != st { + continue; + } + let el = if *n > 1 { + format!("((({st} *)0)->{f}[0])") + } else { + format!("((({st} *)0)->{f})") + }; + let _ = writeln!( + s, + " printf(\"field {st} {f} %zu %zu %s %zu\\n\", offsetof({st}, {f}), \ + sizeof((({st} *)0)->{f}), K({el}), sizeof((({st} *)0)->{f}) / sizeof({el}));" + ); + } + } + for (n, _) in &m.consts { + let _ = writeln!(s, " printf(\"const {n} %lld\\n\", (long long)({n}));"); + } + s.push_str(" return 0;\n}\n"); + s +} + +fn run_probe(c: &CCheck) -> Result, String> { + std::fs::create_dir_all(c.work).map_err(|e| format!("probe dir: {e}"))?; + let src = c.work.join("abi_probe.c"); + let bin = c.work.join("abi_probe"); + std::fs::write(&src, probe_source(c.manifest)).map_err(|e| format!("probe source: {e}"))?; + let mut cmd = Command::new(&c.cc); + cmd.arg("-std=gnu11") + .arg("-D_GNU_SOURCE") + .arg("-w") + .arg("-I") + .arg(c.root); + for i in &c.includes { + cmd.arg("-I").arg(i); + } + let out = cmd + .arg("-o") + .arg(&bin) + .arg(&src) + .output() + .map_err(|e| format!("cannot run {}: {e}", c.cc))?; + if !out.status.success() { + let err = String::from_utf8_lossy(&out.stderr); + let first: Vec<&str> = err + .lines() + .filter(|l| l.contains("error")) + .take(6) + .collect(); + return Err(format!( + "layout probe did not compile against the headers (a field or constant the manifest names is missing or changed shape): {}", + first.join(" | ") + )); + } + let run = Command::new(&bin) + .output() + .map_err(|e| format!("cannot run the layout probe: {e}"))?; + if !run.status.success() { + return Err("layout probe exited nonzero".into()); + } + Ok(String::from_utf8_lossy(&run.stdout) + .lines() + .map(str::to_string) + .collect()) +} + +/// Global symbols the archive defines (`nm -g --defined-only`). +pub fn defined_symbols(archive: &Path) -> Result, String> { + let out = Command::new("nm") + .arg("-g") + .arg("--defined-only") + .arg(archive) + .output() + .map_err(|e| format!("cannot run nm on {}: {e}", archive.display()))?; + if !out.status.success() { + return Err(format!( + "nm failed on {} (corrupt or truncated archive?): {}", + archive.display(), + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&out.stdout) + .lines() + .filter_map(|l| { + let w: Vec<&str> = l.split_whitespace().collect(); + (w.len() == 3 && matches!(w[1], "T" | "D" | "R" | "B")).then(|| w[2].to_string()) + }) + .collect()) +} diff --git a/crates/aien-abi-conformance/src/rust.rs b/crates/aien-abi-conformance/src/rust.rs new file mode 100644 index 00000000..88dcb6df --- /dev/null +++ b/crates/aien-abi-conformance/src/rust.rs @@ -0,0 +1,268 @@ +//! Rust side: declaration macros that record what they declare, and the manifest renderer. + +use crate::manifest::{canon_sig, make_sig}; + +/// Kind of a field's element type, as the C probe names it. +pub trait CKind { + const KIND: &'static str; + const COUNT: usize = 1; +} + +macro_rules! ckind { + ($($t:ty => $k:literal),*) => { $(impl CKind for $t { const KIND: &'static str = $k; })* }; +} +ckind!(bool => "bool", i8 => "i8", u8 => "u8", i16 => "i16", u16 => "u16", i32 => "i32", + u32 => "u32", i64 => "i64", u64 => "u64", f32 => "f32", f64 => "f64"); +#[cfg(target_pointer_width = "64")] +ckind!(usize => "u64", isize => "i64"); + +impl CKind for [T; N] { + const KIND: &'static str = T::KIND; + const COUNT: usize = N; +} + +/// One field as recorded by [`abi_struct!`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Field { + pub name: &'static str, + pub offset: usize, + pub size: usize, + pub kind: &'static str, + pub count: usize, +} + +impl Field { + /// `ty` is the declared type's tokens: a `c_char` element is reported as `c_char` + /// (the C probe's name for plain `char`), whatever its signedness on this target. + pub fn of(name: &'static str, offset: usize, ty: &'static str) -> Field { + let kind = if ty.contains("c_char") { + "c_char" + } else { + T::KIND + }; + Field { + name, + offset, + size: std::mem::size_of::(), + kind, + count: T::COUNT, + } + } +} + +/// A `#[repr(C)]` struct declared through [`abi_struct!`]. +pub trait AbiStruct: Sized { + const NAME: &'static str; + fn fields() -> Vec; + fn manifest_lines() -> Vec { + let mut v = vec![format!( + "struct {} {} {}", + Self::NAME, + std::mem::size_of::(), + std::mem::align_of::() + )]; + for f in Self::fields() { + v.push(format!( + "field {} {} {} {} {} {}", + Self::NAME, + f.name, + f.offset, + f.size, + f.kind, + f.count + )); + } + v + } +} + +/// A recorded extern or callback signature: (name, return type tokens, parameter type tokens). +pub type FnSig = (&'static str, &'static str, &'static [&'static str]); + +/// Everything one boundary's Rust mirror declares. +#[derive(Default)] +pub struct RustAbi { + pub structs: Vec>, + pub consts: Vec<(&'static str, i128)>, + pub fnptrs: Vec, + pub fns: Vec, +} + +impl RustAbi { + pub fn with_struct(mut self) -> Self { + self.structs.push(T::manifest_lines()); + self + } + pub fn with_consts(mut self, c: &[(&'static str, i128)]) -> Self { + self.consts.extend_from_slice(c); + self + } + pub fn with_fnptrs(mut self, f: &[FnSig]) -> Self { + self.fnptrs.extend_from_slice(f); + self + } + pub fn with_fns(mut self, f: &[FnSig]) -> Self { + self.fns.extend_from_slice(f); + self + } +} + +fn sig_text(ret: &str, params: &[&str]) -> String { + let s = make_sig(params, ret); + canon_sig(&s).unwrap_or(s) +} + +/// The Rust mirror rendered as manifest fact lines, in the same order as +/// [`crate::Manifest::fact_lines`] renders a file (structs with their fields, constants, +/// callbacks, functions). +pub fn rust_manifest(abi: &RustAbi) -> Vec { + let mut v: Vec = abi.structs.iter().flatten().cloned().collect(); + for (n, val) in &abi.consts { + v.push(format!("const {n} {val}")); + } + for (n, r, p) in &abi.fnptrs { + v.push(format!("fnptr {n} {}", sig_text(r, p))); + } + for (n, r, p) in &abi.fns { + v.push(format!("fn {n} {}", sig_text(r, p))); + } + v +} + +/// Declare a `#[repr(C)]` struct and record its fields in declaration order +/// (implements [`AbiStruct`]). Attributes and doc comments pass through unchanged. +#[macro_export] +macro_rules! abi_struct { + ($(#[$m:meta])* $vis:vis struct $name:ident { + $($(#[$fm:meta])* $fvis:vis $f:ident : $t:ty),* $(,)? + }) => { + $(#[$m])* $vis struct $name { $($(#[$fm])* $fvis $f : $t),* } + impl $crate::AbiStruct for $name { + const NAME: &'static str = stringify!($name); + fn fields() -> ::std::vec::Vec<$crate::Field> { + ::std::vec![$($crate::Field::of::<$t>( + stringify!($f), ::core::mem::offset_of!($name, $f), stringify!($t))),*] + } + } + }; +} + +/// Declare an `extern "C"` block (attributes on the block, such as a `cfg`, apply to it as +/// usual) and a `pub const $table: &[FnSig]` naming every function's types. The table exists +/// in stub builds too, so the signatures are checked even where nothing links. +#[macro_export] +macro_rules! abi_externs { + ($table:ident; $(#[$bm:meta])* extern "C" { + $( $(#[$m:meta])* pub fn $name:ident ( $($p:ident : $t:ty),* $(,)? ) $(-> $r:ty)? ; )* + }) => { + $(#[$bm])* extern "C" { $( $(#[$m])* pub fn $name($($p: $t),*) $(-> $r)?; )* } + pub const $table: &[$crate::FnSig] = + &[$( (stringify!($name), stringify!($($r)?), &[$(stringify!($t)),*]) ),*]; + }; +} + +/// Declare `unsafe extern "C" fn` callback types and a table of their signatures. +#[macro_export] +macro_rules! abi_fnptr { + ($table:ident; $( $(#[$m:meta])* pub type $name:ident = + unsafe extern "C" fn( $($p:ident : $t:ty),* $(,)? ) $(-> $r:ty)? ; )*) => { + $( $(#[$m])* pub type $name = unsafe extern "C" fn($($p: $t),*) $(-> $r)?; )* + pub const $table: &[$crate::FnSig] = + &[$( (stringify!($name), stringify!($($r)?), &[$(stringify!($t)),*]) ),*]; + }; +} + +/// Declare integer constants mirrored from C and a table of their values. +#[macro_export] +macro_rules! abi_consts { + ($table:ident; $( $(#[$m:meta])* pub const $name:ident : $t:ty = $v:expr ; )*) => { + $( $(#[$m])* pub const $name: $t = $v; )* + pub const $table: &[(&str, i128)] = &[$( (stringify!($name), $name as i128) ),*]; + }; +} + +/// Compare a Rust mirror with its checked-in manifest file. With `AIEN_ABI_BLESS=1` the file's +/// fact lines are rewritten from the Rust side instead (its `abi`/`header` lines and comments +/// are kept); the C side then has to agree in `build.rs` before anything links. +pub fn assert_manifest(abi: &RustAbi, path: &std::path::Path) { + let text = std::fs::read_to_string(path) + .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); + let rust = rust_manifest(abi); + if std::env::var("AIEN_ABI_BLESS").as_deref() == Ok("1") { + let mut out: Vec = text + .lines() + .take_while(|l| { + let t = l.trim_start(); + t.is_empty() + || t.starts_with('#') + || t.starts_with("abi ") + || t.starts_with("header ") + }) + .map(str::to_string) + .collect(); + out.extend(rust.iter().cloned()); + std::fs::write(path, out.join("\n") + "\n").expect("write manifest"); + return; + } + let m = crate::Manifest::parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let file = m.fact_lines(); + if file != rust { + let only_rust: Vec<&String> = rust.iter().filter(|l| !file.contains(l)).collect(); + let only_file: Vec<&String> = file.iter().filter(|l| !rust.contains(l)).collect(); + panic!( + "Rust FFI declarations differ from {}\n Rust only: {only_rust:#?}\n manifest only: {only_file:#?}\n (order differs if both are empty). \ + An intended ABI change updates the manifest (AIEN_ABI_BLESS=1) and the omega pin together.", + path.display() + ); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::raw::{c_char, c_int, c_void}; + + crate::abi_struct! { + #[repr(C)] + #[derive(Clone, Copy)] + pub struct Demo { + /// doc on a field + pub a: u8, + pub name: [c_char; 4], + pub b: u64, + pub flag: bool, + pub n: usize, + } + } + crate::abi_fnptr! { CB; #[allow(dead_code)] pub type Cb = unsafe extern "C" fn(ctx: *mut c_void, x: u64) -> c_int; } + crate::abi_externs! { FNS; #[cfg(any())] extern "C" { + /// doc + pub fn demo_open(p: *const c_char, cb: Option, out: *mut *mut Demo) -> c_int; + pub fn demo_close(); + } } + crate::abi_consts! { K; pub const DEMO_E: c_int = -3; pub const DEMO_V: u32 = 2; } + + #[test] + fn macros_record_layout_and_signatures() { + let abi = RustAbi::default() + .with_struct::() + .with_consts(K) + .with_fnptrs(CB) + .with_fns(FNS); + let got = rust_manifest(&abi); + let want = [ + "struct Demo 32 8", + "field Demo a 0 1 u8 1", + "field Demo name 1 4 c_char 4", + "field Demo b 8 8 u64 1", + "field Demo flag 16 1 bool 1", + "field Demo n 24 8 u64 1", + "const DEMO_E -3", + "const DEMO_V 2", + "fnptr Cb fn(*mut c_void, u64) -> i32", + "fn demo_open fn(*const c_char, Cb, *mut *mut Demo) -> i32", + "fn demo_close fn() -> ()", + ]; + assert_eq!(got, want); + } +} diff --git a/crates/aien-abi-conformance/tests/c_side.rs b/crates/aien-abi-conformance/tests/c_side.rs new file mode 100644 index 00000000..65e4b6c9 --- /dev/null +++ b/crates/aien-abi-conformance/tests/c_side.rs @@ -0,0 +1,214 @@ +//! The C-side check against small synthetic headers and archives: one compatible case and one +//! negative case per kind of drift the mission names (equal-size reorder, width, signedness, +//! parameter type, ABI version constant, missing symbol, corrupted archive). +//! Needs `cc`, `ar` and `nm` (the same tools the native build needs). + +use aien_abi_conformance::{check_c, CCheck, Manifest}; +use std::path::PathBuf; +use std::process::Command; + +const MANIFEST: &str = "\ +abi demo 2 +header demo.h +struct DemoInfo 24 8 +field DemoInfo version 0 4 u32 1 +field DemoInfo rc 4 4 i32 1 +field DemoInfo name 8 4 c_char 4 +field DemoInfo ok 12 1 bool 1 +field DemoInfo total 16 8 u64 1 +const DEMO_ABI_VERSION 2 +const DEMO_E_ARG -1 +fnptr DemoCb fn(*mut c_void, u64) -> i32 +fn demo_open fn(*const c_char, u32, DemoCb, *mut DemoInfo) -> i32 +fn demo_close fn(*mut c_void) -> () +"; + +const HEADER: &str = "\ +#include +#include +#define DEMO_ABI_VERSION 2u +enum { DEMO_OK = 0, DEMO_E_ARG = -1 }; +typedef int (*DemoCb)(void *ctx, uint64_t x); +typedef struct { + uint32_t version; + int32_t rc; + char name[4]; + bool ok; + uint64_t total; +} DemoInfo; +int demo_open(const char *dir, uint32_t n, DemoCb cb, DemoInfo *out); +void demo_close(void *h); +"; + +const SOURCE: &str = "\ +#include \"demo.h\" +int demo_open(const char *dir, uint32_t n, DemoCb cb, DemoInfo *out) { (void)dir; (void)n; (void)cb; (void)out; return 0; } +void demo_close(void *h) { (void)h; } +"; + +struct Case { + dir: PathBuf, +} + +impl Case { + fn new(tag: &str, header: &str, source: &str) -> Case { + let dir = std::env::temp_dir().join(format!("abi-c-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("demo.h"), header).unwrap(); + std::fs::write(dir.join("demo.c"), source).unwrap(); + let ok = Command::new("cc") + .current_dir(&dir) + .args(["-c", "-o", "demo.o", "demo.c"]) + .status() + .unwrap() + .success(); + assert!(ok, "cc demo.c"); + let ok = Command::new("ar") + .current_dir(&dir) + .args(["rcs", "libdemo.a", "demo.o"]) + .status() + .unwrap() + .success(); + assert!(ok, "ar"); + Case { dir } + } + + fn check(&self, manifest: &str) -> Result> { + let m = Manifest::parse(manifest).unwrap(); + let archive = self.dir.join("libdemo.a"); + let work = self.dir.join("probe"); + check_c(&CCheck { + manifest: &m, + root: &self.dir, + includes: vec![], + archive: Some(archive.as_path()), + work: work.as_path(), + cc: "cc".into(), + }) + } +} + +impl Drop for Case { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.dir); + } +} + +fn expect_err(r: Result>, needle: &str) { + match r { + Ok(rep) => panic!("expected a failure mentioning `{needle}`, got PASS:\n{rep}"), + Err(e) => assert!( + e.iter().any(|l| l.contains(needle)), + "no error mentions `{needle}`: {e:#?}" + ), + } +} + +#[test] +fn compatible_header_and_archive_pass() { + let c = Case::new("ok", HEADER, SOURCE); + let rep = c.check(MANIFEST).expect("compatible case must pass"); + assert!( + rep.contains("probe: 8 layout/constant facts match"), + "{rep}" + ); +} + +#[test] +fn equal_size_reorder_is_caught() { + // version and rc swapped: same size, same alignment, same total + let h = HEADER.replace( + " uint32_t version;\n int32_t rc;", + " int32_t rc;\n uint32_t version;", + ); + let c = Case::new("reorder", &h, SOURCE); + expect_err(c.check(MANIFEST), "reordered"); + expect_err(c.check(MANIFEST), "field DemoInfo version 4 4 u32 1"); +} + +#[test] +fn width_change_is_caught() { + let h = HEADER.replace("uint32_t version;", "uint64_t version;"); + let c = Case::new("width", &h, SOURCE); + expect_err(c.check(MANIFEST), "struct DemoInfo"); +} + +#[test] +fn signedness_change_is_caught() { + let h = HEADER.replace("int32_t rc;", "uint32_t rc;"); + let c = Case::new("sign", &h, SOURCE); + expect_err(c.check(MANIFEST), "field DemoInfo rc 4 4 u32 1"); +} + +#[test] +fn bool_to_byte_change_is_caught() { + let h = HEADER.replace("bool ok;", "uint8_t ok;"); + let c = Case::new("bool", &h, SOURCE); + expect_err(c.check(MANIFEST), "field DemoInfo ok 12 1 u8 1"); +} + +#[test] +fn parameter_type_change_is_caught() { + let h = HEADER.replace( + "int demo_open(const char *dir, uint32_t n,", + "int demo_open(const char *dir, uint64_t n,", + ); + let s = SOURCE.replace("uint32_t n", "uint64_t n"); + let c = Case::new("param", &h, &s); + expect_err(c.check(MANIFEST), "fn demo_open: C signature"); +} + +#[test] +fn callback_signature_change_is_caught() { + let h = HEADER.replace("(void *ctx, uint64_t x)", "(void *ctx, uint32_t x)"); + let c = Case::new("cb", &h, SOURCE); + expect_err(c.check(MANIFEST), "fnptr DemoCb"); +} + +#[test] +fn abi_version_mismatch_is_caught() { + let h = HEADER.replace("#define DEMO_ABI_VERSION 2u", "#define DEMO_ABI_VERSION 3u"); + let c = Case::new("ver", &h, SOURCE); + expect_err(c.check(MANIFEST), "const DEMO_ABI_VERSION 3"); +} + +#[test] +fn removed_field_is_caught_even_when_size_is_kept() { + // `ok` dropped: the struct keeps 24 bytes because of padding + let h = HEADER.replace(" bool ok;\n", ""); + let c = Case::new("drop", &h, SOURCE); + let r = c.check(MANIFEST); + expect_err(r, "reordered"); +} + +#[test] +fn missing_symbol_is_caught() { + let s = SOURCE.replace("void demo_close(void *h) { (void)h; }\n", ""); + let c = Case::new("sym", HEADER, &s); + expect_err(c.check(MANIFEST), "symbol demo_close: not defined"); +} + +#[test] +fn corrupted_archive_is_caught() { + let c = Case::new("corrupt", HEADER, SOURCE); + let a = c.dir.join("libdemo.a"); + let bytes = std::fs::read(&a).unwrap(); + std::fs::write(&a, &bytes[..bytes.len() / 3]).unwrap(); + let r = c.check(MANIFEST); + match r { + Ok(rep) => panic!("truncated archive passed: {rep}"), + Err(e) => assert!( + e.iter() + .any(|l| l.contains("nm failed") || l.contains("not defined")), + "{e:#?}" + ), + } +} + +#[test] +fn missing_header_struct_is_caught() { + let c = Case::new("nostruct", HEADER, SOURCE); + let m = format!("{MANIFEST}struct Ghost 8 8\nfield Ghost a 0 8 u64 1\n"); + expect_err(c.check(&m), "struct Ghost: not declared"); +} diff --git a/crates/aien-omega-compose/Cargo.toml b/crates/aien-omega-compose/Cargo.toml index 53978fe6..c4c10bfb 100644 --- a/crates/aien-omega-compose/Cargo.toml +++ b/crates/aien-omega-compose/Cargo.toml @@ -11,7 +11,11 @@ build = "build.rs" links = "rx_compose" [dependencies] +aien-abi-conformance = { path = "../aien-abi-conformance" } sha2 = "0.10" +[build-dependencies] +aien-abi-conformance = { path = "../aien-abi-conformance" } + [dev-dependencies] tempfile = "3.10" diff --git a/crates/aien-omega-compose/abi/rxc_host_abi.manifest b/crates/aien-omega-compose/abi/rxc_host_abi.manifest new file mode 100644 index 00000000..3cf0e6d6 --- /dev/null +++ b/crates/aien-omega-compose/abi/rxc_host_abi.manifest @@ -0,0 +1,118 @@ +# The rxc_host C ABI contract (omega src/runtime/rxc_host_abi.h) that aien-omega-compose +# mirrors in src/ffi.rs. Checked from both sides: tests/abi_manifest.rs (Rust declarations, +# every build) and build.rs (pinned C header, compiled layout probe, archive symbols). +# Format: aien-abi-conformance src/manifest.rs. Regenerate the fact lines from Rust with +# AIEN_ABI_BLESS=1 cargo test -p aien-omega-compose --test abi_manifest +# only together with the omega.lock change that makes the C side agree. +abi rxc_host 2 +header src/runtime/rxc_host_abi.h +struct RxcHostInfo 88 8 +field RxcHostInfo abi_version 0 4 u32 1 +field RxcHostInfo machine_root 4 1 u8 1 +field RxcHostInfo machine_id 5 32 u8 32 +field RxcHostInfo machine_id_was_stored 40 4 u32 1 +field RxcHostInfo tail_torn 44 4 u32 1 +field RxcHostInfo opened 48 4 u32 1 +field RxcHostInfo open_rc 52 4 i32 1 +field RxcHostInfo records 56 8 u64 1 +field RxcHostInfo recovered_record 64 8 u64 1 +field RxcHostInfo rolled_back 72 4 u32 1 +field RxcHostInfo recovered_completed 76 4 u32 1 +field RxcHostInfo anchor_unknown 80 4 u32 1 +field RxcHostInfo n_skills 84 4 u32 1 +struct RxcHostResult 168 8 +field RxcHostResult run_rc 0 4 i32 1 +field RxcHostResult outcome 4 4 i32 1 +field RxcHostResult committed 8 4 u32 1 +field RxcHostResult n_branches 12 4 u32 1 +field RxcHostResult branches_reclaimed 16 4 u32 1 +field RxcHostResult winner 20 4 u32 1 +field RxcHostResult winner_skill 24 4 u32 1 +field RxcHostResult aegis_pass_mask 28 4 u32 1 +field RxcHostResult task 32 8 u64 1 +field RxcHostResult result 40 8 u64 1 +field RxcHostResult cx_goal 48 8 u64 1 +field RxcHostResult cx_candidate 56 16 u64 2 +field RxcHostResult cx_evidence 72 8 u64 1 +field RxcHostResult cx_promotion 80 8 u64 1 +field RxcHostResult cx_admission 88 16 u64 2 +field RxcHostResult winner_digest 104 32 u8 32 +field RxcHostResult record_digest 136 32 u8 32 +struct RxcHostRecord 120 8 +field RxcHostRecord id 0 8 u64 1 +field RxcHostRecord cls 8 4 u32 1 +field RxcHostRecord kind 12 4 u32 1 +field RxcHostRecord subject 16 8 u64 1 +field RxcHostRecord t 24 8 u64 1 +field RxcHostRecord generation 32 8 u64 1 +field RxcHostRecord tag 40 8 u64 1 +field RxcHostRecord links 48 32 u64 4 +field RxcHostRecord n_payload 80 4 u32 1 +field RxcHostRecord verified 84 4 u32 1 +field RxcHostRecord digest 88 32 u8 32 +struct RxcHostRepair 160 8 +field RxcHostRepair repaired 0 4 u32 1 +field RxcHostRepair tail_torn 4 4 u32 1 +field RxcHostRepair anchor_present 8 4 u32 1 +field RxcHostRepair cause 12 4 i32 1 +field RxcHostRepair opens 16 4 u32 1 +field RxcHostRepair open_rc 20 4 i32 1 +field RxcHostRepair rolled_back 24 4 u32 1 +field RxcHostRepair recovered_completed 28 4 u32 1 +field RxcHostRepair cut_lo 32 8 u64 1 +field RxcHostRepair cut_hi 40 8 u64 1 +field RxcHostRepair partial_records 48 8 u64 1 +field RxcHostRepair anchor_records 56 8 u64 1 +field RxcHostRepair records_kept 64 8 u64 1 +field RxcHostRepair dropped_records 72 8 u64 1 +field RxcHostRepair event_id 80 8 u64 1 +field RxcHostRepair cut_bytes_kept 88 8 u64 1 +field RxcHostRepair cut_sha256 96 32 u8 32 +field RxcHostRepair anchor_head 128 32 u8 32 +const RXC_HOST_ABI_VERSION 2 +const RXC_HOST_MAX_HANDLES 4 +const RXC_HOST_MAX_SKILLS 2 +const RXC_HOST_NAME_MAX 64 +const RXC_HOST_NONE 4294967295 +const RXC_HOST_SUBJECT_GOAL 1 +const RXC_HOST_SUBJECT_STATE 5 +const RXC_HOST_SUBJECT_HOST 0 +const RXC_HOST_TAG_REPAIR_TAIL 1 +const RXC_HOST_NOTE_CONSTRAINT 2 +const RXC_HOST_NOTE_AUTHORIZATION 3 +const RXC_HOST_NOTE_EFFECT 4 +const RXC_HOST_NOTE_MAX 16384 +const RXC_HOST_NP_LEN 0 +const RXC_HOST_NP_SHA 1 +const RXC_HOST_NP_BYTES 5 +const RXC_HOST_RP_CUT_LO 0 +const RXC_HOST_RP_CUT_HI 1 +const RXC_HOST_RP_DROPPED 5 +const RXC_HOST_RP_CAUSE 6 +const RXC_HOST_OK 0 +const RXC_HOST_E_ARG -1 +const RXC_HOST_E_IDENTITY -2 +const RXC_HOST_E_TORN -3 +const RXC_HOST_E_OPEN -4 +const RXC_HOST_E_FULL -5 +const RXC_HOST_E_STATE -6 +const RXC_HOST_E_RUN -7 +const RXC_HOST_E_NOMEM -8 +const RXC_HOST_E_NOT_FOUND -9 +const RXC_HOST_E_DIGEST -10 +const RXC_HOST_E_REPLAY -11 +fnptr RxcHostSkillFn fn(*mut c_void, u64, *mut u64) -> i32 +fnptr RxcHostVerifyFn fn(*mut c_void, u64, u64) -> i32 +fn rxc_host_abi_layout fn(*mut u32) -> u32 +fn rxc_host_open fn(*const c_char, u32, *const u8, usize, u64, u32, *mut *mut RxcHost, *mut RxcHostInfo) -> i32 +fn rxc_host_register_skill fn(*mut RxcHost, *const c_char, *const u8, u64, RxcHostSkillFn, *mut c_void) -> i32 +fn rxc_host_set_verify fn(*mut RxcHost, RxcHostVerifyFn, *mut c_void) -> i32 +fn rxc_host_run fn(*mut RxcHost, u64, u64, *mut RxcHostResult) -> i32 +fn rxc_host_recall fn(*mut RxcHost, u64, *mut RxcHostRecord, u32, *mut u32, *mut u64) -> i32 +fn rxc_host_record fn(*mut RxcHost, u64, *mut RxcHostRecord) -> i32 +fn rxc_host_payload fn(*mut RxcHost, u64, *mut u64, u32) -> i32 +fn rxc_host_info fn(*mut RxcHost, *mut RxcHostInfo) -> i32 +fn rxc_host_note fn(*mut RxcHost, u32, *const u64, *const u8, usize, *mut u64) -> i32 +fn rxc_host_recover fn(*const c_char, u32, *const u8, usize, *mut RxcHostRepair) -> i32 +fn rxc_host_close fn(*mut RxcHost) -> () +fn rxc_host_set_wait_ms fn(*mut RxcHost, u32) -> i32 diff --git a/crates/aien-omega-compose/build.rs b/crates/aien-omega-compose/build.rs index 364bcabf..15887429 100644 --- a/crates/aien-omega-compose/build.rs +++ b/crates/aien-omega-compose/build.rs @@ -2,8 +2,10 @@ //! //! Offline: nothing is downloaded. Order: //! 1. `AIEN_FORCE_CPU_STUB=1` -> stub (no library; every call returns -//! `ComposeError::Unavailable`). -//! 2. `AIEN_OMEGA_COMPOSE_LIB=` -> link that prebuilt archive (not sha-checked). +//! `ComposeError::Unavailable`). Refused when `AIEN_REQUIRE_NATIVE_LIBS=1`. +//! 2. `AIEN_OMEGA_COMPOSE_LIB=` -> link that prebuilt archive; `AIEN_OMEGA_COMPOSE_LIB_SHA256` +//! must name its sha256 (checked) and it must define every function in the ABI manifest. +//! A development override: its identity says `prebuilt` and it never qualifies. //! 3. `AIEN_OMEGA_COMPOSE_DIR=`, else `AIEN_OMEGA_DIR` (the checkout //! aien-omega-gpu builds from) -> its HEAD must equal omega.lock, then //! `make /librx_compose.a` runs in it. `AIEN_OMEGA_COMPOSE_SHA=<40-hex>` @@ -16,9 +18,17 @@ //! `AIEN_OMEGA_COMPOSE_DIR` exists so a developer override never touches the //! checkout aien-omega-gpu checks against omega.lock. //! `cfg(has_omega_compose)` is set only when the real library is linked. +//! +//! Before linking a checkout build, `aien_abi_conformance::build::qualify_built` checks the +//! pinned `rxc_host_abi.h`, a compiled layout probe and the archive symbols against +//! `abi/rxc_host_abi.manifest`, and the archive sha256 against `native-artifacts.lock`; any +//! mismatch fails the build. The result is recorded for `native_identity()`. +use aien_abi_conformance::build; use std::path::{Path, PathBuf}; use std::process::Command; +const PREFIX: &str = "AIEN_OMEGA_COMPOSE"; + fn main() { println!("cargo:rustc-check-cfg=cfg(has_omega_compose)"); println!("cargo:rustc-check-cfg=cfg(has_omega_wait_ms)"); @@ -55,7 +65,14 @@ fn main() { }; println!("cargo:rustc-env=AIEN_OMEGA_COMPOSE_EXPECTED_SHA={expected}"); + let root = PathBuf::from(env("CARGO_MANIFEST_DIR")); + let manifest = root.join("abi/rxc_host_abi.manifest"); + let artifacts_lock = root.join("../../native-artifacts.lock"); + println!("cargo:rerun-if-env-changed=AIEN_OMEGA_COMPOSE_LIB_SHA256"); + if std::env::var("AIEN_FORCE_CPU_STUB").as_deref() == Ok("1") { + build::refuse_stub_if_required("aien-omega-compose"); + build::Identity::stub(&expected).emit(PREFIX); return; } if let Ok(lib) = std::env::var("AIEN_OMEGA_COMPOSE_LIB") { @@ -65,6 +82,14 @@ fn main() { "AIEN_OMEGA_COMPOSE_LIB {} is not a file", lib.display() ); + build::qualify_prebuilt( + "aien-omega-compose", + &manifest, + &lib, + "AIEN_OMEGA_COMPOSE_LIB_SHA256", + "unverified", + ) + .emit(PREFIX); require_wait_ms_symbol(&lib); link(&lib); return; @@ -74,10 +99,11 @@ fn main() { else { // See aien-omega-gpu/build.rs: AIEN_REQUIRE_NATIVE_LIBS=1 refuses the stub. assert!( - std::env::var("AIEN_REQUIRE_NATIVE_LIBS").as_deref() != Ok("1"), + !build::require_native(), "aien-omega-compose: AIEN_REQUIRE_NATIVE_LIBS=1 but no AIEN_OMEGA_COMPOSE_DIR, AIEN_OMEGA_DIR or AIEN_OMEGA_COMPOSE_LIB is set (run scripts/pins.sh and source target/pins/env.sh)" ); println!("cargo:warning=aien-omega-compose: no AIEN_OMEGA_COMPOSE_DIR, AIEN_OMEGA_DIR or AIEN_OMEGA_COMPOSE_LIB, building the stub"); + build::Identity::stub(&expected).emit(PREFIX); return; }; let dir = PathBuf::from(dir); @@ -119,8 +145,20 @@ fn main() { dir.display() ); detect_wait_ms(&dir); - require_wait_ms_symbol(&out.join("librx_compose.a")); - link(&out.join("librx_compose.a")); + let archive = out.join("librx_compose.a"); + build::qualify_built( + "aien-omega-compose", + &manifest, + &artifacts_lock, + &dir, + &physics, + &archive, + &expected, + expected == pinned, + ) + .emit(PREFIX); + require_wait_ms_symbol(&archive); + link(&archive); } /// Check the omega checkout's host header. omega.lock pins a commit that diff --git a/crates/aien-omega-compose/src/ffi.rs b/crates/aien-omega-compose/src/ffi.rs index 88ca3eb5..7dd4eacc 100644 --- a/crates/aien-omega-compose/src/ffi.rs +++ b/crates/aien-omega-compose/src/ffi.rs @@ -1,195 +1,235 @@ -//! Raw declarations of omega `src/runtime/rxc_host_abi.h` (ABI version 1). -//! Layouts are `#[repr(C)]` mirrors; `Compose::open` compares their sizes with +//! Raw declarations of omega `src/runtime/rxc_host_abi.h` (ABI version 2). +//! +//! Every mirrored constant, callback type, struct and function is declared through the +//! `aien-abi-conformance` macros, which record what they declare. The contract they must +//! match is `abi/rxc_host_abi.manifest`: the crate's `abi_manifest` test checks these Rust +//! declarations against it (every build, stub included) and `build.rs` checks the pinned C +//! header, a compiled layout probe and the archive's symbols against it before linking. +//! At run time `Compose::open` still compares the four struct sizes with //! `rxc_host_abi_layout` before any other call. + #![allow(non_camel_case_types)] +use aien_abi_conformance::{abi_consts, abi_externs, abi_fnptr, abi_struct}; #[cfg(has_omega_compose)] use std::os::raw::c_char; use std::os::raw::{c_int, c_void}; -pub const RXC_HOST_ABI_VERSION: u32 = 2; -pub const RXC_HOST_NONE: u32 = 0xFFFF_FFFF; -pub const RXC_HOST_SUBJECT_GOAL: u64 = 1; -pub const RXC_HOST_SUBJECT_STATE: u64 = 5; -/// Host records (notes, repair records): no World object. -pub const RXC_HOST_SUBJECT_HOST: u64 = 0; -pub const RXC_HOST_TAG_REPAIR_TAIL: u64 = 1; -pub const RXC_HOST_NOTE_CONSTRAINT: u32 = 2; -pub const RXC_HOST_NOTE_AUTHORIZATION: u32 = 3; -pub const RXC_HOST_NOTE_EFFECT: u32 = 4; -pub const RXC_HOST_NOTE_MAX: usize = 16384; -pub const RXC_HOST_NP_LEN: usize = 0; -pub const RXC_HOST_NP_SHA: usize = 1; -pub const RXC_HOST_NP_BYTES: usize = 5; -pub const RXC_HOST_RP_CUT_LO: usize = 0; -pub const RXC_HOST_RP_CUT_HI: usize = 1; -pub const RXC_HOST_RP_DROPPED: usize = 5; -pub const RXC_HOST_RP_CAUSE: usize = 6; - -pub const RXC_HOST_OK: c_int = 0; -pub const RXC_HOST_E_ARG: c_int = -1; -pub const RXC_HOST_E_IDENTITY: c_int = -2; -pub const RXC_HOST_E_TORN: c_int = -3; -pub const RXC_HOST_E_OPEN: c_int = -4; -pub const RXC_HOST_E_FULL: c_int = -5; -pub const RXC_HOST_E_STATE: c_int = -6; -pub const RXC_HOST_E_RUN: c_int = -7; -pub const RXC_HOST_E_NOMEM: c_int = -8; -pub const RXC_HOST_E_NOT_FOUND: c_int = -9; -pub const RXC_HOST_E_DIGEST: c_int = -10; -pub const RXC_HOST_E_REPLAY: c_int = -11; +abi_consts! { CONSTS; + pub const RXC_HOST_ABI_VERSION: u32 = 2; + pub const RXC_HOST_MAX_HANDLES: u32 = 4; + pub const RXC_HOST_MAX_SKILLS: u32 = 2; + pub const RXC_HOST_NAME_MAX: u32 = 64; + pub const RXC_HOST_NONE: u32 = 0xFFFF_FFFF; + pub const RXC_HOST_SUBJECT_GOAL: u64 = 1; + pub const RXC_HOST_SUBJECT_STATE: u64 = 5; + /// Host records (notes, repair records): no World object. + pub const RXC_HOST_SUBJECT_HOST: u64 = 0; + pub const RXC_HOST_TAG_REPAIR_TAIL: u64 = 1; + pub const RXC_HOST_NOTE_CONSTRAINT: u32 = 2; + pub const RXC_HOST_NOTE_AUTHORIZATION: u32 = 3; + pub const RXC_HOST_NOTE_EFFECT: u32 = 4; + pub const RXC_HOST_NOTE_MAX: usize = 16384; + pub const RXC_HOST_NP_LEN: usize = 0; + pub const RXC_HOST_NP_SHA: usize = 1; + pub const RXC_HOST_NP_BYTES: usize = 5; + pub const RXC_HOST_RP_CUT_LO: usize = 0; + pub const RXC_HOST_RP_CUT_HI: usize = 1; + pub const RXC_HOST_RP_DROPPED: usize = 5; + pub const RXC_HOST_RP_CAUSE: usize = 6; + pub const RXC_HOST_OK: c_int = 0; + pub const RXC_HOST_E_ARG: c_int = -1; + pub const RXC_HOST_E_IDENTITY: c_int = -2; + pub const RXC_HOST_E_TORN: c_int = -3; + pub const RXC_HOST_E_OPEN: c_int = -4; + pub const RXC_HOST_E_FULL: c_int = -5; + pub const RXC_HOST_E_STATE: c_int = -6; + pub const RXC_HOST_E_RUN: c_int = -7; + pub const RXC_HOST_E_NOMEM: c_int = -8; + pub const RXC_HOST_E_NOT_FOUND: c_int = -9; + pub const RXC_HOST_E_DIGEST: c_int = -10; + pub const RXC_HOST_E_REPLAY: c_int = -11; +} #[repr(C)] pub struct RxcHost { _private: [u8; 0], } -pub type RxcHostSkillFn = - unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: *mut u64) -> c_int; -pub type RxcHostVerifyFn = unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: u64) -> c_int; +abi_fnptr! { FNPTRS; + pub type RxcHostSkillFn = + unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: *mut u64) -> c_int; + pub type RxcHostVerifyFn = + unsafe extern "C" fn(ctx: *mut c_void, task: u64, result: u64) -> c_int; +} -#[repr(C)] -#[derive(Debug, Clone, Copy, Default)] -pub struct RxcHostInfo { - pub abi_version: u32, - pub machine_root: u8, - pub machine_id: [u8; 32], - pub machine_id_was_stored: u32, - pub tail_torn: u32, - pub opened: u32, - pub open_rc: i32, - pub records: u64, - pub recovered_record: u64, - pub rolled_back: u32, - pub recovered_completed: u32, - pub anchor_unknown: u32, - pub n_skills: u32, +abi_struct! { + #[repr(C)] + #[derive(Debug, Clone, Copy, Default)] + pub struct RxcHostInfo { + pub abi_version: u32, + pub machine_root: u8, + pub machine_id: [u8; 32], + pub machine_id_was_stored: u32, + pub tail_torn: u32, + pub opened: u32, + pub open_rc: i32, + pub records: u64, + pub recovered_record: u64, + pub rolled_back: u32, + pub recovered_completed: u32, + pub anchor_unknown: u32, + pub n_skills: u32, + } } -#[repr(C)] -#[derive(Debug, Clone, Copy, Default)] -pub struct RxcHostResult { - pub run_rc: i32, - pub outcome: i32, - pub committed: u32, - pub n_branches: u32, - pub branches_reclaimed: u32, - pub winner: u32, - pub winner_skill: u32, - pub aegis_pass_mask: u32, - pub task: u64, - pub result: u64, - pub cx_goal: u64, - pub cx_candidate: [u64; 2], - pub cx_evidence: u64, - pub cx_promotion: u64, - pub cx_admission: [u64; 2], - pub winner_digest: [u8; 32], - pub record_digest: [u8; 32], +abi_struct! { + #[repr(C)] + #[derive(Debug, Clone, Copy, Default)] + pub struct RxcHostResult { + pub run_rc: i32, + pub outcome: i32, + pub committed: u32, + pub n_branches: u32, + pub branches_reclaimed: u32, + pub winner: u32, + pub winner_skill: u32, + pub aegis_pass_mask: u32, + pub task: u64, + pub result: u64, + pub cx_goal: u64, + pub cx_candidate: [u64; 2], + pub cx_evidence: u64, + pub cx_promotion: u64, + pub cx_admission: [u64; 2], + pub winner_digest: [u8; 32], + pub record_digest: [u8; 32], + } } -#[repr(C)] -#[derive(Debug, Clone, Copy, Default)] -pub struct RxcHostRecord { - pub id: u64, - pub cls: u32, - pub kind: u32, - pub subject: u64, - pub t: u64, - pub generation: u64, - pub tag: u64, - pub links: [u64; 4], - pub n_payload: u32, - pub verified: u32, - pub digest: [u8; 32], +abi_struct! { + #[repr(C)] + #[derive(Debug, Clone, Copy, Default)] + pub struct RxcHostRecord { + pub id: u64, + pub cls: u32, + pub kind: u32, + pub subject: u64, + pub t: u64, + pub generation: u64, + pub tag: u64, + pub links: [u64; 4], + pub n_payload: u32, + pub verified: u32, + pub digest: [u8; 32], + } } -#[repr(C)] -#[derive(Debug, Clone, Copy, Default)] -pub struct RxcHostRepair { - pub repaired: u32, - pub tail_torn: u32, - pub anchor_present: u32, - pub cause: i32, - pub opens: u32, - pub open_rc: i32, - pub rolled_back: u32, - pub recovered_completed: u32, - pub cut_lo: u64, - pub cut_hi: u64, - pub partial_records: u64, - pub anchor_records: u64, - pub records_kept: u64, - pub dropped_records: u64, - pub event_id: u64, - pub cut_bytes_kept: u64, - pub cut_sha256: [u8; 32], - pub anchor_head: [u8; 32], +abi_struct! { + #[repr(C)] + #[derive(Debug, Clone, Copy, Default)] + pub struct RxcHostRepair { + pub repaired: u32, + pub tail_torn: u32, + pub anchor_present: u32, + pub cause: i32, + pub opens: u32, + pub open_rc: i32, + pub rolled_back: u32, + pub recovered_completed: u32, + pub cut_lo: u64, + pub cut_hi: u64, + pub partial_records: u64, + pub anchor_records: u64, + pub records_kept: u64, + pub dropped_records: u64, + pub event_id: u64, + pub cut_bytes_kept: u64, + pub cut_sha256: [u8; 32], + pub anchor_head: [u8; 32], + } } -#[cfg(has_omega_compose)] -extern "C" { - pub fn rxc_host_abi_layout(out: *mut u32) -> u32; - pub fn rxc_host_open( - dir: *const c_char, - root_kind: u32, - root: *const u8, - root_len: usize, - session: u64, - flags: u32, - out: *mut *mut RxcHost, - info: *mut RxcHostInfo, - ) -> c_int; - pub fn rxc_host_register_skill( - h: *mut RxcHost, - name: *const c_char, - digest32: *const u8, - cost: u64, - f: RxcHostSkillFn, - ctx: *mut c_void, - ) -> c_int; - pub fn rxc_host_set_verify( - h: *mut RxcHost, - f: Option, - ctx: *mut c_void, - ) -> c_int; - pub fn rxc_host_run(h: *mut RxcHost, task: u64, now_us: u64, out: *mut RxcHostResult) -> c_int; - pub fn rxc_host_recall( - h: *mut RxcHost, - subject: u64, - out: *mut RxcHostRecord, - max: u32, - n_filled: *mut u32, - n_total: *mut u64, - ) -> c_int; - pub fn rxc_host_record(h: *mut RxcHost, id: u64, out: *mut RxcHostRecord) -> c_int; - pub fn rxc_host_payload(h: *mut RxcHost, id: u64, out: *mut u64, max: u32) -> c_int; - pub fn rxc_host_info(h: *mut RxcHost, info: *mut RxcHostInfo) -> c_int; - pub fn rxc_host_note( - h: *mut RxcHost, - note: u32, - links: *const u64, - bytes: *const u8, - len: usize, - out_id: *mut u64, - ) -> c_int; - pub fn rxc_host_recover( - dir: *const c_char, - root_kind: u32, - root: *const u8, - root_len: usize, - out: *mut RxcHostRepair, - ) -> c_int; - pub fn rxc_host_close(h: *mut RxcHost); +abi_externs! { FNS; + #[cfg(has_omega_compose)] + extern "C" { + pub fn rxc_host_abi_layout(out: *mut u32) -> u32; + pub fn rxc_host_open( + dir: *const c_char, + root_kind: u32, + root: *const u8, + root_len: usize, + session: u64, + flags: u32, + out: *mut *mut RxcHost, + info: *mut RxcHostInfo, + ) -> c_int; + pub fn rxc_host_register_skill( + h: *mut RxcHost, + name: *const c_char, + digest32: *const u8, + cost: u64, + f: RxcHostSkillFn, + ctx: *mut c_void, + ) -> c_int; + pub fn rxc_host_set_verify( + h: *mut RxcHost, + f: Option, + ctx: *mut c_void, + ) -> c_int; + pub fn rxc_host_run(h: *mut RxcHost, task: u64, now_us: u64, out: *mut RxcHostResult) -> c_int; + pub fn rxc_host_recall( + h: *mut RxcHost, + subject: u64, + out: *mut RxcHostRecord, + max: u32, + n_filled: *mut u32, + n_total: *mut u64, + ) -> c_int; + pub fn rxc_host_record(h: *mut RxcHost, id: u64, out: *mut RxcHostRecord) -> c_int; + pub fn rxc_host_payload(h: *mut RxcHost, id: u64, out: *mut u64, max: u32) -> c_int; + pub fn rxc_host_info(h: *mut RxcHost, info: *mut RxcHostInfo) -> c_int; + pub fn rxc_host_note( + h: *mut RxcHost, + note: u32, + links: *const u64, + bytes: *const u8, + len: usize, + out_id: *mut u64, + ) -> c_int; + pub fn rxc_host_recover( + dir: *const c_char, + root_kind: u32, + root: *const u8, + root_len: usize, + out: *mut RxcHostRepair, + ) -> c_int; + pub fn rxc_host_close(h: *mut RxcHost); + } } -// Present only when the omega checkout exposes it (build.rs sets -// `has_omega_wait_ms` after finding the symbol in rxc_host_abi.h). -#[cfg(has_omega_wait_ms)] -extern "C" { - /// Wraps omega `rx_compose_set_wait_ms` on the handle's composition. - pub fn rxc_host_set_wait_ms(h: *mut RxcHost, wait_ms: u32) -> c_int; +// Present only when the archive defines it (build.rs sets `has_omega_wait_ms` after finding +// the declaration in rxc_host_abi.h and the symbol in the archive). +abi_externs! { WAIT_FNS; + #[cfg(has_omega_wait_ms)] + extern "C" { + /// Wraps omega `rx_compose_set_wait_ms` on the handle's composition. + pub fn rxc_host_set_wait_ms(h: *mut RxcHost, wait_ms: u32) -> c_int; + } } /// omega settle wait when `rxc_host_set_wait_ms` is never called. pub const WAIT_MS_DEFAULT: u32 = 30_000; + +/// The Rust side of the `rxc_host` contract, for the manifest check. +pub fn rust_abi() -> aien_abi_conformance::RustAbi { + aien_abi_conformance::RustAbi::default() + .with_struct::() + .with_struct::() + .with_struct::() + .with_struct::() + .with_consts(CONSTS) + .with_fnptrs(FNPTRS) + .with_fns(FNS) + .with_fns(WAIT_FNS) +} diff --git a/crates/aien-omega-compose/src/lib.rs b/crates/aien-omega-compose/src/lib.rs index cf4184de..9cb633c6 100644 --- a/crates/aien-omega-compose/src/lib.rs +++ b/crates/aien-omega-compose/src/lib.rs @@ -23,6 +23,24 @@ pub static LAST_WAIT_MS: std::sync::atomic::AtomicU32 = std::sync::atomic::Atomi pub const LINKED: bool = cfg!(has_omega_compose); /// The omega commit this build expected (omega.lock or `AIEN_OMEGA_COMPOSE_SHA`). pub const EXPECTED_OMEGA_SHA: &str = env!("AIEN_OMEGA_COMPOSE_EXPECTED_SHA"); + +/// What this binary linked for the omega composition library (stub, pinned source, developer override or +/// prebuilt), the C ABI check result and the archive digest, as `build.rs` established them. +/// Only `qualifies()` identities count as release-grade native qualification. +pub fn native_identity() -> aien_abi_conformance::NativeIdentity { + aien_abi_conformance::NativeIdentity { + component: "librx_compose.a", + link: env!("AIEN_OMEGA_COMPOSE_LINK"), + abi: env!("AIEN_OMEGA_COMPOSE_ABI"), + digest: env!("AIEN_OMEGA_COMPOSE_DIGEST"), + archive_sha256: env!("AIEN_OMEGA_COMPOSE_ARCHIVE_SHA256"), + source_sha: env!("AIEN_OMEGA_COMPOSE_SOURCE_SHA"), + aienos_lock: env!("AIEN_OMEGA_COMPOSE_AIENOS_LOCK"), + physics_lock: env!("AIEN_OMEGA_COMPOSE_PHYSICS_LOCK"), + target: env!("AIEN_OMEGA_COMPOSE_TARGET"), + cc: env!("AIEN_OMEGA_COMPOSE_CC"), + } +} pub use ffi::{RXC_HOST_SUBJECT_GOAL as SUBJECT_GOAL, RXC_HOST_SUBJECT_STATE as SUBJECT_STATE}; /// No winner / no Skill. pub const NONE: u32 = ffi::RXC_HOST_NONE; @@ -193,6 +211,9 @@ mod linked { } unsafe extern "C" fn skill_tramp(ctx: *mut c_void, task: u64, result: *mut u64) -> c_int { + if ctx.is_null() || result.is_null() { + return 1; + } let f = &*(ctx as *const Box); match catch_unwind(AssertUnwindSafe(|| f(task))) { Ok(Some(r)) if r != 0 => { @@ -204,6 +225,9 @@ mod linked { } unsafe extern "C" fn verify_tramp(ctx: *mut c_void, task: u64, result: u64) -> c_int { + if ctx.is_null() { + return 0; + } let f = &*(ctx as *const Box); matches!(catch_unwind(AssertUnwindSafe(|| f(task, result))), Ok(true)) as c_int } diff --git a/crates/aien-omega-compose/tests/abi_manifest.rs b/crates/aien-omega-compose/tests/abi_manifest.rs new file mode 100644 index 00000000..d695ff2c --- /dev/null +++ b/crates/aien-omega-compose/tests/abi_manifest.rs @@ -0,0 +1,34 @@ +//! The Rust mirror of the rxc_host ABI (src/ffi.rs) must equal abi/rxc_host_abi.manifest, +//! field by field (offset, size, kind, order), constant by constant and signature by +//! signature. Runs in every build, the stub included. + +#[test] +fn rust_ffi_matches_the_manifest() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("abi/rxc_host_abi.manifest"); + aien_abi_conformance::assert_manifest(&aien_omega_compose::ffi::rust_abi(), &path); +} + +/// What this test binary linked, as `build.rs` recorded it. Prints one +/// `AIEN_NATIVE_IDENTITY {json}` line (scripts/abi-qualify.sh collects it). A linked build +/// must never report the stub, a stub build must never qualify, and with +/// `AIEN_ABI_QUALIFY=1` (the qualification run) the identity must qualify. +#[test] +fn native_identity_matches_the_link() { + let id = aien_omega_compose::native_identity(); + println!("AIEN_NATIVE_IDENTITY {}", id.to_json()); + if cfg!(has_omega_compose) { + assert_ne!(id.link, "stub", "{id:?}"); + assert!(id.digest != "none", "{id:?}"); + } else { + assert_eq!(id.link, "stub", "{id:?}"); + assert!(!id.qualifies()); + } + if std::env::var("AIEN_ABI_QUALIFY").as_deref() == Ok("1") { + assert!( + id.qualifies(), + "{} does not qualify: {:?}", + id.component, + id.gaps() + ); + } +} diff --git a/crates/aien-omega-compose/tests/callbacks.rs b/crates/aien-omega-compose/tests/callbacks.rs new file mode 100644 index 00000000..a7ae9c96 --- /dev/null +++ b/crates/aien-omega-compose/tests/callbacks.rs @@ -0,0 +1,149 @@ +//! Callback safety across the rxc_host boundary, against the real librx_compose.a: +//! a failing or panicking Skill or verifier is contained and reported as a failed alternative +//! (never unwinds into C), repeated open/close neither leaks handle slots nor keeps callback +//! state alive, and several homes driven from several threads at once keep their own +//! callbacks apart (the C side routes ctx-less trampolines through a shared slot table). +//! +//! Ignored unless the library is linked. Note: the workspace release profile sets +//! `panic = "abort"`, so in a release binary a panicking callback aborts the process instead +//! (also never an unwind across C); these tests run in the unwinding test profile, where the +//! `catch_unwind` in the trampolines is what keeps the panic out of C. + +use aien_omega_compose::*; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::Arc; + +const ROOT: &[u8] = b"abi-qual-callback-test-machine"; + +fn propose(t: u64) -> u64 { + t.wrapping_mul(7).wrapping_add(3) +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn panicking_skill_is_contained_and_reported_as_failure() { + let tmp = tempfile::tempdir().unwrap(); + let (mut c, _) = Compose::open(&tmp.path().join("h"), RootKind::Provisioned, ROOT, 1).unwrap(); + c.register_skill("abi.panics", None, 1, |_| panic!("skill panic")) + .unwrap(); + let r = c.run(0xA1, 1_000_000).unwrap(); + assert_eq!(r.committed, 0, "a panicking Skill must not commit: {r:?}"); + assert_ne!(r.outcome, OUT_COMMITTED); + assert_eq!(r.result, 0); + // The handle is still usable after the contained panic. + let r2 = c.run(0xA2, 2_000_000).unwrap(); + assert_eq!(r2.committed, 0); +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn failing_and_zero_results_do_not_commit() { + let tmp = tempfile::tempdir().unwrap(); + let (mut c, _) = Compose::open(&tmp.path().join("h"), RootKind::Provisioned, ROOT, 2).unwrap(); + c.register_skill("abi.none", None, 1, |_| None).unwrap(); + c.register_skill("abi.zero", None, 2, |_| Some(0)).unwrap(); + let r = c.run(0xB1, 1_000_000).unwrap(); + assert_eq!(r.committed, 0, "{r:?}"); + assert_eq!(r.aegis_pass_mask, 0, "{r:?}"); +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn panicking_verifier_fails_the_contract() { + let tmp = tempfile::tempdir().unwrap(); + let (mut c, _) = Compose::open(&tmp.path().join("h"), RootKind::Provisioned, ROOT, 3).unwrap(); + c.register_skill("abi.ok", None, 1, |t| Some(propose(t))) + .unwrap(); + c.set_verify(|_, _| panic!("verifier panic")).unwrap(); + let r = c.run(0xC1, 1_000_000).unwrap(); + assert_eq!(r.committed, 0, "{r:?}"); + assert_eq!(r.aegis_pass_mask, 0, "{r:?}"); +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn repeated_open_close_releases_slots_and_callback_state() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("h"); + let state = Arc::new(AtomicU64::new(0)); + // More cycles than RXC_HOST_MAX_HANDLES (4): a leaked slot would refuse with E_FULL. + for i in 0..12u64 { + let s = state.clone(); + let (mut c, info) = Compose::open(&home, RootKind::Provisioned, ROOT, 10 + i).unwrap(); + assert_eq!(info.abi_version, ffi::RXC_HOST_ABI_VERSION); + c.register_skill("abi.count", None, 1, move |t| { + s.fetch_add(1, Ordering::SeqCst); + Some(propose(t)) + }) + .unwrap(); + let r = c.run(0xD000 + i, 1_000_000 * (i + 1)).unwrap(); + assert_eq!(r.committed, 1, "cycle {i}: {r:?}"); + assert_eq!(r.result, propose(0xD000 + i)); + drop(c); + // The closure (and its clone of `state`) is freed with the handle. + assert_eq!( + Arc::strong_count(&state), + 1, + "cycle {i}: callback state outlived close" + ); + } + assert_eq!(state.load(Ordering::SeqCst), 12); +} + +#[test] +#[cfg_attr( + not(has_omega_compose), + ignore = "needs librx_compose.a (AIEN_OMEGA_COMPOSE_DIR)" +)] +fn concurrent_homes_keep_their_callbacks_apart() { + let tmp = Arc::new(tempfile::tempdir().unwrap()); + let calls = Arc::new(AtomicUsize::new(0)); + let threads: Vec<_> = (0..3u64) + .map(|k| { + let tmp = tmp.clone(); + let calls = calls.clone(); + std::thread::spawn(move || { + let home = tmp.path().join(format!("h{k}")); + let (mut c, _) = + Compose::open(&home, RootKind::Provisioned, ROOT, 100 + k).unwrap(); + let tag = k << 56; + let seen = Arc::new(AtomicU64::new(0)); + let s2 = seen.clone(); + let calls2 = calls.clone(); + c.register_skill("abi.tagged", None, 1, move |t| { + calls2.fetch_add(1, Ordering::SeqCst); + s2.store(t, Ordering::SeqCst); + Some(propose(t) | 1) + }) + .unwrap(); + // A verifier that only accepts this home's own tag: a callback routed to the + // wrong handle would fail the contract. + c.set_verify(move |t, r| t >> 56 == k && r == (propose(t) | 1)) + .unwrap(); + for i in 1..=5u64 { + let task = tag | i; + let r = c.run(task, i * 1_000_000).unwrap(); + assert_eq!(r.committed, 1, "home {k} goal {i}: {r:?}"); + assert_eq!(r.result, propose(task) | 1); + assert_eq!(seen.load(Ordering::SeqCst), task); + } + }) + }) + .collect(); + for t in threads { + t.join().expect("worker thread"); + } + assert_eq!(calls.load(Ordering::SeqCst), 15); +} diff --git a/crates/aien-omega-gpu/Cargo.toml b/crates/aien-omega-gpu/Cargo.toml index 9f571e78..3437059d 100644 --- a/crates/aien-omega-gpu/Cargo.toml +++ b/crates/aien-omega-gpu/Cargo.toml @@ -8,3 +8,7 @@ license.workspace = true build = "build.rs" [dependencies] +aien-abi-conformance = { path = "../aien-abi-conformance" } + +[build-dependencies] +aien-abi-conformance = { path = "../aien-abi-conformance" } diff --git a/crates/aien-omega-gpu/abi/omega_gpu.manifest b/crates/aien-omega-gpu/abi/omega_gpu.manifest new file mode 100644 index 00000000..fe74b65e --- /dev/null +++ b/crates/aien-omega-gpu/abi/omega_gpu.manifest @@ -0,0 +1,151 @@ +# The omega GPU engine C ABI (libomega_gpu.a) that aien-omega-gpu mirrors in src/ffi.rs. +# Checked from both sides: tests/abi_manifest.rs (Rust declarations, every build) and build.rs +# (pinned C headers, compiled layout probe, archive symbols). +# Format: aien-abi-conformance src/manifest.rs. Regenerate the fact lines from Rust with +# AIEN_ABI_BLESS=1 cargo test -p aien-omega-gpu --test abi_manifest +# only together with the omega.lock change that makes the C side agree. +abi omega_gpu 1 +header src/omega_gpu_matmul_api.h +header src/omega_gpu_session.h +header src/omega_gpu_serving.h +header src/omega_gpu_elementwise_api.h +header src/omega_gpu_attention_api.h +struct OmegaGpuMatmulInfo 160 8 +field OmegaGpuMatmulInfo m 0 4 u32 1 +field OmegaGpuMatmulInfo k 4 4 u32 1 +field OmegaGpuMatmulInfo n 8 4 u32 1 +field OmegaGpuMatmulInfo padded_m 12 4 u32 1 +field OmegaGpuMatmulInfo padded_n 16 4 u32 1 +field OmegaGpuMatmulInfo k_slices 20 4 u32 1 +field OmegaGpuMatmulInfo chip_calls 24 4 u32 1 +field OmegaGpuMatmulInfo rows_per_call 28 4 u32 1 +field OmegaGpuMatmulInfo elapsed_ns 32 8 u64 1 +field OmegaGpuMatmulInfo max_abs_err 40 4 f32 1 +field OmegaGpuMatmulInfo max_rel_err 44 4 f32 1 +field OmegaGpuMatmulInfo mismatch_count 48 8 u64 1 +field OmegaGpuMatmulInfo parity_verified 56 1 bool 1 +field OmegaGpuMatmulInfo completion_marker 60 4 u32 1 +field OmegaGpuMatmulInfo kernel_cache_hit 64 1 bool 1 +field OmegaGpuMatmulInfo target_chip 65 64 c_char 64 +field OmegaGpuMatmulInfo sm_architecture 132 4 u32 1 +field OmegaGpuMatmulInfo grid_x 136 4 u32 1 +field OmegaGpuMatmulInfo grid_y 140 4 u32 1 +field OmegaGpuMatmulInfo padded_k 144 4 u32 1 +field OmegaGpuMatmulInfo resident 148 1 bool 1 +field OmegaGpuMatmulInfo oracle_ran 149 1 bool 1 +field OmegaGpuMatmulInfo call_ns 152 8 u64 1 +struct OmegaGpuAllocStats 32 8 +field OmegaGpuAllocStats allocs 0 8 u64 1 +field OmegaGpuAllocStats alloc_bytes 8 8 u64 1 +field OmegaGpuAllocStats alloc_failures 16 8 u64 1 +field OmegaGpuAllocStats frees 24 8 u64 1 +struct OmegaGpuServingBounds 44 4 +field OmegaGpuServingBounds max_context 0 4 u32 1 +field OmegaGpuServingBounds max_seqs 4 4 u32 1 +field OmegaGpuServingBounds num_q_heads 8 4 u32 1 +field OmegaGpuServingBounds num_kv_heads 12 4 u32 1 +field OmegaGpuServingBounds head_dim 16 4 u32 1 +field OmegaGpuServingBounds kv_block_size 20 4 u32 1 +field OmegaGpuServingBounds max_rows 24 4 u32 1 +field OmegaGpuServingBounds max_k 28 4 u32 1 +field OmegaGpuServingBounds max_n 32 4 u32 1 +field OmegaGpuServingBounds max_n_one_row 36 4 u32 1 +field OmegaGpuServingBounds kernel_slots 40 4 u32 1 +struct OmegaGpuEwInfo 120 8 +field OmegaGpuEwInfo chip_calls 0 4 u32 1 +field OmegaGpuEwInfo elapsed_ns 8 8 u64 1 +field OmegaGpuEwInfo completion_marker 16 4 u32 1 +field OmegaGpuEwInfo unwritten_words 20 4 u32 1 +field OmegaGpuEwInfo kernel_cache_hit 24 1 bool 1 +field OmegaGpuEwInfo gpr_count 28 4 u32 1 +field OmegaGpuEwInfo insn_count 32 4 u32 1 +field OmegaGpuEwInfo threads_per_cta 36 4 u32 1 +field OmegaGpuEwInfo ctas_last_launch 40 4 u32 1 +field OmegaGpuEwInfo target_chip 44 64 c_char 64 +field OmegaGpuEwInfo sm_architecture 108 4 u32 1 +field OmegaGpuEwInfo call_ns 112 8 u64 1 +struct OmegaGpuAttnInfo 176 8 +field OmegaGpuAttnInfo chip_calls 0 4 u32 1 +field OmegaGpuAttnInfo elapsed_ns 8 8 u64 1 +field OmegaGpuAttnInfo call_ns 16 8 u64 1 +field OmegaGpuAttnInfo completion_marker 24 4 u32 1 +field OmegaGpuAttnInfo unwritten_words 28 4 u32 1 +field OmegaGpuAttnInfo gpr_count 32 4 u32 1 +field OmegaGpuAttnInfo insn_count 36 4 u32 1 +field OmegaGpuAttnInfo kernel_cache_hit 40 1 bool 1 +field OmegaGpuAttnInfo ctas_last_launch 44 4 u32 1 +field OmegaGpuAttnInfo threads_per_cta 48 4 u32 1 +field OmegaGpuAttnInfo target_chip 52 64 c_char 64 +field OmegaGpuAttnInfo sm_architecture 116 4 u32 1 +field OmegaGpuAttnInfo kv_bytes_staged 120 8 u64 1 +field OmegaGpuAttnInfo kv_bytes_naive 128 8 u64 1 +field OmegaGpuAttnInfo kv_blocks_logical 136 4 u32 1 +field OmegaGpuAttnInfo kv_blocks_unique 140 4 u32 1 +field OmegaGpuAttnInfo q_bytes 144 8 u64 1 +field OmegaGpuAttnInfo tab_bytes 152 8 u64 1 +field OmegaGpuAttnInfo out_bytes 160 8 u64 1 +field OmegaGpuAttnInfo kv_source 168 4 u32 1 +struct OmegaGpuKvLayout 64 8 +field OmegaGpuKvLayout block_stride_bytes 0 8 u64 1 +field OmegaGpuKvLayout layer_stride_bytes 8 8 u64 1 +field OmegaGpuKvLayout kv_plane_stride_bytes 16 8 u64 1 +field OmegaGpuKvLayout token_stride_bytes 24 8 u64 1 +field OmegaGpuKvLayout head_stride_bytes 32 8 u64 1 +field OmegaGpuKvLayout pool_bytes 40 8 u64 1 +field OmegaGpuKvLayout num_blocks 48 4 u32 1 +field OmegaGpuKvLayout num_layers 52 4 u32 1 +field OmegaGpuKvLayout block_size 56 4 u32 1 +const OMEGA_GPU_MATMUL_OK 0 +const OMEGA_GPU_MATMUL_BAD_ARGS -1 +const OMEGA_GPU_MATMUL_TOO_LARGE -2 +const OMEGA_GPU_MATMUL_CODEGEN_FAIL -3 +const OMEGA_GPU_MATMUL_CHIP_FAIL -4 +const OMEGA_GPU_MATMUL_PARITY_FAIL -5 +const OMEGA_GPU_MATMUL_TILE_M 16 +const OMEGA_GPU_MATMUL_TILE_N 8 +const OMEGA_GPU_MATMUL_TILE_K 16 +const OMEGA_GPU_MATMUL_MAX_CTAS 64 +const OMEGA_GPU_EW_OK 0 +const OMEGA_GPU_EW_BAD_ARGS -1 +const OMEGA_GPU_EW_TOO_LARGE -2 +const OMEGA_GPU_EW_CODEGEN_FAIL -3 +const OMEGA_GPU_EW_CHIP_FAIL -4 +const OMEGA_GPU_EW_UNWRITTEN -5 +const OMEGA_GPU_ATTN_OK 0 +const OMEGA_GPU_ATTN_BAD_ARGS -1 +const OMEGA_GPU_ATTN_TOO_LARGE -2 +const OMEGA_GPU_ATTN_CODEGEN_FAIL -3 +const OMEGA_GPU_ATTN_CHIP_FAIL -4 +const OMEGA_GPU_ATTN_UNWRITTEN -5 +const OMEGA_GPU_ATTN_KV_STAGED 0 +fn omega_gpu_matmul_bf16 fn(u32, u32, u32, *const u16, *const u16, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 +fn omega_gpu_matmul_f32 fn(u32, u32, u32, *const f32, *const f32, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 +fn omega_gpu_matmul_rc_name fn(i32) -> *const c_char +fn omega_gpu_matmul_cache_clear fn() -> () +fn omega_gpu_tensor_upload_bf16 fn(u32, u32, *const u16, *mut *mut OmegaGpuTensor) -> i32 +fn omega_gpu_tensor_upload_f32 fn(u32, u32, *const f32, *mut *mut OmegaGpuTensor) -> i32 +fn omega_gpu_tensor_free fn(*mut OmegaGpuTensor) -> () +fn omega_gpu_tensor_shape fn(*const OmegaGpuTensor, *mut u32, *mut u32) -> () +fn omega_gpu_matmul_resident_bf16 fn(u32, *const u16, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 +fn omega_gpu_matmul_resident_f32 fn(u32, *const f32, *const OmegaGpuTensor, *mut f32, *mut OmegaGpuMatmulInfo) -> i32 +fn omega_gpu_matmul_last_error fn() -> *const c_char +fn omega_gpu_matmul_is_blocked fn() -> i32 +fn omega_gpu_device_close fn() -> () +fn omega_gpu_matmul_set_cta_budget fn(u32) -> () +fn omega_gpu_matmul_cta_budget fn() -> u32 +fn omega_gpu_session_set_spin_us fn(u32) -> i32 +fn omega_gpu_session_spin_us fn() -> u32 +fn omega_gpu_reserve_serving fn(*const OmegaGpuServingBounds) -> i32 +fn omega_gpu_serving_release fn() -> () +fn omega_gpu_matmul_prepare fn(u32, u32, u32) -> i32 +fn omega_gpu_serving_seal fn() -> () +fn omega_gpu_session_alloc_stats fn(*mut OmegaGpuAllocStats) -> () +fn omega_gpu_rmsnorm_f32 fn(u32, u32, *const f32, *const f32, f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 +fn omega_gpu_rope_f32 fn(u32, u32, *const f32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 +fn omega_gpu_swiglu_f32 fn(u32, *const f32, *const f32, *mut f32, *mut OmegaGpuEwInfo) -> i32 +fn omega_gpu_elementwise_rc_name fn(i32) -> *const c_char +fn omega_gpu_gqa_attention_f32 fn(*const f32, *const f32, *const f32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 +fn omega_gpu_paged_attention_bf16 fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const u32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 +fn omega_gpu_paged_attention_batch_bf16 fn(*const f32, *const c_void, *const OmegaGpuKvLayout, *const i32, *const i32, u32, u32, u32, u32, u32, u32, *mut f32, *mut OmegaGpuAttnInfo) -> i32 +fn omega_gpu_attention_rc_name fn(i32) -> *const c_char +fn omega_gpu_attention_last_error fn() -> *const c_char diff --git a/crates/aien-omega-gpu/build.rs b/crates/aien-omega-gpu/build.rs index 1ba14d68..d13606c1 100644 --- a/crates/aien-omega-gpu/build.rs +++ b/crates/aien-omega-gpu/build.rs @@ -4,16 +4,27 @@ //! 1. `AIEN_FORCE_CPU_STUB=1` -> stub (CI without the chip). BUILD-TIME ONLY: a binary already //! built with the GPU library ignores it at run time. For a CPU-only RUN set `AIEN_BACKEND=cpu`: //! the daemon refuses to start (`CPU_ONLY_BUT_GPU_BUILD`) if the binary would select the GB10 backend. -//! 2. `AIEN_OMEGA_GPU_LIB=` -> link that prebuilt archive (not sha-checked). +//! Refused when `AIEN_REQUIRE_NATIVE_LIBS=1` (a required-native build is never a stub). +//! 2. `AIEN_OMEGA_GPU_LIB=` -> link that prebuilt archive; `AIEN_OMEGA_GPU_LIB_SHA256` must +//! name its sha256 (checked) and it must define every function in the ABI manifest. A +//! development override: its identity says `prebuilt` and it never qualifies. //! 3. `AIEN_OMEGA_DIR=` -> its HEAD must equal omega.lock; built with //! `make libomega_gpu` into OUT_DIR. `AIEN_PHYSICS_DIR` (default `/../physics`) //! is passed as PHYSICS_DIR; omega's own physics.lock check still runs. //! 4. otherwise -> stub, with a build warning. //! //! `cfg(has_omega_gpu)` is set only when the real library is linked. +//! +//! Before linking a checkout build, `aien_abi_conformance::build::qualify_built` checks the +//! pinned headers, a compiled layout probe and the archive symbols against +//! `abi/omega_gpu.manifest`, and the archive sha256 against `native-artifacts.lock`; any mismatch +//! fails the build. The result is recorded for `native_identity()`. +use aien_abi_conformance::build; use std::path::{Path, PathBuf}; use std::process::Command; +const PREFIX: &str = "AIEN_OMEGA_GPU"; + fn main() { println!("cargo:rustc-check-cfg=cfg(has_omega_gpu)"); for v in [ @@ -37,7 +48,13 @@ fn main() { ); println!("cargo:rustc-env=AIEN_OMEGA_PINNED_SHA={pinned}"); + let root = PathBuf::from(env("CARGO_MANIFEST_DIR")); + let manifest = root.join("abi/omega_gpu.manifest"); + let artifacts_lock = root.join("../../native-artifacts.lock"); + println!("cargo:rerun-if-env-changed=AIEN_OMEGA_GPU_LIB_SHA256"); if std::env::var("AIEN_FORCE_CPU_STUB").as_deref() == Ok("1") { + build::refuse_stub_if_required("aien-omega-gpu"); + build::Identity::stub(&pinned).emit(PREFIX); return; } if let Ok(lib) = std::env::var("AIEN_OMEGA_GPU_LIB") { @@ -47,6 +64,14 @@ fn main() { "AIEN_OMEGA_GPU_LIB {} is not a file", lib.display() ); + build::qualify_prebuilt( + "aien-omega-gpu", + &manifest, + &lib, + "AIEN_OMEGA_GPU_LIB_SHA256", + "unverified", + ) + .emit(PREFIX); link(&lib); return; } @@ -59,6 +84,7 @@ fn main() { "aien-omega-gpu: AIEN_REQUIRE_NATIVE_LIBS=1 but neither AIEN_OMEGA_DIR nor AIEN_OMEGA_GPU_LIB is set (run scripts/pins.sh --gpu and source target/pins/env.sh)" ); println!("cargo:warning=aien-omega-gpu: no AIEN_OMEGA_DIR or AIEN_OMEGA_GPU_LIB, building the CPU stub"); + build::Identity::stub(&pinned).emit(PREFIX); return; }; let dir = PathBuf::from(dir); @@ -93,7 +119,19 @@ fn main() { "make libomega_gpu failed in {}", dir.display() ); - link(&out.join("libomega_gpu.a")); + let archive = out.join("libomega_gpu.a"); + build::qualify_built( + "aien-omega-gpu", + &manifest, + &artifacts_lock, + &dir, + &physics, + &archive, + &pinned, + true, + ) + .emit(PREFIX); + link(&archive); } fn link(lib: &Path) { diff --git a/crates/aien-omega-gpu/src/ffi.rs b/crates/aien-omega-gpu/src/ffi.rs index d64335b1..9adec1eb 100644 --- a/crates/aien-omega-gpu/src/ffi.rs +++ b/crates/aien-omega-gpu/src/ffi.rs @@ -1,9 +1,19 @@ -//! Raw declarations, written by hand from omega `src/omega_gpu_matmul_api.h` -//! at the commit pinned in `omega.lock` (e5593ae; matmul header unchanged since 6b940fa, attention header -//! extended by OM-2 e5593ae: staging counters appended to `OmegaGpuAttnInfo`). Nothing generated. -//! Includes the resident-weights handles added by omega FB-1 cut 1b. +//! Raw declarations, written by hand from omega `src/omega_gpu_matmul_api.h`, +//! `omega_gpu_session.h`, `omega_gpu_serving.h`, `omega_gpu_elementwise_api.h` and +//! `omega_gpu_attention_api.h` at the commit pinned in `omega.lock`. Nothing generated. +//! +//! Hand-written, but not unchecked: every mirrored constant, struct and function is declared +//! through the `aien-abi-conformance` macros, and `abi/omega_gpu.manifest` is the contract. +//! `tests/abi_manifest.rs` checks these declarations against it in every build (stub included); +//! `build.rs` checks the pinned C headers (field names and order, prototypes), a compiled layout +//! probe (sizes, alignments, offsets, widths, signedness, constant values) and the archive's +//! symbols against it before linking. +use aien_abi_conformance::{abi_consts, abi_externs, abi_struct}; +#[cfg(has_omega_gpu)] +use std::os::raw::c_void; use std::os::raw::{c_char, c_int}; +abi_consts! { MATMUL_CONSTS; pub const OMEGA_GPU_MATMUL_OK: c_int = 0; pub const OMEGA_GPU_MATMUL_BAD_ARGS: c_int = -1; pub const OMEGA_GPU_MATMUL_TOO_LARGE: c_int = -2; @@ -15,7 +25,9 @@ pub const OMEGA_GPU_MATMUL_TILE_M: u32 = 16; pub const OMEGA_GPU_MATMUL_TILE_N: u32 = 8; pub const OMEGA_GPU_MATMUL_TILE_K: u32 = 16; pub const OMEGA_GPU_MATMUL_MAX_CTAS: u32 = 64; +} +abi_struct! { /// Mirrors `OmegaGpuMatmulInfo` field for field, same order. #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -45,6 +57,7 @@ pub struct OmegaGpuMatmulInfo { pub oracle_ran: bool, pub call_ns: u64, } +} impl OmegaGpuMatmulInfo { pub fn zeroed() -> Self { @@ -81,6 +94,7 @@ impl OmegaGpuMatmulInfo { pub struct OmegaGpuTensor { _private: [u8; 0], } +abi_struct! { /// omega `OmegaGpuAllocStats` (`src/omega_gpu_session.h`), field for field. #[repr(C)] #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -90,7 +104,9 @@ pub struct OmegaGpuAllocStats { pub alloc_failures: u64, pub frees: u64, } +} +abi_struct! { /// omega `OmegaGpuServingBounds` (`src/omega_gpu_serving.h`), field for field. #[repr(C)] #[derive(Debug, Clone, Copy)] @@ -107,7 +123,9 @@ pub struct OmegaGpuServingBounds { pub max_n_one_row: u32, pub kernel_slots: u32, } +} +abi_externs! { MATMUL_FNS; #[cfg(has_omega_gpu)] extern "C" { pub fn omega_gpu_matmul_bf16( @@ -182,15 +200,19 @@ extern "C" { // omega c1/lib-serving bc9fa71 `src/omega_gpu_session.h`: process-wide driver allocation counters. pub fn omega_gpu_session_alloc_stats(out: *mut OmegaGpuAllocStats); } +} // ---- omega `src/omega_gpu_elementwise_api.h` (FB-1 cut 4, pinned 2636409) ---- +abi_consts! { EW_CONSTS; pub const OMEGA_GPU_EW_OK: c_int = 0; pub const OMEGA_GPU_EW_BAD_ARGS: c_int = -1; pub const OMEGA_GPU_EW_TOO_LARGE: c_int = -2; pub const OMEGA_GPU_EW_CODEGEN_FAIL: c_int = -3; pub const OMEGA_GPU_EW_CHIP_FAIL: c_int = -4; pub const OMEGA_GPU_EW_UNWRITTEN: c_int = -5; +} +abi_struct! { /// Mirrors `OmegaGpuEwInfo` field for field, same order. #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -208,6 +230,7 @@ pub struct OmegaGpuEwInfo { pub sm_architecture: u32, pub call_ns: u64, } +} impl OmegaGpuEwInfo { pub fn zeroed() -> Self { @@ -228,6 +251,7 @@ impl OmegaGpuEwInfo { } } +abi_externs! { EW_FNS; #[cfg(has_omega_gpu)] extern "C" { pub fn omega_gpu_rmsnorm_f32( @@ -257,8 +281,10 @@ extern "C" { ) -> c_int; pub fn omega_gpu_elementwise_rc_name(rc: c_int) -> *const c_char; } +} // ---- omega `src/omega_gpu_attention_api.h` (FB-1 cut 5 + 4b + OM-1/OM-2, pinned e5593ae) ---- +abi_consts! { ATTN_CONSTS; pub const OMEGA_GPU_ATTN_OK: c_int = 0; pub const OMEGA_GPU_ATTN_BAD_ARGS: c_int = -1; pub const OMEGA_GPU_ATTN_TOO_LARGE: c_int = -2; @@ -267,7 +293,9 @@ pub const OMEGA_GPU_ATTN_CHIP_FAIL: c_int = -4; pub const OMEGA_GPU_ATTN_UNWRITTEN: c_int = -5; /// `OmegaGpuAttnInfo::kv_source`: KV reached the kernel through the per-call staging copy. pub const OMEGA_GPU_ATTN_KV_STAGED: u32 = 0; +} +abi_struct! { /// Mirrors `OmegaGpuAttnInfo` field for field, same order (note `call_ns` is third). #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -299,6 +327,7 @@ pub struct OmegaGpuAttnInfo { /// `OMEGA_GPU_ATTN_KV_STAGED` (0): the only source in this cut; there is no resident KV. pub kv_source: u32, } +} impl OmegaGpuAttnInfo { pub fn zeroed() -> Self { @@ -337,6 +366,7 @@ const _: () = assert!(std::mem::offset_of!(OmegaGpuAttnInfo, kv_blocks_logical) const _: () = assert!(std::mem::offset_of!(OmegaGpuAttnInfo, q_bytes) == 144); const _: () = assert!(std::mem::offset_of!(OmegaGpuAttnInfo, kv_source) == 168); +abi_struct! { /// Mirrors `OmegaGpuKvLayout` (itself a mirror of aien-kv-cache `KvLayoutDesc`), /// field for field, strides in bytes. #[repr(C)] @@ -352,7 +382,9 @@ pub struct OmegaGpuKvLayout { pub num_layers: u32, pub block_size: u32, } +} +abi_externs! { ATTN_FNS; #[cfg(has_omega_gpu)] extern "C" { pub fn omega_gpu_gqa_attention_f32( @@ -368,7 +400,7 @@ extern "C" { ) -> c_int; pub fn omega_gpu_paged_attention_bf16( q: *const f32, - pool: *const u8, + pool: *const c_void, layout: *const OmegaGpuKvLayout, block_ids: *const u32, num_block_ids: u32, @@ -382,7 +414,7 @@ extern "C" { ) -> c_int; pub fn omega_gpu_paged_attention_batch_bf16( q: *const f32, - pool: *const u8, + pool: *const c_void, layout: *const OmegaGpuKvLayout, block_tables: *const i32, context_lens: *const i32, @@ -398,3 +430,21 @@ extern "C" { pub fn omega_gpu_attention_rc_name(rc: c_int) -> *const c_char; pub fn omega_gpu_attention_last_error() -> *const c_char; } +} + +/// The Rust side of the omega GPU contract, for the manifest check. +pub fn rust_abi() -> aien_abi_conformance::RustAbi { + aien_abi_conformance::RustAbi::default() + .with_struct::() + .with_struct::() + .with_struct::() + .with_struct::() + .with_struct::() + .with_struct::() + .with_consts(MATMUL_CONSTS) + .with_consts(EW_CONSTS) + .with_consts(ATTN_CONSTS) + .with_fns(MATMUL_FNS) + .with_fns(EW_FNS) + .with_fns(ATTN_FNS) +} diff --git a/crates/aien-omega-gpu/src/lib.rs b/crates/aien-omega-gpu/src/lib.rs index 38225aab..5f0de5dc 100644 --- a/crates/aien-omega-gpu/src/lib.rs +++ b/crates/aien-omega-gpu/src/lib.rs @@ -23,6 +23,24 @@ pub const fn is_native() -> bool { cfg!(has_omega_gpu) } +/// What this binary linked for the omega GPU engine (stub, pinned source, developer override or +/// prebuilt), the C ABI check result and the archive digest, as `build.rs` established them. +/// Only `qualifies()` identities count as release-grade native qualification. +pub fn native_identity() -> aien_abi_conformance::NativeIdentity { + aien_abi_conformance::NativeIdentity { + component: "libomega_gpu.a", + link: env!("AIEN_OMEGA_GPU_LINK"), + abi: env!("AIEN_OMEGA_GPU_ABI"), + digest: env!("AIEN_OMEGA_GPU_DIGEST"), + archive_sha256: env!("AIEN_OMEGA_GPU_ARCHIVE_SHA256"), + source_sha: env!("AIEN_OMEGA_GPU_SOURCE_SHA"), + aienos_lock: env!("AIEN_OMEGA_GPU_AIENOS_LOCK"), + physics_lock: env!("AIEN_OMEGA_GPU_PHYSICS_LOCK"), + target: env!("AIEN_OMEGA_GPU_TARGET"), + cc: env!("AIEN_OMEGA_GPU_CC"), + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum OmegaGpuError { /// Stub build: no native library linked. @@ -97,6 +115,18 @@ impl MatmulInfo { } } +/// Element count of a shape, refused with `TOO_LARGE` (before any C call) if the product +/// overflows `usize`: a wrapped product could let a short slice pass `check_len` and hand +/// omega dimensions larger than the buffer behind the pointer. +fn prod(dims: &[usize]) -> Result { + dims.iter() + .try_fold(1usize, |acc, &d| acc.checked_mul(d)) + .ok_or_else(|| OmegaGpuError::Rc { + rc: ffi::OMEGA_GPU_MATMUL_TOO_LARGE, + name: rc_name(ffi::OMEGA_GPU_MATMUL_TOO_LARGE), + }) +} + fn check_len(what: &'static str, expected: usize, got: usize) -> Result<(), OmegaGpuError> { if expected == got { Ok(()) @@ -140,9 +170,9 @@ pub fn matmul_bf16( b: &[u16], c: &mut [f32], ) -> Result { - check_len("a", m * k, a.len())?; - check_len("b", k * n, b.len())?; - check_len("c", m * n, c.len())?; + check_len("a", prod(&[m, k])?, a.len())?; + check_len("b", prod(&[k, n])?, b.len())?; + check_len("c", prod(&[m, n])?, c.len())?; let (mu, ku, nu) = dims(m, k, n)?; #[cfg(has_omega_gpu)] { @@ -178,9 +208,9 @@ pub fn matmul_f32( b: &[f32], c: &mut [f32], ) -> Result { - check_len("a", m * k, a.len())?; - check_len("b", k * n, b.len())?; - check_len("c", m * n, c.len())?; + check_len("a", prod(&[m, k])?, a.len())?; + check_len("b", prod(&[k, n])?, b.len())?; + check_len("c", prod(&[m, n])?, c.len())?; let (mu, ku, nu) = dims(m, k, n)?; #[cfg(has_omega_gpu)] { @@ -239,7 +269,7 @@ impl fmt::Debug for ResidentTensor { impl ResidentTensor { /// Upload a row-major k x n f32 matrix (rounded to bf16 on the host by omega). pub fn upload_f32(k: usize, n: usize, b: &[f32]) -> Result { - check_len("b", k * n, b.len())?; + check_len("b", prod(&[k, n])?, b.len())?; let (_, ku, nu) = dims(1, k, n)?; #[cfg(has_omega_gpu)] { @@ -266,7 +296,7 @@ impl ResidentTensor { /// The resident data equals `upload_f32` of the widened values, except that omega's /// f32-to-bf16 step quiets signaling NaNs (see `aien-inference-abi` `resident.rs`). pub fn upload_bf16(k: usize, n: usize, b: &[u16]) -> Result { - check_len("b", k * n, b.len())?; + check_len("b", prod(&[k, n])?, b.len())?; let (_, ku, nu) = dims(1, k, n)?; #[cfg(has_omega_gpu)] { @@ -304,8 +334,8 @@ impl ResidentTensor { a: &[f32], c: &mut [f32], ) -> Result { - check_len("a", m * self.k, a.len())?; - check_len("c", m * self.n, c.len())?; + check_len("a", prod(&[m, self.k])?, a.len())?; + check_len("c", prod(&[m, self.n])?, c.len())?; let (mu, _, _) = dims(m, self.k, self.n)?; #[cfg(has_omega_gpu)] { @@ -586,9 +616,9 @@ pub fn rmsnorm_f32( eps: f32, out: &mut [f32], ) -> Result { - check_len("x", rows * dim, x.len())?; + check_len("x", prod(&[rows, dim])?, x.len())?; check_len("weight", dim, weight.len())?; - check_len("out", rows * dim, out.len())?; + check_len("out", prod(&[rows, dim])?, out.len())?; let (ru, du) = (ew_dim(rows)?, ew_dim(dim)?); #[cfg(has_omega_gpu)] { @@ -625,10 +655,10 @@ pub fn rope_f32( sin_half: &[f32], out: &mut [f32], ) -> Result { - check_len("v", heads * head_dim, v.len())?; + check_len("v", prod(&[heads, head_dim])?, v.len())?; check_len("cos_half", head_dim / 2, cos_half.len())?; check_len("sin_half", head_dim / 2, sin_half.len())?; - check_len("out", heads * head_dim, out.len())?; + check_len("out", prod(&[heads, head_dim])?, out.len())?; let (hu, du) = (ew_dim(heads)?, ew_dim(head_dim)?); #[cfg(has_omega_gpu)] { @@ -741,10 +771,18 @@ pub fn gqa_attention_f32( head_dim: usize, out: &mut [f32], ) -> Result { - check_len("q", num_q_heads * head_dim, q.len())?; - check_len("k_cache", seq_len * num_kv_heads * head_dim, k_cache.len())?; - check_len("v_cache", seq_len * num_kv_heads * head_dim, v_cache.len())?; - check_len("out", num_q_heads * head_dim, out.len())?; + check_len("q", prod(&[num_q_heads, head_dim])?, q.len())?; + check_len( + "k_cache", + prod(&[seq_len, num_kv_heads, head_dim])?, + k_cache.len(), + )?; + check_len( + "v_cache", + prod(&[seq_len, num_kv_heads, head_dim])?, + v_cache.len(), + )?; + check_len("out", prod(&[num_q_heads, head_dim])?, out.len())?; let (su, qh, kh, hd) = ( attn_dim(seq_len)?, attn_dim(num_q_heads)?, @@ -793,8 +831,8 @@ pub fn paged_attention_bf16( head_dim: usize, out: &mut [f32], ) -> Result { - check_len("q", num_q_heads * head_dim, q.len())?; - check_len("out", num_q_heads * head_dim, out.len())?; + check_len("q", prod(&[num_q_heads, head_dim])?, q.len())?; + check_len("out", prod(&[num_q_heads, head_dim])?, out.len())?; check_pool(pool, layout)?; let (nb, cl, li, qh, kh, hd) = ( attn_dim(block_ids.len())?, @@ -811,7 +849,7 @@ pub fn paged_attention_bf16( let rc = unsafe { ffi::omega_gpu_paged_attention_bf16( q.as_ptr(), - pool.as_ptr(), + pool.as_ptr().cast(), layout, block_ids.as_ptr(), nb, @@ -851,12 +889,12 @@ pub fn paged_attention_batch_bf16( head_dim: usize, out: &mut [f32], ) -> Result { - check_len("q", num_seqs * num_q_heads * head_dim, q.len())?; - check_len("out", num_seqs * num_q_heads * head_dim, out.len())?; + check_len("q", prod(&[num_seqs, num_q_heads, head_dim])?, q.len())?; + check_len("out", prod(&[num_seqs, num_q_heads, head_dim])?, out.len())?; check_len("context_lens", num_seqs, context_lens.len())?; check_len( "block_tables", - num_seqs * max_blocks_per_seq, + prod(&[num_seqs, max_blocks_per_seq])?, block_tables.len(), )?; check_pool(pool, layout)?; @@ -875,7 +913,7 @@ pub fn paged_attention_batch_bf16( let rc = unsafe { ffi::omega_gpu_paged_attention_batch_bf16( q.as_ptr(), - pool.as_ptr(), + pool.as_ptr().cast(), layout, block_tables.as_ptr(), context_lens.as_ptr(), diff --git a/crates/aien-omega-gpu/tests/abi_manifest.rs b/crates/aien-omega-gpu/tests/abi_manifest.rs new file mode 100644 index 00000000..4382250f --- /dev/null +++ b/crates/aien-omega-gpu/tests/abi_manifest.rs @@ -0,0 +1,34 @@ +//! The Rust mirror of the omega GPU ABI (src/ffi.rs) must equal abi/omega_gpu.manifest, +//! field by field (offset, size, kind, order), constant by constant and signature by +//! signature. Runs in every build, the stub included. + +#[test] +fn rust_ffi_matches_the_manifest() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("abi/omega_gpu.manifest"); + aien_abi_conformance::assert_manifest(&aien_omega_gpu::ffi::rust_abi(), &path); +} + +/// What this test binary linked, as `build.rs` recorded it. Prints one +/// `AIEN_NATIVE_IDENTITY {json}` line (scripts/abi-qualify.sh collects it). A linked build +/// must never report the stub, a stub build must never qualify, and with +/// `AIEN_ABI_QUALIFY=1` (the qualification run) the identity must qualify. +#[test] +fn native_identity_matches_the_link() { + let id = aien_omega_gpu::native_identity(); + println!("AIEN_NATIVE_IDENTITY {}", id.to_json()); + if cfg!(has_omega_gpu) { + assert_ne!(id.link, "stub", "{id:?}"); + assert!(id.digest != "none", "{id:?}"); + } else { + assert_eq!(id.link, "stub", "{id:?}"); + assert!(!id.qualifies()); + } + if std::env::var("AIEN_ABI_QUALIFY").as_deref() == Ok("1") { + assert!( + id.qualifies(), + "{} does not qualify: {:?}", + id.component, + id.gaps() + ); + } +} diff --git a/crates/aien-omega-gpu/tests/parity.rs b/crates/aien-omega-gpu/tests/parity.rs index 0d752d94..2d5d6493 100644 --- a/crates/aien-omega-gpu/tests/parity.rs +++ b/crates/aien-omega-gpu/tests/parity.rs @@ -139,3 +139,20 @@ fn chip_parity_f32_and_bf16() { } } } + +/// Shape products that overflow `usize` are refused before the C call (TOO_LARGE), in debug +/// and release alike. Before abi-qual, `seq_len * num_kv_heads * head_dim` wrapped to 0 in a +/// release build, so empty cache slices passed the length check with each dimension still +/// inside u32 range; only omega's own argument checks stood between that call and an +/// out-of-bounds read. +#[test] +fn overflowing_shapes_are_refused_before_ffi() { + let too_large = |e: OmegaGpuError| matches!(e, OmegaGpuError::Rc { rc: -2, .. }); + let q = vec![0f32; 1 << 16]; + let mut out = vec![0f32; 1 << 16]; + let e = gqa_attention_f32(&q, &[], &[], 1 << 31, 1, 1 << 17, 1 << 16, &mut out).unwrap_err(); + assert!(too_large(e.clone()), "{e:?}"); + let mut c = vec![0f32; 0]; + let e = matmul_f32(usize::MAX / 2 + 1, 2, 0, &[], &[], &mut c).unwrap_err(); + assert!(too_large(e.clone()), "{e:?}"); +} diff --git a/docs/abi-qualification/INVENTORY.md b/docs/abi-qualification/INVENTORY.md new file mode 100644 index 00000000..1697d20c --- /dev/null +++ b/docs/abi-qualification/INVENTORY.md @@ -0,0 +1,97 @@ +# Omega and AIEN ABI qualification: inventory (2026-10-11) + +Scope: mission sections 4 to 10 (`~/handoffs/2026-10-11-abi-qualification-mission.md`). +Sources read at: omega `6c6180cf` (omega.lock; ABI headers identical to omega main `82f31173`), +physics `6d7cf0d4`, aienos `b84c0a67` (omega aienos.lock) and aienos main `3b2004b6`, +sovereign-core main `bd438bcc`. Tags: **implemented** (true before this work), **fixed here** +(defect or gap closed by the abi-qual PRs), **partial**, **missing**, **unnecessary**. +`sc` = this repository, `om` = omega, `ao` = aienos. + +## Boundaries + +| Boundary | Producer | Consumer | Linked into production | +|---|---|---|---| +| rxc_host v2 (composition facade) | om `src/runtime/rxc_host_abi.h`, `.c`; archive `librx_compose.a` (`mk/rx_compose_lib.mk`) | sc `crates/aien-omega-compose` | yes (aien-runtime, aien-cli) | +| omega GPU engine | om `src/omega_gpu_{matmul_api,session,serving,elementwise_api,attention_api}.h`; `libomega_gpu.a` | sc `crates/aien-omega-gpu`, used by `aien-inference-abi` | yes on the GB10 build | +| AIENOS capability authority (C, 64-bit generation) | ao `native/capability/aienos_capability.h` | om `src/runtime/aienos_cap.h` (hand copy), merged into `librx_compose.a` | yes, through librx_compose.a | +| AIENOS capability (Rust, 32-bit generation) | ao `crates/aienos-capability-ffi` | nothing in sc, om or ao links it (grep, 2026-10-11) | no | + +## Section 4: ABI compatibility (rxc_host and GPU) + +| Item | Before | Now | Evidence | +|---|---|---|---| +| 4.1 size and alignment | partial: rxc_host checks version + 4 sizes at open (om `rxc_host_abi.c:458-465`, sc `aien-omega-compose/src/lib.rs:238`); GPU none | fixed here | manifests `crates/*/abi/*.manifest` (`struct Name size align`), C probe `sizeof`/`_Alignof` in build.rs | +| 4.2 offsets and order | missing (size only; an equal-size reorder passed) | fixed here | manifest `field` lines in order; header parse checks names and order; test `c_side.rs` equal-size reorder | +| 4.3 widths and signedness | missing | fixed here | C11 `_Generic` kind per field and per constant; tests width + signedness | +| 4.4 enum representation | unnecessary as a type: rxc_host enums are anonymous constant lists and every mirrored function takes and returns plain integers; the one typed enum (`OmegaGpuEwOp`, om `omega_gpu_elementwise_api.h:57-88`) appears only in functions Rust does not mirror | values checked as constants | `const` lines (RXC_HOST_E_*, OMEGA_GPU_RC_*) | +| 4.5 bool representation | unnecessary: no `bool` field or parameter crosses; flags are u32 | guarded | kind check refuses bool vs u8 (test `bool_to_u8`) | +| 4.6 function pointers, calling convention | partial: typed `extern "C"` only | fixed here | `fnptr` + `fn` signature lines from header prototypes; tests param + callback change | +| 4.7 pointer validity, ownership | implemented: safe wrappers own buffers, check lengths before FFI | kept; GPU `pool` param drift fixed (`*const u8` vs `const void *`) | sc `aien-omega-gpu/src/ffi.rs`, found by the C check | +| 4.8 buffer lengths, overflow | partial: GPU length checks multiplied `usize` unchecked (wraps in release) | fixed here | `prod()` sc `aien-omega-gpu/src/lib.rs:121`; test `overflowing_shapes_are_refused_before_ffi` (red on main: overflow panic at lib.rs:745) | +| 4.9 callback lifetime, concurrency, cancellation | implemented: boxes live until `rxc_host_close` returns, close stops workers (sc lib.rs:480-485, om rxc_host_abi.c:448-452); slot table under `g_mu` (om :290) | tested here | `tests/callbacks.rs` 12 open/close cycles (> 4 slots), 3 concurrent homes | +| 4.10 panic and error propagation | implemented: `catch_unwind` in both trampolines (sc lib.rs:218, 232); release `panic = "abort"` (sc Cargo.toml:64) so no unwind reaches C in either profile | strengthened: null `result`/`ctx` refused | `tests/callbacks.rs` panicking Skill and verifier | +| runtime negotiation | rxc_host version + sizes before any other call | kept, unchanged | no new producer descriptor needed: the build-time C check covers layout fully | + +## Section 5: handwritten drift + +Implemented here: one checked-in manifest per boundary, checked from both sides +(`crates/aien-abi-conformance`). Rust side: the `abi_struct!`/`abi_externs!`/`abi_fnptr!`/ +`abi_consts!` declarations render a manifest compared with the file in every `cargo test` +(stub CI included). C side, in build.rs before linking: header parse, compiled layout probe, +`nm` symbol list. No binding generator, no new external dependency (needs `cc` and `nm`, +already required). Results on the Spark: compose 4 structs, 13 functions, 2 callback types, +95 facts; GPU 6 structs, 31 functions, 108 facts; all match. Twelve synthetic drift tests +(`crates/aien-abi-conformance/tests/c_side.rs`) cover reorder, width, signedness, bool, +parameter, callback, version constant, removed field, missing symbol, truncated archive, +missing struct. + +## Section 6: AIENOS capability + +Ruling: two separate implementations that exported the same 17 `aienos_cap_*` symbols with +incompatible `AienosCapRef` layouts (C 16 bytes, 64-bit generation; Rust 8 bytes, 32-bit). +Not linked together today, but interchangeable by link order. aienos `abi-qual/cap-width` +renames the Rust exports to `aienos_cap32_*`, adds `aienos_cap32_abi_layout`, pins the C +layout with `_Static_assert`, adds a symbol-isolation and negative-link script, and fixes a +Rust restart defect (generation reuse after restart, already fixed in C by b1fa747). +Generations were not widened. omega `abi-qual/aienos-cap-conformance` checks +`src/runtime/aienos_cap.h` against the pinned aienos header (25 layout facts, 27 +declarations, 8 refused mutants). Stale ref, recycled slot, exhaustion, unauthorized use: +C side implemented before (`ao native/capability/capability_test.c`); Rust side fixed there. + +## Section 7: native artifact identity + +| Item | Before | Now | +|---|---|---| +| omega.lock checkout check | implemented (compose build.rs, GPU build.rs) | kept | +| prebuilt `*_LIB` | accepted with no digest | fixed: `*_LIB_SHA256` required and matched, every manifest function must be defined; identity `prebuilt`, never qualifies | +| stub under `AIEN_REQUIRE_NATIVE_LIBS=1` | `AIEN_FORCE_CPU_STUB=1` silently won | fixed: refused | +| expected vs actual digest | missing | fixed: `native-artifacts.lock` (archive, omega sha, target, cc version, sha256); mismatch fails the build, unlisted combination warns and does not qualify | +| provenance in the binary | missing | fixed: `native_identity()` in both crates (link kind, ABI result, digest state, archive sha256, omega, aienos.lock, physics.lock, target, cc) | +| sovereign-core commit, flags, tools | missing | `scripts/abi-qualify.sh` evidence.json | + +## Section 8: safe cross-language execution + +Implemented before and confirmed: no unwind across C (catch_unwind + release abort); +callback contexts outlive close; `Compose` is `Send` not `Sync` (sc lib.rs:196); +`ResidentTensor` is `Send` not `Sync` and held in a `Mutex` (sc aien-omega-gpu lib.rs:248-261, +aien-inference-abi resident.rs:36); omega serializes GPU calls with the session lock +(om `omega_gpu_session.c:28,67`). Fixed here: null result pointer in the Skill trampoline, +usize overflow in length checks. Noted, not changed: `check_pool` checks only +`pool.len() >= pool_bytes` and trusts omega for stride bounds (sc lib.rs:939); +`rxc_host_set_wait_ms` returns `RX_ERR_ARG`, not `RXC_HOST_E_ARG` (om rxc_host_abi.c:338-339; +both are -1 (om `rx_world.h:117`, `rxc_host_abi.h` RXC_HOST_E_ARG), so callers see the right code). + +## Sections 9 and 10: tests, CI, entry point + +Covered by tests: compatible pinned build, version mismatch, equal-size reorder, signature +change, wrong prebuilt hash, wrong omega commit, missing symbol, truncated archive, callback +failure and panic, invalid lengths and overflow, repeated init/destroy, concurrent +callbacks, explicit stub, required-native with no library (`scripts/test-native-identity.sh`, +16 cases, in the required CI job), CPU vs GPU path identity (`native_identity()`), GPU +parity (existing chip suites, run by `scripts/abi-qualify.sh --chip`). +Entry point: `scripts/abi-qualify.sh [--chip]`, exit 0 PASS, 1 FAIL, 2 INCOMPLETE. +Registered in the local verification gates (ADR 0033): `tests/gates/sc-native-identity.gate` +(step `native-identity` in `tests/gates/run.sh`), and `native-artifacts.lock` is an input of +SC-TEST and SC-LINKED-COMPOSE. Partial: the GB10 part of `abi-qualify.sh --chip` stays an +operator run with its own evidence.json (no GB10 gate class exists in the manifests yet). +Not wired: the GPU C-side check on hosted CI (the GPU archive builds only on the Spark). diff --git a/native-artifacts.lock b/native-artifacts.lock new file mode 100644 index 00000000..9fb79382 --- /dev/null +++ b/native-artifacts.lock @@ -0,0 +1,8 @@ +# Recorded digests of the omega archives sovereign-core links (aien-abi-conformance). +# One line per archive: +# A build from the pinned omega checkout for a listed target and compiler must produce exactly +# this digest, or build.rs fails. A combination not listed builds with a warning and its +# native_identity() reports digest "unrecorded", which does not qualify. +# Update only from a qualification run (scripts/abi-qualify.sh prints the lines to add). +librx_compose.a 6c6180cf378075b61291f4565d226eba38b4decd aarch64-unknown-linux-gnu 3eb20f5ec60b46541332c5d18ed8bfbf5acec3263073d660ccc2b14ce67b6770 cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 +libomega_gpu.a 6c6180cf378075b61291f4565d226eba38b4decd aarch64-unknown-linux-gnu afe5cb9e0b862cd13c85498f5452e13d95b69e12fcc70ae329a360b4175e6c66 cc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 diff --git a/scripts/.crumb b/scripts/.crumb index 066a2d6b..ef96dde3 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -4,14 +4,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-11T15:24:08Z", + "compiled_at": "2026-10-11T20:24:07Z", "compiler": "crumb-compile/1", - "digest": "sha256:6c97a5cb9d0f05465df81a036e54d7113433b64dcbf9f67bc6453032a1d4cb3f", + "digest": "sha256:07f19c8d7013a03659eb514ccf94dd7ff76f2ff3ce3736cc3bb11c156ed30e1c", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 37, - "generated_at_commit": "2a8b07d0d0139114b4c5be733c069eb8006ba56c", - "source_tree": "sha256:d4ad311f2443c3a556cef59d6d698de2b983131a46b69b57f766e51e68023bbf" + "files": 39, + "generated_at_commit": "cc3fd4f0794c49f5f311e407a290d873bc1417fd", + "source_tree": "sha256:598bb5a2099247f550440bb55a97df08889b7495b1948f56e5611cf1bc2171f5" } }, "parent": { diff --git a/scripts/abi-qualify.sh b/scripts/abi-qualify.sh new file mode 100755 index 00000000..aa50e5cb --- /dev/null +++ b/scripts/abi-qualify.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash +# abi-qualify.sh: qualify the omega and AIEN native boundary on this machine, in one command. +# +# Builds sovereign-core against the pinned omega, physics and aienos checkouts with +# AIEN_REQUIRE_NATIVE_LIBS=1 (a stub is refused, never a quiet pass), then runs: +# conformance aien-abi-conformance unit and C-side tests (synthetic drift cases) +# identity scripts/test-native-identity.sh (stub, prebuilt and wrong-commit refusals) +# compose aien-omega-compose linked: ABI manifest, native identity, callback safety, +# the compose suite (ignored tests included) +# gpu-host aien-omega-gpu linked host tests: ABI manifest, native identity, argument +# refusals (no chip work) +# chip only with --chip: GB10 parity (aien-omega-gpu parity, aien-inference-abi +# omega_backend_parity and the crate's linked tests), under the GPU lease +# The build scripts check the C headers, a compiled layout probe and the archive symbols against +# the checked-in ABI manifests and the archive digests against native-artifacts.lock, and the +# identity tests run with AIEN_ABI_QUALIFY=1, so each linked library must report +# pinned-source + abi pass + digest locked. +# +# Usage: scripts/abi-qualify.sh [--chip] [--pins DIR] [--out DIR] +# --pins DIR pinned checkouts (default target/pins), materialized by scripts/pins.sh --gpu +# --out DIR logs and evidence.json (default target/abi-qualification) +# --chip also run the GB10 tests. Needs `quietlock check` to return 0 and +# /tmp/aien-gb10.lock to be free (taken with flock -n, as omega tools/chip_run.sh +# does); otherwise the chip part is INCOMPLETE. Never killed, never timed out. +# Exit: 0 PASS, 1 FAIL (a check failed), 2 INCOMPLETE (something required could not run). +# Without --chip a PASS covers the host scope only; evidence.json says "scope":"host". +set -uo pipefail +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +PINS="$ROOT/target/pins" +OUT="$ROOT/target/abi-qualification" +CHIP=0 +while [ $# -gt 0 ]; do + case "$1" in + --chip) CHIP=1 ;; + --pins) PINS="${2:?--pins DIR}"; shift ;; + --out) OUT="${2:?--out DIR}"; shift ;; + *) echo "usage: scripts/abi-qualify.sh [--chip] [--pins DIR] [--out DIR]" >&2; exit 2 ;; + esac + shift +done +mkdir -p "$OUT" +OUT="$(cd "$OUT" && pwd)" +cd "$ROOT" + +STEPS=() +fails=0 +incomplete=0 +CHIP_STATE="not-requested" +CHIP_REASON="" +note() { echo "abi-qualify: $*"; } +record() { # record + STEPS+=("{\"name\":\"$1\",\"status\":\"$2\",\"log\":\"$OUT/$1.log\",\"detail\":\"$3\"}") + note "$1: $2${3:+ ($3)}" + case "$2" in fail) fails=$((fails + 1)) ;; incomplete) incomplete=$((incomplete + 1)) ;; esac +} +step() { # step : pass when the command exits 0 + local name=$1 + shift + if "$@" >"$OUT/$name.log" 2>&1; then record "$name" pass ""; else record "$name" fail "exit $?"; fi +} +# A cargo test step must also have run at least one test and left nothing ignored. +tests_ran() { + local log="$OUT/$1.log" + grep -qE '^test result: ok\. [1-9][0-9]* passed' "$log" && + ! grep -qE '^test result:.* [1-9][0-9]* ignored' "$log" +} + +# 1. Pins (omega at omega.lock, physics and aienos at omega's locks). +if bash scripts/pins.sh --gpu "$PINS" >"$OUT/pins.log" 2>&1 && [ -f "$PINS/env.sh" ]; then + record pins pass "" + # shellcheck disable=SC1091 + . "$PINS/env.sh" +else + record pins incomplete "scripts/pins.sh --gpu failed: no pinned omega, nothing native can be qualified" +fi +export AIEN_ABI_QUALIFY=1 + +if [ "${AIEN_REQUIRE_NATIVE_LIBS:-}" = "1" ]; then + step conformance cargo test -p aien-abi-conformance + step identity bash scripts/test-native-identity.sh + step compose cargo test -p aien-omega-compose --test abi_manifest --test callbacks --test compose \ + -- --include-ignored --test-threads=1 --nocapture + tests_ran compose || record compose-ran fail "no linked compose test ran, or some were ignored" + step gpu-host cargo test -p aien-omega-gpu -- --test-threads=1 --nocapture +fi + +# 2. What was linked: one identity line per native library, each must qualify. +IDS=$(cat "$OUT"/compose.log "$OUT"/gpu-host.log 2>/dev/null | sed -n 's/.*AIEN_NATIVE_IDENTITY \({.*}\).*/\1/p' | sort -u) +for c in librx_compose.a libomega_gpu.a; do + if printf '%s\n' "$IDS" | grep -F "\"component\":\"$c\"" | grep -qF '"qualifies":true'; then + record "identity-$c" pass "" + elif [ "${AIEN_REQUIRE_NATIVE_LIBS:-}" = "1" ]; then + record "identity-$c" fail "no qualifying identity reported" + else + record "identity-$c" incomplete "not built" + fi +done + +# 3. GB10 chip tests, only on request, only when the machine is free. +if [ "$CHIP" = 1 ] && [ "$fails" -eq 0 ] && [ "$incomplete" -eq 0 ]; then + if ! command -v quietlock >/dev/null; then + CHIP_STATE=incomplete CHIP_REASON="quietlock not installed" + elif ! quietlock check >"$OUT/quietlock.log" 2>&1; then + CHIP_STATE=incomplete CHIP_REASON="quietlock check is nonzero: a machine hold is up" + else + exec 9>/tmp/aien-gb10.lock + if ! flock -n 9; then + CHIP_STATE=incomplete CHIP_REASON="/tmp/aien-gb10.lock is held by another run" + else + CHIP_STATE=ran + step chip-gpu cargo test -p aien-omega-gpu --test parity -- --include-ignored --test-threads=1 --nocapture + tests_ran chip-gpu || record chip-gpu-ran fail "chip parity did not run" + step chip-inference cargo test -p aien-inference-abi --test omega_backend_parity -- \ + --include-ignored --skip chip_mixed_matmul_then_elementwise --test-threads=1 --nocapture + tests_ran chip-inference || record chip-inference-ran fail "chip backend parity did not run" + step chip-inference-linked cargo test -p aien-inference-abi -- --test-threads=1 + flock -u 9 + fi + exec 9>&- + fi + [ "$CHIP_STATE" = incomplete ] && record chip incomplete "$CHIP_REASON" +elif [ "$CHIP" = 1 ]; then + CHIP_STATE=incomplete CHIP_REASON="host checks did not pass" + record chip incomplete "$CHIP_REASON" +fi + +# 4. Evidence. +if [ "$fails" -gt 0 ]; then VERDICT=FAIL CODE=1 +elif [ "$incomplete" -gt 0 ]; then VERDICT=INCOMPLETE CODE=2 +else VERDICT=PASS CODE=0; fi +SCOPE=host +[ "$CHIP" = 1 ] && SCOPE=host+chip +j() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g' | tr -d '\n'; } +rev() { git -C "$1" rev-parse HEAD 2>/dev/null || echo unknown; } +dirty=false +[ -n "$(git status --porcelain 2>/dev/null)" ] && dirty=true +{ + printf '{\n"verdict":"%s",\n"scope":"%s",\n"date":"%s",\n' "$VERDICT" "$SCOPE" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" + printf '"host":"%s",\n"target":"%s",\n' "$(j "$(uname -srm)")" "$(rustc -vV | sed -n 's/^host: //p')" + printf '"rustc":"%s",\n"cc":"%s",\n"nm":"%s",\n' "$(j "$(rustc -V)")" "$(j "$(${CC:-cc} --version | head -1)")" "$(j "$(nm --version | head -1)")" + printf '"flags":{"RUSTFLAGS":"%s","CFLAGS":"%s","CC":"%s","AIEN_REQUIRE_NATIVE_LIBS":"%s"},\n' \ + "$(j "${RUSTFLAGS:-}")" "$(j "${CFLAGS:-}")" "$(j "${CC:-cc}")" "${AIEN_REQUIRE_NATIVE_LIBS:-}" + printf '"commits":{"sovereign_core":"%s","sovereign_core_dirty":%s,"omega_lock":"%s","omega":"%s","physics":"%s","aienos":"%s"},\n' \ + "$(rev "$ROOT")" "$dirty" "$(tr -d '[:space:]' "$OUT/evidence.json" +note "$VERDICT (scope $SCOPE): evidence $OUT/evidence.json" +exit "$CODE" diff --git a/scripts/test-linked-compose.sh b/scripts/test-linked-compose.sh index 2732dc25..264e9543 100755 --- a/scripts/test-linked-compose.sh +++ b/scripts/test-linked-compose.sh @@ -49,12 +49,14 @@ for f in "$ROOT"/crates/aien-runtime/tests/*.rs; do RT+=(--test "$t") done [ "${#RT[@]}" -ge 90 ] || die "found only $((${#RT[@]} / 2)) aien-runtime test targets" +# aien-omega-compose: the compose suite, callback safety (abi-qual) and the ABI manifest + native identity. +OC=(--test compose --test callbacks --test abi_manifest) CLI=(--test compose_ordinary_flow_test --test allen_concurrency_test) ATT=$(count -p aien-runtime --test approved_attacks_test) -ALL=$(( $(count -p aien-omega-compose --test compose) + $(count -p aien-runtime --lib) + $(count -p aien-runtime "${RT[@]}") + $(count -p aien-cli "${CLI[@]}") )) +ALL=$(( $(count -p aien-omega-compose "${OC[@]}") + $(count -p aien-runtime --lib) + $(count -p aien-runtime "${RT[@]}") + $(count -p aien-cli "${CLI[@]}") )) [ "$ATT" -gt 0 ] && [ "$ALL" -gt "$ATT" ] || die "could not list the linked tests" : >"$LOG" -run -p aien-omega-compose --test compose +run -p aien-omega-compose "${OC[@]}" run -p aien-runtime --lib run -p aien-runtime "${RT[@]}" run -p aien-cli "${CLI[@]}" @@ -69,4 +71,4 @@ want=$(( ALL + ATT * (REPEAT - 1) )) ran=$(grep -E '^test result: ok\. [0-9]+ passed' "$LOG" | awk '{s += $4} END {print s + 0}') [ "$ran" -ge "$want" ] || die "only $ran linked tests passed (expected $want: $ALL linked tests + approved_attacks $ATT x $((REPEAT - 1)) more)" if grep -E '^test result:.* [1-9][0-9]* ignored' "$LOG" >/dev/null; then die "tests were still ignored"; fi -echo "test-linked-compose: PASS ($ran linked tests passed: $ALL across compose, aien-runtime library tests, every aien-runtime test target but prefill_e2e*, aien-cli ordinary flow + ALLEN concurrency; approved_attacks x$REPEAT)" +echo "test-linked-compose: PASS ($ran linked tests passed: $ALL across compose + callbacks + abi_manifest, aien-runtime library tests, every aien-runtime test target but prefill_e2e*, aien-cli ordinary flow + ALLEN concurrency; approved_attacks x$REPEAT)" diff --git a/scripts/test-native-identity.sh b/scripts/test-native-identity.sh new file mode 100755 index 00000000..be8b24ea --- /dev/null +++ b/scripts/test-native-identity.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# Native identity checks in the build scripts of aien-omega-compose and aien-omega-gpu. +# Runs without omega: every case below must be decided by build.rs before any make. +# - a stub together with AIEN_REQUIRE_NATIVE_LIBS=1 is refused +# - AIEN_REQUIRE_NATIVE_LIBS=1 with no library source is refused +# - a prebuilt archive with no expected sha256, a wrong one, or a truncated archive is refused +# - a prebuilt archive that misses one ABI function is refused +# - an omega checkout at a commit other than omega.lock is refused +# - a correct prebuilt archive builds, and its identity says "prebuilt" (never qualifies) +# Exit 0 when every case behaves, 1 otherwise. +set -euo pipefail +ROOT=$(cd "$(dirname "$0")/.." && pwd) +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT +export CARGO_TARGET_DIR="${AIEN_IDENTITY_TARGET_DIR:-$ROOT/target/native-identity}" +for v in $(env | sed -n 's/^\(AIEN_[A-Z0-9_]*\)=.*/\1/p'); do unset "$v"; done + +fails=0 +pass() { echo "ok $1"; } +fail() { echo "FAIL $1"; fails=$((fails + 1)); } + +# expect_refused [VAR=value ...] +expect_refused() { + local crate=$1 name=$2 pat=$3 + shift 3 + local log="$WORK/log" + if env "$@" cargo check -q -p "$crate" >"$log" 2>&1; then + fail "$crate: $name (build was accepted)" + elif grep -qF -- "$pat" "$log"; then + pass "$crate: $name" + else + fail "$crate: $name (refused, but not with '$pat')" + tail -5 "$log" + fi +} + +# fake_archive [function to leave out] +fake_archive() { + local src="$WORK/fake-$$-$RANDOM.c" + sed -n 's/^fn \([A-Za-z0-9_]*\) .*/\1/p' "$1" | { grep -vx "${3:-}" || true; } | + sed 's/.*/int &(void) { return 0; }/' >"$src" + cc -c -o "$src.o" "$src" + rm -f "$2" + ar rcs "$2" "$src.o" +} + +# A git checkout at a commit that is not omega.lock. +WRONG="$WORK/wrong-omega" +git init -q "$WRONG" +git -C "$WRONG" -c user.name=t -c user.email=t@t commit -q --allow-empty -m wrong + +check_crate() { + local crate=$1 manifest=$2 libvar=$3 dirvar=$4 drop=$5 + local good="$WORK/$crate-good.a" short="$WORK/$crate-short.a" miss="$WORK/$crate-miss.a" + fake_archive "$manifest" "$good" + fake_archive "$manifest" "$miss" "$drop" + local sha miss_sha + sha=$(sha256sum "$good" | cut -d' ' -f1) + miss_sha=$(sha256sum "$miss" | cut -d' ' -f1) + head -c 100 "$good" >"$short" + + expect_refused "$crate" "stub with required native" "contradict each other" \ + AIEN_FORCE_CPU_STUB=1 AIEN_REQUIRE_NATIVE_LIBS=1 + expect_refused "$crate" "required native with no library" "AIEN_REQUIRE_NATIVE_LIBS=1 but" \ + AIEN_REQUIRE_NATIVE_LIBS=1 + expect_refused "$crate" "prebuilt with no sha256" "no expected digest" \ + "$libvar=$good" + expect_refused "$crate" "prebuilt with a wrong sha256" "expects" \ + "$libvar=$good" "${libvar}_SHA256=$(printf '0%.0s' {1..64})" + expect_refused "$crate" "truncated prebuilt" "truncated or corrupted" \ + "$libvar=$short" "${libvar}_SHA256=$sha" + expect_refused "$crate" "prebuilt missing $drop" "does not define" \ + "$libvar=$miss" "${libvar}_SHA256=$miss_sha" + expect_refused "$crate" "omega checkout at the wrong commit" "is at '" \ + "$dirvar=$WRONG" + + if env "$libvar=$good" "${libvar}_SHA256=$sha" cargo check -q -p "$crate" >"$WORK/log" 2>&1 && + grep -qsx "cargo:rustc-env=${6}_LINK=prebuilt" "$(ls -t "$CARGO_TARGET_DIR"/debug/build/"$crate"-*/output | head -1)"; then + pass "$crate: matching prebuilt builds and says prebuilt" + else + fail "$crate: matching prebuilt builds and says prebuilt" + tail -5 "$WORK/log" + fi +} + +cd "$ROOT" +check_crate aien-omega-compose crates/aien-omega-compose/abi/rxc_host_abi.manifest \ + AIEN_OMEGA_COMPOSE_LIB AIEN_OMEGA_COMPOSE_DIR rxc_host_recover AIEN_OMEGA_COMPOSE +check_crate aien-omega-gpu crates/aien-omega-gpu/abi/omega_gpu.manifest \ + AIEN_OMEGA_GPU_LIB AIEN_OMEGA_DIR omega_gpu_matmul_f32 AIEN_OMEGA_GPU + +if [ "$fails" -ne 0 ]; then + echo "native identity: $fails case(s) failed" + exit 1 +fi +echo "native identity: all cases behave" diff --git a/tests/gates/run.sh b/tests/gates/run.sh index 8bf6efb8..6813567e 100755 --- a/tests/gates/run.sh +++ b/tests/gates/run.sh @@ -48,6 +48,7 @@ case "$step" in ;; aien-verify-tests) sh tools/aien-verify/tests/run.sh ;; pins-selftest) bash scripts/test-pins.sh ;; + native-identity) bash scripts/test-native-identity.sh ;; install-test) bash scripts/test-install.sh ;; scoring-v5) bash docs/campaigns/scoring/test-scoring-v5.sh ;; check) cargo check --workspace --all-targets ;; diff --git a/tests/gates/sc-linked-compose.gate b/tests/gates/sc-linked-compose.gate index e5ebd923..e6b692f3 100644 --- a/tests/gates/sc-linked-compose.gate +++ b/tests/gates/sc-linked-compose.gate @@ -7,6 +7,7 @@ owner: aien-sovereign-core requires: - host inputs: + - native-artifacts.lock - omega.lock - scripts/test-linked-compose.sh - scripts/pins.sh diff --git a/tests/gates/sc-native-identity.gate b/tests/gates/sc-native-identity.gate new file mode 100644 index 00000000..e7de53f8 --- /dev/null +++ b/tests/gates/sc-native-identity.gate @@ -0,0 +1,29 @@ +# tests/gates/sc-native-identity.gate +# Mirrors hosted: ci.yml verify 'bash scripts/test-native-identity.sh' (build-script refusals: stub under +# AIEN_REQUIRE_NATIVE_LIBS, missing library, prebuilt archive without, with a wrong or with a truncated +# sha256, missing ABI symbol, omega checkout at the wrong commit; no omega needed) +gate: SC-NATIVE-IDENTITY +manifest_version: 2 +owner: aien-sovereign-core +requires: + - host +inputs: + - native-artifacts.lock + - omega.lock + - scripts/test-native-identity.sh + - Cargo.toml + - Cargo.lock + - rust-toolchain.toml + - crates/aien-abi-conformance/ + - crates/aien-omega-compose/ + - crates/aien-omega-gpu/ + - tests/gates/ +run: + exec: tests/gates/run.sh + args: ["native-identity"] +expects: + exit: 0 + verdict: PASS +timeout: 20m +exactness: EXACT +cache_scope: machine diff --git a/tests/gates/sc-test.gate b/tests/gates/sc-test.gate index 766f1ba4..9b24528e 100644 --- a/tests/gates/sc-test.gate +++ b/tests/gates/sc-test.gate @@ -6,6 +6,7 @@ owner: aien-sovereign-core requires: - host inputs: + - native-artifacts.lock - Cargo.toml - Cargo.lock - rust-toolchain.toml ```