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    /// Link-id counter wrapped or exceeded `i64::MAX` (bytecode `Int` bound).
56    LinkIdExhausted,
57    /// Monitor-id counter wrapped or exceeded `i64::MAX` (bytecode `Int` bound).
58    MonitorIdExhausted,
59}
60
61impl fmt::Display for RuntimeError {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        match self {
64            RuntimeError::PoisonedLock(where_) => {
65                write!(f, "runtime mutex poisoned at {where_}")
66            }
67            RuntimeError::Abandoned(where_) => {
68                write!(
69                    f,
70                    "{where_}: flow was destroyed before producing an outcome"
71                )
72            }
73            RuntimeError::AlreadyCollected(where_) => {
74                write!(f, "{where_}: outcome was already collected")
75            }
76            RuntimeError::EntropyFailed => {
77                write!(f, "capability CSPRNG unavailable")
78            }
79            RuntimeError::CapIdCollision => {
80                write!(f, "could not allocate a unique capability id")
81            }
82            RuntimeError::CannotFinalizeHostFlow => {
83                write!(f, "cannot finalize reserved host flow")
84            }
85            RuntimeError::FlowIdExhausted => {
86                write!(f, "flow id space exhausted (counter wrapped)")
87            }
88            RuntimeError::DuplicateFlowId => {
89                write!(f, "directory already has this flow id")
90            }
91            RuntimeError::LinkIdExhausted => {
92                write!(f, "link id space exhausted (counter wrapped)")
93            }
94            RuntimeError::MonitorIdExhausted => {
95                write!(f, "monitor id space exhausted (counter wrapped)")
96            }
97        }
98    }
99}
100
101impl std::error::Error for RuntimeError {}
102
103/// User-facing lifecycle / naming errors (category A).
104///
105/// Distinct from [`RuntimeError`] (infrastructure / poison). Host
106/// `monitor` / `link` / `register_name` return this so a dead FlowId or
107/// a duplicate name is not reported as a poisoned mutex.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum LifecycleError {
110    NoSuchFlow(super::process::FlowId),
111    InvalidCapability,
112    InvalidMonitor,
113    InvalidLink,
114    NotOwner,
115    AlreadyRegistered,
116    AlreadyLinked,
117    EmptyName,
118    SelfRelation,
119    Unavailable,
120    /// Process-wide [`crate::RuntimeConfig::max_links`] reached.
121    LinkLimitReached {
122        limit: u32,
123    },
124    /// Process-wide [`crate::RuntimeConfig::max_monitors`] reached.
125    MonitorLimitReached {
126        limit: u32,
127    },
128    /// Process-wide [`crate::RuntimeConfig::max_registry_names`] reached.
129    RegistryLimitReached {
130        limit: u32,
131    },
132}
133
134impl fmt::Display for LifecycleError {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
138            Self::InvalidCapability => write!(f, "unknown or revoked capability"),
139            Self::InvalidMonitor => write!(f, "unknown monitor"),
140            Self::InvalidLink => write!(f, "unknown link"),
141            Self::NotOwner => write!(f, "caller does not own this relation"),
142            Self::AlreadyRegistered => write!(f, "registry name already taken"),
143            Self::AlreadyLinked => write!(f, "flows are already linked"),
144            Self::EmptyName => write!(f, "registry name must be non-empty"),
145            Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
146            Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
147            Self::LinkLimitReached { limit } => {
148                write!(f, "link limit reached ({limit})")
149            }
150            Self::MonitorLimitReached { limit } => {
151                write!(f, "monitor limit reached ({limit})")
152            }
153            Self::RegistryLimitReached { limit } => {
154                write!(f, "registry name limit reached ({limit})")
155            }
156        }
157    }
158}
159
160impl std::error::Error for LifecycleError {}
161
162/// Record an infrastructure fault (stderr + counter). Does not panic.
163#[cold]
164pub fn report_fault(err: RuntimeError) {
165    FAULTS.fetch_add(1, Ordering::Relaxed);
166    eprintln!("byteflow: {err} — fail-closed");
167}
168
169/// How many [`report_fault`] calls have been made (tests / diagnostics).
170pub fn fault_count() -> u64 {
171    FAULTS.load(Ordering::Relaxed)
172}
173
174/// User-facing spawn / load errors (category A in the taxonomy above).
175///
176/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
177/// OS thread creation. Panic is reserved for *bugs*; a bad function index
178/// or a refused `thread::spawn` is an embedder-visible failure and must
179/// surface as `Result` so the host can recover without taking workers down.
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum SpawnError {
182    /// `function` index is outside the runtime chunk's function table.
183    BadFunction {
184        index: u32,
185        table_size: u32,
186    },
187    /// Chunk failed verification before the runtime could start.
188    VerifyFailed(crate::bytecode::VerifyError),
189    /// Spawn arguments contained an unknown or unusable capability.
190    InvalidCapability,
191    /// Scheduler table poisoned (fail closed).
192    Unavailable,
193    /// Flow-id counter wrapped onto the reserved host id.
194    FlowIdExhausted,
195    /// Live flow count would exceed [`crate::RuntimeConfig::max_flows`].
196    FlowLimit {
197        current: usize,
198        max: u32,
199    },
200    /// Bytecode spawn failed the quota / SPAWN-right / attenuation check.
201    SpawnDenied(String),
202    SpawnRateExceeded,
203    ParentCapRevoked,
204    MissingSpawnRight,
205    /// [`crate::ChildSpec::name`] is already in the runtime registry.
206    NameTaken {
207        name: String,
208    },
209    /// OS refused to create a worker / timer / supervisor thread.
210    ThreadSpawnFailed(String),
211    /// Integrity fingerprint / attested decode failed.
212    Attestation(crate::AttestError),
213    /// `Vm::new` failed for a reason other than a bad function index
214    /// (mapped from [`crate::Fault`] via `From`).
215    VmInit(String),
216}
217
218impl fmt::Display for SpawnError {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        match self {
221            SpawnError::BadFunction { index, table_size } => {
222                write!(
223                    f,
224                    "spawn: function index {index} out of range (table size {table_size})"
225                )
226            }
227            SpawnError::VerifyFailed(err) => write!(f, "chunk verification failed: {err}"),
228            SpawnError::InvalidCapability => {
229                write!(f, "spawn: argument capability is unknown or not held")
230            }
231            SpawnError::Unavailable => write!(f, "spawn: runtime table unavailable"),
232            SpawnError::FlowIdExhausted => {
233                write!(f, "spawn: flow id space exhausted (counter wrapped)")
234            }
235            SpawnError::FlowLimit { current, max } => {
236                write!(f, "spawn: live flow limit reached ({current}/{max})")
237            }
238            SpawnError::SpawnDenied(msg) => write!(f, "spawn: {msg}"),
239            SpawnError::SpawnRateExceeded => write!(f, "spawn: spawn rate exceeded"),
240            SpawnError::ParentCapRevoked => write!(f, "spawn: parent capability revoked"),
241            SpawnError::MissingSpawnRight => write!(f, "spawn: parent lacks SPAWN right"),
242            SpawnError::NameTaken { name } => {
243                write!(f, "spawn: registry name {name:?} already taken")
244            }
245            SpawnError::ThreadSpawnFailed(msg) => {
246                write!(f, "failed to spawn runtime thread: {msg}")
247            }
248            SpawnError::Attestation(err) => write!(f, "attestation failed: {err}"),
249            SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
250        }
251    }
252}
253
254impl std::error::Error for SpawnError {}
255
256impl From<crate::vm::Fault> for SpawnError {
257    fn from(fault: crate::vm::Fault) -> Self {
258        match fault {
259            crate::vm::Fault::BadFunction { index, table_size } => {
260                SpawnError::BadFunction { index, table_size }
261            }
262            other => SpawnError::VmInit(other.to_string()),
263        }
264    }
265}