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        finalize_host_awaits(&self.shared);
855        self.shared.timer.shutdown();
856        let (lock, cvar) = &self.shared.notify;
857        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
858            Ok(_g) => cvar.notify_all(),
859            Err(e) => super::error::report_fault(e),
860        }
861    }
862
863    /// Stop accepting new scheduling work, join every worker + the timer
864    /// thread, then finalize any flow still parked (mailbox, timer, injector,
865    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
866    /// instead of [`super::error::RuntimeError::Abandoned`].
867    ///
868    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
869    /// finalizes at the next loop check (cooperative preemption).
870    pub fn shutdown(mut self) {
871        self.request_shutdown();
872        for w in self.workers.drain(..) {
873            let _ = w.join();
874        }
875        if let Some(t) = self.timer_thread.take() {
876            let _ = t.join();
877        }
878        finalize_stranded(&self.shared);
879    }
880}
881
882fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
883    finalize_flow(
884        shared,
885        flow,
886        FlowOutcome::Failed("runtime shutdown".into()),
887        FlowExitReason::Shutdown,
888    );
889}
890
891fn finalize_host_awaits(shared: &Shared) {
892    match shared.host_awaits.drain_all() {
893        Ok(parked) => {
894            for p in parked {
895                finalize_shutdown_flow(shared, *p.flow);
896            }
897        }
898        Err(e) => super::error::report_fault(e),
899    }
900}
901
902/// After workers and the timer have stopped, take every remaining flow
903/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
904///
905/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
906fn finalize_stranded(shared: &Shared) {
907    finalize_host_awaits(shared);
908    for flow in shared.timer.drain() {
909        finalize_shutdown_flow(shared, *flow);
910    }
911    for _ in 0..8 {
912        let mut n = 0usize;
913        for flow in shared.injector.drain() {
914            finalize_shutdown_flow(shared, *flow);
915            n += 1;
916        }
917        for stealer in &shared.stealers {
918            for flow in stealer.drain() {
919                finalize_shutdown_flow(shared, *flow);
920                n += 1;
921            }
922        }
923        for (_id, mailbox) in shared.directory.snapshot() {
924            match mailbox.take_parked() {
925                Ok(Some(flow)) => {
926                    finalize_shutdown_flow(shared, *flow);
927                    n += 1;
928                }
929                Ok(None) => {}
930                Err(e) => super::error::report_fault(e),
931            }
932            match mailbox.close() {
933                Ok(senders) => {
934                    for sender in senders {
935                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
936                            super::error::report_fault(e);
937                        }
938                        finalize_shutdown_flow(shared, sender);
939                        n += 1;
940                    }
941                }
942                Err(e) => super::error::report_fault(e),
943            }
944        }
945        if n == 0 {
946            break;
947        }
948    }
949}
950
951impl Drop for Runtime {
952    fn drop(&mut self) {
953        if !self.shared.shutdown.load(Ordering::Acquire) {
954            self.request_shutdown();
955        }
956    }
957}
958
959/// A convenience Pid constructor for embedders that stored a raw `u64`
960/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
961/// call APIs that take one.
962pub fn flow_id_from_u64(raw: u64) -> FlowId {
963    FlowId(raw)
964}
965
966/// Why [`Runtime::send`] could not deliver a hop.
967#[derive(Debug, Clone, PartialEq, Eq)]
968pub enum SendError {
969    NoSuchFlow(FlowId),
970    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
971    NotAHop {
972        got: &'static str,
973    },
974    /// Target inbox is at one of its logical bounds
975    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
976    /// [`MailboxFullReason`].
977    MailboxFull {
978        flow: FlowId,
979        reason: MailboxFullReason,
980    },
981    /// Host hop authentication failed (payload Cap reissue).
982    Capability,
983    /// Directory / mailbox mutex poisoned — not "no such flow".
984    Unavailable,
985}
986
987impl std::fmt::Display for SendError {
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        match self {
990            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
991            SendError::NotAHop { got } => {
992                write!(f, "atomic hop requires Value::Message, got {got}")
993            }
994            SendError::MailboxFull { flow, reason } => {
995                write!(f, "mailbox full for {flow} ({reason})")
996            }
997            SendError::Capability => {
998                write!(f, "host send could not reissue a capability in the hop")
999            }
1000            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
1001        }
1002    }
1003}
1004
1005impl std::error::Error for SendError {}
1006
1007/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
1008/// the child. Host spawn passes `None` and mints a trusted root instead.
1009pub(crate) struct BytecodeSpawn<'a> {
1010    pub authority: &'a Cap,
1011    pub cell: &'a crate::bytecode::RevocationCell,
1012    pub quota: &'a super::quota::FlowQuota,
1013    pub requested_rights: CapRights,
1014}
1015
1016/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
1017/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
1018/// mailbox + completion channel), register it in the directory, and push
1019/// it onto the global injector for any worker to pick up.
1020///
1021/// Returns [`SpawnError`] on bad function index / VM init / directory
1022/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
1023/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
1024#[allow(clippy::too_many_arguments)]
1025pub(crate) fn spawn_on(
1026    shared: &Arc<Shared>,
1027    chunk: &Arc<Chunk>,
1028    natives: &Arc<NativeTable>,
1029    function: u32,
1030    args: &[Value],
1031    restart_policy: RestartPolicy,
1032    supervisor: Option<SupervisorLink>,
1033    parent: Option<FlowId>,
1034    bytecode: Option<BytecodeSpawn<'_>>,
1035) -> Result<FlowHandle, SpawnError> {
1036    shared.flow_limit.try_reserve()?;
1037    let id = match super::process::try_next_flow_id() {
1038        Ok(id) => id,
1039        Err(super::error::RuntimeError::FlowIdExhausted) => {
1040            shared.flow_limit.release();
1041            return Err(SpawnError::FlowIdExhausted);
1042        }
1043        Err(_) => {
1044            shared.flow_limit.release();
1045            return Err(SpawnError::Unavailable);
1046        }
1047    };
1048    let cell = match shared.caps.bind_flow(id) {
1049        Ok(c) => c,
1050        Err(_) => {
1051            shared.flow_limit.release();
1052            return Err(SpawnError::Unavailable);
1053        }
1054    };
1055    let authority = match bytecode {
1056        None => Cap::root(
1057            CapTarget::Flow(id.as_u64()),
1058            CapRights::ROOT,
1059            Some(NativeMask::full(natives.len())),
1060            cell.as_ref(),
1061        ),
1062        Some(ctx) => match super::spawn::exec_spawn_authority(
1063            ctx.authority,
1064            ctx.cell,
1065            ctx.quota,
1066            id.as_u64(),
1067            ctx.requested_rights,
1068            None,
1069            cell.as_ref(),
1070        ) {
1071            Ok(cap) => cap,
1072            Err(e) => {
1073                shared.flow_limit.release();
1074                let _ = shared.caps.revoke_flow(id);
1075                return Err(SpawnError::from(e));
1076            }
1077        },
1078    };
1079    let args = match grant_caps_in_args(shared, parent, id, args) {
1080        Ok(a) => a,
1081        Err(e) => {
1082            shared.flow_limit.release();
1083            let _ = shared.caps.revoke_flow(id);
1084            return Err(e);
1085        }
1086    };
1087    let gate = NativeGate::from_authority(
1088        &authority,
1089        Arc::clone(&cell),
1090        shared.caps.native_cell(),
1091        natives.len(),
1092    );
1093    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1094    let mut vm = match Vm::with_native_gate(
1095        chunk.clone(),
1096        natives.clone(),
1097        gate,
1098        function,
1099        args.as_slice(),
1100    ) {
1101        Ok(vm) => vm,
1102        Err(e) => {
1103            shared.flow_limit.release();
1104            let _ = shared.caps.revoke_flow(id);
1105            return Err(e.into());
1106        }
1107    };
1108    vm.set_paranoid_jumps(shared.paranoid_jumps);
1109    vm.set_memory_budget(Arc::clone(&shared.memory));
1110    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
1111        shared.flow_limit.release();
1112        let _ = shared.caps.revoke_flow(id);
1113        return Err(e.into());
1114    }
1115    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1116    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1117        super::error::report_fault(e);
1118        shared.flow_limit.release();
1119        let _ = shared.caps.revoke_flow(id);
1120        return Err(SpawnError::Unavailable);
1121    }
1122    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
1123        super::error::report_fault(e);
1124        let _ = shared.directory.unregister(id);
1125        shared.flow_limit.release();
1126        let _ = shared.caps.revoke_flow(id);
1127        return Err(SpawnError::Unavailable);
1128    }
1129    let (tx, rx) = super::oneshot::channel();
1130    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1131    flow.authority = authority;
1132    flow.cell = cell;
1133    flow.quota = quota;
1134    flow.supervisor = supervisor;
1135    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1136    shared.injector.push(flow);
1137    wake_workers(shared);
1138    Ok(FlowHandle { id, receiver: rx })
1139}
1140
1141fn grant_caps_in_args(
1142    shared: &Shared,
1143    parent: Option<FlowId>,
1144    child: FlowId,
1145    args: &[Value],
1146) -> Result<Vec<Value>, SpawnError> {
1147    let mut out = Vec::with_capacity(args.len());
1148    for arg in args {
1149        match arg {
1150            Value::Cap(id) => {
1151                let granted = match parent {
1152                    None => shared.caps.reissue_for(*id, child),
1153                    Some(p) => shared.caps.delegate(*id, p, child),
1154                };
1155                match granted {
1156                    Ok(cap) => out.push(Value::Cap(cap)),
1157                    Err(_) => return Err(SpawnError::InvalidCapability),
1158                }
1159            }
1160            other => out.push(other.clone()),
1161        }
1162    }
1163    Ok(out)
1164}
1165
1166pub(crate) fn wake_workers(shared: &Shared) {
1167    let (lock, cvar) = &shared.notify;
1168    match super::sync_lock::lock(lock, "wake_workers") {
1169        Ok(_g) => cvar.notify_one(),
1170        Err(e) => super::error::report_fault(e),
1171    }
1172}
1173
1174/// Signal shutdown and join any threads already started during construction
1175/// failure — keeps the "no orphan threads" contract of
1176/// [`Runtime::with_natives_and_config`].
1177fn abort_startup(
1178    shared: &Arc<Shared>,
1179    workers: Vec<std::thread::JoinHandle<()>>,
1180    timer: Option<std::thread::JoinHandle<()>>,
1181) {
1182    shared.shutdown.store(true, Ordering::Release);
1183    shared.timer.shutdown();
1184    let (lock, cvar) = &shared.notify;
1185    match super::sync_lock::lock(lock, "abort_startup") {
1186        Ok(_g) => cvar.notify_all(),
1187        Err(e) => super::error::report_fault(e),
1188    }
1189    for w in workers {
1190        let _ = w.join();
1191    }
1192    if let Some(t) = timer {
1193        let _ = t.join();
1194    }
1195}
1196
1197/// A `Send + Sync`, freely cloneable capability to spawn flows into a
1198/// [`Runtime`], detached from the `Runtime` value itself. Exists because
1199/// [`super::supervisor::Supervisor`] needs to respawn flows from a
1200/// background monitor thread whose lifetime isn't tied to the `Runtime`
1201/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
1202#[derive(Clone)]
1203pub struct RuntimeSpawner {
1204    pub(crate) shared: Arc<Shared>,
1205    pub(crate) chunk: Arc<Chunk>,
1206    pub(crate) natives: Arc<NativeTable>,
1207}
1208
1209impl RuntimeSpawner {
1210    pub fn spawn(
1211        &self,
1212        function: u32,
1213        args: &[Value],
1214        restart_policy: RestartPolicy,
1215    ) -> Result<FlowHandle, SpawnError> {
1216        spawn_on(
1217            &self.shared,
1218            &self.chunk,
1219            &self.natives,
1220            function,
1221            args,
1222            restart_policy,
1223            None,
1224            None,
1225            None,
1226        )
1227    }
1228
1229    pub(crate) fn spawn_linked(
1230        &self,
1231        function: u32,
1232        args: &[Value],
1233        restart_policy: RestartPolicy,
1234        supervisor: SupervisorLink,
1235    ) -> Result<FlowHandle, SpawnError> {
1236        spawn_on(
1237            &self.shared,
1238            &self.chunk,
1239            &self.natives,
1240            function,
1241            args,
1242            restart_policy,
1243            Some(supervisor),
1244            None,
1245            None,
1246        )
1247    }
1248
1249    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1250        self.shared.metrics.snapshot()
1251    }
1252
1253    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1254        super::finalize::request_kill(&self.shared, id, reason);
1255    }
1256}
1257
1258#[cfg(test)]
1259mod tests {
1260    use super::*;
1261    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1262    use crate::scheduler::FlowOutcome;
1263    use std::time::Duration;
1264
1265    fn add_chunk() -> Chunk {
1266        let mut b = ChunkBuilder::new("test");
1267        b.begin_function("main", 0, 2);
1268        b.emit_load_imm(0, 41);
1269        b.emit_load_imm(1, 1);
1270        b.emit_binop(Opcode::Add, 0, 0, 1);
1271        b.emit_return(0);
1272        b.finish()
1273    }
1274
1275    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
1276    /// makes "still running" an observable state from the host thread.
1277    fn sleep_then_return_chunk(millis: i32) -> Chunk {
1278        let mut b = ChunkBuilder::new("test");
1279        b.begin_function("main", 0, 2);
1280        b.emit_load_imm(0, millis);
1281        b.emit_sleep(0);
1282        b.emit_load_imm(0, 7);
1283        b.emit_return(0);
1284        b.finish()
1285    }
1286
1287    /// The host thread must be able to ask "done yet?" and to wait under a
1288    /// bound *it* chooses, instead of surrendering itself to `join` for
1289    /// however long the bytecode decides to take.
1290    #[test]
1291    fn polling_and_bounded_waits_never_commit_the_host_thread(
1292    ) -> Result<(), Box<dyn std::error::Error>> {
1293        const FLOW_SLEEP: i32 = 150;
1294        let rt = Runtime::with_config(
1295            sleep_then_return_chunk(FLOW_SLEEP),
1296            RuntimeConfig {
1297                workers: 1,
1298                quantum: 1_000,
1299                mailbox: MailboxConfig::DEFAULT,
1300                ..Default::default()
1301            },
1302        )?;
1303        let handle = rt.spawn(0, &[])?;
1304
1305        // The flow cannot possibly be finished yet: it has to be picked up
1306        // and then sleep. A poll must say so without waiting.
1307        if let Some(outcome) = handle.try_join() {
1308            rt.shutdown();
1309            return Err(format!("try_join answered too early: {outcome:?}").into());
1310        }
1311
1312        // A bound well below the flow's sleep must expire and hand control
1313        // back, not block until the flow happens to finish.
1314        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1315            rt.shutdown();
1316            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1317        }
1318
1319        // A generous bound collects the real outcome through the same
1320        // (non-consuming) handle.
1321        let outcome = handle.join_timeout(Duration::from_secs(10));
1322        rt.shutdown();
1323        match outcome {
1324            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1325            other => Err(format!("unexpected outcome: {other:?}").into()),
1326        }
1327    }
1328
1329    #[test]
1330    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1331        let rt = Runtime::with_config(
1332            add_chunk(),
1333            RuntimeConfig {
1334                workers: 1,
1335                quantum: 1_000,
1336                mailbox: MailboxConfig::DEFAULT,
1337                ..Default::default()
1338            },
1339        )?;
1340        let outcome = rt.spawn(0, &[])?.join();
1341        rt.shutdown();
1342        match outcome {
1343            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1344            other => Err(format!("unexpected outcome: {other:?}").into()),
1345        }
1346    }
1347
1348    fn receive_forever_chunk() -> Chunk {
1349        let mut b = ChunkBuilder::new("recv");
1350        b.begin_function("main", 0, 1);
1351        b.emit_receive(0);
1352        b.emit_return(0);
1353        b.finish()
1354    }
1355
1356    #[test]
1357    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1358        let rt = Runtime::with_config(
1359            receive_forever_chunk(),
1360            RuntimeConfig {
1361                workers: 1,
1362                quantum: 1_000,
1363                mailbox: MailboxConfig::DEFAULT,
1364                ..Default::default()
1365            },
1366        )?;
1367        let handle = rt.spawn(0, &[])?;
1368        rt.kill(handle.id())?;
1369        let outcome = handle.join();
1370        rt.shutdown();
1371        assert!(
1372            matches!(outcome, FlowOutcome::Failed(_)),
1373            "kill must fail the joiner, got {outcome:?}"
1374        );
1375        Ok(())
1376    }
1377
1378    #[test]
1379    fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
1380        let rt = Runtime::with_config(
1381            receive_forever_chunk(),
1382            RuntimeConfig {
1383                workers: 1,
1384                quantum: 1_000,
1385                mailbox: MailboxConfig::DEFAULT,
1386                ..Default::default()
1387            },
1388        )?;
1389        let handle = rt.spawn(0, &[])?;
1390        std::thread::sleep(Duration::from_millis(30));
1391        rt.shutdown();
1392        match handle.join() {
1393            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1394            other => Err(format!("expected shutdown finalize, got {other:?}").into()),
1395        }
1396    }
1397
1398    #[test]
1399    fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1400        let rt = Runtime::with_config(
1401            sleep_then_return_chunk(60_000),
1402            RuntimeConfig {
1403                workers: 1,
1404                quantum: 1_000,
1405                mailbox: MailboxConfig::DEFAULT,
1406                ..Default::default()
1407            },
1408        )?;
1409        let handle = rt.spawn(0, &[])?;
1410        std::thread::sleep(Duration::from_millis(30));
1411        rt.shutdown();
1412        match handle.join() {
1413            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1414            other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
1415        }
1416    }
1417
1418    #[test]
1419    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1420        let rt = Runtime::with_config(
1421            receive_forever_chunk(),
1422            RuntimeConfig {
1423                workers: 1,
1424                quantum: 1_000,
1425                mailbox: MailboxConfig::DEFAULT,
1426                max_flows: 1,
1427                ..Default::default()
1428            },
1429        )?;
1430        let first = rt.spawn(0, &[])?;
1431        let second = rt.spawn(0, &[]);
1432        rt.kill(first.id())?;
1433        let _ = first.join();
1434        // After finalize, the reserved slot must be free again.
1435        let third = rt.spawn(0, &[])?;
1436        rt.kill(third.id())?;
1437        let _ = third.join();
1438        rt.shutdown();
1439        match second {
1440            Err(SpawnError::FlowLimit { current, max }) => {
1441                assert_eq!(current, 1);
1442                assert_eq!(max, 1);
1443                Ok(())
1444            }
1445            other => Err(format!(
1446                "expected FlowLimit, got {}",
1447                match &other {
1448                    Ok(_) => "Ok(handle)".into(),
1449                    Err(e) => format!("Err({e})"),
1450                }
1451            )
1452            .into()),
1453        }
1454    }
1455
1456    /// Ask must not park waiting for a reply when DropNewest discarded the request.
1457    #[test]
1458    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1459        use crate::bytecode::{Message, Program};
1460        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1461
1462        let mut program = Program::new("ask-drop-newest");
1463        let busy = program.function("busy", 0, |f| {
1464            // Stay alive without spinning the worker: sleep loop.
1465            let loop_lbl = f.label();
1466            f.bind(loop_lbl);
1467            let ms = f.load_i32(50);
1468            f.sleep(ms);
1469            f.jump(loop_lbl);
1470        });
1471        let asker = program.function("asker", 1, |f| {
1472            let server = f.reg(0);
1473            let z = f.load_i32(0);
1474            let req = f.hop_fresh(1, z);
1475            let reply = f.ask(server, req);
1476            f.return_(reply);
1477        });
1478        let chunk = program.build();
1479
1480        let cap = MailboxCapacity::new(1).ok_or("cap")?;
1481        let rt = Runtime::with_natives_and_config(
1482            chunk,
1483            crate::std_native_table(),
1484            RuntimeConfig {
1485                // Busy target must not monopolize scheduling or Ask never runs.
1486                workers: 2,
1487                quantum: 1_000,
1488                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1489                ..Default::default()
1490            },
1491        )?;
1492
1493        let server = rt.spawn(busy, &[])?;
1494        // Fill the only slot so the subsequent Ask is DropNewest'd.
1495        rt.send(
1496            server.id(),
1497            Value::Message(Message::request(1, 9, Value::Int(1))),
1498        )?;
1499        let server_cap = rt.mint_cap(server.id())?;
1500        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1501        let outcome = ask.join_timeout(Duration::from_secs(3));
1502        rt.kill(server.id())?;
1503        let _ = server.join_timeout(Duration::from_millis(500));
1504        rt.shutdown();
1505
1506        match outcome {
1507            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1508            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1509        }
1510    }
1511
1512    #[test]
1513    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1514        use crate::bytecode::Program;
1515
1516        let mut program = Program::new("ask-limit");
1517        let silent = program.function("silent", 0, |f| {
1518            // Accept the request hop but never reply.
1519            let _req = f.receive();
1520            let loop_lbl = f.label();
1521            f.bind(loop_lbl);
1522            let ms = f.load_i32(50);
1523            f.sleep(ms);
1524            f.jump(loop_lbl);
1525        });
1526        let asker = program.function("asker", 1, |f| {
1527            let server = f.reg(0);
1528            let z = f.load_i32(0);
1529            let req = f.hop_fresh(1, z);
1530            let reply = f.ask(server, req);
1531            f.return_(reply);
1532        });
1533        let chunk = program.build();
1534
1535        let rt = Runtime::with_natives_and_config(
1536            chunk,
1537            crate::std_native_table(),
1538            RuntimeConfig {
1539                workers: 2,
1540                quantum: 1_000,
1541                mailbox: MailboxConfig::DEFAULT,
1542                max_ask_waits: 1,
1543                ..Default::default()
1544            },
1545        )?;
1546
1547        let server = rt.spawn(silent, &[])?;
1548        let server_cap = rt.mint_cap(server.id())?;
1549        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1550        // Give the first Ask time to park before the second tries.
1551        std::thread::sleep(Duration::from_millis(30));
1552        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1553        let second_out = second.join_timeout(Duration::from_secs(2));
1554        rt.kill(server.id())?;
1555        let _ = first.join_timeout(Duration::from_millis(500));
1556        let _ = server.join_timeout(Duration::from_millis(500));
1557        rt.shutdown();
1558
1559        match second_out {
1560            Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1561            other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1562        }
1563    }
1564
1565    // HostAwait E2E coverage lives in `host_await::runtime_tests`.
1566
1567    #[cfg(feature = "jit")]
1568    #[test]
1569    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1570        use crate::JitConfig;
1571
1572        let rt = Runtime::with_config(
1573            add_chunk(),
1574            RuntimeConfig {
1575                workers: 1,
1576                quantum: 1_000,
1577                mailbox: MailboxConfig::DEFAULT,
1578                jit: JitConfig {
1579                    enabled: true,
1580                    hot_threshold: 1,
1581                },
1582                ..Default::default()
1583            },
1584        )?;
1585        let outcome = rt.spawn(0, &[])?.join();
1586        rt.shutdown();
1587        match outcome {
1588            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1589            other => Err(format!("unexpected outcome: {other:?}").into()),
1590        }
1591    }
1592
1593    #[test]
1594    fn sandbox_enables_process_wide_relation_caps() {
1595        let config = RuntimeConfig::sandbox();
1596        assert_eq!(config.max_flows, 256);
1597        assert_eq!(config.max_ask_waits, 128);
1598        assert_eq!(config.max_host_awaits, 128);
1599        assert_eq!(config.max_links, 1024);
1600        assert_eq!(config.max_monitors, 1024);
1601        assert_eq!(config.max_registry_names, 256);
1602        assert!(config.paranoid_jumps);
1603        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1604    }
1605
1606    #[test]
1607    fn default_remains_unlimited_for_relation_caps() {
1608        let config = RuntimeConfig::default();
1609        assert_eq!(config.max_links, 0);
1610        assert_eq!(config.max_monitors, 0);
1611        assert_eq!(config.max_registry_names, 0);
1612        assert!(!config.paranoid_jumps);
1613    }
1614
1615    #[test]
1616    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1617        use crate::bytecode::encode;
1618        use crate::{fingerprint_bf, AttestError};
1619
1620        let bytes = encode(&add_chunk());
1621        let mut bad = fingerprint_bf(&bytes);
1622        bad[0] ^= 0xff;
1623        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1624            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1625            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1626            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1627        }
1628    }
1629
1630    #[test]
1631    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1632        use crate::bytecode::encode;
1633        use crate::fingerprint_bf;
1634
1635        let chunk = add_chunk();
1636        let bytes = encode(&chunk);
1637        let digest = fingerprint_bf(&bytes);
1638        let rt = Runtime::with_attested(
1639            &bytes,
1640            digest,
1641            NativeTable::empty(),
1642            RuntimeConfig {
1643                workers: 1,
1644                quantum: 1_000,
1645                mailbox: MailboxConfig::DEFAULT,
1646                ..Default::default()
1647            },
1648        )?;
1649        let outcome = rt.spawn(0, &[])?.join();
1650        rt.shutdown();
1651        match outcome {
1652            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1653            other => Err(format!("expected 42, got {other:?}").into()),
1654        }
1655    }
1656
1657    #[test]
1658    fn untrusted_enables_paranoid_jumps_on_shared() -> Result<(), Box<dyn std::error::Error>> {
1659        // Default trust is Untrusted → Shared.paranoid_jumps must be true
1660        // even when the explicit config flag is false.
1661        let rt = Runtime::with_config(
1662            add_chunk(),
1663            RuntimeConfig {
1664                workers: 1,
1665                quantum: 1_000,
1666                mailbox: MailboxConfig::DEFAULT,
1667                trust: crate::bytecode::TrustLevel::Untrusted,
1668                paranoid_jumps: false,
1669                ..Default::default()
1670            },
1671        )?;
1672        assert!(rt.shared.paranoid_jumps);
1673        rt.shutdown();
1674        Ok(())
1675    }
1676}