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