Skip to main content

coreason_engine/
blast_radius.rs

1// Copyright (c) 2026 CoReason, Inc
2//
3// This software is proprietary and dual-licensed
4// Licensed under the Prosperity Public License 3.0 (the "License")
5// A copy of the license is available at <https://prosperitylicense.com/versions/3.0.0>
6// For details, see the LICENSE file
7// Commercial use beyond a 30-day trial requires a separate license
8//
9// Source Code: <https://github.com/CoReason-AI/coreason-runtime>
10
11//! Defeasible Cascade Blast Radius Calculator (#336).
12
13//!
14
15//! Replaces `coreason_runtime/execution_plane/blast_radius.py`.
16
17//!
18
19//! Computes the propagation blast radius when a belief node is defeated
20
21//! in the epistemic knowledge graph. Tracks cascade depth and affected
22
23//! nodes for rollback planning.
24
25//!
26
27//! Zero Waste: Delegates all graph traversal to `petgraph` (OSS).
28
29//! We only write the domain-specific defeasibility scoring logic.
30
31use petgraph::graph::{DiGraph, NodeIndex};
32
33use petgraph::visit::{Bfs, Reversed};
34
35use serde::{Deserialize, Serialize};
36
37use std::collections::HashMap;
38
39/// Result of a blast radius computation.
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42
43pub struct CascadeResult {
44    pub defeated_node: String,
45
46    pub affected_nodes: Vec<String>,
47
48    pub cascade_depth: u32,
49
50    pub defeasibility_scores: HashMap<String, f64>,
51
52    pub total_affected: usize,
53}
54
55/// Internal graph wrapper that builds a `petgraph::DiGraph` from an adjacency list.
56
57///
58
59/// We keep this thin: the graph construction is our glue code,
60
61/// all traversal is delegated to petgraph's BFS/DFS implementations.
62
63struct EpistemicGraph<'a> {
64    graph: DiGraph<&'a str, ()>,
65
66    node_map: HashMap<&'a str, NodeIndex>,
67}
68
69impl<'a> EpistemicGraph<'a> {
70    /// Build from adjacency list. O(V + E).
71
72    fn from_adjacency(adjacency: &'a HashMap<String, Vec<String>>) -> Result<Self, String> {
73        let mut graph = DiGraph::<&'a str, ()>::new();
74
75        let mut node_map: HashMap<&'a str, NodeIndex> = HashMap::new();
76
77        // Collect all unique nodes
78        for (parent, children) in adjacency {
79            node_map
80                .entry(parent.as_str())
81                .or_insert_with(|| graph.add_node(parent.as_str()));
82
83            for child in children {
84                node_map
85                    .entry(child.as_str())
86                    .or_insert_with(|| graph.add_node(child.as_str()));
87            }
88        }
89
90        // Add edges
91        for (parent, children) in adjacency {
92            let &parent_idx = node_map
93                .get(parent.as_str())
94                .ok_or_else(|| format!("Parent node {} not found", parent))?;
95
96            for child in children {
97                let &child_idx = node_map
98                    .get(child.as_str())
99                    .ok_or_else(|| format!("Child node {} not found", child))?;
100
101                graph.add_edge(parent_idx, child_idx, ());
102            }
103        }
104
105        Ok(Self { graph, node_map })
106    }
107
108    /// Return a reversed view of the graph (swapped edge directions).
109
110    /// Uses petgraph's zero-cost `Reversed` wrapper — no data is copied.
111
112    fn reversed_view(&self) -> Reversed<&DiGraph<&'a str, ()>> {
113        Reversed(&self.graph)
114    }
115}
116
117/// Computes belief invalidation cascades in a knowledge graph (#336).
118
119///
120
121/// When a belief node is defeated (e.g., new evidence contradicts it),
122
123/// all downstream nodes that depend on it may also be invalidated.
124
125/// This calculator delegates BFS traversal to `petgraph`.
126
127pub struct BlastRadiusCalculator;
128
129impl BlastRadiusCalculator {
130    /// Compute the blast radius of defeating a node.
131
132    ///
133
134    /// Uses `petgraph::visit::Bfs` for the forward reachability traversal,
135
136    /// then applies domain-specific defeasibility decay scoring.
137
138    pub fn calculate_blast_radius(
139        defeated_node_cid: &str,
140
141        adjacency: &HashMap<String, Vec<String>>,
142    ) -> CascadeResult {
143        let eg = match EpistemicGraph::from_adjacency(adjacency) {
144            Ok(graph) => graph,
145            Err(_) => {
146                return CascadeResult {
147                    defeated_node: defeated_node_cid.to_string(),
148                    affected_nodes: Vec::new(),
149                    cascade_depth: 0,
150                    defeasibility_scores: HashMap::new(),
151                    total_affected: 0,
152                }
153            }
154        };
155
156        let start_idx = match eg.node_map.get(defeated_node_cid) {
157            Some(&idx) => idx,
158
159            None => {
160                return CascadeResult {
161                    defeated_node: defeated_node_cid.to_string(),
162
163                    affected_nodes: Vec::new(),
164
165                    cascade_depth: 0,
166
167                    defeasibility_scores: HashMap::new(),
168
169                    total_affected: 0,
170                };
171            }
172        };
173
174        // Use petgraph's BFS to discover all reachable nodes
175
176        let mut bfs = Bfs::new(&eg.graph, start_idx);
177
178        let mut depth_map: HashMap<NodeIndex, u32> = HashMap::new();
179
180        depth_map.insert(start_idx, 0);
181
182        let mut affected: Vec<String> = Vec::new();
183
184        let mut defeasibility: HashMap<String, f64> = HashMap::new();
185
186        let mut max_depth: u32 = 0;
187
188        while let Some(node_idx) = bfs.next(&eg.graph) {
189            let node_label = eg.graph[node_idx];
190
191            // Compute depth from parent depths (BFS guarantees shortest path)
192
193            let depth = if node_idx == start_idx {
194                0
195            } else {
196                // Find the minimum depth among predecessors already visited
197
198                eg.graph
199                    .neighbors_directed(node_idx, petgraph::Direction::Incoming)
200                    .filter_map(|pred| depth_map.get(&pred))
201                    .min()
202                    .map(|d| d + 1)
203                    .unwrap_or(0)
204            };
205
206            depth_map.insert(node_idx, depth);
207
208            max_depth = max_depth.max(depth);
209
210            if node_label != defeated_node_cid {
211                affected.push(node_label.to_string());
212            }
213
214            // Domain-specific: defeasibility score decays with depth
215
216            defeasibility.insert(node_label.to_string(), 1.0 / (1.0 + depth as f64));
217        }
218
219        CascadeResult {
220            defeated_node: defeated_node_cid.to_string(),
221
222            affected_nodes: affected.clone(),
223
224            cascade_depth: max_depth,
225
226            defeasibility_scores: defeasibility,
227
228            total_affected: affected.len(),
229        }
230    }
231
232    /// Compute how vulnerable a node is to cascade invalidation.
233
234    ///
235
236    /// Uses `petgraph::visit::Bfs` on the reversed graph to count ancestors.
237
238    /// A node with many ancestors that could be defeated has a high
239
240    /// defeasibility score (0 = safe, 1 = highly vulnerable).
241
242    pub fn compute_defeasibility_score(
243        node_cid: &str,
244
245        adjacency: &HashMap<String, Vec<String>>,
246    ) -> f64 {
247        let eg = match EpistemicGraph::from_adjacency(adjacency) {
248            Ok(graph) => graph,
249            Err(_) => return 0.0,
250        };
251
252        let start_idx = match eg.node_map.get(node_cid) {
253            Some(&idx) => idx,
254
255            None => return 0.0,
256        };
257
258        // Use Reversed view and BFS to count ancestors (zero-cost graph reversal)
259
260        let rev = eg.reversed_view();
261
262        let mut bfs = Bfs::new(&rev, start_idx);
263
264        let mut ancestor_count: usize = 0;
265
266        while let Some(node_idx) = bfs.next(&rev) {
267            if node_idx != start_idx {
268                ancestor_count += 1;
269            }
270        }
271
272        let total_nodes = adjacency.len().max(1);
273
274        (ancestor_count as f64 / total_nodes as f64).min(1.0)
275    }
276}
277
278#[cfg(test)]
279
280mod tests {
281
282    use super::*;
283
284    fn sample_graph() -> HashMap<String, Vec<String>> {
285        let mut g = HashMap::new();
286
287        g.insert("root".to_string(), vec!["a".to_string(), "b".to_string()]);
288
289        g.insert("a".to_string(), vec!["c".to_string(), "d".to_string()]);
290
291        g.insert("b".to_string(), vec!["d".to_string(), "e".to_string()]);
292
293        g.insert("c".to_string(), vec![]);
294
295        g.insert("d".to_string(), vec!["f".to_string()]);
296
297        g.insert("e".to_string(), vec![]);
298
299        g.insert("f".to_string(), vec![]);
300
301        g
302    }
303
304    #[test]
305
306    fn test_blast_radius_from_root() {
307        let graph = sample_graph();
308
309        let result = BlastRadiusCalculator::calculate_blast_radius("root", &graph);
310
311        assert_eq!(result.defeated_node, "root");
312
313        // root → a, b → c, d, e → f = 6 total nodes, 5 affected (excluding root)
314
315        assert!(result.total_affected >= 5);
316
317        assert!(result.cascade_depth >= 2);
318
319        assert_eq!(result.defeasibility_scores["root"], 1.0);
320    }
321
322    #[test]
323
324    fn test_blast_radius_leaf_node() {
325        let graph = sample_graph();
326
327        let result = BlastRadiusCalculator::calculate_blast_radius("f", &graph);
328
329        assert_eq!(result.total_affected, 0);
330
331        assert_eq!(result.cascade_depth, 0);
332    }
333
334    #[test]
335
336    fn test_blast_radius_missing_node() {
337        let graph = sample_graph();
338
339        let result = BlastRadiusCalculator::calculate_blast_radius("nonexistent", &graph);
340
341        assert_eq!(result.total_affected, 0);
342
343        assert_eq!(result.cascade_depth, 0);
344    }
345
346    #[test]
347
348    fn test_defeasibility_score_root_has_no_ancestors() {
349        let graph = sample_graph();
350
351        let score = BlastRadiusCalculator::compute_defeasibility_score("root", &graph);
352
353        assert_eq!(score, 0.0);
354    }
355
356    #[test]
357
358    fn test_defeasibility_score_deep_node_has_ancestors() {
359        let graph = sample_graph();
360
361        let score = BlastRadiusCalculator::compute_defeasibility_score("f", &graph);
362
363        assert!(score > 0.0);
364    }
365}