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