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}
46
47impl fmt::Display for RuntimeError {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 match self {
50 RuntimeError::PoisonedLock(where_) => {
51 write!(f, "runtime mutex poisoned at {where_}")
52 }
53 RuntimeError::Abandoned(where_) => {
54 write!(
55 f,
56 "{where_}: flow was destroyed before producing an outcome"
57 )
58 }
59 RuntimeError::AlreadyCollected(where_) => {
60 write!(f, "{where_}: outcome was already collected")
61 }
62 }
63 }
64}
65
66impl std::error::Error for RuntimeError {}
67
68/// User-facing lifecycle / naming errors (category A).
69///
70/// Distinct from [`RuntimeError`] (infrastructure / poison). Host
71/// `monitor` / `link` / `register_name` return this so a dead FlowId or
72/// a duplicate name is not reported as a poisoned mutex.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum LifecycleError {
75 NoSuchFlow(super::process::FlowId),
76 InvalidCapability,
77 InvalidMonitor,
78 InvalidLink,
79 NotOwner,
80 AlreadyRegistered,
81 AlreadyLinked,
82 EmptyName,
83 SelfRelation,
84 Unavailable,
85}
86
87impl fmt::Display for LifecycleError {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 match self {
90 Self::NoSuchFlow(id) => write!(f, "no live flow {id}"),
91 Self::InvalidCapability => write!(f, "unknown or revoked capability"),
92 Self::InvalidMonitor => write!(f, "unknown monitor"),
93 Self::InvalidLink => write!(f, "unknown link"),
94 Self::NotOwner => write!(f, "caller does not own this relation"),
95 Self::AlreadyRegistered => write!(f, "registry name already taken"),
96 Self::AlreadyLinked => write!(f, "flows are already linked"),
97 Self::EmptyName => write!(f, "registry name must be non-empty"),
98 Self::SelfRelation => write!(f, "cannot link or monitor a flow to itself"),
99 Self::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
100 }
101 }
102}
103
104impl std::error::Error for LifecycleError {}
105
106/// Record an infrastructure fault (stderr + counter). Does not panic.
107#[cold]
108pub fn report_fault(err: RuntimeError) {
109 FAULTS.fetch_add(1, Ordering::Relaxed);
110 eprintln!("byteflow: {err} — fail-closed");
111}
112
113/// How many [`report_fault`] calls have been made (tests / diagnostics).
114pub fn fault_count() -> u64 {
115 FAULTS.load(Ordering::Relaxed)
116}
117
118/// User-facing spawn / load errors (category A in the taxonomy above).
119///
120/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
121/// OS thread creation. Panic is reserved for *bugs*; a bad function index
122/// or a refused `thread::spawn` is an embedder-visible failure and must
123/// surface as `Result` so the host can recover without taking workers down.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum SpawnError {
126 /// `function` index is outside the runtime chunk's function table.
127 BadFunction { index: u32, table_size: u32 },
128 /// Chunk failed verification before the runtime could start.
129 VerifyFailed(String),
130 /// Live flow count would exceed [`crate::RuntimeConfig::max_flows`].
131 FlowLimit { current: usize, max: u32 },
132 /// [`crate::ChildSpec::name`] is already in the runtime registry.
133 NameTaken { name: String },
134 /// OS refused to create a worker / timer / supervisor thread.
135 ThreadSpawnFailed(String),
136 /// `Vm::new` failed for a reason other than a bad function index
137 /// (mapped from [`crate::Fault`] via `From`).
138 VmInit(String),
139}
140
141impl fmt::Display for SpawnError {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 match self {
144 SpawnError::BadFunction { index, table_size } => {
145 write!(
146 f,
147 "spawn: function index {index} out of range (table size {table_size})"
148 )
149 }
150 SpawnError::VerifyFailed(msg) => write!(f, "chunk verification failed: {msg}"),
151 SpawnError::FlowLimit { current, max } => {
152 write!(f, "spawn: live flow limit reached ({current}/{max})")
153 }
154 SpawnError::NameTaken { name } => {
155 write!(f, "spawn: registry name {name:?} already taken")
156 }
157 SpawnError::ThreadSpawnFailed(msg) => {
158 write!(f, "failed to spawn runtime thread: {msg}")
159 }
160 SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
161 }
162 }
163}
164
165impl std::error::Error for SpawnError {}
166
167impl From<crate::vm::Fault> for SpawnError {
168 fn from(fault: crate::vm::Fault) -> Self {
169 match fault {
170 crate::vm::Fault::BadFunction { index, table_size } => {
171 SpawnError::BadFunction { index, table_size }
172 }
173 other => SpawnError::VmInit(other.to_string()),
174 }
175 }
176}