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 / tools / aien-test / src / status.rs

351 lines · 12011 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//! `aien-test status`: what the local pipeline is doing right now (ADR 0033
17//! Decision 10). Read-only: it never takes a lock or runs a gate.
18
19use crate::evidence::{utc_secs, utc_string};
20use crate::process;
21use crate::resources::{GpuConfig, Hardware, PoolSizes};
22use crate::worker::{self, StateDir};
23use serde_json::Value;
24use std::fs;
25use std::os::unix::fs::MetadataExt;
26use std::path::{Path, PathBuf};
27use std::process::Command;
28use std::time::{SystemTime, UNIX_EPOCH};
29
30/// A lock file's state, read from `/proc/locks` by inode (never by probing
31/// the lock, which could disturb a running gate).
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum LockState {
34 Absent,
35 Free,
36 Held(Vec<u32>),
37}
38
39impl LockState {
40 pub fn text(&self) -> String {
41 match self {
42 LockState::Absent => "absent".to_string(),
43 LockState::Free => "free".to_string(),
44 LockState::Held(pids) => format!(
45 "held (pid {})",
46 pids.iter()
47 .map(|p| p.to_string())
48 .collect::<Vec<_>>()
49 .join(",")
50 ),
51 }
52 }
53}
54
55/// Pids holding a FLOCK on `inode` according to `/proc/locks` text.
56pub fn flock_holders(locks: &str, inode: u64) -> Vec<u32> {
57 let mut pids = Vec::new();
58 for line in locks.lines() {
59 let f: Vec<&str> = line.split_whitespace().collect();
60 // "N: FLOCK ADVISORY WRITE pid maj:min:inode start end"
61 if f.len() < 6 || f[1] != "FLOCK" {
62 continue;
63 }
64 let ino = f[5].rsplit(':').next().and_then(|s| s.parse::<u64>().ok());
65 if ino == Some(inode) {
66 if let Ok(pid) = f[4].parse::<u32>() {
67 if !pids.contains(&pid) {
68 pids.push(pid);
69 }
70 }
71 }
72 }
73 pids
74}
75
76pub fn lock_state(path: &Path, locks: &str) -> LockState {
77 match fs::metadata(path) {
78 Err(_) => LockState::Absent,
79 Ok(m) => {
80 let pids = flock_holders(locks, m.ino());
81 if pids.is_empty() {
82 LockState::Free
83 } else {
84 LockState::Held(pids)
85 }
86 }
87 }
88}
89
90fn proc_locks() -> String {
91 fs::read_to_string("/proc/locks").unwrap_or_default()
92}
93
94/// The quiet flag: `quietlock check` exit code when the tool exists, else the
95/// flag file.
96pub fn quiet_flag(gpu: &GpuConfig) -> String {
97 let mut cmd = Command::new("quietlock");
98 cmd.arg("check");
99 match process::output_gated(&mut cmd) {
100 Ok(o) if o.status.success() => "clear (quietlock check rc 0)".to_string(),
101 Ok(o) => format!(
102 "RAISED (quietlock check rc {}): {}",
103 o.status.code().unwrap_or(-1),
104 String::from_utf8_lossy(&o.stdout)
105 .lines()
106 .next()
107 .unwrap_or("")
108 .trim()
109 ),
110 Err(_) => match &gpu.quiet_flag {
111 Some(p) if p.exists() => format!("RAISED (file {})", p.display()),
112 Some(p) => format!("clear (no file {})", p.display()),
113 None => "unknown (no quietlock, no HOME)".to_string(),
114 },
115 }
116}
117
118fn now_secs() -> u64 {
119 SystemTime::now()
120 .duration_since(UNIX_EPOCH)
121 .map(|d| d.as_secs())
122 .unwrap_or(0)
123}
124
125/// The worker heartbeat line.
126pub fn heartbeat_line(state: &StateDir, now: u64) -> String {
127 let p = state.heartbeat();
128 let Ok(text) = fs::read_to_string(&p) else {
129 return "Worker: no heartbeat".to_string();
130 };
131 let Ok(v) = serde_json::from_str::<Value>(&text) else {
132 return "Worker: heartbeat unreadable".to_string();
133 };
134 let age = v["utc"]
135 .as_str()
136 .and_then(utc_secs)
137 .map(|t| now.saturating_sub(t));
138 let alive = v["pid"]
139 .as_u64()
140 .map(|pid| Path::new(&format!("/proc/{pid}")).exists());
141 format!(
142 "Worker: pid {} {} phase {} repo {} sha {} heartbeat {} ago",
143 v["pid"].as_u64().unwrap_or(0),
144 match alive {
145 Some(true) => "alive",
146 Some(false) => "GONE",
147 None => "?",
148 },
149 v["phase"].as_str().unwrap_or("?"),
150 v["repo"].as_str().unwrap_or("-"),
151 v["sha"]
152 .as_str()
153 .map(|s| &s[..12.min(s.len())])
154 .unwrap_or("-"),
155 match age {
156 Some(a) => format!("{a} s"),
157 None => "? s".to_string(),
158 }
159 )
160}
161
162/// Newest bundle per repository: (repo, sha, verdict, finished_utc).
163pub fn newest_bundles(state: &StateDir) -> Vec<(String, String, String, String)> {
164 let mut out = Vec::new();
165 let Ok(repos) = fs::read_dir(state.root.join("bundles")) else {
166 return out;
167 };
168 let mut repos: Vec<PathBuf> = repos.flatten().map(|e| e.path()).collect();
169 repos.sort();
170 for r in repos {
171 let Ok(shas) = fs::read_dir(&r) else {
172 continue;
173 };
174 let mut best: Option<(String, String, String, String)> = None;
175 for s in shas.flatten() {
176 let p = s.path().join("bundle.json");
177 let Ok(text) = fs::read(&p) else {
178 continue;
179 };
180 let Ok(v) = serde_json::from_slice::<Value>(&text) else {
181 continue;
182 };
183 let fin = v["finished_utc"].as_str().unwrap_or("").to_string();
184 if best.as_ref().is_none_or(|b| fin > b.3) {
185 best = Some((
186 r.file_name()
187 .map(|n| n.to_string_lossy().into_owned())
188 .unwrap_or_default(),
189 v["commit"].as_str().unwrap_or("?").to_string(),
190 match v["plan"]["verdict"].as_str() {
191 Some(p) if p != v["verdict"].as_str().unwrap_or("") => {
192 format!("{} (plan {p})", v["verdict"].as_str().unwrap_or("?"))
193 }
194 _ => v["verdict"].as_str().unwrap_or("?").to_string(),
195 },
196 fin,
197 ));
198 }
199 }
200 if let Some(b) = best {
201 out.push(b);
202 }
203 }
204 out
205}
206
207/// The whole status block.
208pub fn lines(state: &StateDir) -> Vec<String> {
209 let now = now_secs();
210 let mut out = vec![
211 "AIEN STATUS".to_string(),
212 format!("Time: {}", utc_string(now)),
213 ];
214 let pools = PoolSizes::detect();
215 let hw = Hardware::detect();
216 out.push(format!(
217 "Pools: host={} qemu={} gb10=1",
218 pools.host, pools.qemu
219 ));
220 out.push(format!(
221 "Hardware: gb10 {} qemu {}",
222 if hw.gb10_present { "present" } else { "absent" },
223 if hw.qemu_available {
224 "available"
225 } else {
226 "absent"
227 }
228 ));
229 let gpu = GpuConfig::detect();
230 let locks = proc_locks();
231 out.push(format!(
232 "GPU lock {}: {}",
233 gpu.lock_path.display(),
234 lock_state(&gpu.lock_path, &locks).text()
235 ));
236 match &gpu.proof_lock_path {
237 Some(p) => {
238 let slots = p.parent().map(Path::to_path_buf).unwrap_or_default();
239 let mut names: Vec<PathBuf> = fs::read_dir(&slots)
240 .map(|rd| rd.flatten().map(|e| e.path()).collect())
241 .unwrap_or_default();
242 names.sort();
243 names.retain(|n| n.extension().is_some_and(|e| e == "lock"));
244 if names.is_empty() {
245 out.push(format!("aien-proof slots {}: none", slots.display()));
246 }
247 for n in names {
248 out.push(format!(
249 "aien-proof slot {}: {}",
250 n.file_stem()
251 .map(|s| s.to_string_lossy().into_owned())
252 .unwrap_or_default(),
253 lock_state(&n, &locks).text()
254 ));
255 }
256 }
257 None => out.push("aien-proof slots: no board".to_string()),
258 }
259 out.push(format!("Quiet flag: {}", quiet_flag(&gpu)));
260 out.push(format!("State dir: {}", state.root.display()));
261 out.push(heartbeat_line(state, now));
262 let triggers = worker::triggers(state);
263 out.push(format!(
264 "Triggers pending: {}{}",
265 triggers.len(),
266 if triggers.is_empty() {
267 String::new()
268 } else {
269 format!(
270 " ({})",
271 triggers
272 .iter()
273 .map(|(r, s, _)| format!("{r}@{}", &s[..12]))
274 .collect::<Vec<_>>()
275 .join(" ")
276 )
277 }
278 ));
279 let outbox = worker::outbox_files(state).len();
280 out.push(format!("Outbox pending: {outbox}"));
281 let bundles = newest_bundles(state);
282 if bundles.is_empty() {
283 out.push("Newest bundles: none".to_string());
284 }
285 for (repo, sha, verdict, fin) in bundles {
286 out.push(format!(
287 "Newest bundle {repo}: {} {verdict} {fin}",
288 &sha[..12.min(sha.len())]
289 ));
290 }
291 out
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297 use crate::testutil::TempDir;
298
299 #[test]
300 fn proc_locks_parsing() {
301 let text = "1: POSIX ADVISORY READ 4076 103:02:10631027 1073741826 1073742335\n\
302 2: FLOCK ADVISORY WRITE 2379546 00:a9:8128022 0 EOF\n\
303 3: FLOCK ADVISORY WRITE 2502 103:02:8128022 0 EOF\n\
304 4: -> FLOCK ADVISORY WRITE 99 00:a9:8128022 0 EOF\n";
305 assert_eq!(flock_holders(text, 8128022), vec![2379546, 2502]);
306 assert!(flock_holders(text, 10631027).is_empty());
307 let t = TempDir::new("status-lock");
308 let f = t.path().join("x.lock");
309 assert_eq!(lock_state(&f, text), LockState::Absent);
310 fs::write(&f, "").unwrap();
311 assert_eq!(lock_state(&f, text), LockState::Free);
312 let ino = fs::metadata(&f).unwrap().ino();
313 let held = format!("5: FLOCK ADVISORY WRITE 777 00:01:{ino} 0 EOF\n");
314 assert_eq!(lock_state(&f, &held), LockState::Held(vec![777]));
315 assert_eq!(LockState::Held(vec![1, 2]).text(), "held (pid 1,2)");
316 }
317
318 #[test]
319 fn heartbeat_and_bundles() {
320 let t = TempDir::new("status-state");
321 let s = StateDir::new(t.path());
322 assert_eq!(heartbeat_line(&s, 10), "Worker: no heartbeat");
323 s.beat("r", &"c".repeat(40), "run");
324 let l = heartbeat_line(&s, now_secs() + 5);
325 assert!(l.contains("alive") && l.contains("phase run"), "{l}");
326 assert!(newest_bundles(&s).is_empty());
327 for (sha, fin, v) in [
328 ("a", "2026-10-11T01:00:00Z", "PASS"),
329 ("b", "2026-10-11T02:00:00Z", "FAIL"),
330 ] {
331 let d = s.root.join("bundles/r").join(sha.repeat(40));
332 fs::create_dir_all(&d).unwrap();
333 fs::write(
334 d.join("bundle.json"),
335 format!(
336 "{{\"commit\":\"{}\",\"verdict\":\"{v}\",\"finished_utc\":\"{fin}\"}}",
337 sha.repeat(40)
338 ),
339 )
340 .unwrap();
341 }
342 let n = newest_bundles(&s);
343 assert_eq!(n.len(), 1);
344 assert_eq!(n[0].2, "FAIL");
345 let all = lines(&s);
346 assert_eq!(all[0], "AIEN STATUS");
347 assert!(all
348 .iter()
349 .any(|l| l.starts_with("Newest bundle r: bbbbbbbbbbbb FAIL")));
350 }
351}