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 = crate::decode_attested(bytes, &expected_digest)
268            .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_fifo()).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 = config.paranoid_jumps
324            || matches!(
325                config.trust,
326                crate::bytecode::TrustLevel::Untrusted
327            );
328
329        let shared = Arc::new(Shared {
330            injector: Injector::new(),
331            stealers,
332            directory: Directory::new(),
333            caps: super::capability::CapTable::new(),
334            timer: TimerWheel::new(),
335            notify: (Mutex::new(()), Condvar::new()),
336            metrics: RuntimeMetrics::default(),
337            shutdown: AtomicBool::new(false),
338            quantum: config.quantum,
339            mailbox: config.mailbox,
340            flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
341            memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
342            quota: config.quota,
343            quotas: super::quota::QuotaTable::new(),
344            monitors: super::monitor::MonitorStore::new(config.max_monitors),
345            links: super::link::LinkStore::new(config.max_links),
346            registry: super::registry::RegistryStore::new(config.max_registry_names),
347            kill_signals: super::finalize::KillSignals::new(),
348            trap_exits: super::finalize::TrapExitFlags::new(),
349            waiting_send_at: super::finalize::WaitingSendIndex::new(),
350            ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
351            host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
352            host_await_bridge: config.host_await.clone(),
353            host_next_request_id: AtomicU64::new(1),
354            paranoid_jumps,
355            #[cfg(feature = "jit")]
356            jit,
357        });
358
359        let mut workers = Vec::with_capacity(workers_n);
360        for local in locals {
361            let shared_w = shared.clone();
362            match std::thread::Builder::new()
363                .name("byteflow-worker".into())
364                .spawn(move || worker::run_worker(shared_w, local))
365            {
366                Ok(handle) => workers.push(handle),
367                Err(e) => {
368                    abort_startup(&shared, workers, None);
369                    return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
370                }
371            }
372        }
373
374        let shared_timer = shared.clone();
375        let timer_thread = match std::thread::Builder::new()
376            .name("byteflow-timer".into())
377            .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
378        {
379            Ok(handle) => handle,
380            Err(e) => {
381                abort_startup(&shared, workers, None);
382                return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
383            }
384        };
385
386        Ok(Runtime {
387            shared,
388            chunk,
389            natives,
390            workers,
391            timer_thread: Some(timer_thread),
392            trust: config.trust,
393        })
394    }
395
396    /// Spawn a top-level flow starting at `function` in this runtime's
397    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
398    ///
399    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
400    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
401        spawn_on(
402            &self.shared,
403            &self.chunk,
404            &self.natives,
405            function,
406            args,
407            RestartPolicy::Never,
408            None,
409            None,
410            None,
411        )
412    }
413
414    /// A cheap, `Send + Sync` handle that can spawn flows into this
415    /// runtime from any thread, independent of `Runtime`'s own lifetime
416    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
417    pub fn spawner(&self) -> RuntimeSpawner {
418        RuntimeSpawner {
419            shared: self.shared.clone(),
420            chunk: self.chunk.clone(),
421            natives: self.natives.clone(),
422        }
423    }
424
425    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
426    /// take supervised children (design notes §15).
427    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
428        super::supervisor::Supervisor::new(self.spawner())
429    }
430
431    /// Look up a function by name in the runtime's chunk — convenience for
432    /// callers that built their chunk with [`crate::Program`]
433    /// and don't want to thread raw indices through their own code.
434    pub fn function_index(&self, name: &str) -> Option<u32> {
435        self.chunk
436            .functions
437            .iter()
438            .position(|f| f.name == name)
439            .map(|i| i as u32)
440    }
441
442    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
443        self.shared.metrics.snapshot()
444    }
445
446    /// Approximate number of flows currently registered in the directory.
447    ///
448    /// Sharded sum without a global snapshot — fine for dashboards
449    /// ([`Self::metrics`]), **not** for admission control (see
450    /// [`super::flow_limit::FlowLimit`] / `max_flows`).
451    pub fn live_flows(&self) -> usize {
452        self.shared.directory.len()
453    }
454
455    /// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
456    pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
457        self.shared.memory.snapshot()
458    }
459
460    pub fn worker_count(&self) -> usize {
461        self.workers.len()
462    }
463
464    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
465    /// embedder (not from bytecode).
466    ///
467    /// # Host trust boundary
468    ///
469    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
470    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
471    /// `Ask`. The hop still goes through the same authentication choke-point
472    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
473    /// is minted when unset, and payload Caps are reissued to the recipient.
474    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
475    /// Bare scalars are rejected ([`SendError::NotAHop`]).
476    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
477        let Some(msg) = message.as_message().cloned() else {
478            return Err(SendError::NotAHop {
479                got: message.type_name(),
480            });
481        };
482        let mailbox = match self.shared.directory.lookup(target) {
483            Ok(Some(m)) => m,
484            Ok(None) => return Err(SendError::NoSuchFlow(target)),
485            Err(e) => {
486                super::error::report_fault(e);
487                return Err(SendError::Unavailable);
488            }
489        };
490        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
491            Ok(m) => Value::Message(m),
492            Err(_) => return Err(SendError::Capability),
493        };
494        match mailbox.push(stamped.clone()) {
495            // Host `send` is fire-and-forget: DropNewest means the hop was
496            // intentionally discarded under policy, not an infrastructure
497            // error. Bytecode `Ask` treats DropNewest as hard failure in
498            // `worker::deliver` (must not park waiting for a reply).
499            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
500                Ok(())
501            }
502            Ok(Ok(Delivery::Handoff(flow))) => {
503                let _ = self.shared.ask_waits.remove_asker(flow.id);
504                match flow.last_receive_dest {
505                    Some(dest) => {
506                        let Some(flow) =
507                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
508                        else {
509                            return Err(SendError::Unavailable);
510                        };
511                        self.shared.injector.push(flow);
512                        wake_workers(&self.shared);
513                        Ok(())
514                    }
515                    None => {
516                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
517                            "Runtime::send handoff missing dest register",
518                        ));
519                        finalize_flow(
520                            &self.shared,
521                            *flow,
522                            FlowOutcome::Failed("handoff missing dest register".into()),
523                            FlowExitReason::Fault,
524                        );
525                        Err(SendError::Unavailable)
526                    }
527                }
528            }
529            Ok(Err(full)) => {
530                if full.reason() == MailboxFullReason::Closed {
531                    return Err(SendError::NoSuchFlow(target));
532                }
533                Err(SendError::MailboxFull {
534                    flow: target,
535                    reason: full.reason(),
536                })
537            }
538            Err(e) => {
539                super::error::report_fault(e);
540                Err(SendError::Unavailable)
541            }
542        }
543    }
544
545    fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
546        match self.shared.directory.lookup(id) {
547            Ok(Some(_)) => Ok(()),
548            Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
549            Err(e) => Err(self.unavailable(e)),
550        }
551    }
552
553    fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
554        super::error::report_fault(err);
555        super::error::LifecycleError::Unavailable
556    }
557
558    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
559    /// (host equivalent of `SelfPid`).
560    pub fn mint_cap(
561        &self,
562        flow: FlowId,
563    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
564        self.require_live(flow)?;
565        self.shared
566            .caps
567            .mint(flow, flow, super::capability::CapRights::ADDRESSING)
568            .map_err(|e| self.unavailable(e))
569    }
570
571    /// Mint a Cap held by `holder` targeting `target` (host introduction).
572    pub fn grant_cap(
573        &self,
574        holder: FlowId,
575        target: FlowId,
576    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
577        self.require_live(holder)?;
578        self.require_live(target)?;
579        self.shared
580            .caps
581            .mint(holder, target, super::capability::CapRights::ADDRESSING)
582            .map_err(|e| self.unavailable(e))
583    }
584
585    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
586    ///
587    /// Both flows must be live. `owner == target` is [`LifecycleError::SelfRelation`].
588    pub fn monitor(
589        &self,
590        owner: FlowId,
591        target: FlowId,
592    ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
593        if owner == target {
594            return Err(super::error::LifecycleError::SelfRelation);
595        }
596        self.require_live(owner)?;
597        self.require_live(target)?;
598        let mon = self
599            .shared
600            .monitors
601            .create(owner, target)
602            .map_err(|e| self.unavailable(e))??;
603        // Target may have finalized between the live check and insert.
604        // Synthesize DOWN and drop the now-useless relation (owner still live).
605        if self.require_live(target).is_err() {
606            let _ = self.shared.monitors.remove_owned(owner, mon);
607            super::finalize::deliver_down(
608                &self.shared,
609                super::monitor::DownEvent {
610                    monitor: mon,
611                    owner,
612                    target,
613                    reason: super::monitor::FlowExitReason::Fault,
614                },
615            );
616        }
617        Ok(mon)
618    }
619
620    /// Drop `monitor` if `owner` still owns it.
621    pub fn demonitor(
622        &self,
623        owner: FlowId,
624        monitor: super::monitor::MonitorRef,
625    ) -> Result<(), super::error::LifecycleError> {
626        self.require_live(owner)?;
627        match self.shared.monitors.remove_owned(owner, monitor) {
628            Ok(inner) => inner,
629            Err(e) => Err(self.unavailable(e)),
630        }
631    }
632
633    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
634    /// kills the peer (`Normal` only drops the link). With
635    /// [`Self::set_trap_exit`] on a peer, that peer receives a
636    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
637    pub fn link(
638        &self,
639        a: FlowId,
640        b: FlowId,
641    ) -> Result<super::link::LinkId, super::error::LifecycleError> {
642        if a == b {
643            return Err(super::error::LifecycleError::SelfRelation);
644        }
645        self.require_live(a)?;
646        self.require_live(b)?;
647        match self.shared.links.link_if_live(a, b, |id| {
648            self.shared.directory.lookup(id).map(|m| m.is_some())
649        }) {
650            Ok(inner) => inner,
651            Err(e) => Err(self.unavailable(e)),
652        }
653    }
654
655    /// BEAM-style `process_flag(trap_exit, …)`.
656    ///
657    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
658    /// (including `Normal`) instead of killing this flow.
659    pub fn set_trap_exit(
660        &self,
661        id: FlowId,
662        enabled: bool,
663    ) -> Result<(), super::error::LifecycleError> {
664        self.require_live(id)?;
665        self.shared
666            .trap_exits
667            .set(id, enabled)
668            .map_err(|e| self.unavailable(e))
669    }
670
671    /// Drop `link` if `owner` is one of the endpoints.
672    pub fn unlink(
673        &self,
674        owner: FlowId,
675        link: super::link::LinkId,
676    ) -> Result<(), super::error::LifecycleError> {
677        self.require_live(owner)?;
678        match self.shared.links.unlink_owned(owner, link) {
679            Ok(inner) => inner,
680            Err(e) => Err(self.unavailable(e)),
681        }
682    }
683
684    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
685    pub fn register_name(
686        &self,
687        name: &str,
688        cap: crate::bytecode::CapId,
689    ) -> Result<(), super::error::LifecycleError> {
690        let entry = match self.shared.caps.lookup(cap) {
691            Ok(Some(e)) => e,
692            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
693            Err(e) => return Err(self.unavailable(e)),
694        };
695        let target = match entry.target() {
696            Some(id) => id,
697            None => return Err(super::error::LifecycleError::InvalidCapability),
698        };
699        self.require_live(target)?;
700        match self
701            .shared
702            .registry
703            .register(super::registry::RegistryName::from(name), cap, target)
704        {
705            Ok(inner) => inner,
706            Err(e) => Err(self.unavailable(e)),
707        }
708    }
709
710    /// Look up a registered Cap, or `None` if the name is free / was swept.
711    pub fn whereis(
712        &self,
713        name: &str,
714    ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
715        self.shared
716            .registry
717            .whereis(name)
718            .map_err(|e| self.unavailable(e))
719    }
720
721    /// Cooperative abort. Parked flows finalize immediately; a running flow
722    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
723    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
724        self.require_live(id)?;
725        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
726        Ok(())
727    }
728
729    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
730    pub fn mint_admin_cap(
731        &self,
732        holder: FlowId,
733    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
734        self.require_live(holder)?;
735        let cap = crate::bytecode::Cap::root(
736            crate::bytecode::CapTarget::Scheduler,
737            CapRights::ADMIN,
738            None,
739            self.shared.caps.scheduler_cell().as_ref(),
740        );
741        self.shared
742            .caps
743            .grant(holder, cap)
744            .map_err(|e| self.unavailable(e))
745    }
746
747    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
748    pub fn admin_kill(
749        &self,
750        holder: FlowId,
751        cap: crate::bytecode::CapId,
752        target: FlowId,
753    ) -> Result<(), super::error::LifecycleError> {
754        self.require_admin(holder, cap)?;
755        self.kill(target)
756    }
757
758    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
759    pub fn admin_top_up_cpu(
760        &self,
761        holder: FlowId,
762        cap: crate::bytecode::CapId,
763        target: FlowId,
764        extra: i64,
765    ) -> Result<(), super::error::LifecycleError> {
766        self.require_admin(holder, cap)?;
767        let quota = match self.shared.quotas.get(target) {
768            Ok(Some(q)) => q,
769            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
770            Err(e) => return Err(self.unavailable(e)),
771        };
772        quota.top_up_cpu(extra);
773        Ok(())
774    }
775
776    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
777    pub fn admin_top_up_mem(
778        &self,
779        holder: FlowId,
780        cap: crate::bytecode::CapId,
781        target: FlowId,
782        extra: usize,
783    ) -> Result<(), super::error::LifecycleError> {
784        self.require_admin(holder, cap)?;
785        let quota = match self.shared.quotas.get(target) {
786            Ok(Some(q)) => q,
787            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
788            Err(e) => return Err(self.unavailable(e)),
789        };
790        quota.top_up_mem(extra);
791        Ok(())
792    }
793
794    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
795    pub fn admin_top_up_send(
796        &self,
797        holder: FlowId,
798        cap: crate::bytecode::CapId,
799        target: FlowId,
800        extra: i64,
801    ) -> Result<(), super::error::LifecycleError> {
802        self.require_admin(holder, cap)?;
803        let quota = match self.shared.quotas.get(target) {
804            Ok(Some(q)) => q,
805            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
806            Err(e) => return Err(self.unavailable(e)),
807        };
808        quota.top_up_send(extra);
809        Ok(())
810    }
811
812    fn require_admin(
813        &self,
814        holder: FlowId,
815        cap: crate::bytecode::CapId,
816    ) -> Result<(), super::error::LifecycleError> {
817        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
818            Ok(e) => e,
819            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
820        };
821        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
822            .map_err(|_| super::error::LifecycleError::InvalidCapability)
823    }
824
825    /// Remove a name without waiting for the flow to exit. `false` if unknown.
826    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
827        self.shared
828            .registry
829            .unregister(name)
830            .map_err(|e| self.unavailable(e))
831    }
832
833    /// Replace the image used by **new host** [`Self::spawn`] calls and
834    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
835    /// existing `Vm` chunk.
836    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
837        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
838            .map_err(SpawnError::VerifyFailed)?;
839        let chunk = Arc::new(chunk);
840        self.chunk = chunk.clone();
841        #[cfg(feature = "jit")]
842        if let Some(jit) = &self.shared.jit {
843            jit.reload(chunk);
844        }
845        Ok(())
846    }
847
848    /// Signal workers and the timer to stop. Does **not** join threads —
849    /// use [`Self::shutdown`] for a deterministic join. [`Drop`] only signals.
850    fn request_shutdown(&self) {
851        self.shared.shutdown.store(true, Ordering::Release);
852        // Settle parked HostAwaits before joining workers: otherwise a bridge
853        // holding Completers could leave joiners blocked after OS threads exit.
854        match self.shared.host_awaits.drain_all() {
855            Ok(parked) => {
856                for p in parked {
857                    finalize_flow(
858                        &self.shared,
859                        *p.flow,
860                        FlowOutcome::Failed("runtime shutdown".into()),
861                        FlowExitReason::Shutdown,
862                    );
863                }
864            }
865            Err(e) => super::error::report_fault(e),
866        }
867        self.shared.timer.shutdown();
868        let (lock, cvar) = &self.shared.notify;
869        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
870            Ok(_g) => cvar.notify_all(),
871            Err(e) => super::error::report_fault(e),
872        }
873    }
874
875    /// Stop accepting new scheduling work and join every worker + the timer
876    /// thread. Processes that are mid-quantum are allowed to reach their
877    /// next natural suspension point; this does **not** forcibly abort
878    /// running bytecode (there is no safe way to do that to an OS thread
879    /// mid-instruction — see design notes §11 on why preemption here is
880    /// cooperative/budgeted rather than signal-based).
881    pub fn shutdown(mut self) {
882        self.request_shutdown();
883        for w in self.workers.drain(..) {
884            let _ = w.join();
885        }
886        if let Some(t) = self.timer_thread.take() {
887            let _ = t.join();
888        }
889    }
890}
891
892impl Drop for Runtime {
893    fn drop(&mut self) {
894        if !self.shared.shutdown.load(Ordering::Acquire) {
895            self.request_shutdown();
896        }
897    }
898}
899
900/// A convenience Pid constructor for embedders that stored a raw `u64`
901/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
902/// call APIs that take one.
903pub fn flow_id_from_u64(raw: u64) -> FlowId {
904    FlowId(raw)
905}
906
907/// Why [`Runtime::send`] could not deliver a hop.
908#[derive(Debug, Clone, PartialEq, Eq)]
909pub enum SendError {
910    NoSuchFlow(FlowId),
911    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
912    NotAHop {
913        got: &'static str,
914    },
915    /// Target inbox is at one of its logical bounds
916    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
917    /// [`MailboxFullReason`].
918    MailboxFull {
919        flow: FlowId,
920        reason: MailboxFullReason,
921    },
922    /// Host hop authentication failed (payload Cap reissue).
923    Capability,
924    /// Directory / mailbox mutex poisoned — not "no such flow".
925    Unavailable,
926}
927
928impl std::fmt::Display for SendError {
929    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
930        match self {
931            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
932            SendError::NotAHop { got } => {
933                write!(f, "atomic hop requires Value::Message, got {got}")
934            }
935            SendError::MailboxFull { flow, reason } => {
936                write!(f, "mailbox full for {flow} ({reason})")
937            }
938            SendError::Capability => {
939                write!(f, "host send could not reissue a capability in the hop")
940            }
941            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
942        }
943    }
944}
945
946impl std::error::Error for SendError {}
947
948/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
949/// the child. Host spawn passes `None` and mints a trusted root instead.
950pub(crate) struct BytecodeSpawn<'a> {
951    pub authority: &'a Cap,
952    pub cell: &'a crate::bytecode::RevocationCell,
953    pub quota: &'a super::quota::FlowQuota,
954    pub requested_rights: CapRights,
955}
956
957/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
958/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
959/// mailbox + completion channel), register it in the directory, and push
960/// it onto the global injector for any worker to pick up.
961///
962/// Returns [`SpawnError`] on bad function index / VM init / directory
963/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
964/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
965#[allow(clippy::too_many_arguments)]
966pub(crate) fn spawn_on(
967    shared: &Arc<Shared>,
968    chunk: &Arc<Chunk>,
969    natives: &Arc<NativeTable>,
970    function: u32,
971    args: &[Value],
972    restart_policy: RestartPolicy,
973    supervisor: Option<SupervisorLink>,
974    parent: Option<FlowId>,
975    bytecode: Option<BytecodeSpawn<'_>>,
976) -> Result<FlowHandle, SpawnError> {
977    shared.flow_limit.try_reserve()?;
978    let id = match super::process::try_next_flow_id() {
979        Ok(id) => id,
980        Err(super::error::RuntimeError::FlowIdExhausted) => {
981            shared.flow_limit.release();
982            return Err(SpawnError::FlowIdExhausted);
983        }
984        Err(_) => {
985            shared.flow_limit.release();
986            return Err(SpawnError::Unavailable);
987        }
988    };
989    let cell = match shared.caps.bind_flow(id) {
990        Ok(c) => c,
991        Err(_) => {
992            shared.flow_limit.release();
993            return Err(SpawnError::Unavailable);
994        }
995    };
996    let authority = match bytecode {
997        None => Cap::root(
998            CapTarget::Flow(id.as_u64()),
999            CapRights::ROOT,
1000            Some(NativeMask::full(natives.len())),
1001            cell.as_ref(),
1002        ),
1003        Some(ctx) => match super::spawn::exec_spawn_authority(
1004            ctx.authority,
1005            ctx.cell,
1006            ctx.quota,
1007            id.as_u64(),
1008            ctx.requested_rights,
1009            None,
1010            cell.as_ref(),
1011        ) {
1012            Ok(cap) => cap,
1013            Err(e) => {
1014                shared.flow_limit.release();
1015                let _ = shared.caps.revoke_flow(id);
1016                return Err(SpawnError::from(e));
1017            }
1018        },
1019    };
1020    let args = match grant_caps_in_args(shared, parent, id, args) {
1021        Ok(a) => a,
1022        Err(e) => {
1023            shared.flow_limit.release();
1024            let _ = shared.caps.revoke_flow(id);
1025            return Err(e);
1026        }
1027    };
1028    let gate = NativeGate::from_authority(
1029        &authority,
1030        Arc::clone(&cell),
1031        shared.caps.native_cell(),
1032        natives.len(),
1033    );
1034    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1035    let mut vm = match Vm::with_native_gate(
1036        chunk.clone(),
1037        natives.clone(),
1038        gate,
1039        function,
1040        args.as_slice(),
1041    ) {
1042        Ok(vm) => vm,
1043        Err(e) => {
1044            shared.flow_limit.release();
1045            let _ = shared.caps.revoke_flow(id);
1046            return Err(e.into());
1047        }
1048    };
1049    vm.set_paranoid_jumps(shared.paranoid_jumps);
1050    vm.set_memory_budget(Arc::clone(&shared.memory));
1051    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
1052        shared.flow_limit.release();
1053        let _ = shared.caps.revoke_flow(id);
1054        return Err(e.into());
1055    }
1056    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1057    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1058        super::error::report_fault(e);
1059        shared.flow_limit.release();
1060        let _ = shared.caps.revoke_flow(id);
1061        return Err(SpawnError::Unavailable);
1062    }
1063    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
1064        super::error::report_fault(e);
1065        let _ = shared.directory.unregister(id);
1066        shared.flow_limit.release();
1067        let _ = shared.caps.revoke_flow(id);
1068        return Err(SpawnError::Unavailable);
1069    }
1070    let (tx, rx) = super::oneshot::channel();
1071    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1072    flow.authority = authority;
1073    flow.cell = cell;
1074    flow.quota = quota;
1075    flow.supervisor = supervisor;
1076    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1077    shared.injector.push(flow);
1078    wake_workers(shared);
1079    Ok(FlowHandle { id, receiver: rx })
1080}
1081
1082fn grant_caps_in_args(
1083    shared: &Shared,
1084    parent: Option<FlowId>,
1085    child: FlowId,
1086    args: &[Value],
1087) -> Result<Vec<Value>, SpawnError> {
1088    let mut out = Vec::with_capacity(args.len());
1089    for arg in args {
1090        match arg {
1091            Value::Cap(id) => {
1092                let granted = match parent {
1093                    None => shared.caps.reissue_for(*id, child),
1094                    Some(p) => shared.caps.delegate(*id, p, child),
1095                };
1096                match granted {
1097                    Ok(cap) => out.push(Value::Cap(cap)),
1098                    Err(_) => return Err(SpawnError::InvalidCapability),
1099                }
1100            }
1101            other => out.push(other.clone()),
1102        }
1103    }
1104    Ok(out)
1105}
1106
1107pub(crate) fn wake_workers(shared: &Shared) {
1108    let (lock, cvar) = &shared.notify;
1109    match super::sync_lock::lock(lock, "wake_workers") {
1110        Ok(_g) => cvar.notify_one(),
1111        Err(e) => super::error::report_fault(e),
1112    }
1113}
1114
1115/// Signal shutdown and join any threads already started during construction
1116/// failure — keeps the "no orphan threads" contract of
1117/// [`Runtime::with_natives_and_config`].
1118fn abort_startup(
1119    shared: &Arc<Shared>,
1120    workers: Vec<std::thread::JoinHandle<()>>,
1121    timer: Option<std::thread::JoinHandle<()>>,
1122) {
1123    shared.shutdown.store(true, Ordering::Release);
1124    shared.timer.shutdown();
1125    let (lock, cvar) = &shared.notify;
1126    match super::sync_lock::lock(lock, "abort_startup") {
1127        Ok(_g) => cvar.notify_all(),
1128        Err(e) => super::error::report_fault(e),
1129    }
1130    for w in workers {
1131        let _ = w.join();
1132    }
1133    if let Some(t) = timer {
1134        let _ = t.join();
1135    }
1136}
1137
1138/// A `Send + Sync`, freely cloneable capability to spawn flows into a
1139/// [`Runtime`], detached from the `Runtime` value itself. Exists because
1140/// [`super::supervisor::Supervisor`] needs to respawn flows from a
1141/// background monitor thread whose lifetime isn't tied to the `Runtime`
1142/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
1143#[derive(Clone)]
1144pub struct RuntimeSpawner {
1145    pub(crate) shared: Arc<Shared>,
1146    pub(crate) chunk: Arc<Chunk>,
1147    pub(crate) natives: Arc<NativeTable>,
1148}
1149
1150impl RuntimeSpawner {
1151    pub fn spawn(
1152        &self,
1153        function: u32,
1154        args: &[Value],
1155        restart_policy: RestartPolicy,
1156    ) -> Result<FlowHandle, SpawnError> {
1157        spawn_on(
1158            &self.shared,
1159            &self.chunk,
1160            &self.natives,
1161            function,
1162            args,
1163            restart_policy,
1164            None,
1165            None,
1166            None,
1167        )
1168    }
1169
1170    pub(crate) fn spawn_linked(
1171        &self,
1172        function: u32,
1173        args: &[Value],
1174        restart_policy: RestartPolicy,
1175        supervisor: SupervisorLink,
1176    ) -> Result<FlowHandle, SpawnError> {
1177        spawn_on(
1178            &self.shared,
1179            &self.chunk,
1180            &self.natives,
1181            function,
1182            args,
1183            restart_policy,
1184            Some(supervisor),
1185            None,
1186            None,
1187        )
1188    }
1189
1190    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1191        self.shared.metrics.snapshot()
1192    }
1193
1194    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1195        super::finalize::request_kill(&self.shared, id, reason);
1196    }
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201    use super::*;
1202    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1203    use crate::scheduler::FlowOutcome;
1204    use std::time::Duration;
1205
1206    fn add_chunk() -> Chunk {
1207        let mut b = ChunkBuilder::new("test");
1208        b.begin_function("main", 0, 2);
1209        b.emit_load_imm(0, 41);
1210        b.emit_load_imm(1, 1);
1211        b.emit_binop(Opcode::Add, 0, 0, 1);
1212        b.emit_return(0);
1213        b.finish()
1214    }
1215
1216    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
1217    /// makes "still running" an observable state from the host thread.
1218    fn sleep_then_return_chunk(millis: i32) -> Chunk {
1219        let mut b = ChunkBuilder::new("test");
1220        b.begin_function("main", 0, 2);
1221        b.emit_load_imm(0, millis);
1222        b.emit_sleep(0);
1223        b.emit_load_imm(0, 7);
1224        b.emit_return(0);
1225        b.finish()
1226    }
1227
1228    /// The host thread must be able to ask "done yet?" and to wait under a
1229    /// bound *it* chooses, instead of surrendering itself to `join` for
1230    /// however long the bytecode decides to take.
1231    #[test]
1232    fn polling_and_bounded_waits_never_commit_the_host_thread(
1233    ) -> Result<(), Box<dyn std::error::Error>> {
1234        const FLOW_SLEEP: i32 = 150;
1235        let rt = Runtime::with_config(
1236            sleep_then_return_chunk(FLOW_SLEEP),
1237            RuntimeConfig {
1238                workers: 1,
1239                quantum: 1_000,
1240                mailbox: MailboxConfig::DEFAULT,
1241                ..Default::default()
1242            },
1243        )?;
1244        let handle = rt.spawn(0, &[])?;
1245
1246        // The flow cannot possibly be finished yet: it has to be picked up
1247        // and then sleep. A poll must say so without waiting.
1248        if let Some(outcome) = handle.try_join() {
1249            rt.shutdown();
1250            return Err(format!("try_join answered too early: {outcome:?}").into());
1251        }
1252
1253        // A bound well below the flow's sleep must expire and hand control
1254        // back, not block until the flow happens to finish.
1255        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1256            rt.shutdown();
1257            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1258        }
1259
1260        // A generous bound collects the real outcome through the same
1261        // (non-consuming) handle.
1262        let outcome = handle.join_timeout(Duration::from_secs(10));
1263        rt.shutdown();
1264        match outcome {
1265            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1266            other => Err(format!("unexpected outcome: {other:?}").into()),
1267        }
1268    }
1269
1270    #[test]
1271    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1272        let rt = Runtime::with_config(
1273            add_chunk(),
1274            RuntimeConfig {
1275                workers: 1,
1276                quantum: 1_000,
1277                mailbox: MailboxConfig::DEFAULT,
1278                ..Default::default()
1279            },
1280        )?;
1281        let outcome = rt.spawn(0, &[])?.join();
1282        rt.shutdown();
1283        match outcome {
1284            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1285            other => Err(format!("unexpected outcome: {other:?}").into()),
1286        }
1287    }
1288
1289    fn receive_forever_chunk() -> Chunk {
1290        let mut b = ChunkBuilder::new("recv");
1291        b.begin_function("main", 0, 1);
1292        b.emit_receive(0);
1293        b.emit_return(0);
1294        b.finish()
1295    }
1296
1297    #[test]
1298    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1299        let rt = Runtime::with_config(
1300            receive_forever_chunk(),
1301            RuntimeConfig {
1302                workers: 1,
1303                quantum: 1_000,
1304                mailbox: MailboxConfig::DEFAULT,
1305                ..Default::default()
1306            },
1307        )?;
1308        let handle = rt.spawn(0, &[])?;
1309        rt.kill(handle.id())?;
1310        let outcome = handle.join();
1311        rt.shutdown();
1312        assert!(
1313            matches!(outcome, FlowOutcome::Failed(_)),
1314            "kill must fail the joiner, got {outcome:?}"
1315        );
1316        Ok(())
1317    }
1318
1319    #[test]
1320    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1321        let rt = Runtime::with_config(
1322            receive_forever_chunk(),
1323            RuntimeConfig {
1324                workers: 1,
1325                quantum: 1_000,
1326                mailbox: MailboxConfig::DEFAULT,
1327                max_flows: 1,
1328                ..Default::default()
1329            },
1330        )?;
1331        let first = rt.spawn(0, &[])?;
1332        let second = rt.spawn(0, &[]);
1333        rt.kill(first.id())?;
1334        let _ = first.join();
1335        // After finalize, the reserved slot must be free again.
1336        let third = rt.spawn(0, &[])?;
1337        rt.kill(third.id())?;
1338        let _ = third.join();
1339        rt.shutdown();
1340        match second {
1341            Err(SpawnError::FlowLimit { current, max }) => {
1342                assert_eq!(current, 1);
1343                assert_eq!(max, 1);
1344                Ok(())
1345            }
1346            other => Err(format!(
1347                "expected FlowLimit, got {}",
1348                match &other {
1349                    Ok(_) => "Ok(handle)".into(),
1350                    Err(e) => format!("Err({e})"),
1351                }
1352            )
1353            .into()),
1354        }
1355    }
1356
1357    /// Ask must not park waiting for a reply when DropNewest discarded the request.
1358    #[test]
1359    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1360        use crate::bytecode::{Message, Program};
1361        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1362
1363        let mut program = Program::new("ask-drop-newest");
1364        let busy = program.function("busy", 0, |f| {
1365            // Stay alive without spinning the worker: sleep loop.
1366            let loop_lbl = f.label();
1367            f.bind(loop_lbl);
1368            let ms = f.load_i32(50);
1369            f.sleep(ms);
1370            f.jump(loop_lbl);
1371        });
1372        let asker = program.function("asker", 1, |f| {
1373            let server = f.reg(0);
1374            let z = f.load_i32(0);
1375            let req = f.hop_fresh(1, z);
1376            let reply = f.ask(server, req);
1377            f.return_(reply);
1378        });
1379        let chunk = program.build();
1380
1381        let cap = MailboxCapacity::new(1).ok_or("cap")?;
1382        let rt = Runtime::with_natives_and_config(
1383            chunk,
1384            crate::std_native_table(),
1385            RuntimeConfig {
1386                // Busy target must not monopolize scheduling or Ask never runs.
1387                workers: 2,
1388                quantum: 1_000,
1389                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1390                ..Default::default()
1391            },
1392        )?;
1393
1394        let server = rt.spawn(busy, &[])?;
1395        // Fill the only slot so the subsequent Ask is DropNewest'd.
1396        rt.send(
1397            server.id(),
1398            Value::Message(Message::request(1, 9, Value::Int(1))),
1399        )?;
1400        let server_cap = rt.mint_cap(server.id())?;
1401        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1402        let outcome = ask.join_timeout(Duration::from_secs(3));
1403        rt.kill(server.id())?;
1404        let _ = server.join_timeout(Duration::from_millis(500));
1405        rt.shutdown();
1406
1407        match outcome {
1408            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1409            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1410        }
1411    }
1412
1413    #[test]
1414    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1415        use crate::bytecode::Program;
1416
1417        let mut program = Program::new("ask-limit");
1418        let silent = program.function("silent", 0, |f| {
1419            // Accept the request hop but never reply.
1420            let _req = f.receive();
1421            let loop_lbl = f.label();
1422            f.bind(loop_lbl);
1423            let ms = f.load_i32(50);
1424            f.sleep(ms);
1425            f.jump(loop_lbl);
1426        });
1427        let asker = program.function("asker", 1, |f| {
1428            let server = f.reg(0);
1429            let z = f.load_i32(0);
1430            let req = f.hop_fresh(1, z);
1431            let reply = f.ask(server, req);
1432            f.return_(reply);
1433        });
1434        let chunk = program.build();
1435
1436        let rt = Runtime::with_natives_and_config(
1437            chunk,
1438            crate::std_native_table(),
1439            RuntimeConfig {
1440                workers: 2,
1441                quantum: 1_000,
1442                mailbox: MailboxConfig::DEFAULT,
1443                max_ask_waits: 1,
1444                ..Default::default()
1445            },
1446        )?;
1447
1448        let server = rt.spawn(silent, &[])?;
1449        let server_cap = rt.mint_cap(server.id())?;
1450        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1451        // Give the first Ask time to park before the second tries.
1452        std::thread::sleep(Duration::from_millis(30));
1453        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1454        let second_out = second.join_timeout(Duration::from_secs(2));
1455        rt.kill(server.id())?;
1456        let _ = first.join_timeout(Duration::from_millis(500));
1457        let _ = server.join_timeout(Duration::from_millis(500));
1458        rt.shutdown();
1459
1460        match second_out {
1461            Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1462            other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1463        }
1464    }
1465
1466    // HostAwait E2E coverage lives in `host_await::runtime_tests`.
1467
1468    #[cfg(feature = "jit")]
1469    #[test]
1470    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1471        use crate::JitConfig;
1472
1473        let rt = Runtime::with_config(
1474            add_chunk(),
1475            RuntimeConfig {
1476                workers: 1,
1477                quantum: 1_000,
1478                mailbox: MailboxConfig::DEFAULT,
1479                jit: JitConfig {
1480                    enabled: true,
1481                    hot_threshold: 1,
1482                },
1483                ..Default::default()
1484            },
1485        )?;
1486        let outcome = rt.spawn(0, &[])?.join();
1487        rt.shutdown();
1488        match outcome {
1489            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1490            other => Err(format!("unexpected outcome: {other:?}").into()),
1491        }
1492    }
1493
1494    #[test]
1495    fn sandbox_enables_process_wide_relation_caps() {
1496        let config = RuntimeConfig::sandbox();
1497        assert_eq!(config.max_flows, 256);
1498        assert_eq!(config.max_ask_waits, 128);
1499        assert_eq!(config.max_host_awaits, 128);
1500        assert_eq!(config.max_links, 1024);
1501        assert_eq!(config.max_monitors, 1024);
1502        assert_eq!(config.max_registry_names, 256);
1503        assert!(config.paranoid_jumps);
1504        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1505    }
1506
1507    #[test]
1508    fn default_remains_unlimited_for_relation_caps() {
1509        let config = RuntimeConfig::default();
1510        assert_eq!(config.max_links, 0);
1511        assert_eq!(config.max_monitors, 0);
1512        assert_eq!(config.max_registry_names, 0);
1513        assert!(!config.paranoid_jumps);
1514    }
1515
1516    #[test]
1517    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1518        use crate::bytecode::encode;
1519        use crate::{fingerprint_bf, AttestError};
1520
1521        let bytes = encode(&add_chunk());
1522        let mut bad = fingerprint_bf(&bytes);
1523        bad[0] ^= 0xff;
1524        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1525            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1526            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1527            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1528        }
1529    }
1530
1531    #[test]
1532    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1533        use crate::bytecode::encode;
1534        use crate::fingerprint_bf;
1535
1536        let chunk = add_chunk();
1537        let bytes = encode(&chunk);
1538        let digest = fingerprint_bf(&bytes);
1539        let rt = Runtime::with_attested(
1540            &bytes,
1541            digest,
1542            NativeTable::empty(),
1543            RuntimeConfig {
1544                workers: 1,
1545                quantum: 1_000,
1546                mailbox: MailboxConfig::DEFAULT,
1547                ..Default::default()
1548            },
1549        )?;
1550        let outcome = rt.spawn(0, &[])?.join();
1551        rt.shutdown();
1552        match outcome {
1553            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1554            other => Err(format!("expected 42, got {other:?}").into()),
1555        }
1556    }
1557
1558    #[test]
1559    fn untrusted_enables_paranoid_jumps_on_shared() -> Result<(), Box<dyn std::error::Error>> {
1560        // Default trust is Untrusted → Shared.paranoid_jumps must be true
1561        // even when the explicit config flag is false.
1562        let rt = Runtime::with_config(
1563            add_chunk(),
1564            RuntimeConfig {
1565                workers: 1,
1566                quantum: 1_000,
1567                mailbox: MailboxConfig::DEFAULT,
1568                trust: crate::bytecode::TrustLevel::Untrusted,
1569                paranoid_jumps: false,
1570                ..Default::default()
1571            },
1572        )?;
1573        assert!(rt.shared.paranoid_jumps);
1574        rt.shutdown();
1575        Ok(())
1576    }
1577}