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