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/blob/main/tools/aien-test/src/graph.rs # 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 branch `main` Branches Tags History `aien-sovereign-core-mv / tools / aien-test / src / graph.rs` 533 lines ยท 17534 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 //! The gate dependency graph (ADR 0028 Decisions 3 and 6). 17 //! 18 //! `load` finds every `*.gate` file under a repository root (the D1 19 //! convention, via `runner::discover`), parses each one strictly, and builds 20 //! a DAG from the `depends_on` lists. A bad manifest, a repeated gate id, an 21 //! unknown dependency and a cycle are all hard errors that name what is wrong. 22 //! Nodes are sorted by gate id, so node numbers, the topological order and 23 //! every query below are deterministic. 24 25 use crate::manifest::{self, Manifest}; 26 use crate::runner::discover; 27 use std::collections::{BTreeMap, BTreeSet}; 28 use std::fmt; 29 use std::fs; 30 use std::path::{Path, PathBuf}; 31 32 #[derive(Debug, Clone)] 33 pub struct Node { 34 pub id: String, 35 pub path: PathBuf, 36 pub manifest: Manifest, 37 /// Node numbers of the gates this gate depends on: sorted, no repeats. 38 pub deps: Vec, 39 } 40 41 #[derive(Debug, Clone, PartialEq, Eq)] 42 pub enum GraphError { 43 Io(String), 44 BadManifest { 45 path: PathBuf, 46 message: String, 47 }, 48 DuplicateGate { 49 id: String, 50 paths: Vec, 51 }, 52 UnknownDependency { 53 gate: String, 54 dep: String, 55 }, 56 /// Gate ids around the cycle; the first id is repeated at the end. 57 Cycle(Vec), 58 } 59 60 impl fmt::Display for GraphError { 61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 62 match self { 63 GraphError::Io(m) => f.write_str(m), 64 GraphError::BadManifest { path, message } => { 65 write!(f, "BAD_MANIFEST {}: {message}", path.display()) 66 } 67 GraphError::DuplicateGate { id, paths } => { 68 let list: Vec = paths.iter().map(|p| p.display().to_string()).collect(); 69 write!(f, "duplicate gate id {id} in: {}", list.join(", ")) 70 } 71 GraphError::UnknownDependency { gate, dep } => { 72 write!(f, "gate {gate} depends on unknown gate {dep}") 73 } 74 GraphError::Cycle(ids) => { 75 write!(f, "dependency cycle: {}", ids.join(" -> ")) 76 } 77 } 78 } 79 } 80 81 #[derive(Debug, Clone)] 82 pub struct Graph { 83 nodes: Vec, 84 index: BTreeMap, 85 dependents: Vec>, 86 order: Vec, 87 } 88 89 /// Discover, parse and link every gate under `root`. 90 pub fn load(root: &Path) -> Result { 91 let mut entries = Vec::new(); 92 for path in discover(root) { 93 let bytes = fs::read(&path) 94 .map_err(|e| GraphError::Io(format!("cannot read {}: {e}", path.display())))?; 95 let m = manifest::parse(&bytes).map_err(|e| GraphError::BadManifest { 96 path: path.clone(), 97 message: e.0, 98 })?; 99 entries.push((path, m)); 100 } 101 build(entries) 102 } 103 104 /// Link already parsed manifests (path, manifest) into a graph. 105 pub fn build(mut entries: Vec<(PathBuf, Manifest)>) -> Result { 106 entries.sort_by(|a, b| a.1.gate.cmp(&b.1.gate).then_with(|| a.0.cmp(&b.0))); 107 for pair in entries.windows(2) { 108 if pair[0].1.gate == pair[1].1.gate { 109 let id = pair[0].1.gate.clone(); 110 let paths = entries 111 .iter() 112 .filter(|e| e.1.gate == id) 113 .map(|e| e.0.clone()) 114 .collect(); 115 return Err(GraphError::DuplicateGate { id, paths }); 116 } 117 } 118 let index: BTreeMap = entries 119 .iter() 120 .enumerate() 121 .map(|(i, e)| (e.1.gate.clone(), i)) 122 .collect(); 123 let mut nodes: Vec = Vec::with_capacity(entries.len()); 124 for (path, m) in entries { 125 let mut deps: BTreeSet = BTreeSet::new(); 126 for d in &m.depends_on { 127 match index.get(d) { 128 Some(&i) => { 129 deps.insert(i); 130 } 131 None => { 132 return Err(GraphError::UnknownDependency { 133 gate: m.gate.clone(), 134 dep: d.clone(), 135 }) 136 } 137 } 138 } 139 nodes.push(Node { 140 id: m.gate.clone(), 141 path, 142 manifest: m, 143 deps: deps.into_iter().collect(), 144 }); 145 } 146 let mut dependents: Vec> = vec![Vec::new(); nodes.len()]; 147 for (i, n) in nodes.iter().enumerate() { 148 for &d in &n.deps { 149 dependents[d].push(i); 150 } 151 } 152 let order = topological_order(&nodes, &dependents); 153 if order.len() != nodes.len() { 154 let adj: Vec<&[usize]> = nodes.iter().map(|n| n.deps.as_slice()).collect(); 155 let cycle = find_cycle(&adj).unwrap_or_default(); 156 let ids = cycle.into_iter().map(|i| nodes[i].id.clone()).collect(); 157 return Err(GraphError::Cycle(ids)); 158 } 159 Ok(Graph { 160 nodes, 161 index, 162 dependents, 163 order, 164 }) 165 } 166 167 /// Kahn's algorithm, always taking the lowest node number (lowest gate id) 168 /// among the ready ones. Gates on a cycle never become ready, so the result 169 /// is shorter than the node list exactly when a cycle exists. 170 fn topological_order(nodes: &[Node], dependents: &[Vec]) -> Vec { 171 let mut waiting: Vec = nodes.iter().map(|n| n.deps.len()).collect(); 172 let mut ready: BTreeSet = waiting 173 .iter() 174 .enumerate() 175 .filter(|(_, w)| **w == 0) 176 .map(|(i, _)| i) 177 .collect(); 178 let mut order = Vec::with_capacity(nodes.len()); 179 while let Some(i) = ready.pop_first() { 180 order.push(i); 181 for &j in &dependents[i] { 182 waiting[j] -= 1; 183 if waiting[j] == 0 { 184 ready.insert(j); 185 } 186 } 187 } 188 order 189 } 190 191 /// Depth-first search for one cycle. Returns the node numbers along it with 192 /// the first one repeated at the end, or None if the graph is acyclic. 193 fn find_cycle(deps: &[&[usize]]) -> Option> { 194 fn visit( 195 n: usize, 196 deps: &[&[usize]], 197 state: &mut [u8], 198 stack: &mut Vec, 199 ) -> Option> { 200 state[n] = 1; 201 stack.push(n); 202 for &d in deps[n] { 203 if state[d] == 1 { 204 let start = stack.iter().position(|&x| x == d).unwrap_or(0); 205 let mut cycle: Vec = stack[start..].to_vec(); 206 cycle.push(d); 207 return Some(cycle); 208 } 209 if state[d] == 0 { 210 if let Some(c) = visit(d, deps, state, stack) { 211 return Some(c); 212 } 213 } 214 } 215 stack.pop(); 216 state[n] = 2; 217 None 218 } 219 let mut state = vec![0u8; deps.len()]; 220 let mut stack = Vec::new(); 221 (0..deps.len()).find_map(|n| { 222 if state[n] == 0 { 223 visit(n, deps, &mut state, &mut stack) 224 } else { 225 None 226 } 227 }) 228 } 229 230 /// Every node reachable from `start` by one or more steps of `next`. 231 fn reach<'a>(start: &[usize], next: impl Fn(usize) -> &'a [usize]) -> BTreeSet { 232 let mut seen = BTreeSet::new(); 233 let mut stack: Vec = start.to_vec(); 234 while let Some(n) = stack.pop() { 235 for &m in next(n) { 236 if seen.insert(m) { 237 stack.push(m); 238 } 239 } 240 } 241 seen 242 } 243 244 impl Graph { 245 pub fn len(&self) -> usize { 246 self.nodes.len() 247 } 248 249 pub fn is_empty(&self) -> bool { 250 self.nodes.is_empty() 251 } 252 253 pub fn nodes(&self) -> &[Node] { 254 &self.nodes 255 } 256 257 pub fn node(&self, i: usize) -> &Node { 258 &self.nodes[i] 259 } 260 261 pub fn index_of(&self, id: &str) -> Option { 262 self.index.get(id).copied() 263 } 264 265 /// Topological order: every gate comes after all the gates it depends on. 266 pub fn order(&self) -> &[usize] { 267 &self.order 268 } 269 270 /// Gates that list `i` directly in their `depends_on`. 271 pub fn direct_dependents(&self, i: usize) -> &[usize] { 272 &self.dependents[i] 273 } 274 275 /// All gates `i` rests on, directly or through other gates (not `i`). 276 pub fn transitive_deps(&self, i: usize) -> BTreeSet { 277 reach(&[i], |n| self.nodes[n].deps.as_slice()) 278 } 279 280 /// All gates that rest on `i`, directly or through other gates (not `i`). 281 pub fn transitive_dependents(&self, i: usize) -> BTreeSet { 282 reach(&[i], |n| self.dependents[n].as_slice()) 283 } 284 285 /// `targets` plus everything they depend on: the set to run to check them. 286 pub fn with_dependencies(&self, targets: &[usize]) -> BTreeSet { 287 let mut set = reach(targets, |n| self.nodes[n].deps.as_slice()); 288 set.extend(targets.iter().copied()); 289 set 290 } 291 292 /// Every gate: what `test ./...` runs and what a full-scope plan selects 293 /// (closed over dependencies by construction). 294 pub fn all(&self) -> BTreeSet { 295 (0..self.nodes.len()).collect() 296 } 297 } 298 299 #[cfg(test)] 300 mod tests { 301 use super::*; 302 use crate::testutil::{write_file, TempDir}; 303 304 fn gate_text(id: &str, deps: &[&str]) -> String { 305 let dep_block = if deps.is_empty() { 306 String::new() 307 } else { 308 format!( 309 "depends_on:\n{}", 310 deps.iter() 311 .map(|d| format!(" - {d}\n")) 312 .collect::() 313 ) 314 }; 315 format!( 316 "gate: {id}\nmanifest_version: 1\nowner: o\nrequires:\n - host\nrun:\n exec: x.sh\nexpects:\n exit: 0\n observe: []\n verdict: PASS\ntimeout: 5s\n{dep_block}" 317 ) 318 } 319 320 fn gate(id: &str, deps: &[&str]) -> (PathBuf, Manifest) { 321 ( 322 PathBuf::from(format!("tests/{id}.gate")), 323 manifest::parse(gate_text(id, deps).as_bytes()).unwrap(), 324 ) 325 } 326 327 fn graph(spec: &[(&str, &[&str])]) -> Result { 328 build(spec.iter().map(|(id, deps)| gate(id, deps)).collect()) 329 } 330 331 fn ids(g: &Graph, set: &BTreeSet) -> Vec { 332 set.iter().map(|&i| g.node(i).id.clone()).collect() 333 } 334 335 /// A -> B, A -> C, B -> D, C -> D (an arrow means "depends on"). 336 fn diamond() -> Graph { 337 graph(&[("A", &["B", "C"]), ("B", &["D"]), ("C", &["D"]), ("D", &[])]).unwrap() 338 } 339 340 #[test] 341 fn order_puts_dependencies_first() { 342 let g = diamond(); 343 let order: Vec<&str> = g.order().iter().map(|&i| g.node(i).id.as_str()).collect(); 344 assert_eq!(order, vec!["D", "B", "C", "A"]); 345 let pos = |id: &str| order.iter().position(|x| *x == id).unwrap(); 346 for n in g.nodes() { 347 for &d in &n.deps { 348 assert!( 349 pos(&g.node(d).id) < pos(&n.id), 350 "{} before {}", 351 g.node(d).id, 352 n.id 353 ); 354 } 355 } 356 } 357 358 #[test] 359 fn order_is_independent_of_input_order() { 360 let a = graph(&[("X", &[]), ("Y", &["X"]), ("Z", &[])]).unwrap(); 361 let b = graph(&[("Z", &[]), ("Y", &["X"]), ("X", &[])]).unwrap(); 362 assert_eq!(a.order(), b.order()); 363 let names: Vec<&str> = a.order().iter().map(|&i| a.node(i).id.as_str()).collect(); 364 assert_eq!(names, vec!["X", "Y", "Z"]); 365 } 366 367 #[test] 368 fn unknown_dependency_names_both_gates() { 369 let e = graph(&[("A", &["GHOST"])]).unwrap_err(); 370 assert_eq!( 371 e, 372 GraphError::UnknownDependency { 373 gate: "A".to_string(), 374 dep: "GHOST".to_string() 375 } 376 ); 377 let msg = e.to_string(); 378 assert!(msg.contains("A") && msg.contains("GHOST"), "{msg}"); 379 } 380 381 #[test] 382 fn cycle_is_named() { 383 let e = graph(&[("A", &["B"]), ("B", &["C"]), ("C", &["A"])]).unwrap_err(); 384 assert_eq!( 385 e, 386 GraphError::Cycle(vec![ 387 "A".to_string(), 388 "B".to_string(), 389 "C".to_string(), 390 "A".to_string() 391 ]) 392 ); 393 assert_eq!(e.to_string(), "dependency cycle: A -> B -> C -> A"); 394 } 395 396 #[test] 397 fn cycle_behind_an_acyclic_prefix_is_found() { 398 let e = graph(&[ 399 ("A", &["B"]), 400 ("B", &[]), 401 ("C", &["D"]), 402 ("D", &["E"]), 403 ("E", &["D"]), 404 ]) 405 .unwrap_err(); 406 assert_eq!(e.to_string(), "dependency cycle: D -> E -> D"); 407 } 408 409 #[test] 410 fn self_dependency_is_a_cycle() { 411 let e = graph(&[("A", &["A"])]).unwrap_err(); 412 assert_eq!(e.to_string(), "dependency cycle: A -> A"); 413 } 414 415 #[test] 416 fn duplicate_gate_ids_name_both_files() { 417 let mut entries = vec![gate("A", &[]), gate("B", &[])]; 418 let mut second = gate("A", &[]); 419 second.0 = PathBuf::from("other/a.gate"); 420 entries.push(second); 421 match build(entries).unwrap_err() { 422 GraphError::DuplicateGate { id, paths } => { 423 assert_eq!(id, "A"); 424 assert_eq!( 425 paths, 426 vec![PathBuf::from("other/a.gate"), PathBuf::from("tests/A.gate")] 427 ); 428 } 429 other => panic!("expected DuplicateGate, got {other:?}"), 430 } 431 } 432 433 #[test] 434 fn repeated_depends_on_entries_collapse() { 435 let g = graph(&[("A", &["B", "B"]), ("B", &[])]).unwrap(); 436 let a = g.index_of("A").unwrap(); 437 assert_eq!(g.node(a).deps.len(), 1); 438 assert_eq!(g.direct_dependents(g.index_of("B").unwrap()), &[a]); 439 } 440 441 #[test] 442 fn transitive_queries() { 443 let g = diamond(); 444 let i = |id: &str| g.index_of(id).unwrap(); 445 assert_eq!(ids(&g, &g.transitive_deps(i("A"))), vec!["B", "C", "D"]); 446 assert_eq!(ids(&g, &g.transitive_deps(i("B"))), vec!["D"]); 447 assert!(g.transitive_deps(i("D")).is_empty()); 448 assert_eq!( 449 ids(&g, &g.transitive_dependents(i("D"))), 450 vec!["A", "B", "C"] 451 ); 452 assert_eq!(ids(&g, &g.transitive_dependents(i("B"))), vec!["A"]); 453 assert!(g.transitive_dependents(i("A")).is_empty()); 454 assert_eq!(ids(&g, &g.with_dependencies(&[i("B")])), vec!["B", "D"]); 455 assert_eq!( 456 ids(&g, &g.with_dependencies(&[i("B"), i("C")])), 457 vec!["B", "C", "D"] 458 ); 459 assert_eq!(ids(&g, &g.with_dependencies(&[i("D")])), vec!["D"]); 460 } 461 462 #[test] 463 fn lookup_and_size() { 464 let g = diamond(); 465 assert_eq!(g.len(), 4); 466 assert!(!g.is_empty()); 467 assert_eq!(g.nodes().len(), 4); 468 assert_eq!(g.index_of("C").map(|i| g.node(i).id.as_str()), Some("C")); 469 assert_eq!(g.index_of("nope"), None); 470 let empty = build(Vec::new()).unwrap(); 471 assert!(empty.is_empty() && empty.order().is_empty()); 472 } 473 474 #[test] 475 fn load_finds_gates_and_skips_build_dirs() { 476 let t = TempDir::new("graph-load"); 477 write_file(t.path(), "tests/a/a.gate", &gate_text("A", &["B"]), false); 478 write_file(t.path(), "tests/b/b.gate", &gate_text("B", &[]), false); 479 write_file( 480 t.path(), 481 "target/ghost.gate", 482 &gate_text("GHOST", &[]), 483 false, 484 ); 485 let g = load(t.path()).unwrap(); 486 assert_eq!(g.len(), 2); 487 let order: Vec<&str> = g.order().iter().map(|&i| g.node(i).id.as_str()).collect(); 488 assert_eq!(order, vec!["B", "A"]); 489 assert!(g 490 .node(g.index_of("A").unwrap()) 491 .path 492 .ends_with("tests/a/a.gate")); 493 } 494 495 #[test] 496 fn load_fails_closed_on_a_bad_manifest() { 497 let t = TempDir::new("graph-bad"); 498 write_file(t.path(), "tests/bad.gate", "gate: X\nbogus: 1\n", false); 499 match load(t.path()).unwrap_err() { 500 GraphError::BadManifest { path, message } => { 501 assert!(path.ends_with("tests/bad.gate")); 502 assert!(!message.is_empty()); 503 } 504 other => panic!("expected BadManifest, got {other:?}"), 505 } 506 } 507 508 #[test] 509 fn error_messages_are_plain() { 510 assert_eq!( 511 GraphError::DuplicateGate { 512 id: "A".to_string(), 513 paths: vec![PathBuf::from("x.gate"), PathBuf::from("y.gate")] 514 } 515 .to_string(), 516 "duplicate gate id A in: x.gate, y.gate" 517 ); 518 assert_eq!( 519 GraphError::UnknownDependency { 520 gate: "A".to_string(), 521 dep: "B".to_string() 522 } 523 .to_string(), 524 "gate A depends on unknown gate B" 525 ); 526 assert_eq!(GraphError::Io("boom".to_string()).to_string(), "boom"); 527 let bad = GraphError::BadManifest { 528 path: PathBuf::from("p.gate"), 529 message: "line 1: nope".to_string(), 530 }; 531 assert_eq!(bad.to_string(), "BAD_MANIFEST p.gate: line 1: nope"); 532 } 533 }