Skip to main content

aimdb_core/
graph.rs

1//! Dependency graph for AimDB record topology
2//!
3//! This module provides the `DependencyGraph` and related types that represent
4//! the entire database topology — sources, links, transforms, taps, and their
5//! relationships.
6//!
7//! The graph is constructed once during `build()` and is immutable thereafter.
8//! It enables:
9//! - Build-time validation (cycle detection, missing inputs; input types are
10//!   checked by `AimDbBuilder::build()` against the record registry)
11//! - Spawn ordering (topological sort)
12//! - Runtime introspection (AimX protocol, MCP tools, CLI)
13
14use alloc::{
15    string::{String, ToString},
16    vec::Vec,
17};
18
19// ============================================================================
20// Record Origin
21// ============================================================================
22
23/// How a record gets its values — part of the dependency graph.
24#[derive(Clone, Debug)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
26#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
27pub enum RecordOrigin {
28    /// Autonomous producer via `.source()`
29    Source,
30    /// Inbound connector via `.link_from()`
31    Link { protocol: String, address: String },
32    /// Single-input reactive derivation via `.transform()`
33    Transform { input: String },
34    /// Multi-input reactive join via `.transform_join()`
35    TransformJoin { inputs: Vec<String> },
36    /// No registered producer (writable via `record.set` / `db.produce()`)
37    Passive,
38}
39
40// ============================================================================
41// Schema
42// ============================================================================
43
44/// The data-contract schema a record carries, set while it is configured
45/// (`RecordRegistrar::schema`; `aimdb-data-contracts` fills it from
46/// `SchemaType`).
47#[derive(Clone, Debug, PartialEq, Eq)]
48#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
49pub struct SchemaInfo {
50    /// Schema name (e.g. "temperature")
51    pub name: String,
52    /// Schema version
53    pub version: u32,
54}
55
56// ============================================================================
57// Graph Node
58// ============================================================================
59
60/// Metadata for one node in the dependency graph.
61#[derive(Clone, Debug)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize))]
63pub struct GraphNode {
64    /// Record key (e.g. "temp.vienna")
65    pub key: String,
66    /// How this record gets its values
67    pub origin: RecordOrigin,
68    /// Buffer type ("spmc_ring", "single_latest", "mailbox", "none")
69    pub buffer_type: String,
70    /// Buffer capacity (None for unbounded or non-ring buffers)
71    pub buffer_capacity: Option<usize>,
72    /// Number of taps attached
73    pub tap_count: usize,
74    /// Whether an outbound link is configured; `!outbound_links.is_empty()`,
75    /// kept for peers that read only this flag.
76    pub has_outbound_link: bool,
77    /// The address of each outbound link (e.g. "mqtt://plant/boiler/flow_avg")
78    pub outbound_links: Vec<String>,
79    /// The schema the record carries, if one was set
80    pub schema: Option<SchemaInfo>,
81}
82
83// ============================================================================
84// Graph Edge
85// ============================================================================
86
87/// One directed edge in the dependency graph.
88#[derive(Clone, Debug)]
89#[cfg_attr(feature = "serde", derive(serde::Serialize))]
90pub struct GraphEdge {
91    /// Source record key (None for external origins like source/link)
92    pub from: Option<String>,
93    /// Target record key (None for side-effects like taps/link_out)
94    pub to: Option<String>,
95    /// Classification of this edge
96    pub edge_type: EdgeType,
97}
98
99/// Classification of a dependency graph edge.
100#[derive(Clone, Debug)]
101#[cfg_attr(feature = "serde", derive(serde::Serialize))]
102#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
103pub enum EdgeType {
104    Source,
105    Link { protocol: String },
106    Transform,
107    TransformJoin,
108    Tap { index: usize },
109    LinkOut { protocol: String },
110}
111
112// ============================================================================
113// Dependency Graph
114// ============================================================================
115
116/// The dependency graph, constructed once during `build()` and immutable thereafter.
117#[derive(Clone, Debug)]
118pub struct DependencyGraph {
119    /// All nodes indexed by record key.
120    pub nodes: Vec<GraphNode>,
121    /// All edges (both internal and external).
122    pub edges: Vec<GraphEdge>,
123    /// Topological order of record keys (transforms come after their inputs).
124    pub topo_order: Vec<String>,
125}
126
127/// SplitMix64: a few lines of seeded PRNG for
128/// [`DependencyGraph::build_and_validate_seeded`]. Not for anything that needs
129/// real randomness.
130struct SplitMix64(u64);
131
132impl SplitMix64 {
133    fn next(&mut self) -> u64 {
134        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
135        let mut z = self.0;
136        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
137        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
138        z ^ (z >> 31)
139    }
140
141    /// An index in `0..len` (`len > 0`).
142    fn below(&mut self, len: usize) -> usize {
143        ((u128::from(self.next()) * len as u128) >> 64) as usize
144    }
145}
146
147impl DependencyGraph {
148    /// Construct and validate the dependency graph from registered records.
149    ///
150    /// This builds a complete `DependencyGraph` with nodes, edges, and topological order.
151    /// The graph is immutable after construction and can be used for introspection.
152    ///
153    /// # Arguments
154    /// * `nodes` - One [`GraphNode`] per registered record (origin, buffer, etc.)
155    ///
156    /// # Returns
157    /// * `Ok(DependencyGraph)` - The complete, validated graph
158    /// * `Err(DbError::TransformInputNotFound)` - If a transform references a missing record
159    /// * `Err(DbError::CyclicDependency)` - If the transform edges form a cycle
160    pub fn build_and_validate(nodes: Vec<GraphNode>) -> crate::DbResult<Self> {
161        Self::build_and_validate_seeded(nodes, None)
162    }
163
164    /// [`build_and_validate`](Self::build_and_validate), with a seed that
165    /// permutes the start order.
166    ///
167    /// Without a seed, records ready at once are taken in registration order.
168    /// With one, the next record is drawn from all ready records by a seeded
169    /// PRNG, so different seeds explore different valid orders and the same
170    /// seed replays one. Either way every record comes after its inputs.
171    pub fn build_and_validate_seeded(
172        nodes: Vec<GraphNode>,
173        seed: Option<u64>,
174    ) -> crate::DbResult<Self> {
175        use alloc::collections::VecDeque;
176
177        // Everything in this block borrows `nodes` (&str keys); scoping it
178        // lets `nodes` move into the returned graph afterwards.
179        let (topo_order, edges) = {
180            // Build set of all keys for validation
181            let all_keys: hashbrown::HashSet<&str> =
182                nodes.iter().map(|info| info.key.as_str()).collect();
183
184            // Extract transform inputs for validation and edge construction
185            let mut transform_inputs: Vec<(&str, Vec<&str>)> = Vec::new();
186            for info in &nodes {
187                match &info.origin {
188                    RecordOrigin::Transform { input } => {
189                        transform_inputs.push((info.key.as_str(), alloc::vec![input.as_str()]));
190                    }
191                    RecordOrigin::TransformJoin { inputs } => {
192                        let input_refs: Vec<&str> = inputs.iter().map(|s| s.as_str()).collect();
193                        transform_inputs.push((info.key.as_str(), input_refs));
194                    }
195                    _ => {}
196                }
197            }
198
199            // Validate: check all transform input keys exist
200            for (output_key, input_keys) in &transform_inputs {
201                for input_key in input_keys {
202                    if !all_keys.contains(input_key) {
203                        return Err(crate::DbError::TransformInputNotFound {
204                            output_key: output_key.to_string(),
205                            input_key: input_key.to_string(),
206                        });
207                    }
208                }
209            }
210
211            // Build adjacency list and in-degree map for Kahn's algorithm
212            let mut in_degree: hashbrown::HashMap<&str, usize> = hashbrown::HashMap::new();
213            let mut adjacency: hashbrown::HashMap<&str, Vec<&str>> = hashbrown::HashMap::new();
214
215            // Initialize all keys with in-degree 0
216            for key in &all_keys {
217                in_degree.entry(*key).or_insert(0);
218                adjacency.entry(*key).or_default();
219            }
220
221            // Add transform edges: input → output
222            for (output_key, input_keys) in &transform_inputs {
223                for input_key in input_keys {
224                    adjacency.entry(*input_key).or_default().push(*output_key);
225                    *in_degree.entry(*output_key).or_insert(0) += 1;
226                }
227            }
228
229            // Kahn's algorithm — topological sort. The queue is seeded in
230            // registration order (`nodes`), not map order: the map's hasher is
231            // randomly seeded, and this order is the record task start order,
232            // so it must not change from build to build (#324). Neighbours
233            // below follow `transform_inputs`, which is registration order too.
234            let mut queue: VecDeque<&str> = nodes
235                .iter()
236                .map(|info| info.key.as_str())
237                .filter(|key| in_degree.get(key) == Some(&0))
238                .collect();
239            let mut topo_order = Vec::new();
240            let mut rng = seed.map(SplitMix64);
241
242            loop {
243                let next = match rng.as_mut() {
244                    Some(rng) if !queue.is_empty() => {
245                        queue.swap_remove_back(rng.below(queue.len()))
246                    }
247                    _ => queue.pop_front(),
248                };
249                let Some(node) = next else { break };
250                topo_order.push(node.to_string());
251                if let Some(neighbors) = adjacency.get(node) {
252                    for &neighbor in neighbors {
253                        if let Some(deg) = in_degree.get_mut(neighbor) {
254                            *deg -= 1;
255                            if *deg == 0 {
256                                queue.push_back(neighbor);
257                            }
258                        }
259                    }
260                }
261            }
262
263            if topo_order.len() != all_keys.len() {
264                // Find the cycle participants for a helpful error message
265                let cycle_records: Vec<String> = nodes
266                    .iter()
267                    .map(|info| info.key.as_str())
268                    .filter(|key| in_degree.get(key).is_some_and(|&deg| deg > 0))
269                    .map(|k| k.to_string())
270                    .collect();
271
272                return Err(crate::DbError::CyclicDependency {
273                    records: cycle_records,
274                });
275            }
276
277            // Build edges from origins
278            let mut edges: Vec<GraphEdge> = Vec::new();
279            for info in &nodes {
280                match &info.origin {
281                    RecordOrigin::Source => {
282                        edges.push(GraphEdge {
283                            from: None,
284                            to: Some(info.key.clone()),
285                            edge_type: EdgeType::Source,
286                        });
287                    }
288                    RecordOrigin::Link { protocol, .. } => {
289                        edges.push(GraphEdge {
290                            from: None,
291                            to: Some(info.key.clone()),
292                            edge_type: EdgeType::Link {
293                                protocol: protocol.clone(),
294                            },
295                        });
296                    }
297                    RecordOrigin::Transform { input } => {
298                        edges.push(GraphEdge {
299                            from: Some(input.clone()),
300                            to: Some(info.key.clone()),
301                            edge_type: EdgeType::Transform,
302                        });
303                    }
304                    RecordOrigin::TransformJoin { inputs } => {
305                        for input in inputs {
306                            edges.push(GraphEdge {
307                                from: Some(input.clone()),
308                                to: Some(info.key.clone()),
309                                edge_type: EdgeType::TransformJoin,
310                            });
311                        }
312                    }
313                    RecordOrigin::Passive => {
314                        // No inbound edge for passive records
315                    }
316                }
317
318                // One edge per outbound link, named by its scheme
319                for address in &info.outbound_links {
320                    let protocol = address.split_once("://").map_or("", |(scheme, _)| scheme);
321                    edges.push(GraphEdge {
322                        from: Some(info.key.clone()),
323                        to: None,
324                        edge_type: EdgeType::LinkOut {
325                            protocol: protocol.to_string(),
326                        },
327                    });
328                }
329
330                // Add tap edges
331                for tap_idx in 0..info.tap_count {
332                    edges.push(GraphEdge {
333                        from: Some(info.key.clone()),
334                        to: None,
335                        edge_type: EdgeType::Tap { index: tap_idx },
336                    });
337                }
338            }
339
340            (topo_order, edges)
341        };
342
343        Ok(DependencyGraph {
344            nodes,
345            edges,
346            topo_order,
347        })
348    }
349
350    /// Get a node by key
351    pub fn node(&self, key: &str) -> Option<&GraphNode> {
352        self.nodes.iter().find(|n| n.key == key)
353    }
354
355    /// Get all nodes
356    pub fn nodes(&self) -> &[GraphNode] {
357        &self.nodes
358    }
359
360    /// Get all edges
361    pub fn edges(&self) -> &[GraphEdge] {
362        &self.edges
363    }
364
365    /// Get the topological order
366    pub fn topo_order(&self) -> &[String] {
367        &self.topo_order
368    }
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374    use alloc::vec;
375
376    fn node(key: &str, origin: RecordOrigin) -> GraphNode {
377        GraphNode {
378            key: key.to_string(),
379            origin,
380            buffer_type: "single_latest".to_string(),
381            buffer_capacity: None,
382            tap_count: 0,
383            has_outbound_link: false,
384            outbound_links: Vec::new(),
385            schema: None,
386        }
387    }
388
389    /// Six sources and a passive record, one join, and three transforms, two
390    /// of which share an input.
391    fn sample_nodes() -> Vec<GraphNode> {
392        vec![
393            node(
394                "sum",
395                RecordOrigin::TransformJoin {
396                    inputs: vec!["zeta".to_string(), "alpha".to_string()],
397                },
398            ),
399            node("zeta", RecordOrigin::Source),
400            node("mid", RecordOrigin::Passive),
401            node("alpha", RecordOrigin::Source),
402            node(
403                "double",
404                RecordOrigin::Transform {
405                    input: "zeta".to_string(),
406                },
407            ),
408            node("omega", RecordOrigin::Source),
409            node("beta", RecordOrigin::Source),
410            node("kappa", RecordOrigin::Source),
411            // Two transforms on one input, released together when `beta`
412            // is taken: they follow registration order, not key order.
413            node(
414                "y_half",
415                RecordOrigin::Transform {
416                    input: "beta".to_string(),
417                },
418            ),
419            node(
420                "b_triple",
421                RecordOrigin::Transform {
422                    input: "beta".to_string(),
423                },
424            ),
425        ]
426    }
427
428    /// #324: records ready at once start in registration order, and records
429    /// that depend on others still come after their inputs, every build.
430    #[test]
431    fn topo_order_is_registration_order_among_ready_records() {
432        // `double` is ready once `zeta` is; `sum` waits for `alpha` as well.
433        let expected = [
434            "zeta", "mid", "alpha", "omega", "beta", "kappa", "double", "sum", "y_half", "b_triple",
435        ];
436
437        // Each build seeds a fresh map hasher; ask enough times that a
438        // map-ordered queue would show.
439        for _ in 0..20 {
440            let graph = DependencyGraph::build_and_validate(sample_nodes()).unwrap();
441            assert_eq!(graph.topo_order(), expected);
442        }
443    }
444
445    fn seeded(seed: u64) -> Vec<String> {
446        DependencyGraph::build_and_validate_seeded(sample_nodes(), Some(seed))
447            .unwrap()
448            .topo_order
449    }
450
451    /// A seed replays its order, which still has every record after its
452    /// inputs and every record exactly once.
453    #[test]
454    fn a_seed_replays_a_valid_order() {
455        let pos = |order: &[String], key: &str| order.iter().position(|k| k == key).unwrap();
456        for seed in 0..64 {
457            let order = seeded(seed);
458            assert_eq!(order, seeded(seed), "seed {seed} must replay");
459            assert_eq!(order.len(), sample_nodes().len());
460            for (record, inputs) in [
461                ("sum", &["zeta", "alpha"][..]),
462                ("double", &["zeta"]),
463                ("y_half", &["beta"]),
464                ("b_triple", &["beta"]),
465            ] {
466                for input in inputs {
467                    assert!(
468                        pos(&order, input) < pos(&order, record),
469                        "seed {seed}: {record} before its input {input}: {order:?}"
470                    );
471                }
472            }
473        }
474    }
475
476    /// Different seeds explore different orders, including among records
477    /// released together (`y_half`, `b_triple`), not just the initial queue.
478    #[test]
479    fn seeds_explore_different_orders() {
480        let unseeded = DependencyGraph::build_and_validate(sample_nodes())
481            .unwrap()
482            .topo_order;
483        let orders: Vec<Vec<String>> = (0..64).map(seeded).collect();
484        let distinct: hashbrown::HashSet<&Vec<String>> = orders.iter().collect();
485        assert!(
486            distinct.len() > 32,
487            "only {} distinct orders",
488            distinct.len()
489        );
490        assert!(orders.iter().any(|o| *o != unseeded));
491        let first = |o: &Vec<String>| {
492            o.iter()
493                .find(|k| *k == "y_half" || *k == "b_triple")
494                .cloned()
495        };
496        let firsts: hashbrown::HashSet<_> = orders.iter().map(first).collect();
497        assert_eq!(
498            firsts.len(),
499            2,
500            "both transforms of `beta` must lead sometimes"
501        );
502    }
503
504    /// #332: one link-out edge per outbound link, named by its scheme.
505    #[test]
506    fn link_out_edges_follow_outbound_links() {
507        let mut out = node("out", RecordOrigin::Source);
508        out.outbound_links = vec![
509            "mqtt://plant/boiler/flow_avg".to_string(),
510            "knx://1/2/3".to_string(),
511        ];
512        out.has_outbound_link = true;
513        let graph = DependencyGraph::build_and_validate(vec![out]).unwrap();
514        let protocols: Vec<&str> = graph
515            .edges()
516            .iter()
517            .filter_map(|e| match &e.edge_type {
518                EdgeType::LinkOut { protocol } => Some(protocol.as_str()),
519                _ => None,
520            })
521            .collect();
522        assert_eq!(protocols, ["mqtt", "knx"]);
523    }
524}