Skip to main content

byteflow/scheduler/
monitor.rs

1//! Monitor table: one-way lifecycle watches (`A ──monitor──> B`).
2//!
3//! A monitor is a **runtime relation**, not a field on [`crate::Message`].
4//! When the target exits, [`MonitorTable::notify_target_exit`] yields
5//! [`DownEvent`]s that [`super::finalize`] delivers as Atomic Hop
6//! [`crate::TAG_SYS_DOWN`] messages.
7//!
8//! Relations are keyed by [`FlowId`] (identity). Bytecode addresses the
9//! target through a Cap; the worker resolves Cap → FlowId before calling
10//! here. Caps are revoked on exit; FlowIds are never reused.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14
15use super::error::{LifecycleError, RuntimeError};
16use super::process::FlowId;
17use super::sync_lock;
18
19/// Opaque monitor reference, echoed on the `DOWN` hop as `request_id`.
20///
21/// The inner id is runtime-minted (`pub(crate)`): bytecode only ever sees
22/// it as `Value::Int` after `Monitor`, never as a host-constructed token.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub struct MonitorRef(pub(crate) u64);
25
26/// Bytecode stores [`MonitorRef`] as [`crate::Value::Int`]; never mint past this.
27const MAX_MONITOR_ID: u64 = i64::MAX as u64;
28
29static NEXT_MONITOR: AtomicU64 = AtomicU64::new(1);
30static MONITOR_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
31
32fn try_next_monitor_id() -> Result<MonitorRef, RuntimeError> {
33    if MONITOR_IDS_EXHAUSTED.load(Ordering::Relaxed) {
34        return Err(RuntimeError::MonitorIdExhausted);
35    }
36    let id = NEXT_MONITOR.fetch_add(1, Ordering::Relaxed);
37    if id == 0 || id > MAX_MONITOR_ID {
38        MONITOR_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
39        return Err(RuntimeError::MonitorIdExhausted);
40    }
41    Ok(MonitorRef(id))
42}
43
44impl MonitorRef {
45    #[inline]
46    pub fn as_u64(self) -> u64 {
47        self.0
48    }
49
50    #[inline]
51    pub(crate) fn from_u64(raw: u64) -> Self {
52        Self(raw)
53    }
54}
55
56impl std::fmt::Display for MonitorRef {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "monitor#{}", self.0)
59    }
60}
61
62/// Why a flow left the directory. Encoded as `Message.payload` on system hops.
63///
64/// Named [`FlowExitReason`] so it does not collide with the JIT
65/// `ExitReason` (trace-compiler control flow).
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67#[repr(u8)]
68pub enum FlowExitReason {
69    Normal = 0,
70    /// Host-wide runtime teardown (parked HostAwait drain, etc.).
71    Shutdown = 1,
72    Killed = 2,
73    Fault = 3,
74    /// Reserved: overflow-kill policy (today overflow is `MailboxFull` / park).
75    MailboxOverflow = 4,
76    Supervisor = 5,
77    Link = 6,
78}
79
80impl FlowExitReason {
81    pub fn from_u64(raw: u64) -> Option<Self> {
82        Some(match raw {
83            0 => Self::Normal,
84            1 => Self::Shutdown,
85            2 => Self::Killed,
86            3 => Self::Fault,
87            4 => Self::MailboxOverflow,
88            5 => Self::Supervisor,
89            6 => Self::Link,
90            _ => return None,
91        })
92    }
93
94    #[inline]
95    pub fn as_u64(self) -> u64 {
96        self as u64
97    }
98
99    /// Abnormal exits propagate through links (BEAM: `normal` does not).
100    ///
101    /// `Shutdown` / `Killed` / `Supervisor` are host-policy reasons;
102    /// they still count as abnormal so a supervisor abort is not
103    /// silently swallowed by links.
104    #[inline]
105    pub fn is_abnormal(self) -> bool {
106        !matches!(self, Self::Normal)
107    }
108}
109
110impl std::fmt::Display for FlowExitReason {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        let name = match self {
113            Self::Normal => "normal",
114            Self::Shutdown => "shutdown",
115            Self::Killed => "killed",
116            Self::Fault => "fault",
117            Self::MailboxOverflow => "mailbox-overflow",
118            Self::Supervisor => "supervisor",
119            Self::Link => "link",
120        };
121        f.write_str(name)
122    }
123}
124
125/// One monitor firing after the target left the runtime.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub struct DownEvent {
128    pub monitor: MonitorRef,
129    pub owner: FlowId,
130    pub target: FlowId,
131    pub reason: FlowExitReason,
132}
133
134#[derive(Debug, Clone, Copy)]
135struct MonitorEntry {
136    owner: FlowId,
137    target: FlowId,
138}
139
140/// `MonitorRef → { owner, target }`. Lives on [`super::runtime::Shared`].
141///
142/// `by_owner` / `by_target` are adjacency indexes so owner-exit and
143/// `DOWN` delivery are O(degree), not a full-table scan.
144pub struct MonitorTable {
145    monitors: HashMap<MonitorRef, MonitorEntry>,
146    by_owner: HashMap<FlowId, Vec<MonitorRef>>,
147    by_target: HashMap<FlowId, Vec<MonitorRef>>,
148}
149
150impl MonitorTable {
151    pub fn new() -> Self {
152        Self {
153            monitors: HashMap::new(),
154            by_owner: HashMap::new(),
155            by_target: HashMap::new(),
156        }
157    }
158
159    #[inline]
160    pub fn len(&self) -> usize {
161        self.monitors.len()
162    }
163
164    fn index_add(map: &mut HashMap<FlowId, Vec<MonitorRef>>, flow: FlowId, id: MonitorRef) {
165        map.entry(flow).or_default().push(id);
166    }
167
168    fn index_remove(map: &mut HashMap<FlowId, Vec<MonitorRef>>, flow: FlowId, id: MonitorRef) {
169        if let Some(ids) = map.get_mut(&flow) {
170            ids.retain(|existing| *existing != id);
171            if ids.is_empty() {
172                map.remove(&flow);
173            }
174        }
175    }
176
177    fn insert(&mut self, monitor: MonitorRef, owner: FlowId, target: FlowId) {
178        self.monitors
179            .insert(monitor, MonitorEntry { owner, target });
180        Self::index_add(&mut self.by_owner, owner, monitor);
181        Self::index_add(&mut self.by_target, target, monitor);
182    }
183
184    fn take(&mut self, monitor: MonitorRef) -> Option<MonitorEntry> {
185        let entry = self.monitors.remove(&monitor)?;
186        Self::index_remove(&mut self.by_owner, entry.owner, monitor);
187        Self::index_remove(&mut self.by_target, entry.target, monitor);
188        Some(entry)
189    }
190
191    #[cfg(test)]
192    pub fn create(&mut self, owner: FlowId, target: FlowId) -> Result<MonitorRef, RuntimeError> {
193        let monitor = try_next_monitor_id()?;
194        self.insert(monitor, owner, target);
195        Ok(monitor)
196    }
197
198    /// Remove `monitor` only if `owner` still owns it.
199    pub fn remove_owned(
200        &mut self,
201        owner: FlowId,
202        monitor: MonitorRef,
203    ) -> Result<(), LifecycleError> {
204        match self.monitors.get(&monitor) {
205            Some(entry) if entry.owner == owner => {
206                let _ = self.take(monitor);
207                Ok(())
208            }
209            Some(_) => Err(LifecycleError::NotOwner),
210            None => Err(LifecycleError::InvalidMonitor),
211        }
212    }
213
214    /// Drop every monitor whose **owner** is `flow` (owner exited).
215    pub fn remove_owned_by(&mut self, owner: FlowId) {
216        let Some(ids) = self.by_owner.remove(&owner) else {
217            return;
218        };
219        for id in ids {
220            if let Some(entry) = self.monitors.remove(&id) {
221                Self::index_remove(&mut self.by_target, entry.target, id);
222            }
223        }
224    }
225
226    /// Collect `DOWN` events for monitors watching `target`, then drop them.
227    pub fn notify_target_exit(&mut self, target: FlowId, reason: FlowExitReason) -> Vec<DownEvent> {
228        let Some(ids) = self.by_target.remove(&target) else {
229            return Vec::new();
230        };
231        let mut events = Vec::with_capacity(ids.len());
232        for monitor in ids {
233            let Some(entry) = self.monitors.remove(&monitor) else {
234                continue;
235            };
236            Self::index_remove(&mut self.by_owner, entry.owner, monitor);
237            events.push(DownEvent {
238                monitor,
239                owner: entry.owner,
240                target,
241                reason,
242            });
243        }
244        events.sort_unstable_by_key(|event| event.monitor.0);
245        events
246    }
247}
248
249impl Default for MonitorTable {
250    fn default() -> Self {
251        Self::new()
252    }
253}
254
255/// Fail-closed wrapper around [`MonitorTable`].
256///
257/// Process-wide monitor quota lives here (`table.len()` under the same lock).
258pub struct MonitorStore {
259    inner: std::sync::Mutex<MonitorTable>,
260    max_monitors: u32,
261}
262
263impl MonitorStore {
264    /// `max_monitors == 0` → unlimited.
265    pub fn new(max_monitors: u32) -> Self {
266        Self {
267            inner: std::sync::Mutex::new(MonitorTable::new()),
268            max_monitors,
269        }
270    }
271
272    pub fn create(
273        &self,
274        owner: FlowId,
275        target: FlowId,
276    ) -> Result<Result<MonitorRef, LifecycleError>, RuntimeError> {
277        let mut table = sync_lock::lock(&self.inner, "MonitorStore::create")?;
278        if self.max_monitors != 0 && table.len() >= self.max_monitors as usize {
279            return Ok(Err(LifecycleError::MonitorLimitReached {
280                limit: self.max_monitors,
281            }));
282        }
283        let monitor = try_next_monitor_id()?;
284        table.insert(monitor, owner, target);
285        Ok(Ok(monitor))
286    }
287
288    pub fn remove_owned(
289        &self,
290        owner: FlowId,
291        monitor: MonitorRef,
292    ) -> Result<Result<(), LifecycleError>, RuntimeError> {
293        Ok(
294            sync_lock::lock(&self.inner, "MonitorStore::remove_owned")?
295                .remove_owned(owner, monitor),
296        )
297    }
298
299    pub fn remove_owned_by(&self, owner: FlowId) -> Result<(), RuntimeError> {
300        sync_lock::lock(&self.inner, "MonitorStore::remove_owned_by")?.remove_owned_by(owner);
301        Ok(())
302    }
303
304    pub fn notify_target_exit(
305        &self,
306        target: FlowId,
307        reason: FlowExitReason,
308    ) -> Result<Vec<DownEvent>, RuntimeError> {
309        Ok(
310            sync_lock::lock(&self.inner, "MonitorStore::notify_target_exit")?
311                .notify_target_exit(target, reason),
312        )
313    }
314}
315
316impl Default for MonitorStore {
317    fn default() -> Self {
318        Self::new(0)
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use crate::scheduler::process::next_flow_id;
326
327    #[test]
328    fn notify_removes_and_sorts() -> Result<(), RuntimeError> {
329        let mut table = MonitorTable::new();
330        let owner = next_flow_id();
331        let target = next_flow_id();
332        let a = table.create(owner, target)?;
333        let b = table.create(owner, target)?;
334        let events = table.notify_target_exit(target, FlowExitReason::Fault);
335        assert_eq!(events.len(), 2);
336        assert_eq!(events[0].monitor, a);
337        assert_eq!(events[1].monitor, b);
338        assert!(table
339            .notify_target_exit(target, FlowExitReason::Fault)
340            .is_empty());
341        Ok(())
342    }
343
344    #[test]
345    fn remove_owned_rejects_other_flow() -> Result<(), RuntimeError> {
346        let mut table = MonitorTable::new();
347        let owner = next_flow_id();
348        let other = next_flow_id();
349        let target = next_flow_id();
350        let mon = table.create(owner, target)?;
351        assert_eq!(
352            table.remove_owned(other, mon),
353            Err(LifecycleError::NotOwner)
354        );
355        assert!(table.remove_owned(owner, mon).is_ok());
356        Ok(())
357    }
358
359    #[test]
360    fn monitor_limit_is_process_wide_and_released() -> Result<(), Box<dyn std::error::Error>> {
361        let store = MonitorStore::new(1);
362        let owner = next_flow_id();
363        let t1 = next_flow_id();
364        let t2 = next_flow_id();
365        let first = store.create(owner, t1)??;
366        let second = store.create(owner, t2)?;
367        assert!(matches!(
368            second,
369            Err(LifecycleError::MonitorLimitReached { limit: 1 })
370        ));
371        store.remove_owned(owner, first)??;
372        match store.create(owner, t2)? {
373            Ok(_) => Ok(()),
374            Err(e) => Err(e.into()),
375        }
376    }
377}