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
aien-sovereign-core-mv / crates / aien-serve-http / src / chip_reservation.rs
| 1 | //! Who holds the chip for this server: itself, or a trusted ancestor. |
| 2 | //! |
| 3 | //! The hive serializes the GB10 under `/tmp/aien-gb10.lock` ([`GPU_LOCK_PATH`]). A normal |
| 4 | //! server takes that lock itself for the upload and around each generation. An aien-test gb10 |
| 5 | //! gate already holds it for the gate's whole life (ADR 0033: the trusted side serializes gb10), |
| 6 | //! so a server the gate starts would queue behind its own caller until its load gave up. The |
| 7 | //! runner says so with `AIEN_GB10_LOCK_HELD=1` ([`LOCK_HELD_ENV`], aien-test `resources.rs`). |
| 8 | //! |
| 9 | //! That marker is an ambient environment variable, so it is not trusted by itself. With it set |
| 10 | //! the server VERIFIES the claim before any chip work: `/proc/locks` must show a `FLOCK` on the |
| 11 | //! canonical lock file's inode whose holder is one of this process's ancestors. A process that |
| 12 | //! cannot show that is refused at startup (exit 1), so a spoofed marker, a marker with nobody |
| 13 | //! holding the lock, or a lock held by a stranger never reaches the chip; the gate then fails, |
| 14 | //! it does not pass. There is no path override: the canonical lock is the only lock. |
| 15 | |
| 16 | use std::fs; |
| 17 | use std::os::unix::fs::MetadataExt; |
| 18 | use std::path::Path; |
| 19 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 20 | |
| 21 | use crate::omega_engine::GPU_LOCK_PATH; |
| 22 | |
| 23 | /// Set by the aien-test runner (and only the runner) for a gb10 gate it holds the GPU lock for. |
| 24 | pub const LOCK_HELD_ENV: &str = "AIEN_GB10_LOCK_HELD"; |
| 25 | |
| 26 | static INHERITED: AtomicBool = AtomicBool::new(false); |
| 27 | |
| 28 | /// How this process is allowed on the chip. |
| 29 | #[derive(Debug, PartialEq, Eq)] |
| 30 | pub enum ChipReservation { |
| 31 | /// Take `/tmp/aien-gb10.lock` ourselves (the live server, a `q36-extra` test server). |
| 32 | Own, |
| 33 | /// An ancestor holds `/tmp/aien-gb10.lock` for our whole life (verified): take nothing. |
| 34 | Inherited { holder_pid: u32 }, |
| 35 | } |
| 36 | |
| 37 | /// Decides the reservation from the environment and `/proc`, and records it for |
| 38 | /// [`inherited`]. Call once at startup, before any lock is taken. `Err` = the marker was set |
| 39 | /// but the claim did not verify; the caller must exit without touching the chip. |
| 40 | pub fn install() -> Result<ChipReservation, String> { |
| 41 | let r = detect( |
| 42 | std::env::var(LOCK_HELD_ENV).ok().as_deref(), |
| 43 | Path::new(GPU_LOCK_PATH), |
| 44 | &fs::read_to_string("/proc/locks").unwrap_or_default(), |
| 45 | &ancestors_of_self(), |
| 46 | )?; |
| 47 | INHERITED.store( |
| 48 | matches!(r, ChipReservation::Inherited { .. }), |
| 49 | Ordering::SeqCst, |
| 50 | ); |
| 51 | Ok(r) |
| 52 | } |
| 53 | |
| 54 | /// `true` after [`install`] verified an ancestor's reservation: the doors take no lock. |
| 55 | pub fn inherited() -> bool { |
| 56 | INHERITED.load(Ordering::SeqCst) |
| 57 | } |
| 58 | |
| 59 | /// [`install`] on explicit inputs (tests). `marker` is the value of [`LOCK_HELD_ENV`]. |
| 60 | pub fn detect( |
| 61 | marker: Option<&str>, |
| 62 | lock_path: &Path, |
| 63 | proc_locks: &str, |
| 64 | ancestors: &[u32], |
| 65 | ) -> Result<ChipReservation, String> { |
| 66 | match marker { |
| 67 | None | Some("") | Some("0") => return Ok(ChipReservation::Own), |
| 68 | Some("1") => {} |
| 69 | Some(other) => { |
| 70 | return Err(format!( |
| 71 | "{LOCK_HELD_ENV}={other:?}: only 1 (set by the aien-test runner) or unset" |
| 72 | )) |
| 73 | } |
| 74 | } |
| 75 | let meta = fs::metadata(lock_path).map_err(|e| { |
| 76 | format!( |
| 77 | "{LOCK_HELD_ENV}=1 but {} cannot be examined ({e}): refusing the chip", |
| 78 | lock_path.display() |
| 79 | ) |
| 80 | })?; |
| 81 | let holders = flock_holders(proc_locks, meta.dev(), meta.ino()); |
| 82 | if holders.is_empty() { |
| 83 | return Err(format!( |
| 84 | "{LOCK_HELD_ENV}=1 but nobody holds {}: refusing the chip (a spoofed marker, or the caller let go)", |
| 85 | lock_path.display() |
| 86 | )); |
| 87 | } |
| 88 | match holders.iter().find(|p| ancestors.contains(p)) { |
| 89 | Some(&holder_pid) => Ok(ChipReservation::Inherited { holder_pid }), |
| 90 | None => Err(format!( |
| 91 | "{LOCK_HELD_ENV}=1 but {} is held by pid(s) {:?}, none an ancestor of this server (ancestors {:?}): refusing the chip", |
| 92 | lock_path.display(), |
| 93 | holders, |
| 94 | ancestors |
| 95 | )), |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// Pids holding an exclusive `FLOCK` (`WRITE`) on the file `(dev, ino)` according to a |
| 100 | /// `/proc/locks` listing; shared holders do not count. |
| 101 | /// `/proc/locks` lines look like `1: FLOCK ADVISORY WRITE 12345 00:2e:1234 0 EOF`; its |
| 102 | /// `maj:min` are the device's major and minor in hex, the inode in decimal. Waiters are listed |
| 103 | /// with `->` after the number and are skipped. |
| 104 | pub fn flock_holders(proc_locks: &str, dev: u64, ino: u64) -> Vec<u32> { |
| 105 | let (want_maj, want_min) = (libc_major(dev), libc_minor(dev)); |
| 106 | proc_locks |
| 107 | .lines() |
| 108 | .filter_map(|line| { |
| 109 | let mut f = line.split_whitespace(); |
| 110 | f.next()?; // "N:"; a waiter's line has "->" here instead of FLOCK and is skipped below |
| 111 | if f.next()? != "FLOCK" { |
| 112 | return None; |
| 113 | } |
| 114 | f.next()?; // ADVISORY / MANDATORY |
| 115 | if f.next()? != "WRITE" { |
| 116 | return None; // a shared (LOCK_SH) holder is not an exclusive reservation |
| 117 | } |
| 118 | let pid: u32 = f.next()?.parse().ok()?; |
| 119 | let mut loc = f.next()?.split(':'); |
| 120 | let maj = u64::from_str_radix(loc.next()?, 16).ok()?; |
| 121 | let min = u64::from_str_radix(loc.next()?, 16).ok()?; |
| 122 | let inode: u64 = loc.next()?.parse().ok()?; |
| 123 | (maj == want_maj && min == want_min && inode == ino).then_some(pid) |
| 124 | }) |
| 125 | .collect() |
| 126 | } |
| 127 | |
| 128 | /// Linux `major()` for `st_dev` (glibc encoding). |
| 129 | fn libc_major(dev: u64) -> u64 { |
| 130 | ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0xfff) |
| 131 | } |
| 132 | |
| 133 | /// Linux `minor()` for `st_dev` (glibc encoding). |
| 134 | fn libc_minor(dev: u64) -> u64 { |
| 135 | ((dev >> 12) & 0xffff_ff00) | (dev & 0xff) |
| 136 | } |
| 137 | |
| 138 | /// This process's ancestors (parent first), from `/proc/<pid>/status` `PPid:` lines. Stops at |
| 139 | /// pid 0 or 1 or at anything unreadable (a different pid namespace fails closed: no ancestors). |
| 140 | pub fn ancestors_of_self() -> Vec<u32> { |
| 141 | let mut out = Vec::new(); |
| 142 | let mut pid = std::process::id(); |
| 143 | for _ in 0..256 { |
| 144 | let status = match fs::read_to_string(format!("/proc/{pid}/status")) { |
| 145 | Ok(s) => s, |
| 146 | Err(_) => break, |
| 147 | }; |
| 148 | let ppid: u32 = match status |
| 149 | .lines() |
| 150 | .find_map(|l| l.strip_prefix("PPid:")) |
| 151 | .and_then(|v| v.trim().parse().ok()) |
| 152 | { |
| 153 | Some(p) => p, |
| 154 | None => break, |
| 155 | }; |
| 156 | if ppid <= 1 { |
| 157 | break; |
| 158 | } |
| 159 | out.push(ppid); |
| 160 | pid = ppid; |
| 161 | } |
| 162 | out |
| 163 | } |
| 164 | |
| 165 | #[cfg(test)] |
| 166 | mod tests { |
| 167 | use super::*; |
| 168 | use std::fs::OpenOptions; |
| 169 | use std::os::unix::io::AsRawFd; |
| 170 | |
| 171 | const LOCKS: &str = "\ |
| 172 | 1: FLOCK ADVISORY WRITE 4242 00:2e:777 0 EOF |
| 173 | 1: -> FLOCK ADVISORY WRITE 9999 00:2e:777 0 EOF |
| 174 | 2: POSIX ADVISORY WRITE 5555 00:2e:777 0 EOF |
| 175 | 3: FLOCK ADVISORY WRITE 1234 00:2e:778 0 EOF |
| 176 | 4: FLOCK ADVISORY READ 3333 00:2e:779 0 EOF |
| 177 | "; |
| 178 | |
| 179 | fn dev(maj: u64, min: u64) -> u64 { |
| 180 | ((maj & 0xffff_f000) << 32) |
| 181 | | ((maj & 0xfff) << 8) |
| 182 | | ((min & 0xffff_ff00) << 12) |
| 183 | | (min & 0xff) |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn holders_are_flock_owners_on_that_inode_only() { |
| 188 | // The waiter (`->`), the POSIX lock and the other inode are not holders. |
| 189 | assert_eq!(flock_holders(LOCKS, dev(0, 0x2e), 777), vec![4242]); |
| 190 | assert_eq!(flock_holders(LOCKS, dev(0, 0x2e), 778), vec![1234]); |
| 191 | assert!(flock_holders(LOCKS, dev(0, 0x2f), 777).is_empty()); |
| 192 | assert!(flock_holders(LOCKS, dev(0, 0x2e), 1).is_empty()); |
| 193 | // A shared holder is not a reservation. |
| 194 | assert!(flock_holders(LOCKS, dev(0, 0x2e), 779).is_empty()); |
| 195 | } |
| 196 | |
| 197 | #[test] |
| 198 | fn without_the_marker_the_server_takes_its_own_lock() { |
| 199 | let p = Path::new("/nonexistent/aien-gb10.lock"); |
| 200 | assert_eq!(detect(None, p, LOCKS, &[4242]), Ok(ChipReservation::Own)); |
| 201 | assert_eq!( |
| 202 | detect(Some(""), p, LOCKS, &[4242]), |
| 203 | Ok(ChipReservation::Own) |
| 204 | ); |
| 205 | assert_eq!( |
| 206 | detect(Some("0"), p, LOCKS, &[4242]), |
| 207 | Ok(ChipReservation::Own) |
| 208 | ); |
| 209 | assert!(detect(Some("yes"), p, LOCKS, &[4242]).is_err()); |
| 210 | } |
| 211 | |
| 212 | /// The negative tests the review asked for: a marker alone never enters the chip. |
| 213 | #[test] |
| 214 | fn marker_is_refused_unless_an_ancestor_holds_the_canonical_lock() { |
| 215 | let dir = |
| 216 | std::env::temp_dir().join(format!("aien-chip-reservation-{}", std::process::id())); |
| 217 | fs::create_dir_all(&dir).unwrap(); |
| 218 | let lock = dir.join("aien-gb10.lock"); |
| 219 | let f = OpenOptions::new() |
| 220 | .create(true) |
| 221 | .truncate(false) |
| 222 | .write(true) |
| 223 | .open(&lock) |
| 224 | .unwrap(); |
| 225 | let meta = fs::metadata(&lock).unwrap(); |
| 226 | let me = std::process::id(); |
| 227 | let line = |pid: u32| { |
| 228 | format!( |
| 229 | "1: FLOCK ADVISORY WRITE {pid} {:02x}:{:02x}:{} 0 EOF\n", |
| 230 | libc_major(meta.dev()), |
| 231 | libc_minor(meta.dev()), |
| 232 | meta.ino() |
| 233 | ) |
| 234 | }; |
| 235 | // Nobody holds it: refused. |
| 236 | assert!(detect(Some("1"), &lock, "", &[1, 2]).is_err()); |
| 237 | // A stranger holds it: refused, even with the marker. |
| 238 | assert!(detect(Some("1"), &lock, &line(424242), &[me + 1]).is_err()); |
| 239 | // The lock file does not exist at all: refused. |
| 240 | assert!(detect(Some("1"), &dir.join("missing"), &line(me), &[me]).is_err()); |
| 241 | // An ancestor holds it: allowed, and the holder is named. |
| 242 | assert_eq!( |
| 243 | detect(Some("1"), &lock, &line(me), &[me]), |
| 244 | Ok(ChipReservation::Inherited { holder_pid: me }) |
| 245 | ); |
| 246 | // The real /proc/locks sees a real flock we take, by (dev, ino): the parser matches the |
| 247 | // kernel's formatting, not only our fixture's. |
| 248 | // SAFETY: flock on a valid descriptor of a private temp file. |
| 249 | assert_eq!(unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) }, 0); |
| 250 | let real = fs::read_to_string("/proc/locks").unwrap(); |
| 251 | assert!( |
| 252 | flock_holders(&real, meta.dev(), meta.ino()).contains(&me), |
| 253 | "our own flock is listed in /proc/locks under our pid" |
| 254 | ); |
| 255 | drop(f); |
| 256 | let _ = fs::remove_dir_all(&dir); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn ancestors_start_at_the_parent_and_exclude_self() { |
| 261 | let a = ancestors_of_self(); |
| 262 | assert!(!a.contains(&std::process::id())); |
| 263 | // A cargo test binary always has a parent (cargo or a shell). |
| 264 | assert!(!a.is_empty()); |
| 265 | } |
| 266 | } |