aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-evidence / src / capture.rs
| 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 | //! Read-only capture of the Linux reference machine (Config A). |
| 17 | //! |
| 18 | //! Sources are procfs, sysfs, git, and the local inference endpoint. GPU |
| 19 | //! identity comes from PCI sysfs rather than vendor userspace tools, and no |
| 20 | //! host boot state is changed. |
| 21 | |
| 22 | use crate::http::{self, Endpoint}; |
| 23 | use aienos_kernel::crypto::sha256::Sha256; |
| 24 | use serde_json::{json, Map, Value}; |
| 25 | use std::collections::BTreeMap; |
| 26 | use std::fs; |
| 27 | use std::io::Read; |
| 28 | use std::path::{Path, PathBuf}; |
| 29 | use std::process::Command; |
| 30 | |
| 31 | pub struct Options { |
| 32 | pub model: PathBuf, |
| 33 | pub endpoint: String, |
| 34 | pub prompt: String, |
| 35 | pub max_tokens: u32, |
| 36 | pub samples: usize, |
| 37 | pub warmup: usize, |
| 38 | pub repos: Vec<(String, PathBuf)>, |
| 39 | pub allow_dirty: bool, |
| 40 | } |
| 41 | |
| 42 | pub const DEFAULT_PROMPT: &str = "Explain in about two hundred words how a copy-on-write page table lets two processes share memory until one of them writes, and what the kernel does on that first write."; |
| 43 | |
| 44 | fn read(path: impl AsRef<Path>) -> Option<String> { |
| 45 | fs::read_to_string(path).ok().map(|s| s.trim().to_string()) |
| 46 | } |
| 47 | |
| 48 | fn command(program: &str, args: &[&str]) -> Option<String> { |
| 49 | let out = Command::new(program).args(args).output().ok()?; |
| 50 | out.status |
| 51 | .success() |
| 52 | .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()) |
| 53 | } |
| 54 | |
| 55 | /// `CPU part` counts from /proc/cpuinfo, e.g. {"0xd85": 10, "0xd87": 10}. |
| 56 | pub fn cpu_parts(cpuinfo: &str) -> BTreeMap<String, u64> { |
| 57 | let mut parts = BTreeMap::new(); |
| 58 | for line in cpuinfo.lines() { |
| 59 | if let Some((key, value)) = line.split_once(':') { |
| 60 | if key.trim() == "CPU part" { |
| 61 | *parts.entry(value.trim().to_string()).or_insert(0) += 1; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | parts |
| 66 | } |
| 67 | |
| 68 | pub fn os_release_pretty(text: &str) -> Option<String> { |
| 69 | text.lines() |
| 70 | .find_map(|l| l.strip_prefix("PRETTY_NAME=")) |
| 71 | .map(|v| v.trim_matches('"').to_string()) |
| 72 | } |
| 73 | |
| 74 | fn meminfo_kb(text: &str, key: &str) -> Option<u64> { |
| 75 | text.lines() |
| 76 | .find_map(|l| l.strip_prefix(key)?.strip_prefix(':')) |
| 77 | .and_then(|v| v.split_whitespace().next()?.parse().ok()) |
| 78 | } |
| 79 | |
| 80 | fn accelerators() -> Vec<Value> { |
| 81 | let mut found = Vec::new(); |
| 82 | let Ok(entries) = fs::read_dir("/sys/bus/pci/devices") else { |
| 83 | return found; |
| 84 | }; |
| 85 | for entry in entries.flatten() { |
| 86 | let dev = entry.path(); |
| 87 | let vendor = read(dev.join("vendor")).unwrap_or_default(); |
| 88 | let class = read(dev.join("class")).unwrap_or_default(); |
| 89 | // NVIDIA display or 3D controller. |
| 90 | if vendor != "0x10de" || !class.starts_with("0x03") { |
| 91 | continue; |
| 92 | } |
| 93 | let device = read(dev.join("device")).unwrap_or_default(); |
| 94 | let driver = fs::read_link(dev.join("driver")) |
| 95 | .ok() |
| 96 | .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())); |
| 97 | let driver_version = driver |
| 98 | .as_ref() |
| 99 | .and_then(|d| read(format!("/sys/module/{d}/version"))); |
| 100 | found.push(json!({ |
| 101 | "pci_bus_id": entry.file_name().to_string_lossy(), |
| 102 | "vendor_device": format!("{}:{}", vendor.trim_start_matches("0x"), device.trim_start_matches("0x")), |
| 103 | "class": class, |
| 104 | "driver": driver, |
| 105 | "driver_version": driver_version, |
| 106 | })); |
| 107 | } |
| 108 | found.sort_by_key(|v| v["pci_bus_id"].as_str().unwrap_or_default().to_string()); |
| 109 | found |
| 110 | } |
| 111 | |
| 112 | fn block_devices() -> Vec<Value> { |
| 113 | let mut devices = Vec::new(); |
| 114 | let Ok(entries) = fs::read_dir("/sys/block") else { |
| 115 | return devices; |
| 116 | }; |
| 117 | for entry in entries.flatten() { |
| 118 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 119 | if ["loop", "ram", "zram"].iter().any(|p| name.starts_with(p)) { |
| 120 | continue; |
| 121 | } |
| 122 | let dev = entry.path(); |
| 123 | let sectors: u64 = read(dev.join("size")) |
| 124 | .and_then(|s| s.parse().ok()) |
| 125 | .unwrap_or(0); |
| 126 | devices.push(json!({ |
| 127 | "name": name, |
| 128 | "size_bytes": sectors * 512, |
| 129 | "model": read(dev.join("device/model")), |
| 130 | })); |
| 131 | } |
| 132 | devices.sort_by_key(|v| v["name"].as_str().unwrap_or_default().to_string()); |
| 133 | devices |
| 134 | } |
| 135 | |
| 136 | pub fn file_sha256(path: &Path) -> std::io::Result<(u64, String)> { |
| 137 | let mut file = fs::File::open(path)?; |
| 138 | let mut hasher = Sha256::new(); |
| 139 | let mut buf = vec![0u8; 4 << 20]; |
| 140 | let mut size = 0u64; |
| 141 | loop { |
| 142 | let n = file.read(&mut buf)?; |
| 143 | if n == 0 { |
| 144 | break; |
| 145 | } |
| 146 | size += n as u64; |
| 147 | hasher.update(&buf[..n]); |
| 148 | } |
| 149 | Ok((size, crate::canon::hex(&hasher.finalize()))) |
| 150 | } |
| 151 | |
| 152 | fn repositories(repos: &[(String, PathBuf)]) -> Result<Vec<Value>, String> { |
| 153 | let mut out = Vec::new(); |
| 154 | for (name, path) in repos { |
| 155 | let p = path.to_string_lossy(); |
| 156 | let commit = command("git", &["-C", &p, "rev-parse", "HEAD"]) |
| 157 | .ok_or_else(|| format!("{name}: not a git checkout at {p}"))?; |
| 158 | let status = command("git", &["-C", &p, "status", "--porcelain"]) |
| 159 | .ok_or_else(|| format!("{name}: git status failed"))?; |
| 160 | out.push(json!({ |
| 161 | "name": name, |
| 162 | "commit": commit, |
| 163 | "branch": command("git", &["-C", &p, "branch", "--show-current"]).filter(|b| !b.is_empty()), |
| 164 | "dirty": !status.is_empty(), |
| 165 | })); |
| 166 | } |
| 167 | Ok(out) |
| 168 | } |
| 169 | |
| 170 | fn workload(opts: &Options) -> Result<Value, String> { |
| 171 | let ep = Endpoint::parse(&opts.endpoint)?; |
| 172 | let model = http::model_ids(&ep)? |
| 173 | .into_iter() |
| 174 | .next() |
| 175 | .ok_or("endpoint lists no models")?; |
| 176 | for _ in 0..opts.warmup { |
| 177 | http::chat_sample(&ep, &model, &opts.prompt, opts.max_tokens)?; |
| 178 | } |
| 179 | let mut samples = Vec::new(); |
| 180 | for index in 0..opts.samples { |
| 181 | let s = http::chat_sample(&ep, &model, &opts.prompt, opts.max_tokens)?; |
| 182 | let round = |x: f64| (x * 1000.0).round() / 1000.0; |
| 183 | samples.push(json!({ |
| 184 | "index": index, |
| 185 | "ttft_ms": round(s.ttft_ms), |
| 186 | "total_ms": round(s.total_ms), |
| 187 | "output_tokens": s.output_tokens, |
| 188 | "decode_tokens_per_second": round(s.decode_tokens_per_second), |
| 189 | })); |
| 190 | } |
| 191 | Ok(json!({ |
| 192 | "endpoint": opts.endpoint, |
| 193 | "model": model, |
| 194 | "prompt": opts.prompt, |
| 195 | "max_tokens": opts.max_tokens, |
| 196 | "temperature": 0, |
| 197 | "warmup_samples": opts.warmup, |
| 198 | "samples": samples, |
| 199 | })) |
| 200 | } |
| 201 | |
| 202 | pub fn capture(opts: &Options) -> Result<Value, String> { |
| 203 | let repos = repositories(&opts.repos)?; |
| 204 | let dirty: Vec<&str> = repos |
| 205 | .iter() |
| 206 | .filter(|r| r["dirty"] == json!(true)) |
| 207 | .filter_map(|r| r["name"].as_str()) |
| 208 | .collect(); |
| 209 | if !dirty.is_empty() && !opts.allow_dirty { |
| 210 | return Err(format!( |
| 211 | "refusing to freeze dirty repositories: {} (commit or use --allow-dirty)", |
| 212 | dirty.join(", ") |
| 213 | )); |
| 214 | } |
| 215 | let (model_size, model_sha) = |
| 216 | file_sha256(&opts.model).map_err(|e| format!("model {}: {e}", opts.model.display()))?; |
| 217 | let cpuinfo = read("/proc/cpuinfo").unwrap_or_default(); |
| 218 | let meminfo = read("/proc/meminfo").unwrap_or_default(); |
| 219 | let parts = cpu_parts(&cpuinfo); |
| 220 | |
| 221 | let mut bundle = Map::new(); |
| 222 | bundle.insert("schema_version".into(), json!(crate::SCHEMA_VERSION)); |
| 223 | bundle.insert("generated_at_utc".into(), json!(crate::time::now_utc())); |
| 224 | bundle.insert( |
| 225 | "capture_tool".into(), |
| 226 | json!({"name": "aienos-evidence", "version": env!("CARGO_PKG_VERSION")}), |
| 227 | ); |
| 228 | bundle.insert( |
| 229 | "config_identity".into(), |
| 230 | json!({ |
| 231 | "host": read("/proc/sys/kernel/hostname"), |
| 232 | "kernel": read("/proc/sys/kernel/osrelease"), |
| 233 | "architecture": std::env::consts::ARCH, |
| 234 | "os_distribution": read("/etc/os-release").as_deref().and_then(os_release_pretty), |
| 235 | "kernel_command_line": read("/proc/cmdline"), |
| 236 | }), |
| 237 | ); |
| 238 | bundle.insert( |
| 239 | "machine_capsule".into(), |
| 240 | json!({ |
| 241 | "firmware": { |
| 242 | "uefi_present": Path::new("/sys/firmware/efi").is_dir(), |
| 243 | "platform_bits": read("/sys/firmware/efi/fw_platform_size"), |
| 244 | }, |
| 245 | "cpu": { |
| 246 | "architecture": std::env::consts::ARCH, |
| 247 | "cores": parts.values().sum::<u64>(), |
| 248 | "parts": parts, |
| 249 | }, |
| 250 | "accelerators": accelerators(), |
| 251 | "memory": { |
| 252 | "total_kb": meminfo_kb(&meminfo, "MemTotal"), |
| 253 | "swap_kb": meminfo_kb(&meminfo, "SwapTotal"), |
| 254 | }, |
| 255 | "block_devices": block_devices(), |
| 256 | }), |
| 257 | ); |
| 258 | bundle.insert( |
| 259 | "toolchains".into(), |
| 260 | json!({ |
| 261 | "rustc": command("rustc", &["--version"]), |
| 262 | "cargo": command("cargo", &["--version"]), |
| 263 | }), |
| 264 | ); |
| 265 | bundle.insert( |
| 266 | "baseline_model".into(), |
| 267 | json!({"path": opts.model, "size_bytes": model_size, "sha256": model_sha}), |
| 268 | ); |
| 269 | bundle.insert("workspace_repositories".into(), Value::Array(repos)); |
| 270 | bundle.insert("reference_workload".into(), workload(opts)?); |
| 271 | bundle.insert( |
| 272 | "recovery_procedure".into(), |
| 273 | json!({"status": "documented_only", "native_boot_rollback_tested": false}), |
| 274 | ); |
| 275 | Ok(crate::canon::seal(Value::Object(bundle))) |
| 276 | } |
| 277 | |
| 278 | #[cfg(test)] |
| 279 | mod tests { |
| 280 | use super::*; |
| 281 | |
| 282 | #[test] |
| 283 | fn counts_heterogeneous_cpu_parts() { |
| 284 | let info = "processor\t: 0\nCPU part\t: 0xd85\n\nprocessor\t: 1\nCPU part\t: 0xd87\n\nprocessor\t: 2\nCPU part\t: 0xd87\n"; |
| 285 | let parts = cpu_parts(info); |
| 286 | assert_eq!(parts.get("0xd85"), Some(&1)); |
| 287 | assert_eq!(parts.get("0xd87"), Some(&2)); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn reads_os_release_and_meminfo() { |
| 292 | assert_eq!( |
| 293 | os_release_pretty("NAME=\"Ubuntu\"\nPRETTY_NAME=\"Ubuntu 24.04.5 LTS\"\n").as_deref(), |
| 294 | Some("Ubuntu 24.04.5 LTS") |
| 295 | ); |
| 296 | assert_eq!( |
| 297 | meminfo_kb( |
| 298 | "MemTotal: 127598748 kB\nSwapTotal: 0 kB\n", |
| 299 | "MemTotal" |
| 300 | ), |
| 301 | Some(127_598_748) |
| 302 | ); |
| 303 | assert_eq!(meminfo_kb("MemTotal: 1 kB\n", "SwapTotal"), None); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn streams_file_hash_matches_one_shot_hash() { |
| 308 | let path = |
| 309 | std::env::temp_dir().join(format!("aienos-evidence-hash-{}", std::process::id())); |
| 310 | let data: Vec<u8> = (0..(9 << 20)).map(|i| (i % 251) as u8).collect(); |
| 311 | fs::write(&path, &data).unwrap(); |
| 312 | let (size, digest) = file_sha256(&path).unwrap(); |
| 313 | fs::remove_file(&path).unwrap(); |
| 314 | assert_eq!(size, data.len() as u64); |
| 315 | assert_eq!( |
| 316 | digest, |
| 317 | crate::canon::hex(&aienos_kernel::crypto::sha256::hash(&data)) |
| 318 | ); |
| 319 | } |
| 320 | } |