interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / e2e_tests / src / harness.rs

244 lines · 8043 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Test harness utilities for AIEN Sovereign Core E2E testing.
17//! Provides safetensors serialization, CLI execution, mathematical telemetry, and invariant auditing.
18//! Uses pure standard library and serde_json to minimize disk space.
19
20use std::collections::HashMap;
21use std::fs;
22use std::path::{Path, PathBuf};
23use std::process::Command;
24use serde_json::{json, Value};
25
26/// Result of executing a CLI binary in opaque-box testing.
27#[derive(Debug, Clone)]
28pub struct CliResult {
29 pub exit_code: i32,
30 pub stdout: String,
31 pub stderr: String,
32}
33
34impl CliResult {
35 pub fn success(&self) -> bool {
36 self.exit_code == 0
37 }
38
39 pub fn assert_no_panics(&self) {
40 assert!(
41 !self.stderr.contains("panicked at"),
42 "CLI panicked in stderr: {}",
43 self.stderr
44 );
45 assert!(
46 !self.stdout.contains("panicked at"),
47 "CLI panicked in stdout: {}",
48 self.stdout
49 );
50 assert!(
51 !self.stderr.contains("SIGSEGV"),
52 "CLI crashed with segmentation fault: {}",
53 self.stderr
54 );
55 }
56}
57
58/// Constructs a raw safetensors binary buffer according to the Hugging Face format specification.
59/// Header: 8-byte little-endian length prefix, JSON metadata, then contiguous raw tensor bytes.
60pub fn create_safetensors_bytes(
61 tensors: &[(&str, &[usize], &str, &[u8])],
62 extra_metadata: Option<HashMap<String, String>>,
63) -> Vec<u8> {
64 let mut header_map = serde_json::Map::new();
65
66 if let Some(meta) = extra_metadata {
67 let mut meta_map = serde_json::Map::new();
68 for (k, v) in meta {
69 meta_map.insert(k, Value::String(v));
70 }
71 header_map.insert("__metadata__".to_string(), Value::Object(meta_map));
72 }
73
74 let mut current_offset: usize = 0;
75 let mut tensor_data = Vec::new();
76
77 for &(name, shape, dtype, data) in tensors {
78 let start = current_offset;
79 let end = current_offset + data.len();
80 current_offset = end;
81 tensor_data.extend_from_slice(data);
82
83 let shape_vals: Vec<Value> = shape.iter().map(|&s| json!(s)).collect();
84 let tensor_entry = json!({
85 "dtype": dtype,
86 "shape": shape_vals,
87 "data_offsets": [start, end]
88 });
89
90 header_map.insert(name.to_string(), tensor_entry);
91 }
92
93 let header_json = serde_json::to_string(&Value::Object(header_map)).expect("JSON serialization");
94 let header_bytes = header_json.as_bytes();
95 let header_len = header_bytes.len() as u64;
96
97 let mut out = Vec::with_capacity(8 + header_bytes.len() + tensor_data.len());
98 out.extend_from_slice(&header_len.to_le_bytes());
99 out.extend_from_slice(header_bytes);
100 out.extend_from_slice(&tensor_data);
101
102 out
103}
104
105/// Executes the compiled aien-cli binary with specified arguments.
106pub fn run_aien_cli(args: &[&str]) -> CliResult {
107 let manifest_dir = env!("CARGO_MANIFEST_DIR");
108 let project_root = Path::new(manifest_dir).parent().unwrap_or(Path::new(manifest_dir));
109 let binary_path = project_root.join("target/debug/aien-cli");
110
111 let mut cmd = if binary_path.exists() {
112 Command::new(&binary_path)
113 } else {
114 let mut c = Command::new("cargo");
115 c.arg("run").arg("-p").arg("aien-cli").arg("--bin").arg("aien-cli").arg("--");
116 c
117 };
118
119 cmd.current_dir(project_root);
120 for arg in args {
121 cmd.arg(arg);
122 }
123
124 let output = cmd.output().expect("Failed to execute aien-cli process");
125
126 CliResult {
127 exit_code: output.status.code().unwrap_or(-1),
128 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
129 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
130 }
131}
132
133/// Computes cosine similarity between two float vectors.
134pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
135 assert_eq!(a.len(), b.len(), "Vector lengths must match for cosine similarity");
136 let mut dot = 0.0f32;
137 let mut norm_a = 0.0f32;
138 let mut norm_b = 0.0f32;
139
140 for i in 0..a.len() {
141 dot += a[i] * b[i];
142 norm_a += a[i] * a[i];
143 norm_b += b[i] * b[i];
144 }
145
146 if norm_a == 0.0 || norm_b == 0.0 {
147 return 0.0;
148 }
149
150 dot / (norm_a.sqrt() * norm_b.sqrt())
151}
152
153/// Computes maximum absolute error between two float vectors.
154pub fn max_absolute_error(a: &[f32], b: &[f32]) -> f32 {
155 assert_eq!(a.len(), b.len(), "Vector lengths must match for absolute error");
156 let mut max_err = 0.0f32;
157 for i in 0..a.len() {
158 let diff = (a[i] - b[i]).abs();
159 if diff > max_err {
160 max_err = diff;
161 }
162 }
163 max_err
164}
165
166/// Computes maximum relative error between two float vectors: |a - b| / max(|a|, |b|, 1e-12).
167pub fn max_relative_error(a: &[f32], b: &[f32]) -> f32 {
168 assert_eq!(a.len(), b.len(), "Vector lengths must match for relative error");
169 let mut max_rel = 0.0f32;
170 for i in 0..a.len() {
171 let denom = a[i].abs().max(b[i].abs()).max(1e-12);
172 let rel = (a[i] - b[i]).abs() / denom;
173 if rel > max_rel {
174 max_rel = rel;
175 }
176 }
177 max_rel
178}
179
180/// Recursive directory scanner using only std::fs.
181fn collect_files_recursively(dir: &Path, files: &mut Vec<PathBuf>) {
182 if let Ok(entries) = fs::read_dir(dir) {
183 for entry in entries.flatten() {
184 let path = entry.path();
185 let file_name = entry.file_name().to_string_lossy().to_string();
186 if file_name == ".git" || file_name == "target" || file_name == ".gemini" {
187 continue;
188 }
189 if path.is_dir() {
190 collect_files_recursively(&path, files);
191 } else if path.is_file() {
192 files.push(path);
193 }
194 }
195 }
196}
197
198/// Scans workspace directory to verify zero plaintext .env or credential secret files exist.
199pub fn audit_zero_disk_secrets(root: &Path) -> Result<(), Vec<PathBuf>> {
200 let mut all_files = Vec::new();
201 collect_files_recursively(root, &mut all_files);
202
203 let mut violations = Vec::new();
204 for path in all_files {
205 if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
206 if name == ".env" || name.starts_with(".env.") {
207 violations.push(path);
208 }
209 }
210 }
211
212 if violations.is_empty() {
213 Ok(())
214 } else {
215 Err(violations)
216 }
217}
218
219/// Audits documentation and code files for strict Sovereign Voice compliance:
220/// Zero em dashes (\u2014) and zero en dashes (\u2013).
221pub fn audit_sovereign_voice_dashes(root: &Path) -> Result<(), Vec<(PathBuf, usize, String)>> {
222 let mut all_files = Vec::new();
223 collect_files_recursively(root, &mut all_files);
224
225 let mut violations = Vec::new();
226 for path in all_files {
227 let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");
228 if ext == "rs" || ext == "md" || ext == "toml" || ext == "sh" {
229 if let Ok(content) = fs::read_to_string(&path) {
230 for (line_idx, line) in content.lines().enumerate() {
231 if line.contains('\u{2014}') || line.contains('\u{2013}') {
232 violations.push((path.clone(), line_idx + 1, line.to_string()));
233 }
234 }
235 }
236 }
237 }
238
239 if violations.is_empty() {
240 Ok(())
241 } else {
242 Err(violations)
243 }
244}