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