Skip to main content

stackless_core/def/
graph.rs

1//! The derived dependency graph (ARCHITECTURE.md §1).
2//!
3//! This graph records workload wiring and explicit readiness dependencies.
4//! Integration references order provisioning. Service origins and endpoint URLs
5//! are wiring edges here; the execution planner adds output dependencies using
6//! the selected provider's ability to supply URLs before startup.
7//!
8//! Representation, ordering, and cycle detection all live in oxgraph: the
9//! nodes and ordering edges feed a `GraphBuilder`, `topological_sort` yields
10//! the startup order, and on the rare cycle `strongly_connected_components`
11//! names the members for the error.
12
13use std::collections::BTreeSet;
14
15use oxgraph::algo::{strongly_connected_components, topological_sort};
16use oxgraph::graph_build::{GraphBuildError, GraphBuilder};
17use serde::Serialize;
18
19use super::error::DefError;
20use super::interp::{self, Reference};
21use super::model::StackDef;
22
23#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
24#[serde(tag = "kind", content = "name", rename_all = "snake_case")]
25pub enum Node {
26    Integration(String),
27    Service(String),
28}
29
30impl Node {
31    pub fn name(&self) -> &str {
32        match self {
33            Self::Integration(name) | Self::Service(name) => name,
34        }
35    }
36}
37
38/// The graph derived from one validated definition.
39#[derive(Debug, Serialize)]
40pub struct DependencyGraph {
41    nodes: Vec<Node>,
42    /// Dependencies before dependents; also the `prepare` order.
43    startup_order: Vec<Node>,
44    /// Every reference edge (referencing service → target), origins
45    /// included — the seam later phases derive egress policy from.
46    wiring: Vec<(Node, Node)>,
47}
48
49impl DependencyGraph {
50    /// Derive edges from the definition's interpolation references.
51    ///
52    /// Call on a validated definition: undeclared references have
53    /// already been rejected, so lookups here cannot miss.
54    pub fn derive(def: &StackDef) -> Result<Self, DefError> {
55        // Dense indices: integrations, then services — all in the
56        // definition's (sorted) order for deterministic ties.
57        let nodes: Vec<Node> = def
58            .integrations
59            .keys()
60            .map(|name| Node::Integration(name.clone()))
61            .chain(def.services.keys().map(|name| Node::Service(name.clone())))
62            .collect();
63        let index_of =
64            |node: &Node| -> Option<u32> { nodes.iter().position(|n| n == node).map(|i| i as u32) };
65
66        let mut ordering_edges: BTreeSet<(u32, u32)> = BTreeSet::new();
67        let mut wiring: BTreeSet<(u32, u32)> = BTreeSet::new();
68        for (service_name, service) in &def.services {
69            let service_node = Node::Service(service_name.clone());
70            let Some(service_idx) = index_of(&service_node) else {
71                continue;
72            };
73            for dependency in service.depends_on.keys() {
74                if let Some(target_idx) = index_of(&Node::Service(dependency.clone())) {
75                    ordering_edges.insert((target_idx, service_idx));
76                    wiring.insert((service_idx, target_idx));
77                }
78            }
79            let mut values: Vec<(String, String)> = service
80                .env
81                .iter()
82                .map(|(k, v)| (format!("services.{service_name}.env.{k}"), v.clone()))
83                .collect();
84            for substrate in service.substrates.keys() {
85                for (k, v) in service.substrate_env(service_name, substrate)? {
86                    values.push((format!("services.{service_name}.{substrate}.env.{k}"), v));
87                }
88            }
89            for (location, value) in &values {
90                for reference in interp::references(value, location)? {
91                    let target = match reference {
92                        Reference::ServiceOrigin(name) => Node::Service(name),
93                        Reference::EndpointUrl(name) => {
94                            let Some(endpoint) = def.endpoints.get(&name) else {
95                                continue;
96                            };
97                            Node::Service(endpoint.workload.clone())
98                        }
99                        Reference::IntegrationOutput { integration, .. } => {
100                            Node::Integration(integration)
101                        }
102                        // Legacy datastore refs are resume-only wiring; the
103                        // provision step is gone from the plan, so they do
104                        // not contribute ordering edges.
105                        Reference::StackName
106                        | Reference::InstanceName
107                        | Reference::Secret(_)
108                        | Reference::DatastoreUrl(_) => {
109                            continue;
110                        }
111                    };
112                    let Some(target_idx) = index_of(&target) else {
113                        continue;
114                    };
115                    wiring.insert((service_idx, target_idx));
116                    if matches!(target, Node::Integration(_)) {
117                        // Edge points dependency → dependent so Kahn
118                        // emits dependencies first.
119                        ordering_edges.insert((target_idx, service_idx));
120                    }
121                }
122            }
123        }
124
125        if let Some(verify) = &def.stack.verify {
126            for (key, value) in &verify.env {
127                let location = format!("stack.verify.env.{key}");
128                for reference in interp::references(value, &location)? {
129                    let Reference::IntegrationOutput { integration, .. } = reference else {
130                        continue;
131                    };
132                    let target = Node::Integration(integration);
133                    let Some(target_idx) = index_of(&target) else {
134                        continue;
135                    };
136                    let _ = target_idx;
137                }
138            }
139            for (tier, spec) in &verify.tiers {
140                for (key, value) in &spec.env {
141                    let location = format!("stack.verify.tiers.{tier}.env.{key}");
142                    for reference in interp::references(value, &location)? {
143                        let Reference::IntegrationOutput { integration, .. } = reference else {
144                            continue;
145                        };
146                        let target = Node::Integration(integration);
147                        let Some(target_idx) = index_of(&target) else {
148                            continue;
149                        };
150                        let _ = target_idx;
151                    }
152                }
153            }
154        }
155
156        let mut builder = GraphBuilder::<u32, u32>::new();
157        let mut node_ids = Vec::with_capacity(nodes.len());
158        for _ in &nodes {
159            node_ids.push(builder.add_node().map_err(internal_layout_error)?);
160        }
161        for &(from, to) in &ordering_edges {
162            builder
163                .add_edge(node_ids[from as usize], node_ids[to as usize])
164                .map_err(internal_layout_error)?;
165        }
166        let graph = builder.freeze().map_err(internal_layout_error)?;
167
168        let order = match topological_sort(&graph, &node_ids) {
169            Ok(order) => order,
170            // Toposort only flags that no order exists; SCC names the cycle
171            // members so the error points at the wiring that closed it.
172            Err(_) => {
173                let cycle = strongly_connected_components(&graph, &node_ids)
174                    .into_iter()
175                    .filter(|component| component.len() > 1)
176                    .flatten()
177                    .map(|id| nodes[id.get() as usize].name().to_owned())
178                    .collect::<Vec<_>>()
179                    .join(" -> ");
180                return Err(DefError::WiringCycle { nodes: cycle });
181            }
182        };
183
184        let startup_order = order
185            .into_iter()
186            .map(|id| nodes[id.get() as usize].clone())
187            .collect();
188        let wiring = wiring
189            .into_iter()
190            .map(|(from, to)| (nodes[from as usize].clone(), nodes[to as usize].clone()))
191            .collect();
192        Ok(Self {
193            nodes,
194            startup_order,
195            wiring,
196        })
197    }
198
199    pub fn nodes(&self) -> &[Node] {
200        &self.nodes
201    }
202
203    pub fn startup_order(&self) -> &[Node] {
204        &self.startup_order
205    }
206
207    pub fn wiring(&self) -> &[(Node, Node)] {
208        &self.wiring
209    }
210}
211
212/// Builder/freeze failures are unreachable for the dense edge set we just
213/// built; surface honestly rather than panic if oxgraph rejects the layout.
214fn internal_layout_error(err: GraphBuildError<u32, u32>) -> DefError {
215    DefError::WiringCycle {
216        nodes: format!("internal graph layout error: {err:?}"),
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use oxgraph::algo::ToposortError;
224    use oxgraph::graph_build::{FrozenGraph, GraphNodeId};
225
226    fn build(
227        node_count: u32,
228        edges: &[(u32, u32)],
229    ) -> (FrozenGraph<u32, u32>, Vec<GraphNodeId<u32>>) {
230        let mut builder = GraphBuilder::<u32, u32>::new();
231        let ids: Vec<_> = (0..node_count)
232            .map(|_| builder.add_node().unwrap())
233            .collect();
234        for &(from, to) in edges {
235            builder
236                .add_edge(ids[from as usize], ids[to as usize])
237                .unwrap();
238        }
239        (builder.freeze().unwrap(), ids)
240    }
241
242    #[test]
243    fn topological_sort_orders_a_dag() {
244        // 0 -> 1 -> 3, 0 -> 2 -> 3
245        let (graph, ids) = build(4, &[(0, 1), (0, 2), (1, 3), (2, 3)]);
246        let order: Vec<u32> = topological_sort(&graph, &ids)
247            .unwrap()
248            .into_iter()
249            .map(|id| id.get())
250            .collect();
251        assert_eq!(order, vec![0, 1, 2, 3]);
252    }
253
254    #[test]
255    fn scc_reports_the_cycle_members() {
256        // 0 -> 1 -> 2 -> 1, 3 isolated
257        let (graph, ids) = build(4, &[(0, 1), (1, 2), (2, 1)]);
258        assert_eq!(
259            topological_sort(&graph, &ids).unwrap_err(),
260            ToposortError::Cycle
261        );
262        let mut cycle: Vec<u32> = strongly_connected_components(&graph, &ids)
263            .into_iter()
264            .filter(|component| component.len() > 1)
265            .flatten()
266            .map(|id| id.get())
267            .collect();
268        cycle.sort_unstable();
269        assert_eq!(cycle, vec![1, 2]);
270    }
271
272    #[test]
273    fn topological_sort_handles_no_edges() {
274        let (graph, ids) = build(3, &[]);
275        assert_eq!(topological_sort(&graph, &ids).unwrap().len(), 3);
276    }
277}