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