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    /// Process-wide [`crate::RuntimeConfig::max_links`] reached.
111    LinkLimitReached {
112        limit: u32,
113    },
114    /// Process-wide [`crate::RuntimeConfig::max_monitors`] reached.
115    MonitorLimitReached {
116        limit: u32,
117    },
118    /// Process-wide [`crate::RuntimeConfig::max_registry_names`] reached.
119    RegistryLimitReached {
120        limit: u32,
121    },
122}
123
124impl fmt::Display for LifecycleError {
125    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
126        match self {
127            Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
128            Self::InvalidCapability => write!(f, "unknown or revoked capability"),
129            Self::InvalidMonitor => write!(f, "unknown monitor"),
130            Self::InvalidLink => write!(f, "unknown link"),
131            Self::NotOwner => write!(f, "caller does not own this relation"),
132            Self::AlreadyRegistered => write!(f, "registry name already taken"),
133            Self::AlreadyLinked => write!(f, "flows are already linked"),
134            Self::EmptyName => write!(f, "registry name must be non-empty"),
135            Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
136            Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
137            Self::LinkLimitReached { limit } => {
138                write!(f, "link limit reached ({limit})")
139            }
140            Self::MonitorLimitReached { limit } => {
141                write!(f, "monitor limit reached ({limit})")
142            }
143            Self::RegistryLimitReached { limit } => {
144                write!(f, "registry name limit reached ({limit})")
145            }
146        }
147    }
148}
149
150impl std::error::Error for LifecycleError {}
151
152/// Record an infrastructure fault (stderr + counter). Does not panic.
153#[cold]
154pub fn report_fault(err: RuntimeError) {
155    FAULTS.fetch_add(1, Ordering::Relaxed);
156    eprintln!("byteflow: {err} — fail-closed");
157}
158
159/// How many [`report_fault`] calls have been made (tests / diagnostics).
160pub fn fault_count() -> u64 {
161    FAULTS.load(Ordering::Relaxed)
162}
163
164/// User-facing spawn / load errors (category A in the taxonomy above).
165///
166/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
167/// OS thread creation. Panic is reserved for *bugs*; a bad function index
168/// or a refused `thread::spawn` is an embedder-visible failure and must
169/// surface as `Result` so the host can recover without taking workers down.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub enum SpawnError {
172    /// `function` index is outside the runtime chunk's function table.
173    BadFunction {
174        index: u32,
175        table_size: u32,
176    },
177    /// Chunk failed verification before the runtime could start.
178    VerifyFailed(crate::bytecode::VerifyError),
179    /// Spawn arguments contained an unknown or unusable capability.
180    InvalidCapability,
181    /// Scheduler table poisoned (fail closed).
182    Unavailable,
183    /// Flow-id counter wrapped onto the reserved host id.
184    FlowIdExhausted,
185    /// Live flow count would exceed [`crate::RuntimeConfig::max_flows`].
186    FlowLimit {
187        current: usize,
188        max: u32,
189    },
190    /// Bytecode spawn failed the quota / SPAWN-right / attenuation check.
191    SpawnDenied(String),
192    SpawnRateExceeded,
193    ParentCapRevoked,
194    MissingSpawnRight,
195    /// [`crate::ChildSpec::name`] is already in the runtime registry.
196    NameTaken {
197        name: String,
198    },
199    /// OS refused to create a worker / timer / supervisor thread.
200    ThreadSpawnFailed(String),
201    /// Integrity fingerprint / attested decode failed.
202    Attestation(crate::AttestError),
203    /// `Vm::new` failed for a reason other than a bad function index
204    /// (mapped from [`crate::Fault`] via `From`).
205    VmInit(String),
206}
207
208impl fmt::Display for SpawnError {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        match self {
211            SpawnError::BadFunction { index, table_size } => {
212                write!(
213                    f,
214                    "spawn: function index {index} out of range (table size {table_size})"
215                )
216            }
217            SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
218            SpawnError::InvalidCapability => {
219                write!(f, "spawn: argument capability is unknown or not held")
220            }
221            SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
222            SpawnError::FlowIdExhausted => {
223                write!(f, "spawn: flow id space exhausted (counter wrapped)")
224            }
225            SpawnError::FlowLimit { current, max } => {
226                write!(f, "spawn: live flow limit reached ({current}/{max})")
227            }
228            SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
229            SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
230            SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
231            SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
232            SpawnError::NameTaken { name } => {
233                write!(f, "spawn: registry name {name:?} already taken")
234            }
235            SpawnError::ThreadSpawnFailed(msg) => {
236                write!(f, "failed to spawn runtime thread: {msg}")
237            }
238            SpawnError::Attestation(err) => write!(f, "attestation failed: {err}"),
239            SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
240        }
241    }
242}
243
244impl std::error::Error for SpawnError {}
245
246impl From<crate::vm::Fault> for SpawnError {
247    fn from(fault: crate::vm::Fault) -> Self {
248        match fault {
249            crate::vm::Fault::BadFunction { index, table_size } => {
250                SpawnError::BadFunction { index, table_size }
251            }
252            other => SpawnError::VmInit(other.to_string()),
253        }
254    }
255}