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-closure / src / graph.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 | //! Dependency graph reconstruction: Rust (cargo metadata) and C (quoted |
| 17 | //! `#include` scanner), plus cycle detection shared by both. |
| 18 | |
| 19 | use serde_json::Value; |
| 20 | use std::collections::{BTreeMap, BTreeSet}; |
| 21 | use std::fs; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::process::Command; |
| 24 | |
| 25 | /// node -> set of nodes it depends on. |
| 26 | pub type Graph = BTreeMap<String, BTreeSet<String>>; |
| 27 | |
| 28 | /// A workspace package that is a node of the internal graph. |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub struct Package { |
| 31 | pub name: String, |
| 32 | pub dir: PathBuf, |
| 33 | /// Internal path dependencies (normal and build kinds), by package name. |
| 34 | pub deps: BTreeSet<String>, |
| 35 | } |
| 36 | |
| 37 | /// Parse `cargo metadata --no-deps` output. Only workspace members are nodes. |
| 38 | /// An edge is a dependency that has a `path` and names another member. Dev |
| 39 | /// dependencies are not part of the built artifact and are skipped. |
| 40 | pub fn packages_from_metadata(meta: &Value) -> Result<Vec<Package>, String> { |
| 41 | let members: BTreeSet<&str> = meta["workspace_members"] |
| 42 | .as_array() |
| 43 | .ok_or("metadata has no workspace_members")? |
| 44 | .iter() |
| 45 | .filter_map(Value::as_str) |
| 46 | .collect(); |
| 47 | let pkgs: Vec<&Value> = meta["packages"] |
| 48 | .as_array() |
| 49 | .ok_or("metadata has no packages")? |
| 50 | .iter() |
| 51 | .filter(|p| p["id"].as_str().is_some_and(|id| members.contains(id))) |
| 52 | .collect(); |
| 53 | let names: BTreeSet<&str> = pkgs.iter().filter_map(|p| p["name"].as_str()).collect(); |
| 54 | let mut out = Vec::new(); |
| 55 | for p in &pkgs { |
| 56 | let name = p["name"].as_str().ok_or("package without name")?; |
| 57 | let manifest = p["manifest_path"] |
| 58 | .as_str() |
| 59 | .ok_or("package without manifest_path")?; |
| 60 | let dir = Path::new(manifest) |
| 61 | .parent() |
| 62 | .ok_or("bad manifest_path")? |
| 63 | .to_path_buf(); |
| 64 | let mut deps = BTreeSet::new(); |
| 65 | for d in p["dependencies"].as_array().into_iter().flatten() { |
| 66 | if d["kind"].as_str() == Some("dev") || d["path"].is_null() { |
| 67 | continue; |
| 68 | } |
| 69 | if let Some(dn) = d["name"].as_str() { |
| 70 | if names.contains(dn) && dn != name { |
| 71 | deps.insert(dn.to_string()); |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | out.push(Package { |
| 76 | name: name.to_string(), |
| 77 | dir, |
| 78 | deps, |
| 79 | }); |
| 80 | } |
| 81 | out.sort_by(|a, b| a.name.cmp(&b.name)); |
| 82 | Ok(out) |
| 83 | } |
| 84 | |
| 85 | /// Run `cargo metadata --offline --locked --no-deps` in `root`. |
| 86 | pub fn cargo_packages(root: &Path) -> Result<Vec<Package>, String> { |
| 87 | let out = Command::new("cargo") |
| 88 | .args([ |
| 89 | "metadata", |
| 90 | "--format-version", |
| 91 | "1", |
| 92 | "--offline", |
| 93 | "--locked", |
| 94 | "--no-deps", |
| 95 | ]) |
| 96 | .current_dir(root) |
| 97 | .output() |
| 98 | .map_err(|e| format!("cannot run cargo: {e}"))?; |
| 99 | if !out.status.success() { |
| 100 | return Err(format!( |
| 101 | "cargo metadata failed: {}", |
| 102 | String::from_utf8_lossy(&out.stderr).trim() |
| 103 | )); |
| 104 | } |
| 105 | let meta: Value = |
| 106 | serde_json::from_slice(&out.stdout).map_err(|e| format!("bad metadata JSON: {e}"))?; |
| 107 | packages_from_metadata(&meta) |
| 108 | } |
| 109 | |
| 110 | pub fn graph_of(packages: &[Package]) -> Graph { |
| 111 | packages |
| 112 | .iter() |
| 113 | .map(|p| (p.name.clone(), p.deps.clone())) |
| 114 | .collect() |
| 115 | } |
| 116 | |
| 117 | /// Returns one cycle as a path `a -> b -> ... -> a` if the graph has any. |
| 118 | /// Iterative, so a deep graph cannot overflow the stack. |
| 119 | pub fn find_cycle(g: &Graph) -> Option<Vec<String>> { |
| 120 | #[derive(Clone, Copy, PartialEq)] |
| 121 | enum Mark { |
| 122 | Open, |
| 123 | Done, |
| 124 | } |
| 125 | let mut mark: BTreeMap<&str, Mark> = BTreeMap::new(); |
| 126 | for start in g.keys() { |
| 127 | if mark.contains_key(start.as_str()) { |
| 128 | continue; |
| 129 | } |
| 130 | let mut stack: Vec<(&str, Vec<&str>)> = vec![( |
| 131 | start.as_str(), |
| 132 | g[start].iter().map(String::as_str).collect(), |
| 133 | )]; |
| 134 | mark.insert(start.as_str(), Mark::Open); |
| 135 | while let Some((node, todo)) = stack.last_mut() { |
| 136 | let node = *node; |
| 137 | match todo.pop() { |
| 138 | Some(next) => match mark.get(next) { |
| 139 | Some(Mark::Open) => { |
| 140 | let mut path: Vec<String> = stack |
| 141 | .iter() |
| 142 | .map(|(n, _)| n.to_string()) |
| 143 | .skip_while(|n| n != next) |
| 144 | .collect(); |
| 145 | path.push(next.to_string()); |
| 146 | return Some(path); |
| 147 | } |
| 148 | Some(Mark::Done) => {} |
| 149 | None => { |
| 150 | mark.insert(next, Mark::Open); |
| 151 | let kids = g |
| 152 | .get(next) |
| 153 | .map(|s| s.iter().map(String::as_str).collect()) |
| 154 | .unwrap_or_default(); |
| 155 | stack.push((next, kids)); |
| 156 | } |
| 157 | }, |
| 158 | None => { |
| 159 | mark.insert(node, Mark::Done); |
| 160 | stack.pop(); |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | None |
| 166 | } |
| 167 | |
| 168 | /// Transitive closure of `start` (excluding `start` itself unless cyclic). |
| 169 | pub fn closure_of(g: &Graph, start: &str) -> BTreeSet<String> { |
| 170 | let mut seen = BTreeSet::new(); |
| 171 | let mut todo: Vec<&str> = g |
| 172 | .get(start) |
| 173 | .into_iter() |
| 174 | .flatten() |
| 175 | .map(String::as_str) |
| 176 | .collect(); |
| 177 | while let Some(n) = todo.pop() { |
| 178 | if seen.insert(n.to_string()) { |
| 179 | todo.extend(g.get(n).into_iter().flatten().map(String::as_str)); |
| 180 | } |
| 181 | } |
| 182 | seen |
| 183 | } |
| 184 | |
| 185 | /// Result of scanning C sources for quoted includes. |
| 186 | #[derive(Debug, Default, PartialEq, Eq)] |
| 187 | pub struct CScan { |
| 188 | /// Files (named relative to the include root) and the files they include. |
| 189 | pub graph: Graph, |
| 190 | /// (file, include text) pairs that resolved to no file. Callers must treat |
| 191 | /// these as findings, never ignore them. |
| 192 | pub unresolved: Vec<(String, String)>, |
| 193 | } |
| 194 | |
| 195 | /// Extract the target of a quoted include from one source line, if any. Only |
| 196 | /// lines whose first token is `#include "..."` count (leading and inner |
| 197 | /// whitespace allowed). Block comments and `#if 0` regions are NOT understood; |
| 198 | /// a commented out include is still reported, which errs on the strict side. |
| 199 | pub fn quoted_include(line: &str) -> Option<&str> { |
| 200 | let rest = line.trim_start().strip_prefix('#')?.trim_start(); |
| 201 | let rest = rest.strip_prefix("include")?.trim_start(); |
| 202 | let rest = rest.strip_prefix('"')?; |
| 203 | let end = rest.find('"')?; |
| 204 | Some(&rest[..end]) |
| 205 | } |
| 206 | |
| 207 | fn walk_c(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> { |
| 208 | for entry in fs::read_dir(dir).map_err(|e| format!("cannot read {}: {e}", dir.display()))? { |
| 209 | let path = entry.map_err(|e| e.to_string())?.path(); |
| 210 | if path.is_dir() { |
| 211 | walk_c(&path, out)?; |
| 212 | } else if matches!(path.extension().and_then(|e| e.to_str()), Some("c" | "h")) { |
| 213 | out.push(path); |
| 214 | } |
| 215 | } |
| 216 | Ok(()) |
| 217 | } |
| 218 | |
| 219 | /// Scan every `.c` and `.h` under `src_dir`. An include resolves first against |
| 220 | /// the including file's directory, then against `include_root` (the `-I` |
| 221 | /// directory). Nodes are named relative to `include_root`, or to `src_dir` |
| 222 | /// when a file lies outside it. |
| 223 | pub fn scan_c_includes(src_dir: &Path, include_root: &Path) -> Result<CScan, String> { |
| 224 | let canon = |p: &Path| fs::canonicalize(p).map_err(|e| format!("{}: {e}", p.display())); |
| 225 | let src_dir = canon(src_dir)?; |
| 226 | let include_root = canon(include_root)?; |
| 227 | let name_of = |p: &Path| -> String { |
| 228 | let rel = p |
| 229 | .strip_prefix(&include_root) |
| 230 | .or_else(|_| p.strip_prefix(&src_dir)) |
| 231 | .unwrap_or(p); |
| 232 | rel.to_string_lossy().replace('\\', "/") |
| 233 | }; |
| 234 | let mut files = Vec::new(); |
| 235 | walk_c(&src_dir, &mut files)?; |
| 236 | files.sort(); |
| 237 | let mut scan = CScan::default(); |
| 238 | for file in &files { |
| 239 | let me = name_of(file); |
| 240 | let text = |
| 241 | fs::read_to_string(file).map_err(|e| format!("cannot read {}: {e}", file.display()))?; |
| 242 | let deps = scan.graph.entry(me.clone()).or_default(); |
| 243 | for line in text.lines() { |
| 244 | let Some(inc) = quoted_include(line) else { |
| 245 | continue; |
| 246 | }; |
| 247 | let here = file.parent().map(|d| d.join(inc)); |
| 248 | let there = include_root.join(inc); |
| 249 | let hit = [here, Some(there)] |
| 250 | .into_iter() |
| 251 | .flatten() |
| 252 | .find(|c| c.is_file()) |
| 253 | .and_then(|c| fs::canonicalize(c).ok()); |
| 254 | match hit { |
| 255 | Some(p) => { |
| 256 | deps.insert(name_of(&p)); |
| 257 | } |
| 258 | None => scan.unresolved.push((me.clone(), inc.to_string())), |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | Ok(scan) |
| 263 | } |
| 264 | |
| 265 | #[cfg(test)] |
| 266 | mod tests { |
| 267 | use super::*; |
| 268 | |
| 269 | fn g(edges: &[(&str, &[&str])]) -> Graph { |
| 270 | edges |
| 271 | .iter() |
| 272 | .map(|(k, v)| (k.to_string(), v.iter().map(|s| s.to_string()).collect())) |
| 273 | .collect() |
| 274 | } |
| 275 | |
| 276 | #[test] |
| 277 | fn cycle_found_and_absent() { |
| 278 | assert!(find_cycle(&g(&[("a", &["b"]), ("b", &["c"]), ("c", &[])])).is_none()); |
| 279 | let c = find_cycle(&g(&[("a", &["b"]), ("b", &["c"]), ("c", &["b"])])).unwrap(); |
| 280 | assert_eq!(c, vec!["b", "c", "b"]); |
| 281 | assert!(find_cycle(&g(&[("a", &["a"])])).is_some()); |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn closure_is_transitive() { |
| 286 | let gr = g(&[("a", &["b"]), ("b", &["c"]), ("c", &[])]); |
| 287 | let c: Vec<String> = closure_of(&gr, "a").into_iter().collect(); |
| 288 | assert_eq!(c, vec!["b", "c"]); |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn include_line_parsing() { |
| 293 | assert_eq!(quoted_include("#include \"a/b.h\""), Some("a/b.h")); |
| 294 | assert_eq!(quoted_include(" # include \"x.h\" // c"), Some("x.h")); |
| 295 | assert_eq!(quoted_include("#include <stdio.h>"), None); |
| 296 | assert_eq!(quoted_include("int x; // #include \"no.h\""), None); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn c_scanner_on_fixture_dir() { |
| 301 | let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/c-include"); |
| 302 | let scan = scan_c_includes(&root.join("src"), &root.join("src")).unwrap(); |
| 303 | let deps = |n: &str| -> Vec<&str> { scan.graph[n].iter().map(String::as_str).collect() }; |
| 304 | assert_eq!(deps("main.c"), vec!["lib/a.h", "lib/b.h"]); |
| 305 | assert_eq!(deps("lib/a.h"), vec!["lib/b.h"]); |
| 306 | assert_eq!(deps("lib/b.h"), Vec::<&str>::new()); |
| 307 | assert_eq!( |
| 308 | scan.unresolved, |
| 309 | vec![("main.c".to_string(), "missing.h".to_string())] |
| 310 | ); |
| 311 | assert!(find_cycle(&scan.graph).is_none()); |
| 312 | } |
| 313 | |
| 314 | #[test] |
| 315 | fn c_scanner_sees_header_cycle() { |
| 316 | let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/c-cycle"); |
| 317 | let scan = scan_c_includes(&root, &root).unwrap(); |
| 318 | assert!(scan.unresolved.is_empty()); |
| 319 | assert!(find_cycle(&scan.graph).is_some()); |
| 320 | } |
| 321 | } |