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 / crates / spark-harness / src / dependency.rs

205 lines · 7156 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//! Producer/consumer dependency graph (Headstart M2, issue #535).
17//!
18//! Nodes are task ids. An edge `producer -> consumer` means the consumer
19//! needs the producer's artifact. Every insert is checked: unknown nodes,
20//! self edges, duplicate edges and edges that would close a cycle are
21//! refused, so the graph is always a DAG. Iteration order is the byte order
22//! of task ids (BTreeMap/BTreeSet), which keeps scheduling deterministic.
23
24use serde::Serialize;
25use std::collections::{BTreeMap, BTreeSet, VecDeque};
26use std::fmt;
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum GraphError {
30 DuplicateNode(String),
31 MissingNode(String),
32 SelfEdge(String),
33 DuplicateEdge {
34 producer: String,
35 consumer: String,
36 },
37 /// Adding the edge would close this cycle (first and last node equal).
38 Cycle(Vec<String>),
39}
40
41impl fmt::Display for GraphError {
42 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43 match self {
44 GraphError::DuplicateNode(n) => write!(f, "task '{n}' already exists"),
45 GraphError::MissingNode(n) => write!(f, "task '{n}' does not exist"),
46 GraphError::SelfEdge(n) => write!(f, "task '{n}' cannot depend on itself"),
47 GraphError::DuplicateEdge { producer, consumer } => {
48 write!(f, "edge {producer} -> {consumer} already exists")
49 }
50 GraphError::Cycle(path) => write!(f, "edge would close cycle {}", path.join(" -> ")),
51 }
52 }
53}
54
55impl std::error::Error for GraphError {}
56
57#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
58pub struct DependencyGraph {
59 /// consumer -> producers
60 producers: BTreeMap<String, BTreeSet<String>>,
61 /// producer -> consumers
62 consumers: BTreeMap<String, BTreeSet<String>>,
63}
64
65impl DependencyGraph {
66 pub fn contains(&self, id: &str) -> bool {
67 self.producers.contains_key(id)
68 }
69
70 pub fn add_node(&mut self, id: &str) -> Result<(), GraphError> {
71 if self.contains(id) {
72 return Err(GraphError::DuplicateNode(id.to_string()));
73 }
74 self.producers.insert(id.to_string(), BTreeSet::new());
75 self.consumers.insert(id.to_string(), BTreeSet::new());
76 Ok(())
77 }
78
79 /// Check an edge without inserting it.
80 pub fn check_edge(&self, producer: &str, consumer: &str) -> Result<(), GraphError> {
81 for n in [producer, consumer] {
82 if !self.contains(n) {
83 return Err(GraphError::MissingNode(n.to_string()));
84 }
85 }
86 if producer == consumer {
87 return Err(GraphError::SelfEdge(producer.to_string()));
88 }
89 if self.consumers[producer].contains(consumer) {
90 return Err(GraphError::DuplicateEdge {
91 producer: producer.to_string(),
92 consumer: consumer.to_string(),
93 });
94 }
95 // The new edge closes a cycle iff the producer is reachable from
96 // the consumer along existing edges.
97 if let Some(mut path) = self.path(consumer, producer) {
98 path.push(consumer.to_string());
99 return Err(GraphError::Cycle(path));
100 }
101 Ok(())
102 }
103
104 pub fn add_edge(&mut self, producer: &str, consumer: &str) -> Result<(), GraphError> {
105 self.check_edge(producer, consumer)?;
106 self.consumers
107 .get_mut(producer)
108 .map(|s| s.insert(consumer.to_string()));
109 self.producers
110 .get_mut(consumer)
111 .map(|s| s.insert(producer.to_string()));
112 Ok(())
113 }
114
115 pub fn producers_of(&self, id: &str) -> impl Iterator<Item = &String> {
116 self.producers.get(id).into_iter().flatten()
117 }
118
119 pub fn consumers_of(&self, id: &str) -> impl Iterator<Item = &String> {
120 self.consumers.get(id).into_iter().flatten()
121 }
122
123 /// Every task reachable from `id` along producer -> consumer edges, in
124 /// breadth-first order, excluding `id`.
125 pub fn descendants(&self, id: &str) -> Vec<String> {
126 let mut seen = BTreeSet::new();
127 let mut out = Vec::new();
128 let mut q: VecDeque<&String> = self.consumers_of(id).collect();
129 while let Some(n) = q.pop_front() {
130 if seen.insert(n.clone()) {
131 out.push(n.clone());
132 q.extend(self.consumers_of(n));
133 }
134 }
135 out
136 }
137
138 /// A path `from -> ... -> to` along existing edges, if one exists.
139 fn path(&self, from: &str, to: &str) -> Option<Vec<String>> {
140 let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
141 let mut q = VecDeque::from([from]);
142 let mut seen = BTreeSet::from([from]);
143 while let Some(n) = q.pop_front() {
144 if n == to {
145 let mut path = vec![to.to_string()];
146 let mut cur = to;
147 while let Some(p) = parent.get(cur) {
148 path.push(p.to_string());
149 cur = p;
150 }
151 path.reverse();
152 return Some(path);
153 }
154 for c in self.consumers_of(n) {
155 if seen.insert(c.as_str()) {
156 parent.insert(c.as_str(), n);
157 q.push_back(c.as_str());
158 }
159 }
160 }
161 None
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 fn graph(nodes: &[&str]) -> DependencyGraph {
170 let mut g = DependencyGraph::default();
171 for n in nodes {
172 g.add_node(n).unwrap();
173 }
174 g
175 }
176
177 #[test]
178 fn refuses_cycles_missing_nodes_and_duplicates() {
179 let mut g = graph(&["a", "b", "c"]);
180 g.add_edge("a", "b").unwrap();
181 g.add_edge("b", "c").unwrap();
182 assert_eq!(
183 g.add_edge("c", "a"),
184 Err(GraphError::Cycle(vec![
185 "a".into(),
186 "b".into(),
187 "c".into(),
188 "a".into()
189 ]))
190 );
191 assert_eq!(g.add_edge("a", "a"), Err(GraphError::SelfEdge("a".into())));
192 assert_eq!(
193 g.add_edge("a", "z"),
194 Err(GraphError::MissingNode("z".into()))
195 );
196 assert!(matches!(
197 g.add_edge("a", "b"),
198 Err(GraphError::DuplicateEdge { .. })
199 ));
200 assert_eq!(g.add_node("a"), Err(GraphError::DuplicateNode("a".into())));
201 // A diamond is fine.
202 g.add_edge("a", "c").unwrap();
203 assert_eq!(g.descendants("a"), vec!["b".to_string(), "c".to_string()]);
204 }
205}