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
15// Docs ratchet: public items here predate `missing_docs`. Delete this
16// allow once they are documented; new files get the lint by default.
17#![allow(missing_docs)]
18
19use std::fmt;
20use std::sync::atomic::{AtomicU64, Ordering};
21
22/// Count of infrastructure faults observed since flow start (Relaxed).
23static FAULTS: AtomicU64 = AtomicU64::new(0);
24
25/// Scheduler / host infrastructure error — not a bytecode flow fault.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum RuntimeError {
28    /// A `Mutex` was poisoned: another thread panicked while holding it.
29    /// Shared tables may be inconsistent; callers must not continue using them.
30    PoisonedLock(&'static str),
31    /// A flow was destroyed before it produced a [`crate::FlowOutcome`], so
32    /// the completion value its handle was waiting for will never arrive.
33    ///
34    /// Reachable when the runtime shuts down while a flow is suspended (in
35    /// the timer, in a worker deque, or parked in its mailbox): those flows
36    /// are dropped without reaching `finish`. The alternative to reporting
37    /// this is worse — a `join()` that blocks the embedder's thread forever
38    /// with no way to tell "still running" from "never will".
39    Abandoned(&'static str),
40    /// The outcome was already collected by an earlier non-consuming
41    /// `try_join` / `join_timeout`, so there is nothing left to hand out.
42    ///
43    /// Caller misuse rather than an infrastructure failure (kind A in the
44    /// table above), reported here because it shares `join`'s return type.
45    /// It exists so a second poll cannot be answered with `Abandoned`, which
46    /// would blame the runtime for destroying a flow that in fact completed
47    /// normally and was already observed.
48    AlreadyCollected(&'static str),
49    /// OS CSPRNG failed while minting a capability.
50    EntropyFailed(crate::entropy::EntropyError),
51    /// Eight draws were the reserved zero id (`CapId::NONE`).
52    ReservedCapId,
53    /// Fresh ids collided in the table beyond the retry budget.
54    CapIdCollision,
55    /// `finalize_flow` was asked to tear down the reserved host FlowId.
56    CannotFinalizeHostFlow,
57    /// `next_flow_id` wrapped onto [`crate::FlowId::HOST`] (`0`).
58    FlowIdExhausted,
59    /// Directory register saw a live id twice (wrap or double-spawn).
60    DuplicateFlowId,
61    /// Link-id counter wrapped or exceeded `i64::MAX` (bytecode `Int` bound).
62    LinkIdExhausted,
63    /// Monitor-id counter wrapped or exceeded `i64::MAX` (bytecode `Int` bound).
64    MonitorIdExhausted,
65    /// A table operation failed (name, capacity, or liveness).
66    Table(String),
67}
68
69impl fmt::Display for RuntimeError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match self {
72            RuntimeError::PoisonedLock(where_) => {
73                write!(f, "runtime mutex poisoned at {where_}")
74            }
75            RuntimeError::Abandoned(where_) => {
76                write!(
77                    f,
78                    "{where_}: flow was destroyed before producing an outcome"
79                )
80            }
81            RuntimeError::AlreadyCollected(where_) => {
82                write!(f, "{where_}: outcome was already collected")
83            }
84            RuntimeError::EntropyFailed(err) => {
85                write!(f, "capability CSPRNG unavailable: {err}")
86            }
87            RuntimeError::ReservedCapId => {
88                write!(f, "capability id draw was the reserved zero")
89            }
90            RuntimeError::CapIdCollision => {
91                write!(f, "could not allocate a unique capability id")
92            }
93            RuntimeError::CannotFinalizeHostFlow => {
94                write!(f, "cannot finalize reserved host flow")
95            }
96            RuntimeError::FlowIdExhausted => {
97                write!(f, "flow id space exhausted (counter wrapped)")
98            }
99            RuntimeError::DuplicateFlowId => {
100                write!(f, "directory already has this flow id")
101            }
102            RuntimeError::LinkIdExhausted => {
103                write!(f, "link id space exhausted (counter wrapped)")
104            }
105            RuntimeError::MonitorIdExhausted => {
106                write!(f, "monitor id space exhausted (counter wrapped)")
107            }
108            RuntimeError::Table(msg) => write!(f, "table: {msg}"),
109        }
110    }
111}
112
113impl From<String> for RuntimeError {
114    fn from(msg: String) -> Self {
115        RuntimeError::Table(msg)
116    }
117}
118impl std::error::Error for RuntimeError {
119    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
120        match self {
121            RuntimeError::EntropyFailed(err) => Some(err),
122            _ => None,
123        }
124    }
125}
126
127/// User-facing lifecycle / naming errors (category A).
128///
129/// Distinct from [`RuntimeError`] (infrastructure / poison). Host
130/// `monitor` / `link` / `register_name` return this so a dead FlowId or
131/// a duplicate name is not reported as a poisoned mutex.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub enum LifecycleError {
134    NoSuchFlow(super::process::FlowId),
135    InvalidCapability,
136    InvalidMonitor,
137    InvalidLink,
138    NotOwner,
139    AlreadyRegistered,
140    AlreadyLinked,
141    EmptyName,
142    SelfRelation,
143    Unavailable,
144    /// Process-wide [`crate::RuntimeConfig::max_links`] reached.
145    LinkLimitReached {
146        limit: u32,
147    },
148    /// Process-wide [`crate::RuntimeConfig::max_monitors`] reached.
149    MonitorLimitReached {
150        limit: u32,
151    },
152    /// Process-wide [`crate::RuntimeConfig::max_registry_names`] reached.
153    RegistryLimitReached {
154        limit: u32,
155    },
156}
157
158impl fmt::Display for LifecycleError {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
162            Self::InvalidCapability => write!(f, "unknown or revoked capability"),
163            Self::InvalidMonitor => write!(f, "unknown monitor"),
164            Self::InvalidLink => write!(f, "unknown link"),
165            Self::NotOwner => write!(f, "caller does not own this relation"),
166            Self::AlreadyRegistered => write!(f, "registry name already taken"),
167            Self::AlreadyLinked => write!(f, "flows are already linked"),
168            Self::EmptyName => write!(f, "registry name must be non-empty"),
169            Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
170            Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
171            Self::LinkLimitReached { limit } => {
172                write!(f, "link limit reached ({limit})")
173            }
174            Self::MonitorLimitReached { limit } => {
175                write!(f, "monitor limit reached ({limit})")
176            }
177            Self::RegistryLimitReached { limit } => {
178                write!(f, "registry name limit reached ({limit})")
179            }
180        }
181    }
182}
183
184impl std::error::Error for LifecycleError {}
185
186/// Record an infrastructure fault (stderr + counter). Does not panic.
187#[cold]
188pub fn report_fault(err: RuntimeError) {
189    FAULTS.fetch_add(1, Ordering::Relaxed);
190    eprintln!("byteflow: {err} — fail-closed");
191}
192
193/// How many [`report_fault`] calls have been made (tests / diagnostics).
194pub fn fault_count() -> u64 {
195    FAULTS.load(Ordering::Relaxed)
196}
197
198/// User-facing spawn / load errors (category A in the taxonomy above).
199///
200/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
201/// OS thread creation. Panic is reserved for *bugs*; a bad function index
202/// or a refused `thread::spawn` is an embedder-visible failure and must
203/// surface as `Result` so the host can recover without taking workers down.
204#[derive(Debug, Clone, PartialEq, Eq)]
205pub enum SpawnError {
206    /// `function` index is outside the runtime chunk's function table.
207    BadFunction {
208        index: u32,
209        table_size: u32,
210    },
211    /// Chunk failed verification before the runtime could start.
212    VerifyFailed(crate::bytecode::VerifyError),
213    /// Spawn arguments contained an unknown or unusable capability.
214    InvalidCapability,
215    /// Scheduler table poisoned (fail closed).
216    Unavailable,
217    /// Flow-id counter wrapped onto the reserved host id.
218    FlowIdExhausted,
219    /// Host correlation counter wrapped. A new id would reuse `1`.
220    RequestIdsExhausted,
221    /// Live flow count would exceed [`crate::RuntimeConfig::max_flows`].
222    FlowLimit {
223        current: usize,
224        max: u32,
225    },
226    /// Bytecode spawn failed the quota / SPAWN-right / attenuation check.
227    SpawnDenied(String),
228    SpawnRateExceeded,
229    ParentCapRevoked,
230    MissingSpawnRight,
231    /// [`crate::ChildSpec::name`] is already in the runtime registry.
232    NameTaken {
233        name: String,
234    },
235    /// OS refused to create a worker / timer / supervisor thread.
236    ThreadSpawnFailed(String),
237    /// Integrity fingerprint / attested decode failed.
238    Attestation(crate::AttestError),
239    /// `Vm::new` failed for a reason other than a bad function index
240    /// (mapped from [`crate::Fault`] via `From`).
241    VmInit(String),
242}
243
244impl fmt::Display for SpawnError {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        match self {
247            SpawnError::BadFunction { index, table_size } => {
248                write!(
249                    f,
250                    "spawn: function index {index} out of range (table size {table_size})"
251                )
252            }
253            SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
254            SpawnError::InvalidCapability => {
255                write!(f, "spawn: argument capability is unknown or not held")
256            }
257            SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
258            SpawnError::FlowIdExhausted => {
259                write!(f, "spawn: flow id space exhausted (counter wrapped)")
260            }
261            SpawnError::RequestIdsExhausted => {
262                write!(f, "spawn: host request ids exhausted")
263            }
264            SpawnError::FlowLimit { current, max } => {
265                write!(f, "spawn: live flow limit reached ({current}/{max})")
266            }
267            SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
268            SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
269            SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
270            SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
271            SpawnError::NameTaken { name } => {
272                write!(f, "spawn: registry name {name:?} already taken")
273            }
274            SpawnError::ThreadSpawnFailed(msg) => {
275                write!(f, "failed to spawn runtime thread: {msg}")
276            }
277            SpawnError::Attestation(err) => write!(f, "attestation failed: {err}"),
278            SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
279        }
280    }
281}
282
283impl std::error::Error for SpawnError {}
284
285impl From<crate::vm::Fault> for SpawnError {
286    fn from(fault: crate::vm::Fault) -> Self {
287        match fault {
288            crate::vm::Fault::BadFunction { index, table_size } => {
289                SpawnError::BadFunction { index, table_size }
290            }
291            other => SpawnError::VmInit(other.to_string()),
292        }
293    }
294}