Skip to main content

byteflow/scheduler/
runtime.rs

1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
2use std::sync::{Arc, Condvar, Mutex};
3use std::thread::JoinHandle;
4
5use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
6use crate::vm::{NativeGate, NativeTable, Vm};
7
8use super::directory::Directory;
9use super::error::SpawnError;
10use super::finalize::finalize_flow;
11use super::handle::FlowHandle;
12use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
13use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
14use super::monitor::FlowExitReason;
15use super::process::{Flow, FlowId, FlowOutcome};
16use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
17use super::supervisor::SupervisorLink;
18use super::timer::TimerWheel;
19use super::worker;
20use crate::bytecode::RestartPolicy;
21
22/// Default instruction budget per scheduling turn (design notes §10).
23/// Chosen as a middle ground: large enough that the per-yield bookkeeping
24/// cost is amortized over meaningful work, small enough that a
25/// pathological `loop {}` in one flow can't visibly stall the others —
26/// at 10k simple instructions/turn and even a conservative tens-of-millions
27/// of instructions/sec per core, worst-case added latency for a sibling
28/// flow is sub-millisecond.
29pub const DEFAULT_QUANTUM: u32 = 10_000;
30
31/// Tunables for [`Runtime::new`]. Everything has a sensible default via
32/// [`RuntimeConfig::default`] so the common case is `Runtime::new(chunk)`.
33#[derive(Clone, Debug)]
34pub struct RuntimeConfig {
35    /// Number of worker OS threads. Defaults to the number of logical CPUs
36    /// — one worker per core is the right starting point for a CPU-bound
37    /// M:N scheduler; embedders running alongside other CPU-heavy work on
38    /// the same machine may want fewer. `0` is raised to `1`: a runtime
39    /// with no worker cannot run a flow.
40    pub workers: usize,
41    /// Instructions a flow runs before being preempted back to the
42    /// scheduler even if it never hits `Yield`. `0` is raised to `1`.
43    /// A zero slice returns `Yield` without executing anything, and the
44    /// worker would requeue that flow forever.
45    pub quantum: u32,
46    /// Memory + overflow contract applied to **every** flow mailbox
47    /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
48    /// See [`MailboxConfig`] / `docs/mailbox.md`.
49    pub mailbox: MailboxConfig,
50    /// Hard cap on concurrently live flows (`0` = unlimited).
51    /// Checked on every host and bytecode `spawn`.
52    pub max_flows: u32,
53    /// Hard cap on outstanding `Ask` / `AskTimeout` waiters process-wide
54    /// (`0` = unlimited). Each asker holds at most one wait; this bounds the
55    /// total index size when many flows park against a silent target.
56    /// See [`crate::docs::security`] (DoS) and [`Self::sandbox`].
57    pub max_ask_waits: u32,
58    /// Hard cap on outstanding `HostAwait` parkers process-wide
59    /// (`0` = unlimited). Each flow holds at most one await.
60    pub max_host_awaits: u32,
61    /// Hard cap on live process-wide links (`0` = unlimited).
62    ///
63    /// Accounting is performed by the link store itself, under
64    /// the same synchronization that protects the link table.
65    pub max_links: u32,
66    /// Hard cap on live process-wide monitors (`0` = unlimited).
67    ///
68    /// Accounting is performed by the monitor store itself.
69    pub max_monitors: u32,
70    /// Hard cap on live process-wide registry names (`0` = unlimited).
71    ///
72    /// The registry store counts only successfully registered names.
73    pub max_registry_names: u32,
74    /// Host async bridge for [`crate::Opcode::HostAwait`]. `None` fails
75    /// any `HostAwait` closed. Not a `CallNative` / std-native slot.
76    pub host_await: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
77    /// Host queue for [`crate::Opcode::SendRemote`]. `None` fails that opcode.
78    /// Byteflow does not open sockets; the embedder drains the bridge.
79    pub distribution: Option<Arc<super::distribution::DistributionBridge>>,
80    /// Process-wide memory ceiling for heap charges (`Str` / `Bytes`
81    /// register stores and shared [`crate::HeapStr`] / [`crate::HeapBytes`]).
82    /// Independent of per-flow [`crate::QuotaConfig::mem_limit`] and mailbox
83    /// byte budgets. Default: 256 MiB.
84    pub max_runtime_bytes: usize,
85    /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
86    /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
87    pub trust: crate::bytecode::TrustLevel,
88    /// Where bytecode `print` (native index 0) writes when using
89    /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
90    pub output: Arc<dyn crate::OutputSink>,
91    /// Scheduler diagnostics (`ask`, `finalize`, …). `None` keeps the
92    /// `BYTEFLOW_LOG` stderr path and adds no collector. The sink is called
93    /// inline and must not block or panic.
94    pub log: Option<Arc<dyn crate::log::LogSink>>,
95    /// Per-flow CPU / memory / spawn-send rate budgets.
96    pub quota: super::quota::QuotaConfig,
97    /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
98    #[cfg(feature = "jit")]
99    pub jit: JitConfig,
100}
101
102/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
103#[cfg(feature = "jit")]
104#[derive(Clone, Debug)]
105pub struct JitConfig {
106    /// When true, workers attempt compiled traces before interpreting.
107    pub enabled: bool,
108    /// How many times a `(function, pc)` pair must run before compilation.
109    pub hot_threshold: u32,
110}
111
112#[cfg(feature = "jit")]
113impl Default for JitConfig {
114    fn default() -> Self {
115        JitConfig {
116            enabled: false,
117            hot_threshold: crate::jit::HOT_THRESHOLD,
118        }
119    }
120}
121
122/// Logical CPU count for [`RuntimeConfig::default`], via `std` only.
123fn default_worker_count() -> usize {
124    match std::thread::available_parallelism() {
125        Ok(n) => n.get().max(1),
126        Err(_) => 1,
127    }
128}
129
130impl Default for RuntimeConfig {
131    fn default() -> Self {
132        RuntimeConfig {
133            workers: default_worker_count(),
134            quantum: DEFAULT_QUANTUM,
135            mailbox: MailboxConfig::DEFAULT,
136            max_flows: 0,
137            max_ask_waits: 0,
138            max_host_awaits: 0,
139            max_links: 0,
140            max_monitors: 0,
141            max_registry_names: 0,
142            host_await: None,
143            distribution: None,
144            max_runtime_bytes: 256 * 1024 * 1024,
145            trust: crate::bytecode::TrustLevel::Untrusted,
146            output: Arc::new(crate::output::NullSink),
147            log: None,
148            quota: super::quota::QuotaConfig::default(),
149            #[cfg(feature = "jit")]
150            jit: JitConfig::default(),
151        }
152    }
153}
154
155impl RuntimeConfig {
156    /// Starting point for untrusted modules: tight per-flow quotas plus
157    /// process-wide caps on live flows, Ask waits, HostAwaits, links,
158    /// monitors, and registry names. Tune under real load before using as
159    /// a production default.
160    pub fn sandbox() -> Self {
161        RuntimeConfig {
162            quota: super::quota::QuotaConfig::sandbox(),
163            max_flows: 256,
164            max_ask_waits: 128,
165            max_host_awaits: 128,
166            max_links: 1024,
167            max_monitors: 1024,
168            max_registry_names: 256,
169            max_runtime_bytes: 64 * 1024 * 1024,
170            ..Default::default()
171        }
172    }
173}
174
175/// State shared by every worker thread and the timer thread. Everything in
176/// here is either internally synchronized (`Injector`, `Directory`,
177/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
178/// construction (`stealers`, `quantum`) — there is no top-level lock
179/// covering the whole runtime, by design: a global lock is exactly what an
180/// M:N scheduler exists to avoid.
181pub struct Shared {
182    pub(crate) injector: Injector<Box<Flow>>,
183    pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
184    /// FlowId → mailbox (delivery after Cap resolution).
185    pub(crate) directory: Directory,
186    /// CapId → { holder, target, rights, native_mask, epoch } (FlowCap).
187    pub(crate) caps: super::capability::CapTable,
188    pub(crate) timer: Arc<TimerWheel>,
189    pub(crate) notify: (Mutex<()>, Condvar),
190    pub(crate) metrics: RuntimeMetrics,
191    pub(crate) shutdown: AtomicBool,
192    pub(crate) quantum: u32,
193    pub(crate) mailbox: MailboxConfig,
194    /// Atomic live-flow budget (`max_flows == 0` → unlimited).
195    pub(crate) flow_limit: super::flow_limit::FlowLimit,
196    pub(crate) memory: Arc<crate::MemoryBudget>,
197    pub(crate) quota: super::quota::QuotaConfig,
198    pub(crate) quotas: super::quota::QuotaTable,
199    pub(crate) monitors: super::monitor::MonitorStore,
200    pub(crate) links: super::link::LinkStore,
201    pub(crate) registry: super::registry::RegistryStore,
202    pub(crate) kill_signals: super::finalize::KillSignals,
203    pub(crate) trap_exits: super::finalize::TrapExitFlags,
204    pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
205    pub(crate) ask_waits: super::finalize::AskWaitIndex,
206    /// In-flight `Opcode::HostAwait` tickets. The flow stays on a worker
207    /// or in its mailbox; completion arrives as a host hop.
208    pub(crate) host_awaits: super::host_await::HostAwaitIndex,
209    /// Host async bridge (`None` ⇒ HostAwait fails closed).
210    pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
211    /// Recorded order for host completions. `None` delivers immediately.
212    pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
213    /// Host `fail` text the worker reads before committing a success.
214    pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
215    /// `SendRemote` queue. `None` fails the opcode.
216    pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
217    /// Embedder copy of scheduler diagnostics. `None` leaves stderr gating
218    /// in [`crate::log`] unchanged.
219    pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
220    /// One named table per flow. Empty until `TableOpen`.
221    pub(crate) tables: super::table::FlowTables,
222    /// Supervisors started by bytecode `StartSupervisor`. Joined from
223    /// [`Runtime::shutdown`] after workers stop.
224    pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
225    /// Correlation ids for host `Runtime::send` when `request_id == 0`.
226    /// Starts at 1; `0` stays the unset sentinel.
227    pub(crate) host_next_request_id: AtomicU64,
228    /// Shared trace JIT state (`feature = "jit"`).
229    #[cfg(feature = "jit")]
230    pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
231}
232
233/// A running Byteflow runtime: worker pool + timer thread over one shared
234/// [`Chunk`].
235///
236/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
237/// FlowCap resolution, supervised restarts). Optional trace JIT when built
238/// with `feature = "jit"` and enabled in `RuntimeConfig`'s `jit` field.
239///
240/// Construct with [`Runtime::new`] (no natives) or
241/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
242/// [`crate::std_native_table`].
243pub struct Runtime {
244    shared: Arc<Shared>,
245    chunk: Arc<Chunk>,
246    natives: Arc<NativeTable>,
247    workers: Vec<JoinHandle<()>>,
248    timer_thread: Option<JoinHandle<()>>,
249    trust: crate::bytecode::TrustLevel,
250}
251
252impl Runtime {
253    /// Convenience constructor for chunks that never call out through
254    /// `Opcode::CallNative`. Equivalent to
255    /// `Runtime::with_natives(chunk, NativeTable::empty())`.
256    ///
257    /// Returns [`SpawnError`] instead of panicking: verify failures and OS
258    /// thread-spawn refusals are category-A errors (see
259    /// [`docs::error_model`](crate::docs::error_model)).
260    pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
261        Self::with_config(chunk, RuntimeConfig::default())
262    }
263
264    /// Construct a runtime whose flows can call into `natives` via
265    /// `Opcode::CallNative` — the host FFI boundary.
266    pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
267        Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
268    }
269
270    pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
271        Self::with_natives_and_config(chunk, NativeTable::empty(), config)
272    }
273
274    /// Decode a `.bf` buffer only if its integrity fingerprint matches
275    /// `expected_digest`, then verify and start the runtime.
276    ///
277    /// Digest mismatch / decode failure → [`SpawnError::Attestation`].
278    /// Semantic verify failure → [`SpawnError::VerifyFailed`].
279    pub fn with_attested(
280        bytes: &[u8],
281        expected_digest: [u8; 32],
282        natives: Arc<NativeTable>,
283        config: RuntimeConfig,
284    ) -> Result<Self, SpawnError> {
285        let chunk =
286            crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
287        Self::with_natives_and_config(chunk, natives, config)
288    }
289
290    /// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
291    /// using [`RuntimeConfig::output`] for the `print` native.
292    pub fn with_std_natives_and_config(
293        chunk: Chunk,
294        config: RuntimeConfig,
295    ) -> Result<Self, SpawnError> {
296        Self::with_natives_and_config(
297            chunk,
298            crate::std_native_table_with(Arc::clone(&config.output)),
299            config,
300        )
301    }
302
303    /// Verify `chunk`, spawn the worker pool + timer thread, and return a
304    /// live [`Runtime`].
305    ///
306    /// Failures here mean the runtime was **never** started (no orphan
307    /// threads): either the bytecode is invalid
308    /// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
309    /// ([`SpawnError::ThreadSpawnFailed`]). Partial spawn failure rolls
310    /// back: already-started workers/timer are shut down and joined before
311    /// the error is returned.
312    pub fn with_natives_and_config(
313        chunk: Chunk,
314        natives: Arc<NativeTable>,
315        config: RuntimeConfig,
316    ) -> Result<Self, SpawnError> {
317        crate::bytecode::verify_with(
318            &chunk,
319            crate::bytecode::VerifyConfig {
320                trust: config.trust,
321            },
322        )
323        .map_err(SpawnError::VerifyFailed)?;
324        let chunk = Arc::new(chunk);
325        let workers_n = config.workers.max(1);
326        let quantum = config.quantum.max(1);
327
328        let locals: Vec<LocalDeque<Box<Flow>>> =
329            (0..workers_n).map(|_| LocalDeque::new()).collect();
330        let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
331
332        #[cfg(feature = "jit")]
333        let jit = if config.jit.enabled {
334            Some(super::jit::new_runtime(
335                chunk.clone(),
336                config.jit.hot_threshold,
337            ))
338        } else {
339            None
340        };
341
342        let shared = Arc::new(Shared {
343            injector: Injector::new(),
344            stealers,
345            directory: Directory::new(),
346            caps: super::capability::CapTable::new(),
347            timer: TimerWheel::new(),
348            notify: (Mutex::new(()), Condvar::new()),
349            metrics: RuntimeMetrics::default(),
350            shutdown: AtomicBool::new(false),
351            quantum,
352            mailbox: config.mailbox,
353            flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
354            memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
355            quota: config.quota,
356            quotas: super::quota::QuotaTable::new(),
357            monitors: super::monitor::MonitorStore::new(config.max_monitors),
358            links: super::link::LinkStore::new(config.max_links),
359            registry: super::registry::RegistryStore::new(config.max_registry_names),
360            kill_signals: super::finalize::KillSignals::new(),
361            trap_exits: super::finalize::TrapExitFlags::new(),
362            waiting_send_at: super::finalize::WaitingSendIndex::new(),
363            ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
364            host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
365            host_await_bridge: config.host_await.clone(),
366            host_replay: Mutex::new(None),
367            host_await_failures: super::host_await::HostAwaitFailures::new(),
368            distribution: config.distribution.clone(),
369            log_sink: config.log.clone(),
370            tables: super::table::FlowTables::new(),
371            flow_supervisors: Mutex::new(Vec::new()),
372            host_next_request_id: AtomicU64::new(1),
373            #[cfg(feature = "jit")]
374            jit,
375        });
376
377        let mut workers = Vec::with_capacity(workers_n);
378        for local in locals {
379            let shared_w = shared.clone();
380            match std::thread::Builder::new()
381                .name("byteflow-worker".into())
382                .spawn(move || worker::run_worker(shared_w, local))
383            {
384                Ok(handle) => workers.push(handle),
385                Err(e) => {
386                    abort_startup(&shared, workers, None);
387                    return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
388                }
389            }
390        }
391
392        let shared_timer = shared.clone();
393        let timer_thread = match std::thread::Builder::new()
394            .name("byteflow-timer".into())
395            .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
396        {
397            Ok(handle) => handle,
398            Err(e) => {
399                abort_startup(&shared, workers, None);
400                return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
401            }
402        };
403
404        Ok(Runtime {
405            shared,
406            chunk,
407            natives,
408            workers,
409            timer_thread: Some(timer_thread),
410            trust: config.trust,
411        })
412    }
413
414    /// Spawn a top-level flow starting at `function` in this runtime's
415    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
416    ///
417    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
418    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
419        spawn_on(
420            &self.shared,
421            &self.chunk,
422            &self.natives,
423            function,
424            args,
425            RestartPolicy::Never,
426            None,
427            None,
428            None,
429        )
430    }
431
432    /// A cheap, `Send + Sync` handle that can spawn flows into this
433    /// runtime from any thread, independent of `Runtime`'s own lifetime
434    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
435    pub fn spawner(&self) -> RuntimeSpawner {
436        RuntimeSpawner {
437            shared: self.shared.clone(),
438            chunk: self.chunk.clone(),
439            natives: self.natives.clone(),
440        }
441    }
442
443    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
444    /// take supervised children (design notes §15).
445    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
446        super::supervisor::Supervisor::new(self.spawner())
447    }
448
449    /// Look up a function by name in the runtime's chunk — convenience for
450    /// callers that built their chunk with [`crate::Program`]
451    /// and don't want to thread raw indices through their own code.
452    pub fn function_index(&self, name: &str) -> Option<u32> {
453        self.chunk
454            .functions
455            .iter()
456            .position(|f| f.name == name)
457            .map(|i| i as u32)
458    }
459
460    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
461        self.shared.metrics.snapshot()
462    }
463
464    /// Approximate number of flows currently registered in the directory.
465    ///
466    /// Sharded sum without a global snapshot — fine for dashboards
467    /// ([`Self::metrics`]), **not** for admission control (see
468    /// the flow limit / `max_flows`).
469    pub fn live_flows(&self) -> usize {
470        self.shared.directory.len()
471    }
472
473    /// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
474    pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
475        self.shared.memory.snapshot()
476    }
477
478    pub fn worker_count(&self) -> usize {
479        self.workers.len()
480    }
481
482    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
483    /// embedder (not from bytecode).
484    ///
485    /// # Host trust boundary
486    ///
487    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
488    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
489    /// `Ask`. The hop still goes through the same authentication choke-point
490    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
491    /// is minted when unset, and payload Caps are reissued to the recipient.
492    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
493    /// Bare scalars are rejected ([`SendError::NotAHop`]).
494    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
495        let Some(msg) = message.as_message().cloned() else {
496            return Err(SendError::NotAHop {
497                got: message.type_name(),
498            });
499        };
500        let mailbox = match self.shared.directory.lookup(target) {
501            Ok(Some(m)) => m,
502            Ok(None) => return Err(SendError::NoSuchFlow(target)),
503            Err(e) => {
504                super::error::report_fault(e);
505                return Err(SendError::Unavailable);
506            }
507        };
508        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
509            Ok(m) => Value::Message(m),
510            Err(_) => return Err(SendError::Capability),
511        };
512        match mailbox.push(stamped.clone()) {
513            // Host `send` is fire-and-forget: DropNewest means the hop was
514            // intentionally discarded under policy, not an infrastructure
515            // error. Bytecode `Ask` treats DropNewest as hard failure in
516            // `worker::deliver` (must not park waiting for a reply).
517            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
518                Ok(())
519            }
520            Ok(Ok(Delivery::Handoff(flow))) => {
521                let _ = self.shared.ask_waits.remove_asker(flow.id);
522                match flow.last_receive_dest {
523                    Some(dest) => {
524                        let Some(flow) =
525                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
526                        else {
527                            return Err(SendError::Unavailable);
528                        };
529                        enqueue_flow(&self.shared, flow);
530                        wake_workers(&self.shared);
531                        Ok(())
532                    }
533                    None => {
534                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
535                            "Runtime::send handoff missing dest register",
536                        ));
537                        finalize_flow(
538                            &self.shared,
539                            *flow,
540                            FlowOutcome::Failed("handoff missing dest register".into()),
541                            FlowExitReason::Fault,
542                        );
543                        Err(SendError::Unavailable)
544                    }
545                }
546            }
547            Ok(Err(full)) => {
548                if full.reason() == MailboxFullReason::Closed {
549                    return Err(SendError::NoSuchFlow(target));
550                }
551                Err(SendError::MailboxFull {
552                    flow: target,
553                    reason: full.reason(),
554                })
555            }
556            Err(e) => {
557                super::error::report_fault(e);
558                Err(SendError::Unavailable)
559            }
560        }
561    }
562
563    /// Deliver a hop the host read off its own socket.
564    ///
565    /// The frame's sender is kept. This path does not restamp it as the local
566    /// host (`0`). A `Cap` or `Pid` in the frame is refused. The name must
567    /// already be registered on this node; the host still owns the socket.
568    pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
569        let hop = super::distribution::decode_frame(bytes)?;
570        let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
571            Ok(Some(cap)) => cap,
572            Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
573            Err(err) => {
574                super::error::report_fault(err);
575                return Err(super::distribution::RemoteFrameError::Unavailable);
576            }
577        };
578        let target = match self.shared.caps.lookup(cap) {
579            Ok(Some(entry)) => match entry.target() {
580                Some(id) => id,
581                None => return Err(super::distribution::RemoteFrameError::NoSuchName),
582            },
583            Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
584            Err(err) => {
585                super::error::report_fault(err);
586                return Err(super::distribution::RemoteFrameError::Unavailable);
587            }
588        };
589        let mailbox = match self.shared.directory.lookup(target) {
590            Ok(Some(mailbox)) => mailbox,
591            Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
592            Err(err) => {
593                super::error::report_fault(err);
594                return Err(super::distribution::RemoteFrameError::Unavailable);
595            }
596        };
597        let stamped = Value::Message(hop.message);
598        match mailbox.push(stamped.clone()) {
599            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
600                Ok(())
601            }
602            Ok(Ok(Delivery::Handoff(flow))) => {
603                let _ = self.shared.ask_waits.remove_asker(flow.id);
604                match flow.last_receive_dest {
605                    Some(dest) => {
606                        let Some(flow) =
607                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
608                        else {
609                            return Err(super::distribution::RemoteFrameError::Unavailable);
610                        };
611                        enqueue_flow(&self.shared, flow);
612                        wake_workers(&self.shared);
613                        Ok(())
614                    }
615                    None => {
616                        super::finalize::finalize_flow(
617                            &self.shared,
618                            *flow,
619                            FlowOutcome::Failed("handoff missing dest register".into()),
620                            FlowExitReason::Fault,
621                        );
622                        Err(super::distribution::RemoteFrameError::Unavailable)
623                    }
624                }
625            }
626            Ok(Err(full)) => Err(super::distribution::RemoteFrameError::Mailbox(
627                full.reason(),
628            )),
629            Err(err) => {
630                super::error::report_fault(err);
631                Err(super::distribution::RemoteFrameError::Unavailable)
632            }
633        }
634    }
635
636    fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
637        match self.shared.directory.lookup(id) {
638            Ok(Some(_)) => Ok(()),
639            Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
640            Err(e) => Err(self.unavailable(e)),
641        }
642    }
643
644    fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
645        super::error::report_fault(err);
646        super::error::LifecycleError::Unavailable
647    }
648
649    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
650    /// (host equivalent of `SelfPid`).
651    pub fn mint_cap(
652        &self,
653        flow: FlowId,
654    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
655        self.require_live(flow)?;
656        self.shared
657            .caps
658            .mint(flow, flow, super::capability::CapRights::ADDRESSING)
659            .map_err(|e| self.unavailable(e))
660    }
661
662    /// Mint a Cap held by `holder` targeting `target` (host introduction).
663    pub fn grant_cap(
664        &self,
665        holder: FlowId,
666        target: FlowId,
667    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
668        self.require_live(holder)?;
669        self.require_live(target)?;
670        self.shared
671            .caps
672            .mint(holder, target, super::capability::CapRights::ADDRESSING)
673            .map_err(|e| self.unavailable(e))
674    }
675
676    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
677    ///
678    /// Both flows must be live. `owner == target` is `LifecycleError::SelfRelation`.
679    pub fn monitor(
680        &self,
681        owner: FlowId,
682        target: FlowId,
683    ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
684        if owner == target {
685            return Err(super::error::LifecycleError::SelfRelation);
686        }
687        self.require_live(owner)?;
688        self.require_live(target)?;
689        let mon = self
690            .shared
691            .monitors
692            .create(owner, target)
693            .map_err(|e| self.unavailable(e))??;
694        // Target may have finalized between the live check and insert.
695        // Synthesize DOWN and drop the now-useless relation (owner still live).
696        if self.require_live(target).is_err() {
697            let _ = self.shared.monitors.remove_owned(owner, mon);
698            super::finalize::deliver_down(
699                &self.shared,
700                super::monitor::DownEvent {
701                    monitor: mon,
702                    owner,
703                    target,
704                    reason: super::monitor::FlowExitReason::Fault,
705                },
706            );
707        }
708        Ok(mon)
709    }
710
711    /// Drop `monitor` if `owner` still owns it.
712    pub fn demonitor(
713        &self,
714        owner: FlowId,
715        monitor: super::monitor::MonitorRef,
716    ) -> Result<(), super::error::LifecycleError> {
717        self.require_live(owner)?;
718        match self.shared.monitors.remove_owned(owner, monitor) {
719            Ok(inner) => inner,
720            Err(e) => Err(self.unavailable(e)),
721        }
722    }
723
724    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
725    /// kills the peer (`Normal` only drops the link). With
726    /// [`Self::set_trap_exit`] on a peer, that peer receives a
727    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
728    pub fn link(
729        &self,
730        a: FlowId,
731        b: FlowId,
732    ) -> Result<super::link::LinkId, super::error::LifecycleError> {
733        if a == b {
734            return Err(super::error::LifecycleError::SelfRelation);
735        }
736        self.require_live(a)?;
737        self.require_live(b)?;
738        match self.shared.links.link_if_live(a, b, |id| {
739            self.shared.directory.lookup(id).map(|m| m.is_some())
740        }) {
741            Ok(Ok(super::link::LinkOutcome::Linked(id))) => Ok(id),
742            Ok(Ok(super::link::LinkOutcome::Consumed { dead })) => {
743                Err(super::error::LifecycleError::NoSuchFlow(dead))
744            }
745            Ok(Err(error)) => Err(error),
746            Err(e) => Err(self.unavailable(e)),
747        }
748    }
749
750    /// BEAM-style `process_flag(trap_exit, …)`.
751    ///
752    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
753    /// (including `Normal`) instead of killing this flow.
754    pub fn set_trap_exit(
755        &self,
756        id: FlowId,
757        enabled: bool,
758    ) -> Result<(), super::error::LifecycleError> {
759        self.require_live(id)?;
760        self.shared
761            .trap_exits
762            .set(id, enabled)
763            .map_err(|e| self.unavailable(e))
764    }
765
766    /// Drop `link` if `owner` is one of the endpoints.
767    pub fn unlink(
768        &self,
769        owner: FlowId,
770        link: super::link::LinkId,
771    ) -> Result<(), super::error::LifecycleError> {
772        self.require_live(owner)?;
773        match self.shared.links.unlink_owned(owner, link) {
774            Ok(inner) => inner,
775            Err(e) => Err(self.unavailable(e)),
776        }
777    }
778
779    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
780    pub fn register_name(
781        &self,
782        name: &str,
783        cap: crate::bytecode::CapId,
784    ) -> Result<(), super::error::LifecycleError> {
785        let entry = match self.shared.caps.lookup(cap) {
786            Ok(Some(e)) => e,
787            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
788            Err(e) => return Err(self.unavailable(e)),
789        };
790        let target = match entry.target() {
791            Some(id) => id,
792            None => return Err(super::error::LifecycleError::InvalidCapability),
793        };
794        self.require_live(target)?;
795        match self
796            .shared
797            .registry
798            .register(super::registry::RegistryName::from(name), cap, target)
799        {
800            Ok(inner) => inner,
801            Err(e) => Err(self.unavailable(e)),
802        }
803    }
804
805    /// Look up a registered Cap, or `None` if the name is free / was swept.
806    pub fn whereis(
807        &self,
808        name: &str,
809    ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
810        self.shared
811            .registry
812            .whereis(name)
813            .map_err(|e| self.unavailable(e))
814    }
815
816    /// Cooperative abort. Parked flows finalize immediately; a running flow
817    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
818    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
819        self.require_live(id)?;
820        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
821        Ok(())
822    }
823
824    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
825    pub fn mint_admin_cap(
826        &self,
827        holder: FlowId,
828    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
829        self.require_live(holder)?;
830        let cap = crate::bytecode::Cap::root(
831            crate::bytecode::CapTarget::Scheduler,
832            CapRights::ADMIN,
833            None,
834            self.shared.caps.scheduler_cell().as_ref(),
835        );
836        self.shared
837            .caps
838            .grant(holder, cap)
839            .map_err(|e| self.unavailable(e))
840    }
841
842    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
843    pub fn admin_kill(
844        &self,
845        holder: FlowId,
846        cap: crate::bytecode::CapId,
847        target: FlowId,
848    ) -> Result<(), super::error::LifecycleError> {
849        self.require_admin(holder, cap)?;
850        self.kill(target)
851    }
852
853    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
854    pub fn admin_top_up_cpu(
855        &self,
856        holder: FlowId,
857        cap: crate::bytecode::CapId,
858        target: FlowId,
859        extra: i64,
860    ) -> Result<(), super::error::LifecycleError> {
861        self.require_admin(holder, cap)?;
862        let quota = match self.shared.quotas.get(target) {
863            Ok(Some(q)) => q,
864            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
865            Err(e) => return Err(self.unavailable(e)),
866        };
867        quota.top_up_cpu(extra);
868        Ok(())
869    }
870
871    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
872    pub fn admin_top_up_mem(
873        &self,
874        holder: FlowId,
875        cap: crate::bytecode::CapId,
876        target: FlowId,
877        extra: usize,
878    ) -> Result<(), super::error::LifecycleError> {
879        self.require_admin(holder, cap)?;
880        let quota = match self.shared.quotas.get(target) {
881            Ok(Some(q)) => q,
882            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
883            Err(e) => return Err(self.unavailable(e)),
884        };
885        quota.top_up_mem(extra);
886        Ok(())
887    }
888
889    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
890    pub fn admin_top_up_send(
891        &self,
892        holder: FlowId,
893        cap: crate::bytecode::CapId,
894        target: FlowId,
895        extra: i64,
896    ) -> Result<(), super::error::LifecycleError> {
897        self.require_admin(holder, cap)?;
898        let quota = match self.shared.quotas.get(target) {
899            Ok(Some(q)) => q,
900            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
901            Err(e) => return Err(self.unavailable(e)),
902        };
903        quota.top_up_send(extra);
904        Ok(())
905    }
906
907    fn require_admin(
908        &self,
909        holder: FlowId,
910        cap: crate::bytecode::CapId,
911    ) -> Result<(), super::error::LifecycleError> {
912        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
913            Ok(e) => e,
914            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
915        };
916        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
917            .map_err(|_| super::error::LifecycleError::InvalidCapability)
918    }
919
920    /// Remove a name without waiting for the flow to exit. `false` if unknown.
921    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
922        self.shared
923            .registry
924            .unregister(name)
925            .map_err(|e| self.unavailable(e))
926    }
927
928    /// Replace the image used by **new host** [`Self::spawn`] calls and
929    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
930    /// existing `Vm` chunk.
931    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
932        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
933            .map_err(SpawnError::VerifyFailed)?;
934        let chunk = Arc::new(chunk);
935        self.chunk = chunk.clone();
936        #[cfg(feature = "jit")]
937        if let Some(jit) = &self.shared.jit {
938            jit.reload(chunk);
939        }
940        Ok(())
941    }
942
943    /// Signal workers and the timer to stop. Does **not** join those threads.
944    /// [`Self::finish`] joins them and finalizes flows still parked.
945    fn request_shutdown(&self) {
946        self.shared.shutdown.store(true, Ordering::Release);
947        // Settle parked HostAwaits before joining workers: otherwise a bridge
948        // holding Completers could leave joiners blocked after OS threads exit.
949        finalize_host_awaits(&self.shared);
950        self.shared.timer.shutdown();
951        let (lock, cvar) = &self.shared.notify;
952        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
953            Ok(_g) => cvar.notify_all(),
954            Err(e) => super::error::report_fault(e),
955        }
956    }
957
958    /// Install the test-only host-completion replay gate.
959    ///
960    /// Production leaves the gate unset and delivers each completion at once.
961    /// Sequence numbers come from the test, not from arrival order.
962    #[cfg(test)]
963    pub(crate) fn enable_host_await_replay(&self) -> Result<(), super::error::RuntimeError> {
964        let mut gate = super::sync_lock::lock(
965            &self.shared.host_replay,
966            "Runtime::enable_host_await_replay",
967        )?;
968        *gate = Some(super::deterministic::HostReplayGate::default());
969        Ok(())
970    }
971
972    /// Bind a host-await ticket to a recorded sequence and deliver every
973    /// completion that is now the next event.
974    #[cfg(test)]
975    pub(crate) fn bind_host_await_replay(
976        &self,
977        ticket: u64,
978        sequence: u64,
979    ) -> Result<(), super::host_await::HostAwaitError> {
980        let ready = {
981            let mut gate =
982                super::sync_lock::lock(&self.shared.host_replay, "Runtime::bind_host_await_replay")
983                    .map_err(super::host_await::HostAwaitError::Runtime)?;
984            let Some(replay) = gate.as_mut() else {
985                return Err(super::host_await::HostAwaitError::Replay(
986                    "replay gate is not enabled",
987                ));
988            };
989            replay.bind(ticket, sequence).map_err(|err| {
990                super::host_await::HostAwaitError::Replay(super::deterministic::replay_label(err))
991            })?;
992            replay.drain_ready()
993        };
994        super::host_await::deliver_ready(&self.shared, ready)
995    }
996
997    /// Stop accepting new scheduling work, join every worker + the timer
998    /// thread, then finalize any flow still parked (mailbox, timer, injector,
999    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
1000    /// instead of [`super::error::RuntimeError::Abandoned`].
1001    ///
1002    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
1003    /// finalizes at the next loop check (cooperative preemption).
1004    ///
1005    /// [`Drop`] does the same work when it runs off a worker thread. On a
1006    /// worker thread it only signals: joining that thread from itself would
1007    /// deadlock the pool.
1008    pub fn shutdown(mut self) {
1009        self.finish();
1010    }
1011
1012    /// Join the threads started by [`Self::with_natives_and_config`] and
1013    /// finalize every flow they did not finish. Safe to call again after
1014    /// [`Self::shutdown`]: the handles are already taken and the second
1015    /// sweep finds an empty directory.
1016    fn finish(&mut self) {
1017        if !self.shared.shutdown.load(Ordering::Acquire) {
1018            self.request_shutdown();
1019        }
1020        for worker in self.workers.drain(..) {
1021            let _ = worker.join();
1022        }
1023        super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
1024        if let Some(timer) = self.timer_thread.take() {
1025            let _ = timer.join();
1026        }
1027        finalize_stranded(&self.shared);
1028    }
1029}
1030
1031fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
1032    finalize_flow(
1033        shared,
1034        flow,
1035        FlowOutcome::Failed("runtime shutdown".into()),
1036        FlowExitReason::Shutdown,
1037    );
1038}
1039
1040fn finalize_host_awaits(shared: &Shared) {
1041    match shared.host_awaits.cancel_all() {
1042        Ok(notices) => super::host_await::notify_cancelled(shared, notices),
1043        Err(e) => super::error::report_fault(e),
1044    }
1045}
1046
1047/// After workers and the timer have stopped, take every remaining flow
1048/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
1049///
1050/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
1051fn finalize_stranded(shared: &Shared) {
1052    finalize_host_awaits(shared);
1053    for flow in shared.timer.drain() {
1054        finalize_shutdown_flow(shared, flow);
1055    }
1056    for _ in 0..8 {
1057        let mut n = 0usize;
1058        for flow in shared.injector.drain() {
1059            finalize_shutdown_flow(shared, *flow);
1060            n += 1;
1061        }
1062        for stealer in &shared.stealers {
1063            for flow in stealer.drain() {
1064                finalize_shutdown_flow(shared, *flow);
1065                n += 1;
1066            }
1067        }
1068        for (_id, mailbox) in shared.directory.snapshot() {
1069            match mailbox.take_parked() {
1070                Ok(Some(flow)) => {
1071                    finalize_shutdown_flow(shared, *flow);
1072                    n += 1;
1073                }
1074                Ok(None) => {}
1075                Err(e) => super::error::report_fault(e),
1076            }
1077            match mailbox.close() {
1078                Ok(senders) => {
1079                    for sender in senders {
1080                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
1081                            super::error::report_fault(e);
1082                        }
1083                        finalize_shutdown_flow(shared, sender);
1084                        n += 1;
1085                    }
1086                }
1087                Err(e) => super::error::report_fault(e),
1088            }
1089        }
1090        if n == 0 {
1091            break;
1092        }
1093    }
1094}
1095
1096impl Drop for Runtime {
1097    fn drop(&mut self) {
1098        if super::worker::is_on_worker() {
1099            if !self.shared.shutdown.load(Ordering::Acquire) {
1100                self.request_shutdown();
1101            }
1102            super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
1103            return;
1104        }
1105        self.finish();
1106    }
1107}
1108
1109/// A convenience Pid constructor for embedders that stored a raw `u64`
1110/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
1111/// call APIs that take one.
1112pub fn flow_id_from_u64(raw: u64) -> FlowId {
1113    FlowId(raw)
1114}
1115
1116/// Why [`Runtime::send`] could not deliver a hop.
1117#[derive(Debug, Clone, PartialEq, Eq)]
1118pub enum SendError {
1119    NoSuchFlow(FlowId),
1120    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
1121    NotAHop {
1122        got: &'static str,
1123    },
1124    /// Target inbox is at one of its logical bounds
1125    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
1126    /// [`MailboxFullReason`].
1127    MailboxFull {
1128        flow: FlowId,
1129        reason: MailboxFullReason,
1130    },
1131    /// Host hop authentication failed (payload Cap reissue).
1132    Capability,
1133    /// Directory / mailbox mutex poisoned — not "no such flow".
1134    Unavailable,
1135}
1136
1137impl std::fmt::Display for SendError {
1138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1139        match self {
1140            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
1141            SendError::NotAHop { got } => {
1142                write!(f, "atomic hop requires Value::Message, got {got}")
1143            }
1144            SendError::MailboxFull { flow, reason } => {
1145                write!(f, "mailbox full for {flow} ({reason})")
1146            }
1147            SendError::Capability => {
1148                write!(f, "host send could not reissue a capability in the hop")
1149            }
1150            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
1151        }
1152    }
1153}
1154
1155impl std::error::Error for SendError {}
1156
1157/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
1158/// the child. Host spawn passes `None` and mints a trusted root instead.
1159pub(crate) struct BytecodeSpawn<'a> {
1160    pub authority: &'a Cap,
1161    pub cell: &'a crate::bytecode::RevocationCell,
1162    pub quota: &'a super::quota::FlowQuota,
1163    pub requested_rights: CapRights,
1164}
1165
1166/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
1167/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
1168/// mailbox + completion channel), register it in the directory, and push
1169/// it onto the global injector for any worker to pick up.
1170///
1171/// Returns [`SpawnError`] on bad function index / VM init / directory
1172/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
1173/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
1174/// Bytecode `Spawn` must pass exactly the callee's arity. Host spawn is not
1175/// checked here.
1176pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
1177    if argc != usize::from(arity) {
1178        Err(crate::vm::Fault::BadArity {
1179            passed: argc,
1180            expected: arity,
1181        })
1182    } else {
1183        Ok(())
1184    }
1185}
1186
1187#[allow(clippy::too_many_arguments)]
1188pub(crate) fn spawn_on(
1189    shared: &Arc<Shared>,
1190    chunk: &Arc<Chunk>,
1191    natives: &Arc<NativeTable>,
1192    function: u32,
1193    args: &[Value],
1194    restart_policy: RestartPolicy,
1195    supervisor: Option<SupervisorLink>,
1196    parent: Option<FlowId>,
1197    bytecode: Option<BytecodeSpawn<'_>>,
1198) -> Result<FlowHandle, SpawnError> {
1199    // Bytecode `Spawn` encodes argc. Host `Runtime::spawn` does not: a short
1200    // host argument list still fills the rest with `Unit`. Only the bytecode
1201    // path is rejected here, matching `VerifyError::CallArity` / `Fault::BadArity`.
1202    if bytecode.is_some() {
1203        match chunk.function(function) {
1204            Some(def) => {
1205                if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
1206                    return Err(fault.into());
1207                }
1208            }
1209            None => {
1210                return Err(SpawnError::BadFunction {
1211                    index: function,
1212                    table_size: chunk.functions.len() as u32,
1213                });
1214            }
1215        }
1216    }
1217    shared.flow_limit.try_reserve()?;
1218    let id = match super::process::try_next_flow_id() {
1219        Ok(id) => id,
1220        Err(super::error::RuntimeError::FlowIdExhausted) => {
1221            shared.flow_limit.release();
1222            return Err(SpawnError::FlowIdExhausted);
1223        }
1224        Err(_) => {
1225            shared.flow_limit.release();
1226            return Err(SpawnError::Unavailable);
1227        }
1228    };
1229    let cell = match shared.caps.bind_flow(id) {
1230        Ok(c) => c,
1231        Err(_) => {
1232            shared.flow_limit.release();
1233            return Err(SpawnError::Unavailable);
1234        }
1235    };
1236    let authority = match bytecode {
1237        None => Cap::root(
1238            CapTarget::Flow(id.as_u64()),
1239            CapRights::ROOT,
1240            Some(NativeMask::full(natives.len())),
1241            cell.as_ref(),
1242        ),
1243        Some(ctx) => match super::spawn::exec_spawn_authority(
1244            ctx.authority,
1245            ctx.cell,
1246            ctx.quota,
1247            id.as_u64(),
1248            ctx.requested_rights,
1249            None,
1250            cell.as_ref(),
1251        ) {
1252            Ok(cap) => cap,
1253            Err(e) => {
1254                shared.flow_limit.release();
1255                let _ = shared.caps.revoke_flow(id);
1256                return Err(SpawnError::from(e));
1257            }
1258        },
1259    };
1260    let args = match grant_caps_in_args(shared, parent, id, args) {
1261        Ok(a) => a,
1262        Err(e) => {
1263            shared.flow_limit.release();
1264            let _ = shared.caps.revoke_flow(id);
1265            return Err(e);
1266        }
1267    };
1268    let gate = NativeGate::from_authority(
1269        &authority,
1270        Arc::clone(&cell),
1271        shared.caps.native_cell(),
1272        natives.len(),
1273    );
1274    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1275    let mut vm = match Vm::with_native_gate(
1276        chunk.clone(),
1277        natives.clone(),
1278        gate,
1279        function,
1280        args.as_slice(),
1281    ) {
1282        Ok(vm) => vm,
1283        Err(e) => {
1284            shared.flow_limit.release();
1285            let _ = shared.caps.revoke_flow(id);
1286            return Err(e.into());
1287        }
1288    };
1289    vm.set_memory_budget(Arc::clone(&shared.memory));
1290    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
1291        shared.flow_limit.release();
1292        let _ = shared.caps.revoke_flow(id);
1293        return Err(e.into());
1294    }
1295    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1296    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1297        super::error::report_fault(e);
1298        shared.flow_limit.release();
1299        let _ = shared.caps.revoke_flow(id);
1300        return Err(SpawnError::Unavailable);
1301    }
1302    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
1303        super::error::report_fault(e);
1304        let _ = shared.directory.unregister(id);
1305        shared.flow_limit.release();
1306        let _ = shared.caps.revoke_flow(id);
1307        return Err(SpawnError::Unavailable);
1308    }
1309    let (tx, rx) = super::oneshot::channel();
1310    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1311    flow.authority = authority;
1312    flow.cell = cell;
1313    flow.quota = quota;
1314    flow.supervisor = supervisor;
1315    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1316    enqueue_flow(shared, flow);
1317    wake_workers(shared);
1318    Ok(FlowHandle { id, receiver: rx })
1319}
1320
1321fn grant_caps_in_args(
1322    shared: &Shared,
1323    parent: Option<FlowId>,
1324    child: FlowId,
1325    args: &[Value],
1326) -> Result<Vec<Value>, SpawnError> {
1327    let mut out = Vec::with_capacity(args.len());
1328    for arg in args {
1329        if !arg.within_nesting_limit() {
1330            return Err(SpawnError::InvalidCapability);
1331        }
1332        let granted = arg.map_caps(
1333            0,
1334            &SpawnError::InvalidCapability,
1335            &mut |id| {
1336                let next = match parent {
1337                    None => shared.caps.reissue_for(id, child),
1338                    Some(holder) => shared.caps.delegate(id, holder, child),
1339                };
1340                next.map_err(|_| SpawnError::InvalidCapability)
1341            },
1342            &mut |message| {
1343                if let Some(holder) = parent {
1344                    if message.sender == 0 {
1345                        message.sender = holder.as_u64();
1346                    }
1347                }
1348                if message.request_id == 0 {
1349                    message.request_id =
1350                        super::worker::mint_host_request_id(&shared.host_next_request_id)
1351                            .ok_or(SpawnError::RequestIdsExhausted)?;
1352                }
1353                if !message.reply_cap.is_none() {
1354                    message.reply_cap = match parent {
1355                        None => shared.caps.reissue_for(message.reply_cap, child),
1356                        Some(holder) => shared.caps.delegate(message.reply_cap, holder, child),
1357                    }
1358                    .map_err(|_| SpawnError::InvalidCapability)?;
1359                }
1360                Ok(())
1361            },
1362        )?;
1363        out.push(granted);
1364    }
1365    Ok(out)
1366}
1367
1368/// Park `flow` on the global injector.
1369///
1370/// A poisoned injector is cleared inside [`Injector::push`]. The flow stays
1371/// queued with whatever was already there.
1372pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
1373    shared.injector.push(flow);
1374}
1375
1376pub(crate) fn wake_workers(shared: &Shared) {
1377    let (lock, cvar) = &shared.notify;
1378    match super::sync_lock::lock(lock, "wake_workers") {
1379        Ok(_g) => cvar.notify_one(),
1380        Err(e) => super::error::report_fault(e),
1381    }
1382}
1383
1384/// Signal shutdown and join any threads already started during construction
1385/// failure — keeps the "no orphan threads" contract of
1386/// [`Runtime::with_natives_and_config`].
1387fn abort_startup(
1388    shared: &Arc<Shared>,
1389    workers: Vec<std::thread::JoinHandle<()>>,
1390    timer: Option<std::thread::JoinHandle<()>>,
1391) {
1392    shared.shutdown.store(true, Ordering::Release);
1393    shared.timer.shutdown();
1394    let (lock, cvar) = &shared.notify;
1395    match super::sync_lock::lock(lock, "abort_startup") {
1396        Ok(_g) => cvar.notify_all(),
1397        Err(e) => super::error::report_fault(e),
1398    }
1399    for w in workers {
1400        let _ = w.join();
1401    }
1402    if let Some(t) = timer {
1403        let _ = t.join();
1404    }
1405}
1406
1407/// A `Send + Sync`, freely cloneable capability to spawn flows into a
1408/// [`Runtime`], detached from the `Runtime` value itself. Exists because
1409/// [`super::supervisor::Supervisor`] needs to respawn flows from a
1410/// background monitor thread whose lifetime isn't tied to the `Runtime`
1411/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
1412#[derive(Clone)]
1413pub struct RuntimeSpawner {
1414    pub(crate) shared: Arc<Shared>,
1415    pub(crate) chunk: Arc<Chunk>,
1416    pub(crate) natives: Arc<NativeTable>,
1417}
1418
1419impl RuntimeSpawner {
1420    pub fn spawn(
1421        &self,
1422        function: u32,
1423        args: &[Value],
1424        restart_policy: RestartPolicy,
1425    ) -> Result<FlowHandle, SpawnError> {
1426        spawn_on(
1427            &self.shared,
1428            &self.chunk,
1429            &self.natives,
1430            function,
1431            args,
1432            restart_policy,
1433            None,
1434            None,
1435            None,
1436        )
1437    }
1438
1439    pub(crate) fn spawn_linked(
1440        &self,
1441        function: u32,
1442        args: &[Value],
1443        restart_policy: RestartPolicy,
1444        supervisor: SupervisorLink,
1445    ) -> Result<FlowHandle, SpawnError> {
1446        spawn_on(
1447            &self.shared,
1448            &self.chunk,
1449            &self.natives,
1450            function,
1451            args,
1452            restart_policy,
1453            Some(supervisor),
1454            None,
1455            None,
1456        )
1457    }
1458
1459    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1460        self.shared.metrics.snapshot()
1461    }
1462
1463    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1464        super::finalize::request_kill(&self.shared, id, reason);
1465    }
1466}
1467
1468#[cfg(test)]
1469mod tests {
1470    use super::*;
1471    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1472    use crate::scheduler::FlowOutcome;
1473    use std::time::Duration;
1474
1475    #[test]
1476    fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
1477        assert!(super::bytecode_spawn_arity(2, 2).is_ok());
1478        assert!(matches!(
1479            super::bytecode_spawn_arity(2, 1),
1480            Err(crate::vm::Fault::BadArity {
1481                passed: 1,
1482                expected: 2,
1483            })
1484        ));
1485    }
1486
1487    fn add_chunk() -> Chunk {
1488        let mut b = ChunkBuilder::new("test");
1489        b.begin_function("main", 0, 2);
1490        b.emit_load_imm(0, 41);
1491        b.emit_load_imm(1, 1);
1492        b.emit_binop(Opcode::Add, 0, 0, 1);
1493        b.emit_return(0);
1494        b.finish()
1495    }
1496
1497    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
1498    /// makes "still running" an observable state from the host thread.
1499    fn sleep_then_return_chunk(millis: i32) -> Chunk {
1500        let mut b = ChunkBuilder::new("test");
1501        b.begin_function("main", 0, 2);
1502        b.emit_load_imm(0, millis);
1503        b.emit_sleep(0);
1504        b.emit_load_imm(0, 7);
1505        b.emit_return(0);
1506        b.finish()
1507    }
1508
1509    /// The host thread must be able to ask "done yet?" and to wait under a
1510    /// bound *it* chooses, instead of surrendering itself to `join` for
1511    /// however long the bytecode decides to take.
1512    #[test]
1513    fn polling_and_bounded_waits_never_commit_the_host_thread(
1514    ) -> Result<(), Box<dyn std::error::Error>> {
1515        const FLOW_SLEEP: i32 = 150;
1516        let rt = Runtime::with_config(
1517            sleep_then_return_chunk(FLOW_SLEEP),
1518            RuntimeConfig {
1519                workers: 1,
1520                quantum: 1_000,
1521                mailbox: MailboxConfig::DEFAULT,
1522                ..Default::default()
1523            },
1524        )?;
1525        let handle = rt.spawn(0, &[])?;
1526
1527        // The flow cannot possibly be finished yet: it has to be picked up
1528        // and then sleep. A poll must say so without waiting.
1529        if let Some(outcome) = handle.try_join() {
1530            rt.shutdown();
1531            return Err(format!("try_join answered too early: {outcome:?}").into());
1532        }
1533
1534        // A bound well below the flow's sleep must expire and hand control
1535        // back, not block until the flow happens to finish.
1536        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1537            rt.shutdown();
1538            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1539        }
1540
1541        // A generous bound collects the real outcome through the same
1542        // (non-consuming) handle.
1543        let outcome = handle.join_timeout(Duration::from_secs(10));
1544        rt.shutdown();
1545        match outcome {
1546            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1547            other => Err(format!("unexpected outcome: {other:?}").into()),
1548        }
1549    }
1550
1551    #[test]
1552    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1553        let rt = Runtime::with_config(
1554            add_chunk(),
1555            RuntimeConfig {
1556                workers: 1,
1557                quantum: 1_000,
1558                mailbox: MailboxConfig::DEFAULT,
1559                ..Default::default()
1560            },
1561        )?;
1562        let outcome = rt.spawn(0, &[])?.join();
1563        rt.shutdown();
1564        match outcome {
1565            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1566            other => Err(format!("unexpected outcome: {other:?}").into()),
1567        }
1568    }
1569
1570    fn receive_forever_chunk() -> Chunk {
1571        let mut b = ChunkBuilder::new("recv");
1572        b.begin_function("main", 0, 1);
1573        b.emit_receive(0);
1574        b.emit_return(0);
1575        b.finish()
1576    }
1577
1578    #[test]
1579    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1580        let rt = Runtime::with_config(
1581            receive_forever_chunk(),
1582            RuntimeConfig {
1583                workers: 1,
1584                quantum: 1_000,
1585                mailbox: MailboxConfig::DEFAULT,
1586                ..Default::default()
1587            },
1588        )?;
1589        let handle = rt.spawn(0, &[])?;
1590        rt.kill(handle.id())?;
1591        let outcome = handle.join();
1592        rt.shutdown();
1593        assert!(
1594            matches!(outcome, FlowOutcome::Failed(_)),
1595            "kill must fail the joiner, got {outcome:?}"
1596        );
1597        Ok(())
1598    }
1599
1600    #[test]
1601    fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
1602        let rt = Runtime::with_config(
1603            receive_forever_chunk(),
1604            RuntimeConfig {
1605                workers: 1,
1606                quantum: 1_000,
1607                mailbox: MailboxConfig::DEFAULT,
1608                ..Default::default()
1609            },
1610        )?;
1611        let handle = rt.spawn(0, &[])?;
1612        std::thread::sleep(Duration::from_millis(30));
1613        rt.shutdown();
1614        match handle.join() {
1615            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1616            other => Err(format!("expected shutdown finalize, got {other:?}").into()),
1617        }
1618    }
1619
1620    #[test]
1621    fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1622        let rt = Runtime::with_config(
1623            sleep_then_return_chunk(60_000),
1624            RuntimeConfig {
1625                workers: 1,
1626                quantum: 1_000,
1627                mailbox: MailboxConfig::DEFAULT,
1628                ..Default::default()
1629            },
1630        )?;
1631        let handle = rt.spawn(0, &[])?;
1632        std::thread::sleep(Duration::from_millis(30));
1633        rt.shutdown();
1634        match handle.join() {
1635            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1636            other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
1637        }
1638    }
1639
1640    #[test]
1641    fn drop_finalizes_a_parked_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1642        let rt = Runtime::with_config(
1643            sleep_then_return_chunk(60_000),
1644            RuntimeConfig {
1645                workers: 1,
1646                quantum: 1_000,
1647                mailbox: MailboxConfig::DEFAULT,
1648                ..Default::default()
1649            },
1650        )?;
1651        let handle = rt.spawn(0, &[])?;
1652        std::thread::sleep(Duration::from_millis(30));
1653        drop(rt);
1654        match handle.join() {
1655            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1656            other => Err(format!("expected drop to finalize the sleeper, got {other:?}").into()),
1657        }
1658    }
1659
1660    #[test]
1661    fn zero_quantum_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
1662        let rt = Runtime::with_config(
1663            add_chunk(),
1664            RuntimeConfig {
1665                workers: 1,
1666                quantum: 0,
1667                mailbox: MailboxConfig::DEFAULT,
1668                ..Default::default()
1669            },
1670        )?;
1671        let outcome = rt.spawn(0, &[])?.join();
1672        rt.shutdown();
1673        assert!(
1674            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
1675            "got {outcome:?}"
1676        );
1677        Ok(())
1678    }
1679
1680    #[test]
1681    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1682        let rt = Runtime::with_config(
1683            receive_forever_chunk(),
1684            RuntimeConfig {
1685                workers: 1,
1686                quantum: 1_000,
1687                mailbox: MailboxConfig::DEFAULT,
1688                max_flows: 1,
1689                ..Default::default()
1690            },
1691        )?;
1692        let first = rt.spawn(0, &[])?;
1693        let second = rt.spawn(0, &[]);
1694        rt.kill(first.id())?;
1695        let _ = first.join();
1696        // After finalize, the reserved slot must be free again.
1697        let third = rt.spawn(0, &[])?;
1698        rt.kill(third.id())?;
1699        let _ = third.join();
1700        rt.shutdown();
1701        match second {
1702            Err(SpawnError::FlowLimit { current, max }) => {
1703                assert_eq!(current, 1);
1704                assert_eq!(max, 1);
1705                Ok(())
1706            }
1707            other => Err(format!(
1708                "expected FlowLimit, got {}",
1709                match &other {
1710                    Ok(_) => "Ok(handle)".into(),
1711                    Err(e) => format!("Err({e})"),
1712                }
1713            )
1714            .into()),
1715        }
1716    }
1717
1718    /// Ask must not park waiting for a reply when DropNewest discarded the request.
1719    #[test]
1720    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1721        use crate::bytecode::{Message, Program};
1722        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1723
1724        let mut program = Program::new("ask-drop-newest");
1725        let busy = program.function("busy", 0, |f| {
1726            // Stay alive without spinning the worker: sleep loop.
1727            let loop_lbl = f.label();
1728            f.bind(loop_lbl);
1729            let ms = f.load_i32(50);
1730            f.sleep(ms);
1731            f.jump(loop_lbl);
1732        });
1733        let asker = program.function("asker", 1, |f| {
1734            let server = f.reg(0);
1735            let z = f.load_i32(0);
1736            let req = f.hop_fresh(1, z);
1737            let reply = f.ask(server, req);
1738            f.return_(reply);
1739        });
1740        let chunk = program.build();
1741
1742        let cap = MailboxCapacity::new(1).ok_or("cap")?;
1743        let rt = Runtime::with_natives_and_config(
1744            chunk,
1745            crate::std_native_table(),
1746            RuntimeConfig {
1747                // Busy target must not monopolize scheduling or Ask never runs.
1748                workers: 2,
1749                quantum: 1_000,
1750                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1751                ..Default::default()
1752            },
1753        )?;
1754
1755        let server = rt.spawn(busy, &[])?;
1756        // Fill the only slot so the subsequent Ask is DropNewest'd.
1757        rt.send(
1758            server.id(),
1759            Value::Message(Message::request(1, 9, Value::Int(1))),
1760        )?;
1761        let server_cap = rt.mint_cap(server.id())?;
1762        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1763        let outcome = ask.join_timeout(Duration::from_secs(3));
1764        rt.kill(server.id())?;
1765        let _ = server.join_timeout(Duration::from_millis(500));
1766        rt.shutdown();
1767
1768        match outcome {
1769            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1770            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1771        }
1772    }
1773
1774    #[test]
1775    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1776        use crate::bytecode::Program;
1777
1778        let mut program = Program::new("ask-limit");
1779        let silent = program.function("silent", 0, |f| {
1780            // Accept the request hop but never reply.
1781            let _req = f.receive();
1782            let loop_lbl = f.label();
1783            f.bind(loop_lbl);
1784            let ms = f.load_i32(50);
1785            f.sleep(ms);
1786            f.jump(loop_lbl);
1787        });
1788        let asker = program.function("asker", 1, |f| {
1789            let server = f.reg(0);
1790            let z = f.load_i32(0);
1791            let req = f.hop_fresh(1, z);
1792            let reply = f.ask(server, req);
1793            f.return_(reply);
1794        });
1795        let chunk = program.build();
1796
1797        let rt = Runtime::with_natives_and_config(
1798            chunk,
1799            crate::std_native_table(),
1800            RuntimeConfig {
1801                workers: 2,
1802                quantum: 1_000,
1803                mailbox: MailboxConfig::DEFAULT,
1804                max_ask_waits: 1,
1805                ..Default::default()
1806            },
1807        )?;
1808
1809        let server = rt.spawn(silent, &[])?;
1810        let server_cap = rt.mint_cap(server.id())?;
1811        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1812        // Give the first Ask time to park before the second tries.
1813        std::thread::sleep(Duration::from_millis(30));
1814        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1815        let second_out = second.join_timeout(Duration::from_secs(2));
1816        rt.kill(server.id())?;
1817        let _ = first.join_timeout(Duration::from_millis(500));
1818        let _ = server.join_timeout(Duration::from_millis(500));
1819        rt.shutdown();
1820
1821        match second_out {
1822            Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1823            other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1824        }
1825    }
1826
1827    // HostAwait E2E coverage lives in `host_await::runtime_tests`.
1828
1829    #[cfg(feature = "jit")]
1830    #[test]
1831    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1832        use crate::JitConfig;
1833
1834        let rt = Runtime::with_config(
1835            add_chunk(),
1836            RuntimeConfig {
1837                workers: 1,
1838                quantum: 1_000,
1839                mailbox: MailboxConfig::DEFAULT,
1840                jit: JitConfig {
1841                    enabled: true,
1842                    hot_threshold: 1,
1843                },
1844                ..Default::default()
1845            },
1846        )?;
1847        let outcome = rt.spawn(0, &[])?.join();
1848        rt.shutdown();
1849        match outcome {
1850            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1851            other => Err(format!("unexpected outcome: {other:?}").into()),
1852        }
1853    }
1854
1855    #[test]
1856    fn sandbox_enables_process_wide_relation_caps() {
1857        let config = RuntimeConfig::sandbox();
1858        assert_eq!(config.max_flows, 256);
1859        assert_eq!(config.max_ask_waits, 128);
1860        assert_eq!(config.max_host_awaits, 128);
1861        assert_eq!(config.max_links, 1024);
1862        assert_eq!(config.max_monitors, 1024);
1863        assert_eq!(config.max_registry_names, 256);
1864        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1865    }
1866
1867    #[test]
1868    fn default_remains_unlimited_for_relation_caps() {
1869        let config = RuntimeConfig::default();
1870        assert_eq!(config.max_links, 0);
1871        assert_eq!(config.max_monitors, 0);
1872        assert_eq!(config.max_registry_names, 0);
1873    }
1874
1875    #[test]
1876    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1877        use crate::bytecode::encode;
1878        use crate::{fingerprint_bf, AttestError};
1879
1880        let bytes = encode(&add_chunk());
1881        let mut bad = fingerprint_bf(&bytes);
1882        bad[0] ^= 0xff;
1883        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1884            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1885            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1886            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1887        }
1888    }
1889
1890    #[test]
1891    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1892        use crate::bytecode::encode;
1893        use crate::fingerprint_bf;
1894
1895        let chunk = add_chunk();
1896        let bytes = encode(&chunk);
1897        let digest = fingerprint_bf(&bytes);
1898        let rt = Runtime::with_attested(
1899            &bytes,
1900            digest,
1901            NativeTable::empty(),
1902            RuntimeConfig {
1903                workers: 1,
1904                quantum: 1_000,
1905                mailbox: MailboxConfig::DEFAULT,
1906                ..Default::default()
1907            },
1908        )?;
1909        let outcome = rt.spawn(0, &[])?.join();
1910        rt.shutdown();
1911        match outcome {
1912            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1913            other => Err(format!("expected 42, got {other:?}").into()),
1914        }
1915    }
1916
1917    #[test]
1918    fn poisoned_injector_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
1919        let rt = Runtime::new(add_chunk())?;
1920        rt.shared.injector.poison_for_test();
1921        let outcome = rt.spawn(0, &[])?.join_timeout(Duration::from_secs(2));
1922        rt.shutdown();
1923        match outcome {
1924            Some(FlowOutcome::Completed(Value::Int(42))) => Ok(()),
1925            other => Err(format!("expected 42 after a poisoned injector, got {other:?}").into()),
1926        }
1927    }
1928}