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