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