Skip to main content

coreason_engine/
local_simulator.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//! Local Runtime Simulator — DAG verification and fractal URN stitching.
12
13//!
14
15//! Replaces `coreason_runtime/execution_plane/local_simulator.py`.
16
17//!
18
19//! Provides local dry-run simulation of execution DAGs and fractal URN
20
21//! hierarchical binding for capability composition.
22
23//!
24
25//! Zero Waste: Topological sort and cycle detection delegated to
26
27//! `petgraph::algo::toposort` (already in Cargo.toml). We only write the
28
29//! HashMap → DiGraph conversion glue and domain-specific simulation logic.
30
31use serde::Serialize;
32use std::collections::HashMap;
33use thiserror::Error;
34
35/// A node in the simulated execution DAG.
36
37#[derive(Debug, Clone)]
38
39pub struct SimulationNode {
40    pub node_id: String,
41
42    pub node_type: String,
43
44    pub inputs: serde_json::Value,
45
46    pub outputs: serde_json::Value,
47
48    pub dependencies: Vec<String>,
49
50    pub status: NodeStatus,
51}
52
53/// Status of a simulation node.
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
56
57pub enum NodeStatus {
58    Pending,
59
60    Running,
61
62    Completed,
63
64    Blocked,
65
66    Failed,
67}
68
69impl std::fmt::Display for NodeStatus {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            NodeStatus::Pending => write!(f, "PENDING"),
73
74            NodeStatus::Running => write!(f, "RUNNING"),
75
76            NodeStatus::Completed => write!(f, "COMPLETED"),
77
78            NodeStatus::Blocked => write!(f, "BLOCKED"),
79
80            NodeStatus::Failed => write!(f, "FAILED"),
81        }
82    }
83}
84
85impl SimulationNode {
86    pub fn new(node_id: &str, node_type: &str) -> Self {
87        Self {
88            node_id: node_id.to_string(),
89
90            node_type: node_type.to_string(),
91
92            inputs: serde_json::Value::Object(serde_json::Map::new()),
93
94            outputs: serde_json::Value::Object(serde_json::Map::new()),
95
96            dependencies: Vec::new(),
97
98            status: NodeStatus::Pending,
99        }
100    }
101
102    pub fn with_dependencies(mut self, deps: Vec<&str>) -> Self {
103        self.dependencies = deps.into_iter().map(String::from).collect();
104
105        self
106    }
107}
108
109/// Result of a DAG simulation.
110
111#[derive(Debug, Clone, Serialize)]
112
113pub struct SimulationResult {
114    pub success: bool,
115
116    pub executed_nodes: Vec<String>,
117
118    pub failed_nodes: Vec<String>,
119
120    pub execution_order: Vec<String>,
121
122    pub total_time_ms: f64,
123}
124
125/// DAG integrity validation report.
126
127#[derive(Debug, Clone, Serialize)]
128
129pub struct DagValidationReport {
130    pub valid: bool,
131
132    pub has_cycle: bool,
133
134    pub dangling_references: Vec<String>,
135
136    pub topological_order: Vec<String>,
137
138    pub node_count: usize,
139}
140
141/// Verify a DAG has no cycles or dangling references.
142
143///
144
145/// Zero Waste: Cycle detection and topological sorting delegated to
146
147/// `petgraph::algo::toposort` (already in Cargo.toml). We only write the
148
149/// HashMap → DiGraph conversion glue.
150
151pub fn verify_dag_integrity(dag: &HashMap<String, SimulationNode>) -> DagValidationReport {
152    use petgraph::graph::{DiGraph, NodeIndex};
153
154    // Check for dangling references
155
156    let dangling: Vec<String> = dag
157        .iter()
158        .flat_map(|(node_id, node)| {
159            node.dependencies
160                .iter()
161                .filter(|dep| !dag.contains_key(*dep))
162                .map(move |dep| format!("{} → {}", node_id, dep))
163        })
164        .collect();
165
166    // Build petgraph DiGraph from HashMap DAG in deterministic sorted order
167
168    let mut graph = DiGraph::<&str, ()>::new();
169
170    let mut node_map: HashMap<&str, NodeIndex> = HashMap::new();
171
172    // Sort keys to ensure stable deterministic order across different runs/seeds
173
174    let mut sorted_keys: Vec<&str> = dag.keys().map(|k| k.as_str()).collect();
175
176    sorted_keys.sort();
177
178    for node_id in &sorted_keys {
179        let idx = graph.add_node(node_id);
180
181        node_map.insert(node_id, idx);
182    }
183
184    for node_id in &sorted_keys {
185        let node = &dag[*node_id];
186
187        // Deterministically sort dependencies as well
188
189        let mut sorted_deps: Vec<&str> = node.dependencies.iter().map(|d| d.as_str()).collect();
190
191        sorted_deps.sort();
192
193        for dep in sorted_deps {
194            if let (Some(&dep_idx), Some(&node_idx)) = (node_map.get(dep), node_map.get(node_id)) {
195                // Edge from dependency → dependent (dep must come before node)
196
197                graph.add_edge(dep_idx, node_idx, ());
198            }
199        }
200    }
201
202    // Zero Waste: petgraph::algo::toposort handles cycle detection
203
204    match petgraph::algo::toposort(&graph, None) {
205        Ok(sorted_indices) => {
206            let topological_order: Vec<String> = sorted_indices
207                .iter()
208                .map(|&idx| graph[idx].to_string())
209                .collect();
210
211            DagValidationReport {
212                valid: dangling.is_empty(),
213
214                has_cycle: false,
215
216                dangling_references: dangling,
217
218                topological_order,
219
220                node_count: dag.len(),
221            }
222        }
223
224        Err(_cycle) => DagValidationReport {
225            valid: false,
226
227            has_cycle: true,
228
229            dangling_references: dangling,
230
231            topological_order: Vec::new(),
232
233            node_count: dag.len(),
234        },
235    }
236}
237
238/// Simulate DAG execution in topological order (dry-run).
239
240pub fn simulate_execution(dag: &mut HashMap<String, SimulationNode>) -> SimulationResult {
241    let start = std::time::Instant::now();
242
243    let integrity = verify_dag_integrity(dag);
244
245    if !integrity.valid {
246        return SimulationResult {
247            success: false,
248
249            executed_nodes: Vec::new(),
250
251            failed_nodes: dag.keys().cloned().collect(),
252
253            execution_order: Vec::new(),
254
255            total_time_ms: 0.0,
256        };
257    }
258
259    let mut executed: Vec<String> = Vec::new();
260
261    let mut failed: Vec<String> = Vec::new();
262
263    // Execute in topological order
264
265    let order = integrity.topological_order.clone();
266
267    for node_id in &order {
268        // Check if all dependencies are completed
269
270        let deps_met = {
271            let node = &dag[node_id];
272            node.dependencies.iter().all(|dep| {
273                dag.get(dep)
274                    .is_some_and(|n| n.status == NodeStatus::Completed)
275            })
276        };
277
278        if let Some(node) = dag.get_mut(node_id) {
279            node.status = NodeStatus::Running;
280            if deps_met {
281                node.status = NodeStatus::Completed;
282                executed.push(node_id.clone());
283            } else {
284                node.status = NodeStatus::Blocked;
285                failed.push(node_id.clone());
286            }
287        } else {
288            failed.push(node_id.clone());
289        }
290    }
291
292    let elapsed = start.elapsed().as_secs_f64() * 1000.0;
293
294    SimulationResult {
295        success: failed.is_empty(),
296
297        executed_nodes: executed,
298
299        failed_nodes: failed,
300
301        execution_order: order,
302
303        total_time_ms: (elapsed * 100.0).round() / 100.0,
304    }
305}
306
307/// Create hierarchical URN bindings for fractal composition.
308
309///
310
311/// Maps child URNs under a parent namespace, creating a fractal
312
313/// capability hierarchy.
314
315pub fn stitch_fractal_urns(parent_urn: &str, child_urns: &[&str]) -> HashMap<String, String> {
316    child_urns
317        .iter()
318        .map(|&child_urn| {
319            let leaf = child_urn.rsplit(':').next().unwrap_or(child_urn);
320
321            let fractal_urn = format!("{}:{}", parent_urn, leaf);
322
323            (child_urn.to_string(), fractal_urn)
324        })
325        .collect()
326}
327
328/// Topological Compute Enforcer / Causal Clock (`causal_clock`) guard (#338)
329
330///
331
332/// Under Hanson's do-calculus, the system mathematically tracks causal clock logical
333
334/// timestamps on the DAG edges to enforce compute budget constraints and prevent
335
336/// infinite causal execution loops.
337
338pub struct CausalClockEnforcer {
339    pub clock_ticks: u64,
340}
341
342/// A causal intervention specification for Pearl's do-operator.
343
344#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
345
346pub struct CausalIntervention {
347    pub node_id: String,
348
349    pub forced_outputs: serde_json::Value,
350}
351
352/// Error type for causal DAG surgery operations.
353#[derive(Error, Debug, Clone, serde::Serialize)]
354pub enum CausalError {
355    #[error("Node not found in DAG: {0}")]
356    NodeNotFound(String),
357}
358
359/// Pearl's Causal Do-operator simulator.
360
361pub struct DoOperator;
362
363impl DoOperator {
364    /// Performs causal graph surgery on a DAG according to Pearl's do-operator.
365
366    ///
367
368    /// It:
369
370    /// 1. Clones the target DAG.
371
372    /// 2. Clears the target node's dependencies (severing incoming edges).
373
374    /// 3. Forces the target node's outputs to the intervention value.
375
376    /// 4. Simulates execution over the mutilated DAG.
377
378    pub fn apply_intervention(
379        dag: &HashMap<String, SimulationNode>,
380
381        intervention: &CausalIntervention,
382    ) -> Result<SimulationResult, CausalError> {
383        if !dag.contains_key(&intervention.node_id) {
384            return Err(CausalError::NodeNotFound(intervention.node_id.clone()));
385        }
386
387        let mut mutilated_dag = dag.clone();
388
389        // Perform graph surgery: sever incoming edges (clear dependencies)
390        let target_node = mutilated_dag
391            .get_mut(&intervention.node_id)
392            .ok_or_else(|| CausalError::NodeNotFound(intervention.node_id.clone()))?;
393
394        target_node.dependencies.clear();
395
396        target_node.outputs = intervention.forced_outputs.clone();
397
398        target_node.status = NodeStatus::Completed;
399
400        // Run simulation on the mutilated DAG
401
402        let mut result = simulate_execution(&mut mutilated_dag);
403
404        // Ensure the intervened node is registered as executed
405
406        if !result.executed_nodes.contains(&intervention.node_id) {
407            result
408                .executed_nodes
409                .insert(0, intervention.node_id.clone());
410        }
411
412        Ok(result)
413    }
414}
415
416#[cfg(test)]
417
418mod tests {
419
420    use super::*;
421
422    fn make_dag() -> HashMap<String, SimulationNode> {
423        let mut dag = HashMap::new();
424
425        dag.insert("a".into(), SimulationNode::new("a", "compute"));
426
427        dag.insert(
428            "b".into(),
429            SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
430        );
431
432        dag.insert(
433            "c".into(),
434            SimulationNode::new("c", "compute").with_dependencies(vec!["a"]),
435        );
436
437        dag.insert(
438            "d".into(),
439            SimulationNode::new("d", "output").with_dependencies(vec!["b", "c"]),
440        );
441
442        dag
443    }
444
445    #[test]
446
447    fn test_verify_dag_integrity_valid() {
448        let dag = make_dag();
449
450        let report = verify_dag_integrity(&dag);
451
452        assert!(report.valid);
453
454        assert!(!report.has_cycle);
455
456        assert!(report.dangling_references.is_empty());
457
458        assert_eq!(report.node_count, 4);
459
460        // "a" must come before "b" and "c"; "d" must come last
461
462        let order = &report.topological_order;
463
464        let a_pos = order.iter().position(|x| x == "a").unwrap();
465
466        let b_pos = order.iter().position(|x| x == "b").unwrap();
467
468        let c_pos = order.iter().position(|x| x == "c").unwrap();
469
470        let d_pos = order.iter().position(|x| x == "d").unwrap();
471
472        assert!(a_pos < b_pos);
473
474        assert!(a_pos < c_pos);
475
476        assert!(b_pos < d_pos);
477
478        assert!(c_pos < d_pos);
479    }
480
481    #[test]
482
483    fn test_verify_dag_detects_cycle() {
484        let mut dag = HashMap::new();
485
486        dag.insert(
487            "a".into(),
488            SimulationNode::new("a", "compute").with_dependencies(vec!["b"]),
489        );
490
491        dag.insert(
492            "b".into(),
493            SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
494        );
495
496        let report = verify_dag_integrity(&dag);
497
498        assert!(!report.valid);
499
500        assert!(report.has_cycle);
501
502        assert!(report.topological_order.is_empty());
503    }
504
505    #[test]
506
507    fn test_verify_dag_detects_dangling() {
508        let mut dag = HashMap::new();
509
510        dag.insert(
511            "a".into(),
512            SimulationNode::new("a", "compute").with_dependencies(vec!["missing"]),
513        );
514
515        let report = verify_dag_integrity(&dag);
516
517        assert!(!report.valid);
518
519        assert!(!report.dangling_references.is_empty());
520    }
521
522    #[test]
523
524    fn test_simulate_execution_valid() {
525        let mut dag = make_dag();
526
527        let result = simulate_execution(&mut dag);
528
529        assert!(result.success);
530
531        assert_eq!(result.executed_nodes.len(), 4);
532
533        assert!(result.failed_nodes.is_empty());
534    }
535
536    #[test]
537
538    fn test_simulate_execution_invalid_dag() {
539        let mut dag = HashMap::new();
540
541        dag.insert(
542            "a".into(),
543            SimulationNode::new("a", "compute").with_dependencies(vec!["b"]),
544        );
545
546        dag.insert(
547            "b".into(),
548            SimulationNode::new("b", "compute").with_dependencies(vec!["a"]),
549        );
550
551        let result = simulate_execution(&mut dag);
552
553        assert!(!result.success);
554
555        assert_eq!(result.failed_nodes.len(), 2);
556    }
557
558    #[test]
559
560    fn test_stitch_fractal_urns() {
561        let bindings = stitch_fractal_urns(
562            "urn:coreason:agent:orchestrator",
563            &["urn:coreason:tool:calculator", "urn:coreason:tool:search"],
564        );
565
566        assert_eq!(
567            bindings["urn:coreason:tool:calculator"],
568            "urn:coreason:agent:orchestrator:calculator"
569        );
570
571        assert_eq!(
572            bindings["urn:coreason:tool:search"],
573            "urn:coreason:agent:orchestrator:search"
574        );
575    }
576
577    #[test]
578
579    fn test_stitch_fractal_urns_no_colon() {
580        let bindings = stitch_fractal_urns("parent", &["child"]);
581
582        assert_eq!(bindings["child"], "parent:child");
583    }
584
585    #[test]
586
587    fn test_empty_dag() {
588        let dag: HashMap<String, SimulationNode> = HashMap::new();
589
590        let report = verify_dag_integrity(&dag);
591
592        assert!(report.valid);
593
594        assert_eq!(report.node_count, 0);
595    }
596
597    #[test]
598
599    fn test_single_node_dag() {
600        let mut dag = HashMap::new();
601
602        dag.insert("solo".into(), SimulationNode::new("solo", "compute"));
603
604        let mut dag_mut = dag.clone();
605
606        let result = simulate_execution(&mut dag_mut);
607
608        assert!(result.success);
609
610        assert_eq!(result.executed_nodes.len(), 1);
611    }
612
613    #[test]
614
615    fn test_do_operator_surgery() {
616        let dag = make_dag();
617
618        let intervention = CausalIntervention {
619            node_id: "c".to_string(),
620
621            forced_outputs: serde_json::json!({"injected": true}),
622        };
623
624        let result = DoOperator::apply_intervention(&dag, &intervention).unwrap();
625
626        assert!(result.success);
627
628        assert!(result.executed_nodes.contains(&"c".to_string()));
629    }
630
631    #[test]
632
633    fn test_do_operator_node_not_found() {
634        let dag = make_dag();
635
636        let intervention = CausalIntervention {
637            node_id: "missing".to_string(),
638
639            forced_outputs: serde_json::Value::Null,
640        };
641
642        let result = DoOperator::apply_intervention(&dag, &intervention);
643
644        assert!(result.is_err());
645    }
646}