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::{RuntimeError, SpawnError};
10use super::finalize::finalize_flow;
11use super::handle::FlowHandle;
12use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
13use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot};
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. `0` is raised to `1`: a runtime
39    /// with no worker cannot run a flow.
40    pub workers: usize,
41    /// Instructions a flow runs before being preempted back to the
42    /// scheduler even if it never hits `Yield`. `0` is raised to `1`.
43    /// A zero slice returns `Yield` without executing anything, and the
44    /// worker would requeue that flow forever.
45    pub quantum: u32,
46    /// Memory + overflow contract applied to **every** flow mailbox
47    /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
48    /// See [`MailboxConfig`] / `docs/mailbox.md`.
49    pub mailbox: MailboxConfig,
50    /// Hard cap on concurrently live flows (`0` = unlimited).
51    /// Checked on every host and bytecode `spawn`.
52    pub max_flows: u32,
53    /// Hard cap on outstanding `Ask` / `AskTimeout` waiters process-wide
54    /// (`0` = unlimited). Each asker holds at most one wait; this bounds the
55    /// total index size when many flows park against a silent target.
56    /// See [`crate::docs::security`] (DoS) and [`Self::sandbox`].
57    pub max_ask_waits: u32,
58    /// Hard cap on outstanding `HostAwait` parkers process-wide
59    /// (`0` = unlimited). Each flow holds at most one await.
60    pub max_host_awaits: u32,
61    /// Hard cap on live process-wide links (`0` = unlimited).
62    ///
63    /// Accounting is performed by the link store itself, under
64    /// the same synchronization that protects the link table.
65    pub max_links: u32,
66    /// Hard cap on live process-wide monitors (`0` = unlimited).
67    ///
68    /// Accounting is performed by the monitor store itself.
69    pub max_monitors: u32,
70    /// Hard cap on live process-wide registry names (`0` = unlimited).
71    ///
72    /// The registry store counts only successfully registered names.
73    pub max_registry_names: u32,
74    /// Host async bridge for [`crate::Opcode::HostAwait`]. `None` fails
75    /// any `HostAwait` closed. Not a `CallNative` / std-native slot.
76    pub host_await: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
77    /// `0` = disabled. When set, [`Runtime::deliver_frame`] ignores duplicate
78    /// `(sender, request_id)` pairs within the window (at-least-once wire).
79    pub remote_dedup_window: u32,
80    /// Host queue for [`crate::Opcode::SendRemote`]. `None` fails that opcode.
81    /// Byteflow does not open sockets; the embedder drains the bridge.
82    pub distribution: Option<Arc<super::distribution::DistributionBridge>>,
83    /// Process-wide memory ceiling for heap charges (`Str` / `Bytes`
84    /// register stores and shared [`crate::HeapStr`] / [`crate::HeapBytes`]).
85    /// Independent of per-flow [`crate::QuotaConfig::mem_limit`] and mailbox
86    /// byte budgets. Default: 256 MiB.
87    pub max_runtime_bytes: usize,
88    /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
89    /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
90    pub trust: crate::bytecode::TrustLevel,
91    /// Where bytecode `print` (native index 0) writes when using
92    /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
93    pub output: Arc<dyn crate::OutputSink>,
94    /// Scheduler diagnostics (`ask`, `finalize`, …). `None` keeps the
95    /// `BYTEFLOW_LOG` stderr path and adds no collector. The sink is called
96    /// inline and must not block or panic.
97    pub log: Option<Arc<dyn crate::log::LogSink>>,
98    /// Per-flow CPU / memory / spawn-send rate budgets.
99    pub quota: super::quota::QuotaConfig,
100    /// Optional security audit sink (capability / quota / module denials).
101    /// Independent of [`Self::log`]; never receives full CapId tokens.
102    pub security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
103    /// Authority minted for host [`Runtime::spawn`] (not bytecode `Spawn`).
104    ///
105    /// Default [`RootAuthorityPolicy::TrustedHost`] preserves historical
106    /// ROOT + full native mask. [`Self::sandbox`] does **not** change this —
107    /// use [`Runtime::spawn_untrusted`] or set this field explicitly.
108    pub root_authority: RootAuthorityPolicy,
109    /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
110    #[cfg(feature = "jit")]
111    pub jit: JitConfig,
112}
113
114/// Initial Cap rights for host-spawned root flows.
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116pub enum RootAuthorityPolicy {
117    /// [`CapRights::ROOT`] + full native mask (historical host spawn).
118    #[default]
119    TrustedHost,
120    /// Flow rights without [`CapRights::NATIVE`]; empty native mask.
121    Restricted,
122    /// [`CapRights::NONE`] + empty native mask (minimum authority).
123    Untrusted,
124}
125
126impl RootAuthorityPolicy {
127    fn mint(self, flow: u64, natives_len: usize, cell: &crate::bytecode::RevocationCell) -> Cap {
128        match self {
129            Self::TrustedHost => Cap::root(
130                CapTarget::Flow(flow),
131                CapRights::ROOT,
132                Some(NativeMask::full(natives_len)),
133                cell,
134            ),
135            Self::Restricted => Cap::root(
136                CapTarget::Flow(flow),
137                CapRights::from_bits(CapRights::FLOW.bits() & !CapRights::NATIVE.bits()),
138                Some(NativeMask::empty(natives_len)),
139                cell,
140            ),
141            Self::Untrusted => Cap::root(
142                CapTarget::Flow(flow),
143                CapRights::NONE,
144                Some(NativeMask::empty(natives_len)),
145                cell,
146            ),
147        }
148    }
149}
150
151/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
152#[cfg(feature = "jit")]
153#[derive(Clone, Debug)]
154pub struct JitConfig {
155    /// When true, workers attempt compiled traces before interpreting.
156    pub enabled: bool,
157    /// How many times a `(function, pc)` pair must run before compilation.
158    pub hot_threshold: u32,
159}
160
161#[cfg(feature = "jit")]
162impl Default for JitConfig {
163    fn default() -> Self {
164        JitConfig {
165            enabled: false,
166            hot_threshold: crate::jit::HOT_THRESHOLD,
167        }
168    }
169}
170
171/// Logical CPU count for [`RuntimeConfig::default`], via `std` only.
172fn default_worker_count() -> usize {
173    match std::thread::available_parallelism() {
174        Ok(n) => n.get().max(1),
175        Err(_) => 1,
176    }
177}
178
179impl Default for RuntimeConfig {
180    fn default() -> Self {
181        RuntimeConfig {
182            workers: default_worker_count(),
183            quantum: DEFAULT_QUANTUM,
184            mailbox: MailboxConfig::DEFAULT,
185            max_flows: 0,
186            max_ask_waits: 0,
187            max_host_awaits: 0,
188            max_links: 0,
189            max_monitors: 0,
190            max_registry_names: 0,
191            host_await: None,
192            remote_dedup_window: 0,
193            distribution: None,
194            max_runtime_bytes: 256 * 1024 * 1024,
195            trust: crate::bytecode::TrustLevel::Untrusted,
196            output: Arc::new(crate::output::NullSink),
197            log: None,
198            quota: super::quota::QuotaConfig::default(),
199            security_audit: None,
200            root_authority: RootAuthorityPolicy::TrustedHost,
201            #[cfg(feature = "jit")]
202            jit: JitConfig::default(),
203        }
204    }
205}
206
207impl RuntimeConfig {
208    /// Opt-in sandbox profile for untrusted modules.
209    ///
210    /// Default [`RuntimeConfig`] stays permissive (`max_* = 0` unlimited,
211    /// [`QuotaConfig::permissive`](super::quota::QuotaConfig::permissive)).
212    /// This profile enables fail-closed process-wide caps and tight
213    /// per-flow budgets. Trust defaults to [`TrustLevel::Untrusted`]
214    /// (inherited from [`Default`]) so Cap/Pid/Message constants are
215    /// rejected at verify time.
216    ///
217    /// Does **not** change [`Self::root_authority`]: host [`Runtime::spawn`]
218    /// still mints trusted ROOT unless you set the policy or call
219    /// [`Runtime::spawn_untrusted`].
220    ///
221    /// Limits (starting point — tune under load):
222    /// - `max_flows = 128` live flows
223    /// - `max_ask_waits = 64`, `max_host_awaits = 128`
224    /// - `max_runtime_bytes = 64 MiB` process heap accounting
225    /// - mailbox: 256 hops / 4 MiB / Reject ( [`MailboxConfig::DEFAULT`] )
226    /// - per-flow: [`QuotaConfig::sandbox`](super::quota::QuotaConfig::sandbox)
227    pub fn sandbox() -> Self {
228        RuntimeConfig {
229            quota: super::quota::QuotaConfig::sandbox(),
230            max_flows: 128,
231            max_ask_waits: 64,
232            max_host_awaits: 128,
233            max_links: 1024,
234            max_monitors: 1024,
235            max_registry_names: 256,
236            max_runtime_bytes: 64 * 1024 * 1024,
237            trust: crate::bytecode::TrustLevel::Untrusted,
238            ..Default::default()
239        }
240    }
241
242    /// Same process-wide caps as [`Self::sandbox`], but
243    /// [`TrustLevel::Restricted`]: still no Cap/Pid/Message in the constant
244    /// pool; host may grant Caps / natives after admission.
245    pub fn sandbox_restricted() -> Self {
246        RuntimeConfig {
247            trust: crate::bytecode::TrustLevel::Restricted,
248            ..Self::sandbox()
249        }
250    }
251
252    /// Stable identity of the security-relevant knobs on this config.
253    pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
254        super::sandbox::policy_fingerprint(self)
255    }
256
257    /// True when at least one process-wide sandbox ceiling is armed
258    /// (`max_flows` / ask / host-await / runtime bytes tighter than the
259    /// permissive defaults). Does not imply the chunk was verified as
260    /// Untrusted — check [`Self::trust`] separately.
261    pub fn applies_sandbox_caps(&self) -> bool {
262        self.max_flows != 0
263            || self.max_ask_waits != 0
264            || self.max_host_awaits != 0
265            || self.max_links != 0
266            || self.max_monitors != 0
267            || self.max_registry_names != 0
268            || self.max_runtime_bytes < 256 * 1024 * 1024
269            || self.quota.cpu_budget < super::quota::QuotaConfig::permissive().cpu_budget
270    }
271}
272
273/// State shared by every worker thread and the timer thread. Everything in
274/// here is either internally synchronized (`Injector`, `Directory`,
275/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
276/// construction (`stealers`, `quantum`) — there is no top-level lock
277/// covering the whole runtime, by design: a global lock is exactly what an
278/// M:N scheduler exists to avoid.
279pub struct Shared {
280    pub(crate) injector: Injector<Box<Flow>>,
281    pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
282    /// FlowId → mailbox (delivery after Cap resolution).
283    pub(crate) directory: Directory,
284    /// CapId → { holder, target, rights, native_mask, epoch } (FlowCap).
285    pub(crate) caps: super::capability::CapTable,
286    pub(crate) timer: Arc<TimerWheel>,
287    pub(crate) notify: (Mutex<()>, Condvar),
288    pub(crate) metrics: RuntimeMetrics,
289    pub(crate) shutdown: AtomicBool,
290    pub(crate) quantum: u32,
291    pub(crate) mailbox: MailboxConfig,
292    /// Atomic live-flow budget (`max_flows == 0` → unlimited).
293    pub(crate) flow_limit: super::flow_limit::FlowLimit,
294    pub(crate) memory: Arc<crate::MemoryBudget>,
295    pub(crate) quota: super::quota::QuotaConfig,
296    pub(crate) quotas: super::quota::QuotaTable,
297    pub(crate) monitors: super::monitor::MonitorStore,
298    pub(crate) links: super::link::LinkStore,
299    pub(crate) registry: super::registry::RegistryStore,
300    pub(crate) kill_signals: super::finalize::KillSignals,
301    pub(crate) trap_exits: super::finalize::TrapExitFlags,
302    pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
303    pub(crate) ask_waits: super::finalize::AskWaitIndex,
304    /// In-flight `Opcode::HostAwait` tickets. The flow stays on a worker
305    /// or in its mailbox; completion arrives as a host hop.
306    pub(crate) host_awaits: super::host_await::HostAwaitIndex,
307    /// Host async bridge (`None` ⇒ HostAwait fails closed).
308    pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
309    /// Recorded order for host completions. `None` delivers immediately.
310    pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
311    /// Host `fail` text the worker reads before committing a success.
312    pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
313    /// `SendRemote` queue. `None` fails the opcode.
314    pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
315    /// Optional replay filter for inbound remote frames.
316    pub(crate) remote_dedup: Option<Arc<super::distribution::RemoteFrameDedup>>,
317    /// Embedder copy of scheduler diagnostics. `None` leaves stderr gating
318    /// in [`crate::log`] unchanged.
319    pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
320    /// One named table per flow. Empty until `TableOpen`.
321    pub(crate) tables: super::table::FlowTables,
322    /// Supervisors started by bytecode `StartSupervisor`. Joined from
323    /// [`Runtime::shutdown`] after workers stop.
324    pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
325    /// Correlation ids for host `Runtime::send` when `request_id == 0`.
326    /// Starts at 1; `0` stays the unset sentinel.
327    pub(crate) host_next_request_id: AtomicU64,
328    /// Shared trace JIT state (`feature = "jit"`).
329    #[cfg(feature = "jit")]
330    pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
331    /// Sandbox observability (host-only; bytecode cannot mutate).
332    pub(crate) security: Arc<super::sandbox::SecurityCounters>,
333    pub(crate) security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
334    pub(crate) policy: super::sandbox::PolicyFingerprint,
335    pub(crate) trust: crate::bytecode::TrustLevel,
336    pub(crate) root_authority: RootAuthorityPolicy,
337}
338
339/// A running Byteflow runtime: worker pool + timer thread over one shared
340/// [`Chunk`].
341///
342/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
343/// FlowCap resolution, supervised restarts). Optional trace JIT when built
344/// with `feature = "jit"` and enabled in `RuntimeConfig`'s `jit` field.
345///
346/// Construct with [`Runtime::new`] (no natives) or
347/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
348/// [`crate::std_native_table`].
349pub struct Runtime {
350    shared: Arc<Shared>,
351    chunk: Arc<Chunk>,
352    natives: Arc<NativeTable>,
353    workers: Vec<JoinHandle<()>>,
354    timer_thread: Option<JoinHandle<()>>,
355    trust: crate::bytecode::TrustLevel,
356}
357
358impl Runtime {
359    /// Convenience constructor for chunks that never call out through
360    /// `Opcode::CallNative`. Equivalent to
361    /// `Runtime::with_natives(chunk, NativeTable::empty())`.
362    ///
363    /// Returns [`SpawnError`] instead of panicking: verify failures and OS
364    /// thread-spawn refusals are category-A errors (see
365    /// [`docs::error_model`](crate::docs::error_model)).
366    pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
367        Self::with_config(chunk, RuntimeConfig::default())
368    }
369
370    /// Construct a runtime whose flows can call into `natives` via
371    /// `Opcode::CallNative` — the host FFI boundary.
372    pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
373        Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
374    }
375
376    pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
377        Self::with_natives_and_config(chunk, NativeTable::empty(), config)
378    }
379
380    /// Decode a `.bf` buffer only if its integrity fingerprint matches
381    /// `expected_digest`, then verify and start the runtime.
382    ///
383    /// Digest mismatch / decode failure → [`SpawnError::Attestation`].
384    /// Semantic verify failure → [`SpawnError::VerifyFailed`].
385    pub fn with_attested(
386        bytes: &[u8],
387        expected_digest: [u8; 32],
388        natives: Arc<NativeTable>,
389        config: RuntimeConfig,
390    ) -> Result<Self, SpawnError> {
391        let chunk =
392            crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
393        Self::with_natives_and_config(chunk, natives, config)
394    }
395
396    /// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
397    /// using [`RuntimeConfig::output`] for the `print` native.
398    pub fn with_std_natives_and_config(
399        chunk: Chunk,
400        config: RuntimeConfig,
401    ) -> Result<Self, SpawnError> {
402        Self::with_natives_and_config(
403            chunk,
404            crate::std_native_table_with(Arc::clone(&config.output)),
405            config,
406        )
407    }
408
409    /// Verify `chunk`, spawn the worker pool + timer thread, and return a
410    /// live [`Runtime`].
411    ///
412    /// Failures here mean the runtime was **never** started (no orphan
413    /// threads): either the bytecode is invalid
414    /// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
415    /// ([`SpawnError::ThreadSpawnFailed`]). Partial spawn failure rolls
416    /// back: already-started workers/timer are shut down and joined before
417    /// the error is returned.
418    pub fn with_natives_and_config(
419        chunk: Chunk,
420        natives: Arc<NativeTable>,
421        config: RuntimeConfig,
422    ) -> Result<Self, SpawnError> {
423        if let Err(err) = crate::bytecode::verify_with(
424            &chunk,
425            crate::bytecode::VerifyConfig {
426                trust: config.trust,
427            },
428        ) {
429            if let Some(sink) = config.security_audit.as_ref() {
430                sink.record(&super::sandbox::SecurityEvent::ModuleRejected {
431                    reason: "verify_failed",
432                });
433            }
434            return Err(SpawnError::VerifyFailed(err));
435        }
436        let chunk = Arc::new(chunk);
437        let workers_n = config.workers.max(1);
438        let quantum = config.quantum.max(1);
439
440        let locals: Vec<LocalDeque<Box<Flow>>> =
441            (0..workers_n).map(|_| LocalDeque::new()).collect();
442        let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
443
444        #[cfg(feature = "jit")]
445        let jit = if config.jit.enabled {
446            Some(super::jit::new_runtime(
447                chunk.clone(),
448                config.jit.hot_threshold,
449            ))
450        } else {
451            None
452        };
453
454        let shared = Arc::new(Shared {
455            injector: Injector::new(),
456            stealers,
457            directory: Directory::new(),
458            caps: super::capability::CapTable::new(),
459            timer: TimerWheel::new(),
460            notify: (Mutex::new(()), Condvar::new()),
461            metrics: RuntimeMetrics::default(),
462            shutdown: AtomicBool::new(false),
463            quantum,
464            mailbox: config.mailbox,
465            flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
466            memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
467            quota: config.quota,
468            quotas: super::quota::QuotaTable::new(),
469            monitors: super::monitor::MonitorStore::new(config.max_monitors),
470            links: super::link::LinkStore::new(config.max_links),
471            registry: super::registry::RegistryStore::new(config.max_registry_names),
472            kill_signals: super::finalize::KillSignals::new(),
473            trap_exits: super::finalize::TrapExitFlags::new(),
474            waiting_send_at: super::finalize::WaitingSendIndex::new(),
475            ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
476            host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
477            host_await_bridge: config.host_await.clone(),
478            host_replay: Mutex::new(None),
479            host_await_failures: super::host_await::HostAwaitFailures::new(),
480            distribution: config.distribution.clone(),
481            remote_dedup: if config.remote_dedup_window == 0 {
482                None
483            } else {
484                Some(super::distribution::RemoteFrameDedup::new(
485                    config.remote_dedup_window as usize,
486                ))
487            },
488            log_sink: config.log.clone(),
489            tables: super::table::FlowTables::new(),
490            flow_supervisors: Mutex::new(Vec::new()),
491            host_next_request_id: AtomicU64::new(1),
492            #[cfg(feature = "jit")]
493            jit,
494            security: Arc::new(super::sandbox::SecurityCounters::default()),
495            security_audit: config.security_audit.clone(),
496            policy: config.policy_fingerprint(),
497            trust: config.trust,
498            root_authority: config.root_authority,
499        });
500
501        let mut workers = Vec::with_capacity(workers_n);
502        for local in locals {
503            let shared_w = shared.clone();
504            match std::thread::Builder::new()
505                .name("byteflow-worker".into())
506                .spawn(move || worker::run_worker(shared_w, local))
507            {
508                Ok(handle) => workers.push(handle),
509                Err(e) => {
510                    abort_startup(&shared, workers, None);
511                    return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
512                }
513            }
514        }
515
516        let shared_timer = shared.clone();
517        let timer_thread = match std::thread::Builder::new()
518            .name("byteflow-timer".into())
519            .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
520        {
521            Ok(handle) => handle,
522            Err(e) => {
523                abort_startup(&shared, workers, None);
524                return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
525            }
526        };
527
528        Ok(Runtime {
529            shared,
530            chunk,
531            natives,
532            workers,
533            timer_thread: Some(timer_thread),
534            trust: config.trust,
535        })
536    }
537
538    /// Spawn a top-level flow starting at `function` in this runtime's
539    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
540    ///
541    /// Host authority follows [`RuntimeConfig::root_authority`] (default
542    /// trusted ROOT). For untrusted admission see [`Self::spawn_untrusted`].
543    ///
544    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
545    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
546        spawn_on(
547            &self.shared,
548            &self.chunk,
549            &self.natives,
550            function,
551            args,
552            RestartPolicy::Never,
553            None,
554            None,
555            None,
556            None,
557        )
558    }
559
560    /// Like [`Self::spawn`], but forces [`RootAuthorityPolicy::Untrusted`]
561    /// (no Cap rights, empty native mask) regardless of config.
562    pub fn spawn_untrusted(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
563        spawn_on(
564            &self.shared,
565            &self.chunk,
566            &self.natives,
567            function,
568            args,
569            RestartPolicy::Never,
570            None,
571            None,
572            None,
573            Some(RootAuthorityPolicy::Untrusted),
574        )
575    }
576
577    /// A cheap, `Send + Sync` handle that can spawn flows into this
578    /// runtime from any thread, independent of `Runtime`'s own lifetime
579    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
580    pub fn spawner(&self) -> RuntimeSpawner {
581        RuntimeSpawner {
582            shared: self.shared.clone(),
583            chunk: self.chunk.clone(),
584            natives: self.natives.clone(),
585        }
586    }
587
588    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
589    /// take supervised children (design notes §15).
590    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
591        super::supervisor::Supervisor::new(self.spawner())
592    }
593
594    /// Look up a function by name in the runtime's chunk — convenience for
595    /// callers that built their chunk with [`crate::Program`]
596    /// and don't want to thread raw indices through their own code.
597    pub fn function_index(&self, name: &str) -> Option<u32> {
598        self.chunk
599            .functions
600            .iter()
601            .position(|f| f.name == name)
602            .map(|i| i as u32)
603    }
604
605    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
606        self.shared.metrics.snapshot()
607    }
608
609    /// Sandbox security counters (host-only).
610    pub fn security_counters(&self) -> super::sandbox::SecurityCountersSnapshot {
611        self.shared.security.snapshot()
612    }
613
614    /// Policy fingerprint recorded at construction.
615    pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
616        self.shared.policy
617    }
618
619    /// Trust level used for constant-pool verification at construction.
620    pub fn trust_level(&self) -> crate::bytecode::TrustLevel {
621        self.trust
622    }
623
624    /// Host attestation of Caps currently held by `flow`.
625    pub fn attest_capabilities(
626        &self,
627        flow: FlowId,
628    ) -> Result<super::sandbox::CapabilityAttestation, RuntimeError> {
629        super::sandbox::CapabilityAttestation::from_table(
630            &self.shared.caps,
631            flow,
632            self.trust,
633            self.shared.policy,
634        )
635    }
636
637    /// Point-in-time view for dashboards and debug tooling.
638    pub fn snapshot(&self) -> RuntimeSnapshot {
639        RuntimeSnapshot {
640            metrics: self.metrics(),
641            live_flows: self.live_flows(),
642            flow_limit_live: self.shared.flow_limit.reserved_live(),
643            max_flows: self.shared.flow_limit.max_flows(),
644            distribution_pending: self
645                .shared
646                .distribution
647                .as_ref()
648                .and_then(|b| b.outbound_pending().ok()),
649            memory: self.memory_snapshot(),
650            workers: self.worker_count(),
651        }
652    }
653
654    /// Approximate number of flows currently registered in the directory.
655    ///
656    /// Sharded sum without a global snapshot — fine for dashboards
657    /// ([`Self::metrics`]), **not** for admission control (see
658    /// the flow limit / `max_flows`).
659    pub fn live_flows(&self) -> usize {
660        self.shared.directory.len()
661    }
662
663    /// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
664    pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
665        self.shared.memory.snapshot()
666    }
667
668    pub fn worker_count(&self) -> usize {
669        self.workers.len()
670    }
671
672    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
673    /// embedder (not from bytecode).
674    ///
675    /// # Host trust boundary
676    ///
677    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
678    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
679    /// `Ask`. The hop still goes through the same authentication choke-point
680    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
681    /// is minted when unset, and payload Caps are reissued to the recipient.
682    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
683    /// Bare scalars are rejected ([`SendError::NotAHop`]).
684    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
685        let Some(msg) = message.as_message().cloned() else {
686            return Err(SendError::NotAHop {
687                got: message.type_name(),
688            });
689        };
690        let mailbox = match self.shared.directory.lookup(target) {
691            Ok(Some(m)) => m,
692            Ok(None) => return Err(SendError::NoSuchFlow(target)),
693            Err(e) => {
694                super::error::report_fault(e);
695                return Err(SendError::Unavailable);
696            }
697        };
698        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
699            Ok(m) => Value::Message(m),
700            Err(_) => return Err(SendError::Capability),
701        };
702        match mailbox.push(stamped.clone()) {
703            // Host `send` is fire-and-forget: DropNewest means the hop was
704            // intentionally discarded under policy, not an infrastructure
705            // error. Bytecode `Ask` treats DropNewest as hard failure in
706            // `worker::deliver` (must not park waiting for a reply).
707            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
708                Ok(())
709            }
710            Ok(Ok(Delivery::Handoff(flow))) => {
711                let _ = self.shared.ask_waits.remove_asker(flow.id);
712                match flow.last_receive_dest {
713                    Some(dest) => {
714                        let Some(flow) =
715                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
716                        else {
717                            return Err(SendError::Unavailable);
718                        };
719                        enqueue_flow(&self.shared, flow);
720                        wake_workers(&self.shared);
721                        Ok(())
722                    }
723                    None => {
724                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
725                            "Runtime::send handoff missing dest register",
726                        ));
727                        finalize_flow(
728                            &self.shared,
729                            *flow,
730                            FlowOutcome::Failed("handoff missing dest register".into()),
731                            FlowExitReason::Fault,
732                        );
733                        Err(SendError::Unavailable)
734                    }
735                }
736            }
737            Ok(Err(full)) => {
738                if full.reason() == MailboxFullReason::Closed {
739                    return Err(SendError::NoSuchFlow(target));
740                }
741                Err(SendError::MailboxFull {
742                    flow: target,
743                    reason: full.reason(),
744                })
745            }
746            Err(e) => {
747                super::error::report_fault(e);
748                Err(SendError::Unavailable)
749            }
750        }
751    }
752
753    /// Deliver a hop the host read off its own socket.
754    ///
755    /// The frame's sender is kept. This path does not restamp it as the local
756    /// host (`0`). A `Cap` or `Pid` in the frame is refused. The name must
757    /// already be registered on this node; the host still owns the socket.
758    ///
759    /// When [`RuntimeConfig::remote_dedup_window`] is set, acceptance is
760    /// transactional: a failed delivery (unknown name, full mailbox) rolls
761    /// back the reservation so the host may retransmit the same
762    /// `(sender, request_id)`.
763    pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
764        let hop = super::distribution::decode_frame(bytes)?;
765        let reservation = if hop.message.request_id != 0 {
766            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
767                match dedup
768                    .reserve(hop.sender.as_u64(), hop.message.request_id)
769                    .map_err(|_| super::distribution::RemoteFrameError::Unavailable)?
770                {
771                    super::distribution::DedupTicket::Duplicate => return Ok(()),
772                    super::distribution::DedupTicket::Fresh { sender, request_id } => {
773                        Some((sender, request_id))
774                    }
775                }
776            } else {
777                None
778            }
779        } else {
780            None
781        };
782
783        let outcome = self.deliver_frame_after_dedup(hop);
784        if let Some((sender, request_id)) = reservation {
785            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
786                match &outcome {
787                    // Mailbox accepted the hop (queued or handoff taken).
788                    Ok(()) | Err(DeliverAcceptError::AfterAccept(_)) => {
789                        let _ = dedup.commit(sender, request_id);
790                    }
791                    Err(DeliverAcceptError::BeforeAccept(_)) => {
792                        let _ = dedup.rollback(sender, request_id);
793                    }
794                }
795            }
796        }
797        match outcome {
798            Ok(()) => Ok(()),
799            Err(DeliverAcceptError::BeforeAccept(e) | DeliverAcceptError::AfterAccept(e)) => Err(e),
800        }
801    }
802
803    fn deliver_frame_after_dedup(
804        &self,
805        hop: super::distribution::OutboundHop,
806    ) -> Result<(), DeliverAcceptError> {
807        let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
808            Ok(Some(cap)) => cap,
809            Ok(None) => {
810                return Err(DeliverAcceptError::BeforeAccept(
811                    super::distribution::RemoteFrameError::NoSuchName,
812                ))
813            }
814            Err(err) => {
815                super::error::report_fault(err);
816                return Err(DeliverAcceptError::BeforeAccept(
817                    super::distribution::RemoteFrameError::Unavailable,
818                ));
819            }
820        };
821        let target = match self.shared.caps.lookup(cap) {
822            Ok(Some(entry)) => match entry.target() {
823                Some(id) => id,
824                None => {
825                    return Err(DeliverAcceptError::BeforeAccept(
826                        super::distribution::RemoteFrameError::NoSuchName,
827                    ))
828                }
829            },
830            Ok(None) => {
831                return Err(DeliverAcceptError::BeforeAccept(
832                    super::distribution::RemoteFrameError::NoSuchName,
833                ))
834            }
835            Err(err) => {
836                super::error::report_fault(err);
837                return Err(DeliverAcceptError::BeforeAccept(
838                    super::distribution::RemoteFrameError::Unavailable,
839                ));
840            }
841        };
842        let mailbox = match self.shared.directory.lookup(target) {
843            Ok(Some(mailbox)) => mailbox,
844            Ok(None) => {
845                return Err(DeliverAcceptError::BeforeAccept(
846                    super::distribution::RemoteFrameError::NoSuchName,
847                ))
848            }
849            Err(err) => {
850                super::error::report_fault(err);
851                return Err(DeliverAcceptError::BeforeAccept(
852                    super::distribution::RemoteFrameError::Unavailable,
853                ));
854            }
855        };
856        let stamped = Value::Message(hop.message);
857        match mailbox.push(stamped.clone()) {
858            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
859                Ok(())
860            }
861            Ok(Ok(Delivery::Handoff(flow))) => {
862                let _ = self.shared.ask_waits.remove_asker(flow.id);
863                match flow.last_receive_dest {
864                    Some(dest) => {
865                        let Some(flow) =
866                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
867                        else {
868                            return Err(DeliverAcceptError::AfterAccept(
869                                super::distribution::RemoteFrameError::Unavailable,
870                            ));
871                        };
872                        enqueue_flow(&self.shared, flow);
873                        wake_workers(&self.shared);
874                        Ok(())
875                    }
876                    None => {
877                        super::finalize::finalize_flow(
878                            &self.shared,
879                            *flow,
880                            FlowOutcome::Failed("handoff missing dest register".into()),
881                            FlowExitReason::Fault,
882                        );
883                        Err(DeliverAcceptError::AfterAccept(
884                            super::distribution::RemoteFrameError::Unavailable,
885                        ))
886                    }
887                }
888            }
889            Ok(Err(full)) => Err(DeliverAcceptError::BeforeAccept(
890                super::distribution::RemoteFrameError::Mailbox(full.reason()),
891            )),
892            Err(err) => {
893                super::error::report_fault(err);
894                Err(DeliverAcceptError::BeforeAccept(
895                    super::distribution::RemoteFrameError::Unavailable,
896                ))
897            }
898        }
899    }
900}
901
902/// Internal split for remote dedup: rollback only when the mailbox never
903/// accepted the hop.
904enum DeliverAcceptError {
905    BeforeAccept(super::distribution::RemoteFrameError),
906    AfterAccept(super::distribution::RemoteFrameError),
907}
908
909impl Runtime {
910    fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
911        match self.shared.directory.lookup(id) {
912            Ok(Some(_)) => Ok(()),
913            Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
914            Err(e) => Err(self.unavailable(e)),
915        }
916    }
917
918    fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
919        super::error::report_fault(err);
920        super::error::LifecycleError::Unavailable
921    }
922
923    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
924    /// (host equivalent of `SelfPid`).
925    pub fn mint_cap(
926        &self,
927        flow: FlowId,
928    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
929        self.require_live(flow)?;
930        self.shared
931            .caps
932            .mint(flow, flow, super::capability::CapRights::ADDRESSING)
933            .map_err(|e| self.unavailable(e))
934    }
935
936    /// Mint a Cap held by `holder` targeting `target` (host introduction).
937    pub fn grant_cap(
938        &self,
939        holder: FlowId,
940        target: FlowId,
941    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
942        self.require_live(holder)?;
943        self.require_live(target)?;
944        self.shared
945            .caps
946            .mint(holder, target, super::capability::CapRights::ADDRESSING)
947            .map_err(|e| self.unavailable(e))
948    }
949
950    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
951    ///
952    /// Both flows must be live. `owner == target` is `LifecycleError::SelfRelation`.
953    pub fn monitor(
954        &self,
955        owner: FlowId,
956        target: FlowId,
957    ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
958        if owner == target {
959            return Err(super::error::LifecycleError::SelfRelation);
960        }
961        self.require_live(owner)?;
962        self.require_live(target)?;
963        let mon = self
964            .shared
965            .monitors
966            .create(owner, target)
967            .map_err(|e| self.unavailable(e))??;
968        // Target may have finalized between the live check and insert.
969        // Synthesize DOWN and drop the now-useless relation (owner still live).
970        if self.require_live(target).is_err() {
971            let _ = self.shared.monitors.remove_owned(owner, mon);
972            super::finalize::deliver_down(
973                &self.shared,
974                super::monitor::DownEvent {
975                    monitor: mon,
976                    owner,
977                    target,
978                    reason: super::monitor::FlowExitReason::Fault,
979                },
980            );
981        }
982        Ok(mon)
983    }
984
985    /// Drop `monitor` if `owner` still owns it.
986    pub fn demonitor(
987        &self,
988        owner: FlowId,
989        monitor: super::monitor::MonitorRef,
990    ) -> Result<(), super::error::LifecycleError> {
991        self.require_live(owner)?;
992        match self.shared.monitors.remove_owned(owner, monitor) {
993            Ok(inner) => inner,
994            Err(e) => Err(self.unavailable(e)),
995        }
996    }
997
998    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
999    /// kills the peer (`Normal` only drops the link). With
1000    /// [`Self::set_trap_exit`] on a peer, that peer receives a
1001    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
1002    pub fn link(
1003        &self,
1004        a: FlowId,
1005        b: FlowId,
1006    ) -> Result<super::link::LinkId, super::error::LifecycleError> {
1007        if a == b {
1008            return Err(super::error::LifecycleError::SelfRelation);
1009        }
1010        self.require_live(a)?;
1011        self.require_live(b)?;
1012        match self.shared.links.link_if_live(a, b, |id| {
1013            self.shared.directory.lookup(id).map(|m| m.is_some())
1014        }) {
1015            Ok(Ok(super::link::LinkOutcome::Linked(id))) => Ok(id),
1016            Ok(Ok(super::link::LinkOutcome::Consumed { dead })) => {
1017                Err(super::error::LifecycleError::NoSuchFlow(dead))
1018            }
1019            Ok(Err(error)) => Err(error),
1020            Err(e) => Err(self.unavailable(e)),
1021        }
1022    }
1023
1024    /// BEAM-style `process_flag(trap_exit, …)`.
1025    ///
1026    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
1027    /// (including `Normal`) instead of killing this flow.
1028    pub fn set_trap_exit(
1029        &self,
1030        id: FlowId,
1031        enabled: bool,
1032    ) -> Result<(), super::error::LifecycleError> {
1033        self.require_live(id)?;
1034        self.shared
1035            .trap_exits
1036            .set(id, enabled)
1037            .map_err(|e| self.unavailable(e))
1038    }
1039
1040    /// Drop `link` if `owner` is one of the endpoints.
1041    pub fn unlink(
1042        &self,
1043        owner: FlowId,
1044        link: super::link::LinkId,
1045    ) -> Result<(), super::error::LifecycleError> {
1046        self.require_live(owner)?;
1047        match self.shared.links.unlink_owned(owner, link) {
1048            Ok(inner) => inner,
1049            Err(e) => Err(self.unavailable(e)),
1050        }
1051    }
1052
1053    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
1054    pub fn register_name(
1055        &self,
1056        name: &str,
1057        cap: crate::bytecode::CapId,
1058    ) -> Result<(), super::error::LifecycleError> {
1059        let entry = match self.shared.caps.lookup(cap) {
1060            Ok(Some(e)) => e,
1061            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
1062            Err(e) => return Err(self.unavailable(e)),
1063        };
1064        let target = match entry.target() {
1065            Some(id) => id,
1066            None => return Err(super::error::LifecycleError::InvalidCapability),
1067        };
1068        self.require_live(target)?;
1069        match self
1070            .shared
1071            .registry
1072            .register(super::registry::RegistryName::from(name), cap, target)
1073        {
1074            Ok(inner) => inner,
1075            Err(e) => Err(self.unavailable(e)),
1076        }
1077    }
1078
1079    /// Look up a registered Cap, or `None` if the name is free / was swept.
1080    pub fn whereis(
1081        &self,
1082        name: &str,
1083    ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
1084        self.shared
1085            .registry
1086            .whereis(name)
1087            .map_err(|e| self.unavailable(e))
1088    }
1089
1090    /// Cooperative abort. Parked flows finalize immediately; a running flow
1091    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
1092    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
1093        self.require_live(id)?;
1094        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
1095        Ok(())
1096    }
1097
1098    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
1099    pub fn mint_admin_cap(
1100        &self,
1101        holder: FlowId,
1102    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
1103        self.require_live(holder)?;
1104        let cap = crate::bytecode::Cap::root(
1105            crate::bytecode::CapTarget::Scheduler,
1106            CapRights::ADMIN,
1107            None,
1108            self.shared.caps.scheduler_cell().as_ref(),
1109        );
1110        self.shared
1111            .caps
1112            .grant(holder, cap)
1113            .map_err(|e| self.unavailable(e))
1114    }
1115
1116    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
1117    pub fn admin_kill(
1118        &self,
1119        holder: FlowId,
1120        cap: crate::bytecode::CapId,
1121        target: FlowId,
1122    ) -> Result<(), super::error::LifecycleError> {
1123        self.require_admin(holder, cap)?;
1124        self.kill(target)
1125    }
1126
1127    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
1128    pub fn admin_top_up_cpu(
1129        &self,
1130        holder: FlowId,
1131        cap: crate::bytecode::CapId,
1132        target: FlowId,
1133        extra: i64,
1134    ) -> Result<(), super::error::LifecycleError> {
1135        self.require_admin(holder, cap)?;
1136        let quota = match self.shared.quotas.get(target) {
1137            Ok(Some(q)) => q,
1138            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
1139            Err(e) => return Err(self.unavailable(e)),
1140        };
1141        quota.top_up_cpu(extra);
1142        Ok(())
1143    }
1144
1145    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
1146    pub fn admin_top_up_mem(
1147        &self,
1148        holder: FlowId,
1149        cap: crate::bytecode::CapId,
1150        target: FlowId,
1151        extra: usize,
1152    ) -> Result<(), super::error::LifecycleError> {
1153        self.require_admin(holder, cap)?;
1154        let quota = match self.shared.quotas.get(target) {
1155            Ok(Some(q)) => q,
1156            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
1157            Err(e) => return Err(self.unavailable(e)),
1158        };
1159        quota.top_up_mem(extra);
1160        Ok(())
1161    }
1162
1163    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
1164    pub fn admin_top_up_send(
1165        &self,
1166        holder: FlowId,
1167        cap: crate::bytecode::CapId,
1168        target: FlowId,
1169        extra: i64,
1170    ) -> Result<(), super::error::LifecycleError> {
1171        self.require_admin(holder, cap)?;
1172        let quota = match self.shared.quotas.get(target) {
1173            Ok(Some(q)) => q,
1174            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
1175            Err(e) => return Err(self.unavailable(e)),
1176        };
1177        quota.top_up_send(extra);
1178        Ok(())
1179    }
1180
1181    fn require_admin(
1182        &self,
1183        holder: FlowId,
1184        cap: crate::bytecode::CapId,
1185    ) -> Result<(), super::error::LifecycleError> {
1186        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
1187            Ok(e) => e,
1188            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
1189        };
1190        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
1191            .map_err(|_| super::error::LifecycleError::InvalidCapability)
1192    }
1193
1194    /// Remove a name without waiting for the flow to exit. `false` if unknown.
1195    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
1196        self.shared
1197            .registry
1198            .unregister(name)
1199            .map_err(|e| self.unavailable(e))
1200    }
1201
1202    /// Replace the image used by **new host** [`Self::spawn`] calls and
1203    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
1204    /// existing `Vm` chunk.
1205    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
1206        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
1207            .map_err(SpawnError::VerifyFailed)?;
1208        let chunk = Arc::new(chunk);
1209        self.chunk = chunk.clone();
1210        #[cfg(feature = "jit")]
1211        if let Some(jit) = &self.shared.jit {
1212            jit.reload(chunk);
1213        }
1214        Ok(())
1215    }
1216
1217    /// Signal workers and the timer to stop. Does **not** join those threads.
1218    /// [`Self::finish`] joins them and finalizes flows still parked.
1219    fn request_shutdown(&self) {
1220        self.shared.shutdown.store(true, Ordering::Release);
1221        // Settle parked HostAwaits before joining workers: otherwise a bridge
1222        // holding Completers could leave joiners blocked after OS threads exit.
1223        finalize_host_awaits(&self.shared);
1224        self.shared.timer.shutdown();
1225        let (lock, cvar) = &self.shared.notify;
1226        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
1227            Ok(_g) => cvar.notify_all(),
1228            Err(e) => super::error::report_fault(e),
1229        }
1230    }
1231
1232    /// Install the test-only host-completion replay gate.
1233    ///
1234    /// Production leaves the gate unset and delivers each completion at once.
1235    /// Sequence numbers come from the test, not from arrival order.
1236    #[cfg(test)]
1237    pub(crate) fn enable_host_await_replay(&self) -> Result<(), super::error::RuntimeError> {
1238        let mut gate = super::sync_lock::lock(
1239            &self.shared.host_replay,
1240            "Runtime::enable_host_await_replay",
1241        )?;
1242        *gate = Some(super::deterministic::HostReplayGate::default());
1243        Ok(())
1244    }
1245
1246    /// Bind a host-await ticket to a recorded sequence and deliver every
1247    /// completion that is now the next event.
1248    #[cfg(test)]
1249    pub(crate) fn bind_host_await_replay(
1250        &self,
1251        ticket: u64,
1252        sequence: u64,
1253    ) -> Result<(), super::host_await::HostAwaitError> {
1254        let ready = {
1255            let mut gate =
1256                super::sync_lock::lock(&self.shared.host_replay, "Runtime::bind_host_await_replay")
1257                    .map_err(super::host_await::HostAwaitError::Runtime)?;
1258            let Some(replay) = gate.as_mut() else {
1259                return Err(super::host_await::HostAwaitError::Replay(
1260                    "replay gate is not enabled",
1261                ));
1262            };
1263            replay.bind(ticket, sequence).map_err(|err| {
1264                super::host_await::HostAwaitError::Replay(super::deterministic::replay_label(err))
1265            })?;
1266            replay.drain_ready()
1267        };
1268        super::host_await::deliver_ready(&self.shared, ready)
1269    }
1270
1271    /// Stop accepting new scheduling work, join every worker + the timer
1272    /// thread, then finalize any flow still parked (mailbox, timer, injector,
1273    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
1274    /// instead of [`super::error::RuntimeError::Abandoned`].
1275    ///
1276    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
1277    /// finalizes at the next loop check (cooperative preemption).
1278    ///
1279    /// [`Drop`] does the same work when it runs off a worker thread. On a
1280    /// worker thread it only signals: joining that thread from itself would
1281    /// deadlock the pool.
1282    /// Register a process-wide (global) table under `name`.
1283    ///
1284    /// A flow that calls `TableOpen(name)` afterwards receives a Cap to this
1285    /// table instead of opening its own per-flow table. The table survives
1286    /// any single flow's exit; each opener's Cap is revoked when that flow
1287    /// exits. Names must be 1..=256 bytes and unique.
1288    pub fn register_table(&self, name: &str) -> Result<(), super::error::RuntimeError> {
1289        self.shared
1290            .tables
1291            .register_global(&self.shared, name)
1292            .map_err(super::error::RuntimeError::from)
1293    }
1294
1295    /// Drop a previously registered global table and revoke every Cap that
1296    /// still references it.
1297    pub fn unregister_table(&self, name: &str) -> Result<(), super::error::RuntimeError> {
1298        self.shared
1299            .tables
1300            .unregister_global(&self.shared, name)
1301            .map_err(super::error::RuntimeError::from)
1302    }
1303
1304    /// Names of the currently registered global tables.
1305    pub fn global_tables(&self) -> Vec<String> {
1306        self.shared.tables.list_global()
1307    }
1308
1309    pub fn shutdown(mut self) {
1310        self.finish();
1311    }
1312
1313    /// Join the threads started by [`Self::with_natives_and_config`] and
1314    /// finalize every flow they did not finish. Safe to call again after
1315    /// [`Self::shutdown`]: the handles are already taken and the second
1316    /// sweep finds an empty directory.
1317    fn finish(&mut self) {
1318        if !self.shared.shutdown.load(Ordering::Acquire) {
1319            self.request_shutdown();
1320        }
1321        for worker in self.workers.drain(..) {
1322            let _ = worker.join();
1323        }
1324        super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
1325        if let Some(timer) = self.timer_thread.take() {
1326            let _ = timer.join();
1327        }
1328        finalize_stranded(&self.shared);
1329    }
1330}
1331
1332fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
1333    finalize_flow(
1334        shared,
1335        flow,
1336        FlowOutcome::Failed("runtime shutdown".into()),
1337        FlowExitReason::Shutdown,
1338    );
1339}
1340
1341fn finalize_host_awaits(shared: &Shared) {
1342    match shared.host_awaits.cancel_all() {
1343        Ok(notices) => super::host_await::notify_cancelled(shared, notices),
1344        Err(e) => super::error::report_fault(e),
1345    }
1346}
1347
1348/// After workers and the timer have stopped, take every remaining flow
1349/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
1350///
1351/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
1352fn finalize_stranded(shared: &Shared) {
1353    finalize_host_awaits(shared);
1354    for flow in shared.timer.drain() {
1355        finalize_shutdown_flow(shared, flow);
1356    }
1357    for _ in 0..8 {
1358        let mut n = 0usize;
1359        for flow in shared.injector.drain() {
1360            finalize_shutdown_flow(shared, *flow);
1361            n += 1;
1362        }
1363        for stealer in &shared.stealers {
1364            for flow in stealer.drain() {
1365                finalize_shutdown_flow(shared, *flow);
1366                n += 1;
1367            }
1368        }
1369        for (_id, mailbox) in shared.directory.snapshot() {
1370            match mailbox.take_parked() {
1371                Ok(Some(flow)) => {
1372                    finalize_shutdown_flow(shared, *flow);
1373                    n += 1;
1374                }
1375                Ok(None) => {}
1376                Err(e) => super::error::report_fault(e),
1377            }
1378            match mailbox.close() {
1379                Ok(senders) => {
1380                    for sender in senders {
1381                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
1382                            super::error::report_fault(e);
1383                        }
1384                        finalize_shutdown_flow(shared, sender);
1385                        n += 1;
1386                    }
1387                }
1388                Err(e) => super::error::report_fault(e),
1389            }
1390        }
1391        if n == 0 {
1392            break;
1393        }
1394    }
1395}
1396
1397impl Drop for Runtime {
1398    fn drop(&mut self) {
1399        if super::worker::is_on_worker() {
1400            if !self.shared.shutdown.load(Ordering::Acquire) {
1401                self.request_shutdown();
1402            }
1403            super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
1404            return;
1405        }
1406        self.finish();
1407    }
1408}
1409
1410/// A convenience Pid constructor for embedders that stored a raw `u64`
1411/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
1412/// call APIs that take one.
1413pub fn flow_id_from_u64(raw: u64) -> FlowId {
1414    FlowId(raw)
1415}
1416
1417/// Why [`Runtime::send`] could not deliver a hop.
1418#[derive(Debug, Clone, PartialEq, Eq)]
1419pub enum SendError {
1420    NoSuchFlow(FlowId),
1421    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
1422    NotAHop {
1423        got: &'static str,
1424    },
1425    /// Target inbox is at one of its logical bounds
1426    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
1427    /// [`MailboxFullReason`].
1428    MailboxFull {
1429        flow: FlowId,
1430        reason: MailboxFullReason,
1431    },
1432    /// Host hop authentication failed (payload Cap reissue).
1433    Capability,
1434    /// Directory / mailbox mutex poisoned — not "no such flow".
1435    Unavailable,
1436}
1437
1438impl std::fmt::Display for SendError {
1439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1440        match self {
1441            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
1442            SendError::NotAHop { got } => {
1443                write!(f, "atomic hop requires Value::Message, got {got}")
1444            }
1445            SendError::MailboxFull { flow, reason } => {
1446                write!(f, "mailbox full for {flow} ({reason})")
1447            }
1448            SendError::Capability => {
1449                write!(f, "host send could not reissue a capability in the hop")
1450            }
1451            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
1452        }
1453    }
1454}
1455
1456impl std::error::Error for SendError {}
1457
1458/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
1459/// the child. Host spawn passes `None` and mints a trusted root instead.
1460pub(crate) struct BytecodeSpawn<'a> {
1461    pub authority: &'a Cap,
1462    pub cell: &'a crate::bytecode::RevocationCell,
1463    pub quota: &'a super::quota::FlowQuota,
1464    pub requested_rights: CapRights,
1465}
1466
1467/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
1468/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
1469/// mailbox + completion channel), register it in the directory, and push
1470/// it onto the global injector for any worker to pick up.
1471///
1472/// Returns [`SpawnError`] on bad function index / VM init / directory
1473/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
1474/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
1475/// Bytecode `Spawn` must pass exactly the callee's arity. Host spawn is not
1476/// checked here.
1477pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
1478    if argc != usize::from(arity) {
1479        Err(crate::vm::Fault::BadArity {
1480            passed: argc,
1481            expected: arity,
1482        })
1483    } else {
1484        Ok(())
1485    }
1486}
1487
1488#[allow(clippy::too_many_arguments)]
1489pub(crate) fn spawn_on(
1490    shared: &Arc<Shared>,
1491    chunk: &Arc<Chunk>,
1492    natives: &Arc<NativeTable>,
1493    function: u32,
1494    args: &[Value],
1495    restart_policy: RestartPolicy,
1496    supervisor: Option<SupervisorLink>,
1497    parent: Option<FlowId>,
1498    bytecode: Option<BytecodeSpawn<'_>>,
1499    // When `bytecode` is `None`, overrides `Shared::root_authority`.
1500    host_authority: Option<RootAuthorityPolicy>,
1501) -> Result<FlowHandle, SpawnError> {
1502    // Bytecode `Spawn` encodes argc. Host `Runtime::spawn` does not: a short
1503    // host argument list still fills the rest with `Unit`. Only the bytecode
1504    // path is rejected here, matching `VerifyError::CallArity` / `Fault::BadArity`.
1505    if bytecode.is_some() {
1506        match chunk.function(function) {
1507            Some(def) => {
1508                if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
1509                    return Err(fault.into());
1510                }
1511            }
1512            None => {
1513                return Err(SpawnError::BadFunction {
1514                    index: function,
1515                    table_size: chunk.functions.len() as u32,
1516                });
1517            }
1518        }
1519    }
1520    shared.flow_limit.try_reserve()?;
1521    let id = match super::process::try_next_flow_id() {
1522        Ok(id) => id,
1523        Err(super::error::RuntimeError::FlowIdExhausted) => {
1524            shared.flow_limit.release();
1525            return Err(SpawnError::FlowIdExhausted);
1526        }
1527        Err(_) => {
1528            shared.flow_limit.release();
1529            return Err(SpawnError::Unavailable);
1530        }
1531    };
1532    let cell = match shared.caps.bind_flow(id) {
1533        Ok(c) => c,
1534        Err(_) => {
1535            shared.flow_limit.release();
1536            return Err(SpawnError::Unavailable);
1537        }
1538    };
1539    let authority = match bytecode {
1540        None => {
1541            let policy = host_authority.unwrap_or(shared.root_authority);
1542            policy.mint(id.as_u64(), natives.len(), cell.as_ref())
1543        }
1544        Some(ctx) => match super::spawn::exec_spawn_authority(
1545            ctx.authority,
1546            ctx.cell,
1547            ctx.quota,
1548            id.as_u64(),
1549            ctx.requested_rights,
1550            None,
1551            cell.as_ref(),
1552        ) {
1553            Ok(cap) => cap,
1554            Err(e) => {
1555                shared.flow_limit.release();
1556                let _ = shared.caps.revoke_flow(id);
1557                return Err(SpawnError::from(e));
1558            }
1559        },
1560    };
1561    let args = match grant_caps_in_args(shared, parent, id, args) {
1562        Ok(a) => a,
1563        Err(e) => {
1564            shared.flow_limit.release();
1565            let _ = shared.caps.revoke_flow(id);
1566            return Err(e);
1567        }
1568    };
1569    let gate = NativeGate::from_authority(
1570        &authority,
1571        Arc::clone(&cell),
1572        shared.caps.native_cell(),
1573        natives.len(),
1574    );
1575    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1576    let mut vm = match Vm::with_native_gate(
1577        chunk.clone(),
1578        natives.clone(),
1579        gate,
1580        function,
1581        args.as_slice(),
1582    ) {
1583        Ok(vm) => vm,
1584        Err(e) => {
1585            shared.flow_limit.release();
1586            let _ = shared.caps.revoke_flow(id);
1587            return Err(e.into());
1588        }
1589    };
1590    vm.set_memory_budget(Arc::clone(&shared.memory));
1591    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
1592        shared.flow_limit.release();
1593        let _ = shared.caps.revoke_flow(id);
1594        return Err(e.into());
1595    }
1596    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1597    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1598        super::error::report_fault(e);
1599        shared.flow_limit.release();
1600        let _ = shared.caps.revoke_flow(id);
1601        return Err(SpawnError::Unavailable);
1602    }
1603    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
1604        super::error::report_fault(e);
1605        let _ = shared.directory.unregister(id);
1606        shared.flow_limit.release();
1607        let _ = shared.caps.revoke_flow(id);
1608        return Err(SpawnError::Unavailable);
1609    }
1610    let (tx, rx) = super::oneshot::channel();
1611    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1612    flow.authority = authority;
1613    flow.cell = cell;
1614    flow.quota = quota;
1615    flow.supervisor = supervisor;
1616    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1617    record_security_event(
1618        shared,
1619        &super::sandbox::SecurityEvent::CapabilityCreated {
1620            holder: id.as_u64(),
1621        },
1622    );
1623    if matches!(
1624        shared.trust,
1625        crate::bytecode::TrustLevel::Untrusted | crate::bytecode::TrustLevel::Restricted
1626    ) {
1627        super::sandbox::SecurityCounters::inc(&shared.security.active_untrusted_flows);
1628    }
1629    enqueue_flow(shared, flow);
1630    wake_workers(shared);
1631    Ok(FlowHandle { id, receiver: rx })
1632}
1633
1634fn grant_caps_in_args(
1635    shared: &Shared,
1636    parent: Option<FlowId>,
1637    child: FlowId,
1638    args: &[Value],
1639) -> Result<Vec<Value>, SpawnError> {
1640    let mut out = Vec::with_capacity(args.len());
1641    for arg in args {
1642        if !arg.within_nesting_limit() {
1643            return Err(SpawnError::InvalidCapability);
1644        }
1645        let granted = arg.map_caps(
1646            0,
1647            &SpawnError::InvalidCapability,
1648            &mut |id| {
1649                let next = match parent {
1650                    None => shared.caps.reissue_for(id, child),
1651                    Some(holder) => shared.caps.delegate(id, holder, child),
1652                };
1653                next.map_err(|_| SpawnError::InvalidCapability)
1654            },
1655            &mut |message| {
1656                if let Some(holder) = parent {
1657                    if message.sender == 0 {
1658                        message.sender = holder.as_u64();
1659                    }
1660                }
1661                if message.request_id == 0 {
1662                    message.request_id =
1663                        super::worker::mint_host_request_id(&shared.host_next_request_id)
1664                            .ok_or(SpawnError::RequestIdsExhausted)?;
1665                }
1666                if !message.reply_cap.is_none() {
1667                    message.reply_cap = match parent {
1668                        None => shared.caps.reissue_for(message.reply_cap, child),
1669                        Some(holder) => shared.caps.delegate(message.reply_cap, holder, child),
1670                    }
1671                    .map_err(|_| SpawnError::InvalidCapability)?;
1672                }
1673                Ok(())
1674            },
1675        )?;
1676        out.push(granted);
1677    }
1678    Ok(out)
1679}
1680
1681/// Park `flow` on the global injector.
1682///
1683/// A poisoned injector is cleared inside [`Injector::push`]. The flow stays
1684/// queued with whatever was already there.
1685pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
1686    shared.injector.push(flow);
1687}
1688
1689pub(crate) fn wake_workers(shared: &Shared) {
1690    let (lock, cvar) = &shared.notify;
1691    match super::sync_lock::lock(lock, "wake_workers") {
1692        Ok(_g) => cvar.notify_one(),
1693        Err(e) => super::error::report_fault(e),
1694    }
1695}
1696
1697/// Signal shutdown and join any threads already started during construction
1698/// failure — keeps the "no orphan threads" contract of
1699/// [`Runtime::with_natives_and_config`].
1700pub(crate) fn record_security_event(shared: &Shared, event: &super::sandbox::SecurityEvent) {
1701    use super::sandbox::{SecurityCounters, SecurityEvent};
1702    match event {
1703        SecurityEvent::AccessDenied { .. } => {
1704            SecurityCounters::inc(&shared.security.denied_operations);
1705        }
1706        SecurityEvent::QuotaExceeded { .. } => {
1707            SecurityCounters::inc(&shared.security.quota_exceeded);
1708        }
1709        SecurityEvent::CapabilityCreated { .. } => {
1710            SecurityCounters::inc(&shared.security.capabilities_created);
1711        }
1712        SecurityEvent::CapabilityRevoked { .. } => {
1713            SecurityCounters::inc(&shared.security.capabilities_revoked);
1714        }
1715        SecurityEvent::ModuleRejected { .. } => {
1716            SecurityCounters::inc(&shared.security.invalid_modules);
1717        }
1718        SecurityEvent::NativeDenied { .. } => {
1719            SecurityCounters::inc(&shared.security.native_denied);
1720        }
1721        SecurityEvent::CapabilityDelegated { .. } | SecurityEvent::FlowFinalized { .. } => {}
1722    }
1723    if let Some(sink) = shared.security_audit.as_ref() {
1724        sink.record(event);
1725    }
1726}
1727
1728fn abort_startup(
1729    shared: &Arc<Shared>,
1730    workers: Vec<std::thread::JoinHandle<()>>,
1731    timer: Option<std::thread::JoinHandle<()>>,
1732) {
1733    shared.shutdown.store(true, Ordering::Release);
1734    shared.timer.shutdown();
1735    let (lock, cvar) = &shared.notify;
1736    match super::sync_lock::lock(lock, "abort_startup") {
1737        Ok(_g) => cvar.notify_all(),
1738        Err(e) => super::error::report_fault(e),
1739    }
1740    for w in workers {
1741        let _ = w.join();
1742    }
1743    if let Some(t) = timer {
1744        let _ = t.join();
1745    }
1746}
1747
1748/// A `Send + Sync`, freely cloneable capability to spawn flows into a
1749/// [`Runtime`], detached from the `Runtime` value itself. Exists because
1750/// [`super::supervisor::Supervisor`] needs to respawn flows from a
1751/// background monitor thread whose lifetime isn't tied to the `Runtime`
1752/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
1753#[derive(Clone)]
1754pub struct RuntimeSpawner {
1755    pub(crate) shared: Arc<Shared>,
1756    pub(crate) chunk: Arc<Chunk>,
1757    pub(crate) natives: Arc<NativeTable>,
1758}
1759
1760impl RuntimeSpawner {
1761    pub fn spawn(
1762        &self,
1763        function: u32,
1764        args: &[Value],
1765        restart_policy: RestartPolicy,
1766    ) -> Result<FlowHandle, SpawnError> {
1767        spawn_on(
1768            &self.shared,
1769            &self.chunk,
1770            &self.natives,
1771            function,
1772            args,
1773            restart_policy,
1774            None,
1775            None,
1776            None,
1777            None,
1778        )
1779    }
1780
1781    /// Host spawn with [`RootAuthorityPolicy::Untrusted`].
1782    pub fn spawn_untrusted(
1783        &self,
1784        function: u32,
1785        args: &[Value],
1786        restart_policy: RestartPolicy,
1787    ) -> Result<FlowHandle, SpawnError> {
1788        spawn_on(
1789            &self.shared,
1790            &self.chunk,
1791            &self.natives,
1792            function,
1793            args,
1794            restart_policy,
1795            None,
1796            None,
1797            None,
1798            Some(RootAuthorityPolicy::Untrusted),
1799        )
1800    }
1801
1802    pub(crate) fn spawn_linked(
1803        &self,
1804        function: u32,
1805        args: &[Value],
1806        restart_policy: RestartPolicy,
1807        supervisor: SupervisorLink,
1808    ) -> Result<FlowHandle, SpawnError> {
1809        spawn_on(
1810            &self.shared,
1811            &self.chunk,
1812            &self.natives,
1813            function,
1814            args,
1815            restart_policy,
1816            Some(supervisor),
1817            None,
1818            None,
1819            None,
1820        )
1821    }
1822
1823    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1824        self.shared.metrics.snapshot()
1825    }
1826
1827    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1828        super::finalize::request_kill(&self.shared, id, reason);
1829    }
1830}
1831
1832#[cfg(test)]
1833mod tests {
1834    use super::*;
1835    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1836    use crate::scheduler::FlowOutcome;
1837    use std::time::Duration;
1838
1839    #[test]
1840    fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
1841        assert!(super::bytecode_spawn_arity(2, 2).is_ok());
1842        assert!(matches!(
1843            super::bytecode_spawn_arity(2, 1),
1844            Err(crate::vm::Fault::BadArity {
1845                passed: 1,
1846                expected: 2,
1847            })
1848        ));
1849    }
1850
1851    fn add_chunk() -> Chunk {
1852        let mut b = ChunkBuilder::new("test");
1853        b.begin_function("main", 0, 2);
1854        b.emit_load_imm(0, 41);
1855        b.emit_load_imm(1, 1);
1856        b.emit_binop(Opcode::Add, 0, 0, 1);
1857        b.emit_return(0);
1858        b.finish()
1859    }
1860
1861    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
1862    /// makes "still running" an observable state from the host thread.
1863    fn sleep_then_return_chunk(millis: i32) -> Chunk {
1864        let mut b = ChunkBuilder::new("test");
1865        b.begin_function("main", 0, 2);
1866        b.emit_load_imm(0, millis);
1867        b.emit_sleep(0);
1868        b.emit_load_imm(0, 7);
1869        b.emit_return(0);
1870        b.finish()
1871    }
1872
1873    /// The host thread must be able to ask "done yet?" and to wait under a
1874    /// bound *it* chooses, instead of surrendering itself to `join` for
1875    /// however long the bytecode decides to take.
1876    #[test]
1877    fn polling_and_bounded_waits_never_commit_the_host_thread(
1878    ) -> Result<(), Box<dyn std::error::Error>> {
1879        const FLOW_SLEEP: i32 = 150;
1880        let rt = Runtime::with_config(
1881            sleep_then_return_chunk(FLOW_SLEEP),
1882            RuntimeConfig {
1883                workers: 1,
1884                quantum: 1_000,
1885                mailbox: MailboxConfig::DEFAULT,
1886                ..Default::default()
1887            },
1888        )?;
1889        let handle = rt.spawn(0, &[])?;
1890
1891        // The flow cannot possibly be finished yet: it has to be picked up
1892        // and then sleep. A poll must say so without waiting.
1893        if let Some(outcome) = handle.try_join() {
1894            rt.shutdown();
1895            return Err(format!("try_join answered too early: {outcome:?}").into());
1896        }
1897
1898        // A bound well below the flow's sleep must expire and hand control
1899        // back, not block until the flow happens to finish.
1900        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1901            rt.shutdown();
1902            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1903        }
1904
1905        // A generous bound collects the real outcome through the same
1906        // (non-consuming) handle.
1907        let outcome = handle.join_timeout(Duration::from_secs(10));
1908        rt.shutdown();
1909        match outcome {
1910            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1911            other => Err(format!("unexpected outcome: {other:?}").into()),
1912        }
1913    }
1914
1915    #[test]
1916    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1917        let rt = Runtime::with_config(
1918            add_chunk(),
1919            RuntimeConfig {
1920                workers: 1,
1921                quantum: 1_000,
1922                mailbox: MailboxConfig::DEFAULT,
1923                ..Default::default()
1924            },
1925        )?;
1926        let outcome = rt.spawn(0, &[])?.join();
1927        rt.shutdown();
1928        match outcome {
1929            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1930            other => Err(format!("unexpected outcome: {other:?}").into()),
1931        }
1932    }
1933
1934    fn receive_forever_chunk() -> Chunk {
1935        let mut b = ChunkBuilder::new("recv");
1936        b.begin_function("main", 0, 1);
1937        b.emit_receive(0);
1938        b.emit_return(0);
1939        b.finish()
1940    }
1941
1942    #[test]
1943    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1944        let rt = Runtime::with_config(
1945            receive_forever_chunk(),
1946            RuntimeConfig {
1947                workers: 1,
1948                quantum: 1_000,
1949                mailbox: MailboxConfig::DEFAULT,
1950                ..Default::default()
1951            },
1952        )?;
1953        let handle = rt.spawn(0, &[])?;
1954        rt.kill(handle.id())?;
1955        let outcome = handle.join();
1956        rt.shutdown();
1957        assert!(
1958            matches!(outcome, FlowOutcome::Failed(_)),
1959            "kill must fail the joiner, got {outcome:?}"
1960        );
1961        Ok(())
1962    }
1963
1964    #[test]
1965    fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
1966        let rt = Runtime::with_config(
1967            receive_forever_chunk(),
1968            RuntimeConfig {
1969                workers: 1,
1970                quantum: 1_000,
1971                mailbox: MailboxConfig::DEFAULT,
1972                ..Default::default()
1973            },
1974        )?;
1975        let handle = rt.spawn(0, &[])?;
1976        std::thread::sleep(Duration::from_millis(30));
1977        rt.shutdown();
1978        match handle.join() {
1979            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1980            other => Err(format!("expected shutdown finalize, got {other:?}").into()),
1981        }
1982    }
1983
1984    #[test]
1985    fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1986        let rt = Runtime::with_config(
1987            sleep_then_return_chunk(60_000),
1988            RuntimeConfig {
1989                workers: 1,
1990                quantum: 1_000,
1991                mailbox: MailboxConfig::DEFAULT,
1992                ..Default::default()
1993            },
1994        )?;
1995        let handle = rt.spawn(0, &[])?;
1996        std::thread::sleep(Duration::from_millis(30));
1997        rt.shutdown();
1998        match handle.join() {
1999            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
2000            other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
2001        }
2002    }
2003
2004    #[test]
2005    fn drop_finalizes_a_parked_sleeper() -> Result<(), Box<dyn std::error::Error>> {
2006        let rt = Runtime::with_config(
2007            sleep_then_return_chunk(60_000),
2008            RuntimeConfig {
2009                workers: 1,
2010                quantum: 1_000,
2011                mailbox: MailboxConfig::DEFAULT,
2012                ..Default::default()
2013            },
2014        )?;
2015        let handle = rt.spawn(0, &[])?;
2016        std::thread::sleep(Duration::from_millis(30));
2017        drop(rt);
2018        match handle.join() {
2019            FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
2020            other => Err(format!("expected drop to finalize the sleeper, got {other:?}").into()),
2021        }
2022    }
2023
2024    #[test]
2025    fn zero_quantum_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
2026        let rt = Runtime::with_config(
2027            add_chunk(),
2028            RuntimeConfig {
2029                workers: 1,
2030                quantum: 0,
2031                mailbox: MailboxConfig::DEFAULT,
2032                ..Default::default()
2033            },
2034        )?;
2035        let outcome = rt.spawn(0, &[])?.join();
2036        rt.shutdown();
2037        assert!(
2038            matches!(outcome, FlowOutcome::Completed(Value::Int(42))),
2039            "got {outcome:?}"
2040        );
2041        Ok(())
2042    }
2043
2044    #[test]
2045    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
2046        let rt = Runtime::with_config(
2047            receive_forever_chunk(),
2048            RuntimeConfig {
2049                workers: 1,
2050                quantum: 1_000,
2051                mailbox: MailboxConfig::DEFAULT,
2052                max_flows: 1,
2053                ..Default::default()
2054            },
2055        )?;
2056        let first = rt.spawn(0, &[])?;
2057        let second = rt.spawn(0, &[]);
2058        rt.kill(first.id())?;
2059        let _ = first.join();
2060        // After finalize, the reserved slot must be free again.
2061        let third = rt.spawn(0, &[])?;
2062        rt.kill(third.id())?;
2063        let _ = third.join();
2064        rt.shutdown();
2065        match second {
2066            Err(SpawnError::FlowLimit { current, max }) => {
2067                assert_eq!(current, 1);
2068                assert_eq!(max, 1);
2069                Ok(())
2070            }
2071            other => Err(format!(
2072                "expected FlowLimit, got {}",
2073                match &other {
2074                    Ok(_) => "Ok(handle)".into(),
2075                    Err(e) => format!("Err({e})"),
2076                }
2077            )
2078            .into()),
2079        }
2080    }
2081
2082    /// Ask must not park waiting for a reply when DropNewest discarded the request.
2083    #[test]
2084    fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
2085        use crate::bytecode::{Message, Program};
2086        use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
2087
2088        let mut program = Program::new("ask-drop-newest");
2089        let busy = program.function("busy", 0, |f| {
2090            // Stay alive without spinning the worker: sleep loop.
2091            let loop_lbl = f.label();
2092            f.bind(loop_lbl);
2093            let ms = f.load_i32(50);
2094            f.sleep(ms);
2095            f.jump(loop_lbl);
2096        });
2097        let asker = program.function("asker", 1, |f| {
2098            let server = f.reg(0);
2099            let z = f.load_i32(0);
2100            let req = f.hop_fresh(1, z);
2101            let reply = f.ask(server, req);
2102            f.return_(reply);
2103        });
2104        let chunk = program.build();
2105
2106        let cap = MailboxCapacity::new(1).ok_or("cap")?;
2107        let rt = Runtime::with_natives_and_config(
2108            chunk,
2109            crate::std_native_table(),
2110            RuntimeConfig {
2111                // Busy target must not monopolize scheduling or Ask never runs.
2112                workers: 2,
2113                quantum: 1_000,
2114                mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
2115                ..Default::default()
2116            },
2117        )?;
2118
2119        let server = rt.spawn(busy, &[])?;
2120        // Fill the only slot so the subsequent Ask is DropNewest'd.
2121        rt.send(
2122            server.id(),
2123            Value::Message(Message::request(1, 9, Value::Int(1))),
2124        )?;
2125        let server_cap = rt.mint_cap(server.id())?;
2126        let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
2127        let outcome = ask.join_timeout(Duration::from_secs(3));
2128        rt.kill(server.id())?;
2129        let _ = server.join_timeout(Duration::from_millis(500));
2130        rt.shutdown();
2131
2132        match outcome {
2133            Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
2134            other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
2135        }
2136    }
2137
2138    #[test]
2139    fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
2140        use crate::bytecode::Program;
2141
2142        let mut program = Program::new("ask-limit");
2143        let silent = program.function("silent", 0, |f| {
2144            // Accept the request hop but never reply.
2145            let _req = f.receive();
2146            let loop_lbl = f.label();
2147            f.bind(loop_lbl);
2148            let ms = f.load_i32(50);
2149            f.sleep(ms);
2150            f.jump(loop_lbl);
2151        });
2152        let asker = program.function("asker", 1, |f| {
2153            let server = f.reg(0);
2154            let z = f.load_i32(0);
2155            let req = f.hop_fresh(1, z);
2156            let reply = f.ask(server, req);
2157            f.return_(reply);
2158        });
2159        let chunk = program.build();
2160
2161        let rt = Runtime::with_natives_and_config(
2162            chunk,
2163            crate::std_native_table(),
2164            RuntimeConfig {
2165                workers: 2,
2166                quantum: 1_000,
2167                mailbox: MailboxConfig::DEFAULT,
2168                max_ask_waits: 1,
2169                ..Default::default()
2170            },
2171        )?;
2172
2173        let server = rt.spawn(silent, &[])?;
2174        let server_cap = rt.mint_cap(server.id())?;
2175        let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
2176        // Give the first Ask time to park before the second tries.
2177        std::thread::sleep(Duration::from_millis(30));
2178        let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
2179        let second_out = second.join_timeout(Duration::from_secs(2));
2180        rt.kill(server.id())?;
2181        let _ = first.join_timeout(Duration::from_millis(500));
2182        let _ = server.join_timeout(Duration::from_millis(500));
2183        rt.shutdown();
2184
2185        match second_out {
2186            Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
2187            other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
2188        }
2189    }
2190
2191    // HostAwait E2E coverage lives in `host_await::runtime_tests`.
2192
2193    #[cfg(feature = "jit")]
2194    #[test]
2195    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
2196        use crate::JitConfig;
2197
2198        let rt = Runtime::with_config(
2199            add_chunk(),
2200            RuntimeConfig {
2201                workers: 1,
2202                quantum: 1_000,
2203                mailbox: MailboxConfig::DEFAULT,
2204                jit: JitConfig {
2205                    enabled: true,
2206                    hot_threshold: 1,
2207                },
2208                ..Default::default()
2209            },
2210        )?;
2211        let outcome = rt.spawn(0, &[])?.join();
2212        rt.shutdown();
2213        match outcome {
2214            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
2215            other => Err(format!("unexpected outcome: {other:?}").into()),
2216        }
2217    }
2218
2219    #[test]
2220    fn sandbox_enables_process_wide_relation_caps() {
2221        let config = RuntimeConfig::sandbox();
2222        assert_eq!(config.max_flows, 128);
2223        assert_eq!(config.max_ask_waits, 64);
2224        assert_eq!(config.max_host_awaits, 128);
2225        assert_eq!(config.trust, crate::bytecode::TrustLevel::Untrusted);
2226        assert_ne!(
2227            config.policy_fingerprint(),
2228            RuntimeConfig::default().policy_fingerprint()
2229        );
2230        assert_eq!(config.max_links, 1024);
2231        assert_eq!(config.max_monitors, 1024);
2232        assert_eq!(config.max_registry_names, 256);
2233        assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
2234    }
2235
2236    #[test]
2237    fn default_remains_unlimited_for_relation_caps() {
2238        let config = RuntimeConfig::default();
2239        assert_eq!(config.max_links, 0);
2240        assert_eq!(config.max_monitors, 0);
2241        assert_eq!(config.max_registry_names, 0);
2242    }
2243
2244    #[test]
2245    fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
2246        use crate::bytecode::encode;
2247        use crate::{fingerprint_bf, AttestError};
2248
2249        let bytes = encode(&add_chunk());
2250        let mut bad = fingerprint_bf(&bytes);
2251        bad[0] ^= 0xff;
2252        match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
2253            Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
2254            Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
2255            Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
2256        }
2257    }
2258
2259    #[test]
2260    fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
2261        use crate::bytecode::encode;
2262        use crate::fingerprint_bf;
2263
2264        let chunk = add_chunk();
2265        let bytes = encode(&chunk);
2266        let digest = fingerprint_bf(&bytes);
2267        let rt = Runtime::with_attested(
2268            &bytes,
2269            digest,
2270            NativeTable::empty(),
2271            RuntimeConfig {
2272                workers: 1,
2273                quantum: 1_000,
2274                mailbox: MailboxConfig::DEFAULT,
2275                ..Default::default()
2276            },
2277        )?;
2278        let outcome = rt.spawn(0, &[])?.join();
2279        rt.shutdown();
2280        match outcome {
2281            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
2282            other => Err(format!("expected 42, got {other:?}").into()),
2283        }
2284    }
2285
2286    #[test]
2287    fn poisoned_injector_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
2288        let rt = Runtime::new(add_chunk())?;
2289        rt.shared.injector.poison_for_test();
2290        let outcome = rt.spawn(0, &[])?.join_timeout(Duration::from_secs(2));
2291        rt.shutdown();
2292        match outcome {
2293            Some(FlowOutcome::Completed(Value::Int(42))) => Ok(()),
2294            other => Err(format!("expected 42 after a poisoned injector, got {other:?}").into()),
2295        }
2296    }
2297}