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(a, b) {
648            Ok(inner) => inner,
649            Err(e) => Err(self.unavailable(e)),
650        }
651    }
652
653    /// BEAM-style `process_flag(trap_exit, …)`.
654    ///
655    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
656    /// (including `Normal`) instead of killing this flow.
657    pub fn set_trap_exit(
658        &self,
659        id: FlowId,
660        enabled: bool,
661    ) -> Result<(), super::error::LifecycleError> {
662        self.require_live(id)?;
663        self.shared
664            .trap_exits
665            .set(id, enabled)
666            .map_err(|e| self.unavailable(e))
667    }
668
669    /// Drop `link` if `owner` is one of the endpoints.
670    pub fn unlink(
671        &self,
672        owner: FlowId,
673        link: super::link::LinkId,
674    ) -> Result<(), super::error::LifecycleError> {
675        self.require_live(owner)?;
676        match self.shared.links.unlink_owned(owner, link) {
677            Ok(inner) => inner,
678            Err(e) => Err(self.unavailable(e)),
679        }
680    }
681
682    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
683    pub fn register_name(
684        &self,
685        name: &str,
686        cap: crate::bytecode::CapId,
687    ) -> Result<(), super::error::LifecycleError> {
688        let entry = match self.shared.caps.lookup(cap) {
689            Ok(Some(e)) => e,
690            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
691            Err(e) => return Err(self.unavailable(e)),
692        };
693        let target = match entry.target() {
694            Some(id) => id,
695            None => return Err(super::error::LifecycleError::InvalidCapability),
696        };
697        self.require_live(target)?;
698        match self
699            .shared
700            .registry
701            .register(super::registry::RegistryName::from(name), cap, target)
702        {
703            Ok(inner) => inner,
704            Err(e) => Err(self.unavailable(e)),
705        }
706    }
707
708    /// Look up a registered Cap, or `None` if the name is free / was swept.
709    pub fn whereis(
710        &self,
711        name: &str,
712    ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
713        self.shared
714            .registry
715            .whereis(name)
716            .map_err(|e| self.unavailable(e))
717    }
718
719    /// Cooperative abort. Parked flows finalize immediately; a running flow
720    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
721    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
722        self.require_live(id)?;
723        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
724        Ok(())
725    }
726
727    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
728    pub fn mint_admin_cap(
729        &self,
730        holder: FlowId,
731    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
732        self.require_live(holder)?;
733        let cap = crate::bytecode::Cap::root(
734            crate::bytecode::CapTarget::Scheduler,
735            CapRights::ADMIN,
736            None,
737            self.shared.caps.scheduler_cell().as_ref(),
738        );
739        self.shared
740            .caps
741            .grant(holder, cap)
742            .map_err(|e| self.unavailable(e))
743    }
744
745    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
746    pub fn admin_kill(
747        &self,
748        holder: FlowId,
749        cap: crate::bytecode::CapId,
750        target: FlowId,
751    ) -> Result<(), super::error::LifecycleError> {
752        self.require_admin(holder, cap)?;
753        self.kill(target)
754    }
755
756    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
757    pub fn admin_top_up_cpu(
758        &self,
759        holder: FlowId,
760        cap: crate::bytecode::CapId,
761        target: FlowId,
762        extra: i64,
763    ) -> Result<(), super::error::LifecycleError> {
764        self.require_admin(holder, cap)?;
765        let quota = match self.shared.quotas.get(target) {
766            Ok(Some(q)) => q,
767            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
768            Err(e) => return Err(self.unavailable(e)),
769        };
770        quota.top_up_cpu(extra);
771        Ok(())
772    }
773
774    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
775    pub fn admin_top_up_mem(
776        &self,
777        holder: FlowId,
778        cap: crate::bytecode::CapId,
779        target: FlowId,
780        extra: usize,
781    ) -> Result<(), super::error::LifecycleError> {
782        self.require_admin(holder, cap)?;
783        let quota = match self.shared.quotas.get(target) {
784            Ok(Some(q)) => q,
785            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
786            Err(e) => return Err(self.unavailable(e)),
787        };
788        quota.top_up_mem(extra);
789        Ok(())
790    }
791
792    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
793    pub fn admin_top_up_send(
794        &self,
795        holder: FlowId,
796        cap: crate::bytecode::CapId,
797        target: FlowId,
798        extra: i64,
799    ) -> Result<(), super::error::LifecycleError> {
800        self.require_admin(holder, cap)?;
801        let quota = match self.shared.quotas.get(target) {
802            Ok(Some(q)) => q,
803            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
804            Err(e) => return Err(self.unavailable(e)),
805        };
806        quota.top_up_send(extra);
807        Ok(())
808    }
809
810    fn require_admin(
811        &self,
812        holder: FlowId,
813        cap: crate::bytecode::CapId,
814    ) -> Result<(), super::error::LifecycleError> {
815        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
816            Ok(e) => e,
817            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
818        };
819        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
820            .map_err(|_| super::error::LifecycleError::InvalidCapability)
821    }
822
823    /// Remove a name without waiting for the flow to exit. `false` if unknown.
824    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
825        self.shared
826            .registry
827            .unregister(name)
828            .map_err(|e| self.unavailable(e))
829    }
830
831    /// Replace the image used by **new host** [`Self::spawn`] calls and
832    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
833    /// existing `Vm` chunk.
834    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
835        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
836            .map_err(SpawnError::VerifyFailed)?;
837        let chunk = Arc::new(chunk);
838        self.chunk = chunk.clone();
839        #[cfg(feature = "jit")]
840        if let Some(jit) = &self.shared.jit {
841            jit.reload(chunk);
842        }
843        Ok(())
844    }
845
846    /// Signal workers and the timer to stop. Does **not** join threads —
847    /// use [`Self::shutdown`] for a deterministic join. [`Drop`] only signals.
848    fn request_shutdown(&self) {
849        self.shared.shutdown.store(true, Ordering::Release);
850        // Settle parked HostAwaits before joining workers: otherwise a bridge
851        // holding Completers could leave joiners blocked after OS threads exit.
852        match self.shared.host_awaits.drain_all() {
853            Ok(parked) => {
854                for p in parked {
855                    finalize_flow(
856                        &self.shared,
857                        *p.flow,
858                        FlowOutcome::Failed("runtime shutdown".into()),
859                        FlowExitReason::Shutdown,
860                    );
861                }
862            }
863            Err(e) => super::error::report_fault(e),
864        }
865        self.shared.timer.shutdown();
866        let (lock, cvar) = &self.shared.notify;
867        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
868            Ok(_g) => cvar.notify_all(),
869            Err(e) => super::error::report_fault(e),
870        }
871    }
872
873    /// Stop accepting new scheduling work and join every worker + the timer
874    /// thread. Processes that are mid-quantum are allowed to reach their
875    /// next natural suspension point; this does **not** forcibly abort
876    /// running bytecode (there is no safe way to do that to an OS thread
877    /// mid-instruction — see design notes §11 on why preemption here is
878    /// cooperative/budgeted rather than signal-based).
879    pub fn shutdown(mut self) {
880        self.request_shutdown();
881        for w in self.workers.drain(..) {
882            let _ = w.join();
883        }
884        if let Some(t) = self.timer_thread.take() {
885            let _ = t.join();
886        }
887    }
888}
889
890impl Drop for Runtime {
891    fn drop(&mut self) {
892        if !self.shared.shutdown.load(Ordering::Acquire) {
893            self.request_shutdown();
894        }
895    }
896}
897
898/// A convenience Pid constructor for embedders that stored a raw `u64`
899/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
900/// call APIs that take one.
901pub fn flow_id_from_u64(raw: u64) -> FlowId {
902    FlowId(raw)
903}
904
905/// Why [`Runtime::send`] could not deliver a hop.
906#[derive(Debug, Clone, PartialEq, Eq)]
907pub enum SendError {
908    NoSuchFlow(FlowId),
909    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
910    NotAHop {
911        got: &'static str,
912    },
913    /// Target inbox is at one of its logical bounds
914    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
915    /// [`MailboxFullReason`].
916    MailboxFull {
917        flow: FlowId,
918        reason: MailboxFullReason,
919    },
920    /// Host hop authentication failed (payload Cap reissue).
921    Capability,
922    /// Directory / mailbox mutex poisoned — not "no such flow".
923    Unavailable,
924}
925
926impl std::fmt::Display for SendError {
927    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
928        match self {
929            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
930            SendError::NotAHop { got } => {
931                write!(f, "atomic hop requires Value::Message, got {got}")
932            }
933            SendError::MailboxFull { flow, reason } => {
934                write!(f, "mailbox full for {flow} ({reason})")
935            }
936            SendError::Capability => {
937                write!(f, "host send could not reissue a capability in the hop")
938            }
939            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
940        }
941    }
942}
943
944impl std::error::Error for SendError {}
945
946/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
947/// the child. Host spawn passes `None` and mints a trusted root instead.
948pub(crate) struct BytecodeSpawn<'a> {
949    pub authority: &'a Cap,
950    pub cell: &'a crate::bytecode::RevocationCell,
951    pub quota: &'a super::quota::FlowQuota,
952    pub requested_rights: CapRights,
953}
954
955/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
956/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
957/// mailbox + completion channel), register it in the directory, and push
958/// it onto the global injector for any worker to pick up.
959///
960/// Returns [`SpawnError`] on bad function index / VM init / directory
961/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
962/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
963#[allow(clippy::too_many_arguments)]
964pub(crate) fn spawn_on(
965    shared: &Arc<Shared>,
966    chunk: &Arc<Chunk>,
967    natives: &Arc<NativeTable>,
968    function: u32,
969    args: &[Value],
970    restart_policy: RestartPolicy,
971    supervisor: Option<SupervisorLink>,
972    parent: Option<FlowId>,
973    bytecode: Option<BytecodeSpawn<'_>>,
974) -> Result<FlowHandle, SpawnError> {
975    shared.flow_limit.try_reserve()?;
976    let id = match super::process::try_next_flow_id() {
977        Ok(id) => id,
978        Err(super::error::RuntimeError::FlowIdExhausted) => {
979            shared.flow_limit.release();
980            return Err(SpawnError::FlowIdExhausted);
981        }
982        Err(_) => {
983            shared.flow_limit.release();
984            return Err(SpawnError::Unavailable);
985        }
986    };
987    let cell = match shared.caps.bind_flow(id) {
988        Ok(c) => c,
989        Err(_) => {
990            shared.flow_limit.release();
991            return Err(SpawnError::Unavailable);
992        }
993    };
994    let authority = match bytecode {
995        None => Cap::root(
996            CapTarget::Flow(id.as_u64()),
997            CapRights::ROOT,
998            Some(NativeMask::full(natives.len())),
999            cell.as_ref(),
1000        ),
1001        Some(ctx) => match super::spawn::exec_spawn_authority(
1002            ctx.authority,
1003            ctx.cell,
1004            ctx.quota,
1005            id.as_u64(),
1006            ctx.requested_rights,
1007            None,
1008            cell.as_ref(),
1009        ) {
1010            Ok(cap) => cap,
1011            Err(e) => {
1012                shared.flow_limit.release();
1013                let _ = shared.caps.revoke_flow(id);
1014                return Err(SpawnError::from(e));
1015            }
1016        },
1017    };
1018    let args = match grant_caps_in_args(shared, parent, id, args) {
1019        Ok(a) => a,
1020        Err(e) => {
1021            shared.flow_limit.release();
1022            let _ = shared.caps.revoke_flow(id);
1023            return Err(e);
1024        }
1025    };
1026    let gate = NativeGate::from_authority(
1027        &authority,
1028        Arc::clone(&cell),
1029        shared.caps.native_cell(),
1030        natives.len(),
1031    );
1032    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1033    let mut vm = match Vm::with_native_gate(
1034        chunk.clone(),
1035        natives.clone(),
1036        gate,
1037        function,
1038        args.as_slice(),
1039    ) {
1040        Ok(vm) => vm,
1041        Err(e) => {
1042            shared.flow_limit.release();
1043            let _ = shared.caps.revoke_flow(id);
1044            return Err(e.into());
1045        }
1046    };
1047    vm.set_paranoid_jumps(shared.paranoid_jumps);
1048    vm.set_memory_budget(Arc::clone(&shared.memory));
1049    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
1050        shared.flow_limit.release();
1051        let _ = shared.caps.revoke_flow(id);
1052        return Err(e.into());
1053    }
1054    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1055    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1056        super::error::report_fault(e);
1057        shared.flow_limit.release();
1058        let _ = shared.caps.revoke_flow(id);
1059        return Err(SpawnError::Unavailable);
1060    }
1061    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
1062        super::error::report_fault(e);
1063        let _ = shared.directory.unregister(id);
1064        shared.flow_limit.release();
1065        let _ = shared.caps.revoke_flow(id);
1066        return Err(SpawnError::Unavailable);
1067    }
1068    let (tx, rx) = super::oneshot::channel();
1069    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1070    flow.authority = authority;
1071    flow.cell = cell;
1072    flow.quota = quota;
1073    flow.supervisor = supervisor;
1074    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1075    shared.injector.push(flow);
1076    wake_workers(shared);
1077    Ok(FlowHandle { id, receiver: rx })
1078}
1079
1080fn grant_caps_in_args(
1081    shared: &Shared,
1082    parent: Option<FlowId>,
1083    child: FlowId,
1084    args: &[Value],
1085) -> Result<Vec<Value>, SpawnError> {
1086    let mut out = Vec::with_capacity(args.len());
1087    for arg in args {
1088        match arg {
1089            Value::Cap(id) => {
1090                let granted = match parent {
1091                    None => shared.caps.reissue_for(*id, child),
1092                    Some(p) => shared.caps.delegate(*id, p, child),
1093                };
1094                match granted {
1095                    Ok(cap) => out.push(Value::Cap(cap)),
1096                    Err(_) => return Err(SpawnError::InvalidCapability),
1097                }
1098            }
1099            other => out.push(other.clone()),
1100        }
1101    }
1102    Ok(out)
1103}
1104
1105pub(crate) fn wake_workers(shared: &Shared) {
1106    let (lock, cvar) = &shared.notify;
1107    match super::sync_lock::lock(lock, "wake_workers") {
1108        Ok(_g) => cvar.notify_one(),
1109        Err(e) => super::error::report_fault(e),
1110    }
1111}
1112
1113/// Signal shutdown and join any threads already started during construction
1114/// failure — keeps the "no orphan threads" contract of
1115/// [`Runtime::with_natives_and_config`].
1116fn abort_startup(
1117    shared: &Arc<Shared>,
1118    workers: Vec<std::thread::JoinHandle<()>>,
1119    timer: Option<std::thread::JoinHandle<()>>,
1120) {
1121    shared.shutdown.store(true, Ordering::Release);
1122    shared.timer.shutdown();
1123    let (lock, cvar) = &shared.notify;
1124    match super::sync_lock::lock(lock, "abort_startup") {
1125        Ok(_g) => cvar.notify_all(),
1126        Err(e) => super::error::report_fault(e),
1127    }
1128    for w in workers {
1129        let _ = w.join();
1130    }
1131    if let Some(t) = timer {
1132        let _ = t.join();
1133    }
1134}
1135
1136/// A `Send + Sync`, freely cloneable capability to spawn flows into a
1137/// [`Runtime`], detached from the `Runtime` value itself. Exists because
1138/// [`super::supervisor::Supervisor`] needs to respawn flows from a
1139/// background monitor thread whose lifetime isn't tied to the `Runtime`
1140/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
1141#[derive(Clone)]
1142pub struct RuntimeSpawner {
1143    pub(crate) shared: Arc<Shared>,
1144    pub(crate) chunk: Arc<Chunk>,
1145    pub(crate) natives: Arc<NativeTable>,
1146}
1147
1148impl RuntimeSpawner {
1149    pub fn spawn(
1150        &self,
1151        function: u32,
1152        args: &[Value],
1153        restart_policy: RestartPolicy,
1154    ) -> Result<FlowHandle, SpawnError> {
1155        spawn_on(
1156            &self.shared,
1157            &self.chunk,
1158            &self.natives,
1159            function,
1160            args,
1161            restart_policy,
1162            None,
1163            None,
1164            None,
1165        )
1166    }
1167
1168    pub(crate) fn spawn_linked(
1169        &self,
1170        function: u32,
1171        args: &[Value],
1172        restart_policy: RestartPolicy,
1173        supervisor: SupervisorLink,
1174    ) -> Result<FlowHandle, SpawnError> {
1175        spawn_on(
1176            &self.shared,
1177            &self.chunk,
1178            &self.natives,
1179            function,
1180            args,
1181            restart_policy,
1182            Some(supervisor),
1183            None,
1184            None,
1185        )
1186    }
1187
1188    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1189        self.shared.metrics.snapshot()
1190    }
1191
1192    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1193        super::finalize::request_kill(&self.shared, id, reason);
1194    }
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199    use super::*;
1200    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1201    use crate::scheduler::FlowOutcome;
1202    use std::time::Duration;
1203
1204    fn add_chunk() -> Chunk {
1205        let mut b = ChunkBuilder::new("test");
1206        b.begin_function("main", 0, 2);
1207        b.emit_load_imm(0, 41);
1208        b.emit_load_imm(1, 1);
1209        b.emit_binop(Opcode::Add, 0, 0, 1);
1210        b.emit_return(0);
1211        b.finish()
1212    }
1213
1214    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
1215    /// makes "still running" an observable state from the host thread.
1216    fn sleep_then_return_chunk(millis: i32) -> Chunk {
1217        let mut b = ChunkBuilder::new("test");
1218        b.begin_function("main", 0, 2);
1219        b.emit_load_imm(0, millis);
1220        b.emit_sleep(0);
1221        b.emit_load_imm(0, 7);
1222        b.emit_return(0);
1223        b.finish()
1224    }
1225
1226    /// The host thread must be able to ask "done yet?" and to wait under a
1227    /// bound *it* chooses, instead of surrendering itself to `join` for
1228    /// however long the bytecode decides to take.
1229    #[test]
1230    fn polling_and_bounded_waits_never_commit_the_host_thread(
1231    ) -> Result<(), Box<dyn std::error::Error>> {
1232        const FLOW_SLEEP: i32 = 150;
1233        let rt = Runtime::with_config(
1234            sleep_then_return_chunk(FLOW_SLEEP),
1235            RuntimeConfig {
1236                workers: 1,
1237                quantum: 1_000,
1238                mailbox: MailboxConfig::DEFAULT,
1239                ..Default::default()
1240            },
1241        )?;
1242        let handle = rt.spawn(0, &[])?;
1243
1244        // The flow cannot possibly be finished yet: it has to be picked up
1245        // and then sleep. A poll must say so without waiting.
1246        if let Some(outcome) = handle.try_join() {
1247            rt.shutdown();
1248            return Err(format!("try_join answered too early: {outcome:?}").into());
1249        }
1250
1251        // A bound well below the flow's sleep must expire and hand control
1252        // back, not block until the flow happens to finish.
1253        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1254            rt.shutdown();
1255            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1256        }
1257
1258        // A generous bound collects the real outcome through the same
1259        // (non-consuming) handle.
1260        let outcome = handle.join_timeout(Duration::from_secs(10));
1261        rt.shutdown();
1262        match outcome {
1263            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1264            other => Err(format!("unexpected outcome: {other:?}").into()),
1265        }
1266    }
1267
1268    #[test]
1269    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1270        let rt = Runtime::with_config(
1271            add_chunk(),
1272            RuntimeConfig {
1273                workers: 1,
1274                quantum: 1_000,
1275                mailbox: MailboxConfig::DEFAULT,
1276                ..Default::default()
1277            },
1278        )?;
1279        let outcome = rt.spawn(0, &[])?.join();
1280        rt.shutdown();
1281        match outcome {
1282            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1283            other => Err(format!("unexpected outcome: {other:?}").into()),
1284        }
1285    }
1286
1287    fn receive_forever_chunk() -> Chunk {
1288        let mut b = ChunkBuilder::new("recv");
1289        b.begin_function("main", 0, 1);
1290        b.emit_receive(0);
1291        b.emit_return(0);
1292        b.finish()
1293    }
1294
1295    #[test]
1296    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1297        let rt = Runtime::with_config(
1298            receive_forever_chunk(),
1299            RuntimeConfig {
1300                workers: 1,
1301                quantum: 1_000,
1302                mailbox: MailboxConfig::DEFAULT,
1303                ..Default::default()
1304            },
1305        )?;
1306        let handle = rt.spawn(0, &[])?;
1307        rt.kill(handle.id())?;
1308        let outcome = handle.join();
1309        rt.shutdown();
1310        assert!(
1311            matches!(outcome, FlowOutcome::Failed(_)),
1312            "kill must fail the joiner, got {outcome:?}"
1313        );
1314        Ok(())
1315    }
1316
1317    #[test]
1318    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1319        let rt = Runtime::with_config(
1320            receive_forever_chunk(),
1321            RuntimeConfig {
1322                workers: 1,
1323                quantum: 1_000,
1324                mailbox: MailboxConfig::DEFAULT,
1325                max_flows: 1,
1326                ..Default::default()
1327            },
1328        )?;
1329        let first = rt.spawn(0, &[])?;
1330        let second = rt.spawn(0, &[]);
1331        rt.kill(first.id())?;
1332        let _ = first.join();
1333        // After finalize, the reserved slot must be free again.
1334        let third = rt.spawn(0, &[])?;
1335        rt.kill(third.id())?;
1336        let _ = third.join();
1337        rt.shutdown();
1338        match second {
1339            Err(SpawnError::FlowLimit { current, max }) => {
1340                assert_eq!(current, 1);
1341                assert_eq!(max, 1);
1342                Ok(())
1343            }
1344            other => Err(format!(
1345                "expected FlowLimit, got {}",
1346                match &other {
1347                    Ok(_) => "Ok(handle)".into(),
1348                    Err(e) => format!("Err({e})"),
1349                }
1350            )
1351            .into()),
1352        }
1353    }
1354
1355    /// Ask must not park waiting for a reply when DropNewest discarded the request.
1356    #[test]
1357    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1358        use crate::bytecode::{Message, Program};
1359        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1360
1361        let mut program = Program::new("ask-drop-newest");
1362        let busy = program.function("busy", 0, |f| {
1363            // Stay alive without spinning the worker: sleep loop.
1364            let loop_lbl = f.label();
1365            f.bind(loop_lbl);
1366            let ms = f.load_i32(50);
1367            f.sleep(ms);
1368            f.jump(loop_lbl);
1369        });
1370        let asker = program.function("asker", 1, |f| {
1371            let server = f.reg(0);
1372            let z = f.load_i32(0);
1373            let req = f.hop_fresh(1, z);
1374            let reply = f.ask(server, req);
1375            f.return_(reply);
1376        });
1377        let chunk = program.build();
1378
1379        let cap = MailboxCapacity::new(1).ok_or("cap")?;
1380        let rt = Runtime::with_natives_and_config(
1381            chunk,
1382            crate::std_native_table(),
1383            RuntimeConfig {
1384                // Busy target must not monopolize scheduling or Ask never runs.
1385                workers: 2,
1386                quantum: 1_000,
1387                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1388                ..Default::default()
1389            },
1390        )?;
1391
1392        let server = rt.spawn(busy, &[])?;
1393        // Fill the only slot so the subsequent Ask is DropNewest'd.
1394        rt.send(
1395            server.id(),
1396            Value::Message(Message::request(1, 9, Value::Int(1))),
1397        )?;
1398        let server_cap = rt.mint_cap(server.id())?;
1399        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1400        let outcome = ask.join_timeout(Duration::from_secs(3));
1401        rt.kill(server.id())?;
1402        let _ = server.join_timeout(Duration::from_millis(500));
1403        rt.shutdown();
1404
1405        match outcome {
1406            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1407            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1408        }
1409    }
1410
1411    #[test]
1412    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1413        use crate::bytecode::Program;
1414
1415        let mut program = Program::new("ask-limit");
1416        let silent = program.function("silent", 0, |f| {
1417            // Accept the request hop but never reply.
1418            let _req = f.receive();
1419            let loop_lbl = f.label();
1420            f.bind(loop_lbl);
1421            let ms = f.load_i32(50);
1422            f.sleep(ms);
1423            f.jump(loop_lbl);
1424        });
1425        let asker = program.function("asker", 1, |f| {
1426            let server = f.reg(0);
1427            let z = f.load_i32(0);
1428            let req = f.hop_fresh(1, z);
1429            let reply = f.ask(server, req);
1430            f.return_(reply);
1431        });
1432        let chunk = program.build();
1433
1434        let rt = Runtime::with_natives_and_config(
1435            chunk,
1436            crate::std_native_table(),
1437            RuntimeConfig {
1438                workers: 2,
1439                quantum: 1_000,
1440                mailbox: MailboxConfig::DEFAULT,
1441                max_ask_waits: 1,
1442                ..Default::default()
1443            },
1444        )?;
1445
1446        let server = rt.spawn(silent, &[])?;
1447        let server_cap = rt.mint_cap(server.id())?;
1448        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1449        // Give the first Ask time to park before the second tries.
1450        std::thread::sleep(Duration::from_millis(30));
1451        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1452        let second_out = second.join_timeout(Duration::from_secs(2));
1453        rt.kill(server.id())?;
1454        let _ = first.join_timeout(Duration::from_millis(500));
1455        let _ = server.join_timeout(Duration::from_millis(500));
1456        rt.shutdown();
1457
1458        match second_out {
1459            Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1460            other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1461        }
1462    }
1463
1464    // HostAwait E2E coverage lives in `host_await::runtime_tests`.
1465
1466    #[cfg(feature = "jit")]
1467    #[test]
1468    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1469        use crate::JitConfig;
1470
1471        let rt = Runtime::with_config(
1472            add_chunk(),
1473            RuntimeConfig {
1474                workers: 1,
1475                quantum: 1_000,
1476                mailbox: MailboxConfig::DEFAULT,
1477                jit: JitConfig {
1478                    enabled: true,
1479                    hot_threshold: 1,
1480                },
1481                ..Default::default()
1482            },
1483        )?;
1484        let outcome = rt.spawn(0, &[])?.join();
1485        rt.shutdown();
1486        match outcome {
1487            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1488            other => Err(format!("unexpected outcome: {other:?}").into()),
1489        }
1490    }
1491
1492    #[test]
1493    fn sandbox_enables_process_wide_relation_caps() {
1494        let config = RuntimeConfig::sandbox();
1495        assert_eq!(config.max_flows, 256);
1496        assert_eq!(config.max_ask_waits, 128);
1497        assert_eq!(config.max_host_awaits, 128);
1498        assert_eq!(config.max_links, 1024);
1499        assert_eq!(config.max_monitors, 1024);
1500        assert_eq!(config.max_registry_names, 256);
1501        assert!(config.paranoid_jumps);
1502        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1503    }
1504
1505    #[test]
1506    fn default_remains_unlimited_for_relation_caps() {
1507        let config = RuntimeConfig::default();
1508        assert_eq!(config.max_links, 0);
1509        assert_eq!(config.max_monitors, 0);
1510        assert_eq!(config.max_registry_names, 0);
1511        assert!(!config.paranoid_jumps);
1512    }
1513
1514    #[test]
1515    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1516        use crate::bytecode::encode;
1517        use crate::{fingerprint_bf, AttestError};
1518
1519        let bytes = encode(&add_chunk());
1520        let mut bad = fingerprint_bf(&bytes);
1521        bad[0] ^= 0xff;
1522        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1523            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1524            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1525            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1526        }
1527    }
1528
1529    #[test]
1530    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1531        use crate::bytecode::encode;
1532        use crate::fingerprint_bf;
1533
1534        let chunk = add_chunk();
1535        let bytes = encode(&chunk);
1536        let digest = fingerprint_bf(&bytes);
1537        let rt = Runtime::with_attested(
1538            &bytes,
1539            digest,
1540            NativeTable::empty(),
1541            RuntimeConfig {
1542                workers: 1,
1543                quantum: 1_000,
1544                mailbox: MailboxConfig::DEFAULT,
1545                ..Default::default()
1546            },
1547        )?;
1548        let outcome = rt.spawn(0, &[])?.join();
1549        rt.shutdown();
1550        match outcome {
1551            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1552            other => Err(format!("expected 42, got {other:?}").into()),
1553        }
1554    }
1555
1556    #[test]
1557    fn untrusted_enables_paranoid_jumps_on_shared() -> Result<(), Box<dyn std::error::Error>> {
1558        // Default trust is Untrusted → Shared.paranoid_jumps must be true
1559        // even when the explicit config flag is false.
1560        let rt = Runtime::with_config(
1561            add_chunk(),
1562            RuntimeConfig {
1563                workers: 1,
1564                quantum: 1_000,
1565                mailbox: MailboxConfig::DEFAULT,
1566                trust: crate::bytecode::TrustLevel::Untrusted,
1567                paranoid_jumps: false,
1568                ..Default::default()
1569            },
1570        )?;
1571        assert!(rt.shared.paranoid_jumps);
1572        rt.shutdown();
1573        Ok(())
1574    }
1575}