Skip to main content

byteflow/scheduler/
error.rs

1//! Infrastructure failures of the scheduler (category C in the error model).
2//!
3//! # Failure taxonomy (Byteflow)
4//!
5//! | Kind | Example | Surface |
6//! |------|---------|---------|
7//! | A — user / API | `spawn` bad function index | `Result<_, SpawnError>` |
8//! | B — flow | `HwError`, native fault | `FlowOutcome::Failed` → Supervisor |
9//! | C — infrastructure | mutex poison, dead worker | [`RuntimeError`] + fail-closed |
10//! | D — invariant | empty frame stack while running | types / `debug_assert` — not `unwrap` |
11//!
12//! **Panic is a runtime bug, not an error-handling mechanism.** Device faults
13//! kill actors; scheduler faults are explicit and fail-closed.
14
15use std::fmt;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18/// Count of infrastructure faults observed since flow start (Relaxed).
19static FAULTS: AtomicU64 = AtomicU64::new(0);
20
21/// Scheduler / host infrastructure error — not a bytecode flow fault.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum RuntimeError {
24    /// A `Mutex` was poisoned: another thread panicked while holding it.
25    /// Shared tables may be inconsistent; callers must not continue using them.
26    PoisonedLock(&'static str),
27    /// A flow was destroyed before it produced a [`crate::FlowOutcome`], so
28    /// the completion value its handle was waiting for will never arrive.
29    ///
30    /// Reachable when the runtime shuts down while a flow is suspended (in
31    /// the timer, in a worker deque, or parked in its mailbox): those flows
32    /// are dropped without reaching `finish`. The alternative to reporting
33    /// this is worse — a `join()` that blocks the embedder's thread forever
34    /// with no way to tell "still running" from "never will".
35    Abandoned(&'static str),
36    /// The outcome was already collected by an earlier non-consuming
37    /// `try_join` / `join_timeout`, so there is nothing left to hand out.
38    ///
39    /// Caller misuse rather than an infrastructure failure (kind A in the
40    /// table above), reported here because it shares `join`'s return type.
41    /// It exists so a second poll cannot be answered with `Abandoned`, which
42    /// would blame the runtime for destroying a flow that in fact completed
43    /// normally and was already observed.
44    AlreadyCollected(&'static str),
45    /// OS CSPRNG failed while minting a capability.
46    EntropyFailed,
47    /// CSPRNG produced colliding ids beyond the retry budget (should not happen).
48    CapIdCollision,
49    /// `finalize_flow` was asked to tear down the reserved host FlowId.
50    CannotFinalizeHostFlow,
51    /// `next_flow_id` wrapped onto [`crate::FlowId::HOST`] (`0`).
52    FlowIdExhausted,
53    /// Directory register saw a live id twice (wrap or double-spawn).
54    DuplicateFlowId,
55}
56
57impl fmt::Display for RuntimeError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            RuntimeError::PoisonedLock(where_) => {
61                write!(f, "runtime mutex poisoned at {where_}")
62            }
63            RuntimeError::Abandoned(where_) => {
64                write!(
65                    f,
66                    "{where_}: flow was destroyed before producing an outcome"
67                )
68            }
69            RuntimeError::AlreadyCollected(where_) => {
70                write!(f, "{where_}: outcome was already collected")
71            }
72            RuntimeError::EntropyFailed => {
73                write!(f, "capability CSPRNG unavailable")
74            }
75            RuntimeError::CapIdCollision => {
76                write!(f, "could not allocate a unique capability id")
77            }
78            RuntimeError::CannotFinalizeHostFlow => {
79                write!(f, "cannot finalize reserved host flow")
80            }
81            RuntimeError::FlowIdExhausted => {
82                write!(f, "flow id space exhausted (counter wrapped)")
83            }
84            RuntimeError::DuplicateFlowId => {
85                write!(f, "directory already has this flow id")
86            }
87        }
88    }
89}
90
91impl std::error::Error for RuntimeError {}
92
93/// User-facing lifecycle / naming errors (category A).
94///
95/// Distinct from [`RuntimeError`] (infrastructure / poison). Host
96/// `monitor` / `link` / `register_name` return this so a dead FlowId or
97/// a duplicate name is not reported as a poisoned mutex.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum LifecycleError {
100    NoSuchFlow(super::process::FlowId),
101    InvalidCapability,
102    InvalidMonitor,
103    InvalidLink,
104    NotOwner,
105    AlreadyRegistered,
106    AlreadyLinked,
107    EmptyName,
108    SelfRelation,
109    Unavailable,
110}
111
112impl fmt::Display for LifecycleError {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        match self {
115            Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
116            Self::InvalidCapability => write!(f, "unknown or revoked capability"),
117            Self::InvalidMonitor => write!(f, "unknown monitor"),
118            Self::InvalidLink => write!(f, "unknown link"),
119            Self::NotOwner => write!(f, "caller does not own this relation"),
120            Self::AlreadyRegistered => write!(f, "registry name already taken"),
121            Self::AlreadyLinked => write!(f, "flows are already linked"),
122            Self::EmptyName => write!(f, "registry name must be non-empty"),
123            Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
124            Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
125        }
126    }
127}
128
129impl std::error::Error for LifecycleError {}
130
131/// Record an infrastructure fault (stderr + counter). Does not panic.
132#[cold]
133pub fn report_fault(err: RuntimeError) {
134    FAULTS.fetch_add(1, Ordering::Relaxed);
135    eprintln!("byteflow: {err} — fail-closed");
136}
137
138/// How many [`report_fault`] calls have been made (tests / diagnostics).
139pub fn fault_count() -> u64 {
140    FAULTS.load(Ordering::Relaxed)
141}
142
143/// User-facing spawn / load errors (category A in the taxonomy above).
144///
145/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
146/// OS thread creation. Panic is reserved for *bugs*; a bad function index
147/// or a refused `thread::spawn` is an embedder-visible failure and must
148/// surface as `Result` so the host can recover without taking workers down.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum SpawnError {
151    /// `function` index is outside the runtime chunk's function table.
152    BadFunction {
153        index: u32,
154        table_size: u32,
155    },
156    /// Chunk failed verification before the runtime could start.
157    VerifyFailed(crate::bytecode::VerifyError),
158    /// Spawn arguments contained an unknown or unusable capability.
159    InvalidCapability,
160    /// Scheduler table poisoned (fail closed).
161    Unavailable,
162    /// Flow-id counter wrapped onto the reserved host id.
163    FlowIdExhausted,
164    /// Live flow count would exceed [`crate::RuntimeConfig::max_flows`].
165    FlowLimit {
166        current: usize,
167        max: u32,
168    },
169    /// Bytecode spawn failed the quota / SPAWN-right / attenuation check.
170    SpawnDenied(String),
171    SpawnRateExceeded,
172    ParentCapRevoked,
173    MissingSpawnRight,
174    /// [`crate::ChildSpec::name`] is already in the runtime registry.
175    NameTaken {
176        name: String,
177    },
178    /// OS refused to create a worker / timer / supervisor thread.
179    ThreadSpawnFailed(String),
180    /// `Vm::new` failed for a reason other than a bad function index
181    /// (mapped from [`crate::Fault`] via `From`).
182    VmInit(String),
183}
184
185impl fmt::Display for SpawnError {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            SpawnError::BadFunction { index, table_size } => {
189                write!(
190                    f,
191                    "spawn: function index {index} out of range (table size {table_size})"
192                )
193            }
194            SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
195            SpawnError::InvalidCapability => {
196                write!(f, "spawn: argument capability is unknown or not held")
197            }
198            SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
199            SpawnError::FlowIdExhausted => {
200                write!(f, "spawn: flow id space exhausted (counter wrapped)")
201            }
202            SpawnError::FlowLimit { current, max } => {
203                write!(f, "spawn: live flow limit reached ({current}/{max})")
204            }
205            SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
206            SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
207            SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
208            SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
209            SpawnError::NameTaken { name } => {
210                write!(f, "spawn: registry name {name:?} already taken")
211            }
212            SpawnError::ThreadSpawnFailed(msg) => {
213                write!(f, "failed to spawn runtime thread: {msg}")
214            }
215            SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
216        }
217    }
218}
219
220impl std::error::Error for SpawnError {}
221
222impl From<crate::vm::Fault> for SpawnError {
223    fn from(fault: crate::vm::Fault) -> Self {
224        match fault {
225            crate::vm::Fault::BadFunction { index, table_size } => {
226                SpawnError::BadFunction { index, table_size }
227            }
228            other => SpawnError::VmInit(other.to_string()),
229        }
230    }
231}