Skip to main content

telltale_vm/
nested.rs

1//! Nested VM handler for distributed simulation.
2//!
3//! The outer VM schedules site coroutines; each site handler advances an
4//! inner VM that runs site-local protocols.
5
6use std::collections::BTreeMap;
7use std::sync::Mutex;
8
9use crate::coroutine::Value;
10use crate::effect::EffectHandler;
11use crate::vm::{ObsEvent, StepResult, VMError, VM};
12
13struct SiteRunner {
14    vm: Mutex<VM>,
15    handler: Box<dyn EffectHandler>,
16}
17
18/// Effect handler that dispatches to inner VMs keyed by outer role name.
19pub struct NestedVMHandler {
20    sites: BTreeMap<String, SiteRunner>,
21    max_rounds_per_step: usize,
22}
23
24impl NestedVMHandler {
25    /// Create an empty nested handler.
26    #[must_use]
27    pub fn new() -> Self {
28        Self {
29            sites: BTreeMap::new(),
30            max_rounds_per_step: 1,
31        }
32    }
33
34    /// Set how many inner VM rounds to advance per outer handler call.
35    #[must_use]
36    pub fn with_rounds_per_step(mut self, rounds: usize) -> Self {
37        self.max_rounds_per_step = rounds.max(1);
38        self
39    }
40
41    /// Number of inner VM rounds attempted per outer handler call.
42    #[must_use]
43    pub fn rounds_per_step(&self) -> usize {
44        self.max_rounds_per_step
45    }
46
47    /// Register a site by name with its inner VM and handler.
48    pub fn add_site(&mut self, name: impl Into<String>, vm: VM, handler: Box<dyn EffectHandler>) {
49        self.sites.insert(
50            name.into(),
51            SiteRunner {
52                vm: Mutex::new(vm),
53                handler,
54            },
55        );
56    }
57
58    /// Get a copy of the inner VM trace for a site.
59    ///
60    /// # Panics
61    ///
62    /// Panics if the site VM mutex is poisoned.
63    #[must_use]
64    pub fn site_trace(&self, name: &str) -> Option<Vec<ObsEvent>> {
65        self.sites.get(name).map(|site| {
66            site.vm
67                .lock()
68                .expect("site vm lock poisoned")
69                .trace()
70                .to_vec()
71        })
72    }
73
74    /// Check whether all coroutines in a site VM are terminal.
75    ///
76    /// # Panics
77    ///
78    /// Panics if the site VM mutex is poisoned.
79    #[must_use]
80    pub fn site_all_done(&self, name: &str) -> Option<bool> {
81        self.sites
82            .get(name)
83            .map(|site| site.vm.lock().expect("site vm lock poisoned").all_done())
84    }
85
86    fn step_site(&self, name: &str) -> Result<(), String> {
87        let site = self
88            .sites
89            .get(name)
90            .ok_or_else(|| format!("unknown site: {name}"))?;
91
92        let mut vm = site
93            .vm
94            .lock()
95            .map_err(|_| "site vm lock poisoned".to_string())?;
96        let handler = site.handler.as_ref();
97
98        for _ in 0..self.max_rounds_per_step {
99            match vm.step_round(handler, 1) {
100                Ok(StepResult::Continue) => {}
101                Ok(StepResult::AllDone | StepResult::Stuck) => break,
102                Err(VMError::Fault { fault, .. }) => {
103                    return Err(format!("inner vm fault: {fault}"));
104                }
105                Err(e) => return Err(e.to_string()),
106            }
107        }
108
109        Ok(())
110    }
111}
112
113impl Default for NestedVMHandler {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119impl EffectHandler for NestedVMHandler {
120    fn handle_send(
121        &self,
122        role: &str,
123        _partner: &str,
124        _label: &str,
125        _state: &[Value],
126    ) -> Result<Value, String> {
127        self.step_site(role)?;
128        Ok(Value::Unit)
129    }
130
131    fn handle_recv(
132        &self,
133        role: &str,
134        _partner: &str,
135        _label: &str,
136        _state: &mut Vec<Value>,
137        _payload: &Value,
138    ) -> Result<(), String> {
139        self.step_site(role)
140    }
141
142    fn handle_choose(
143        &self,
144        _role: &str,
145        _partner: &str,
146        labels: &[String],
147        _state: &[Value],
148    ) -> Result<String, String> {
149        labels
150            .first()
151            .cloned()
152            .ok_or_else(|| "no labels available".into())
153    }
154
155    fn step(&self, role: &str, _state: &mut Vec<Value>) -> Result<(), String> {
156        self.step_site(role)
157    }
158}