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/// Record an infrastructure fault (stderr + counter). Does not panic.
69#[cold]
70pub fn report_fault(err: RuntimeError) {
71 FAULTS.fetch_add(1, Ordering::Relaxed);
72 eprintln!("byteflow: {err} — fail-closed");
73}
74
75/// How many [`report_fault`] calls have been made (tests / diagnostics).
76pub fn fault_count() -> u64 {
77 FAULTS.load(Ordering::Relaxed)
78}
79
80/// User-facing spawn / load errors (category A in the taxonomy above).
81///
82/// These used to be `.expect(...)` panics on `Runtime::new` / `spawn` /
83/// OS thread creation. Panic is reserved for *bugs*; a bad function index
84/// or a refused `thread::spawn` is an embedder-visible failure and must
85/// surface as `Result` so the host can recover without taking workers down.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum SpawnError {
88 /// `function` index is outside the runtime chunk's function table.
89 BadFunction { index: u32, table_size: u32 },
90 /// Chunk failed verification before the runtime could start.
91 VerifyFailed(String),
92 /// OS refused to create a worker / timer / supervisor thread.
93 ThreadSpawnFailed(String),
94 /// `Vm::new` failed for a reason other than a bad function index
95 /// (mapped from [`crate::Fault`] via `From`).
96 VmInit(String),
97}
98
99impl fmt::Display for SpawnError {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 match self {
102 SpawnError::BadFunction { index, table_size } => {
103 write!(
104 f,
105 "spawn: function index {index} out of range (table size {table_size})"
106 )
107 }
108 SpawnError::VerifyFailed(msg) => write!(f, "chunk verification failed: {msg}"),
109 SpawnError::ThreadSpawnFailed(msg) => {
110 write!(f, "failed to spawn runtime thread: {msg}")
111 }
112 SpawnError::VmInit(msg) => write!(f, "vm init failed: {msg}"),
113 }
114 }
115}
116
117impl std::error::Error for SpawnError {}
118
119impl From<crate::vm::Fault> for SpawnError {
120 fn from(fault: crate::vm::Fault) -> Self {
121 match fault {
122 crate::vm::Fault::BadFunction { index, table_size } => {
123 SpawnError::BadFunction { index, table_size }
124 }
125 other => SpawnError::VmInit(other.to_string()),
126 }
127 }
128}