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};
7use crossbeam_deque::{Injector, Stealer, Worker as LocalDeque};
8
9use super::directory::Directory;
10use super::error::SpawnError;
11use super::finalize::finalize_flow;
12use super::handle::FlowHandle;
13use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
14use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
15use super::monitor::FlowExitReason;
16use super::process::{Flow, FlowId, FlowOutcome, RestartPolicy};
17use super::supervisor::SupervisorLink;
18use super::timer::TimerWheel;
19use super::worker;
20
21/// Default instruction budget per scheduling turn (design notes §10).
22/// Chosen as a middle ground: large enough that the per-yield bookkeeping
23/// cost is amortized over meaningful work, small enough that a
24/// pathological `loop {}` in one flow can't visibly stall the others —
25/// at 10k simple instructions/turn and even a conservative tens-of-millions
26/// of instructions/sec per core, worst-case added latency for a sibling
27/// flow is sub-millisecond.
28pub const DEFAULT_QUANTUM: u32 = 10_000;
29
30/// Tunables for [`Runtime::new`]. Everything has a sensible default via
31/// [`RuntimeConfig::default`] so the common case is `Runtime::new(chunk)`.
32#[derive(Clone, Debug)]
33pub struct RuntimeConfig {
34    /// Number of worker OS threads. Defaults to the number of logical CPUs
35    /// — one worker per core is the right starting point for a CPU-bound
36    /// M:N scheduler; embedders running alongside other CPU-heavy work on
37    /// the same machine may want fewer.
38    pub workers: usize,
39    /// Instructions a flow runs before being preempted back to the
40    /// scheduler even if it never hits `Yield`.
41    pub quantum: u32,
42    /// Memory + overflow contract applied to **every** flow mailbox
43    /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
44    /// See [`MailboxConfig`] / `docs/mailbox.md`.
45    pub mailbox: MailboxConfig,
46    /// Hard cap on concurrently live flows (`0` = unlimited).
47    /// Checked on every host and bytecode `spawn`.
48    pub max_flows: u32,
49    /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
50    /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
51    pub trust: crate::bytecode::TrustLevel,
52    /// Where bytecode `print` (native index 0) writes when using
53    /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
54    pub output: Arc<dyn crate::OutputSink>,
55    /// Per-flow CPU / memory / spawn-send rate budgets.
56    pub quota: super::quota::QuotaConfig,
57    /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
58    #[cfg(feature = "jit")]
59    pub jit: JitConfig,
60}
61
62/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
63#[cfg(feature = "jit")]
64#[derive(Clone, Debug)]
65pub struct JitConfig {
66    /// When true, workers attempt compiled traces before interpreting.
67    pub enabled: bool,
68    /// How many times a `(function, pc)` pair must run before compilation.
69    pub hot_threshold: u32,
70}
71
72#[cfg(feature = "jit")]
73impl Default for JitConfig {
74    fn default() -> Self {
75        JitConfig {
76            enabled: false,
77            hot_threshold: crate::jit::HOT_THRESHOLD,
78        }
79    }
80}
81
82impl Default for RuntimeConfig {
83    fn default() -> Self {
84        RuntimeConfig {
85            workers: num_cpus::get().max(1),
86            quantum: DEFAULT_QUANTUM,
87            mailbox: MailboxConfig::DEFAULT,
88            max_flows: 0,
89            trust: crate::bytecode::TrustLevel::Untrusted,
90            output: Arc::new(crate::output::NullSink),
91            quota: super::quota::QuotaConfig::default(),
92            #[cfg(feature = "jit")]
93            jit: JitConfig::default(),
94        }
95    }
96}
97
98/// State shared by every worker thread and the timer thread. Everything in
99/// here is either internally synchronized (`Injector`, `Directory`,
100/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
101/// construction (`stealers`, `quantum`) — there is no top-level lock
102/// covering the whole runtime, by design: a global lock is exactly what an
103/// M:N scheduler exists to avoid.
104pub struct Shared {
105    pub(crate) injector: Injector<Box<Flow>>,
106    pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
107    /// FlowId → mailbox (delivery after Cap resolution).
108    pub(crate) directory: Directory,
109    /// CapId → { FlowId, rights } (bytecode Send/Ask addressing — FlowCap).
110    pub(crate) caps: super::capability::CapTable,
111    pub(crate) timer: Arc<TimerWheel>,
112    pub(crate) notify: (Mutex<()>, Condvar),
113    pub(crate) metrics: RuntimeMetrics,
114    pub(crate) shutdown: AtomicBool,
115    pub(crate) quantum: u32,
116    pub(crate) mailbox: MailboxConfig,
117    pub(crate) max_flows: u32,
118    pub(crate) quota: super::quota::QuotaConfig,
119    pub(crate) quotas: super::quota::QuotaTable,
120    pub(crate) monitors: super::monitor::MonitorStore,
121    pub(crate) links: super::link::LinkStore,
122    pub(crate) registry: super::registry::RegistryStore,
123    pub(crate) kill_signals: super::finalize::KillSignals,
124    pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
125    pub(crate) ask_waits: super::finalize::AskWaitIndex,
126    /// Correlation ids for host `Runtime::send` when `request_id == 0`.
127    /// Starts at 1; `0` stays the unset sentinel.
128    pub(crate) host_next_request_id: AtomicU64,
129    /// Shared trace JIT state (`feature = "jit"`).
130    #[cfg(feature = "jit")]
131    pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
132}
133
134/// A running Byteflow runtime: worker pool + timer thread over one shared
135/// [`Chunk`].
136///
137/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
138/// FlowCap resolution, supervised restarts). Optional trace JIT when built
139/// with `feature = "jit"` and enabled in [`RuntimeConfig::jit`].
140///
141/// Construct with [`Runtime::new`] (no natives) or
142/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
143/// [`crate::std_native_table`].
144pub struct Runtime {
145    shared: Arc<Shared>,
146    chunk: Arc<Chunk>,
147    natives: Arc<NativeTable>,
148    workers: Vec<JoinHandle<()>>,
149    timer_thread: Option<JoinHandle<()>>,
150    trust: crate::bytecode::TrustLevel,
151}
152
153impl Runtime {
154    /// Convenience constructor for chunks that never call out through
155    /// `Opcode::CallNative`. Equivalent to
156    /// `Runtime::with_natives(chunk, NativeTable::empty())`.
157    ///
158    /// Returns [`SpawnError`] instead of panicking: verify failures and OS
159    /// thread-spawn refusals are category-A errors (see
160    /// [`docs::error_model`](crate::docs::error_model)).
161    pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
162        Self::with_config(chunk, RuntimeConfig::default())
163    }
164
165    /// Construct a runtime whose flows can call into `natives` via
166    /// `Opcode::CallNative` — the host FFI boundary.
167    pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
168        Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
169    }
170
171    pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
172        Self::with_natives_and_config(chunk, NativeTable::empty(), config)
173    }
174
175    /// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
176    /// using [`RuntimeConfig::output`] for the `print` native.
177    pub fn with_std_natives_and_config(
178        chunk: Chunk,
179        config: RuntimeConfig,
180    ) -> Result<Self, SpawnError> {
181        Self::with_natives_and_config(
182            chunk,
183            crate::std_native_table_with(Arc::clone(&config.output)),
184            config,
185        )
186    }
187
188    /// Verify `chunk`, spawn the worker pool + timer thread, and return a
189    /// live [`Runtime`].
190    ///
191    /// Failures here mean the runtime was **never** started (no orphan
192    /// threads): either the bytecode is invalid
193    /// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
194    /// ([`SpawnError::ThreadSpawnFailed`]).
195    pub fn with_natives_and_config(
196        chunk: Chunk,
197        natives: Arc<NativeTable>,
198        config: RuntimeConfig,
199    ) -> Result<Self, SpawnError> {
200        crate::bytecode::verify_with(
201            &chunk,
202            crate::bytecode::VerifyConfig {
203                trust: config.trust,
204            },
205        )
206        .map_err(SpawnError::VerifyFailed)?;
207        let chunk = Arc::new(chunk);
208        let workers_n = config.workers.max(1);
209
210        let locals: Vec<LocalDeque<Box<Flow>>> =
211            (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
212        let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
213
214        #[cfg(feature = "jit")]
215        let jit = if config.jit.enabled {
216            Some(super::jit::new_runtime(chunk.clone(), config.jit.hot_threshold))
217        } else {
218            None
219        };
220
221        let shared = Arc::new(Shared {
222            injector: Injector::new(),
223            stealers,
224            directory: Directory::new(),
225            caps: super::capability::CapTable::new(),
226            timer: TimerWheel::new(),
227            notify: (Mutex::new(()), Condvar::new()),
228            metrics: RuntimeMetrics::default(),
229            shutdown: AtomicBool::new(false),
230            quantum: config.quantum,
231            mailbox: config.mailbox,
232            max_flows: config.max_flows,
233            quota: config.quota,
234            quotas: super::quota::QuotaTable::new(),
235            monitors: super::monitor::MonitorStore::new(),
236            links: super::link::LinkStore::new(),
237            registry: super::registry::RegistryStore::new(),
238            kill_signals: super::finalize::KillSignals::new(),
239            waiting_send_at: super::finalize::WaitingSendIndex::new(),
240            ask_waits: super::finalize::AskWaitIndex::new(),
241            host_next_request_id: AtomicU64::new(1),
242            #[cfg(feature = "jit")]
243            jit,
244        });
245
246        let mut workers = Vec::with_capacity(workers_n);
247        for local in locals {
248            let shared = shared.clone();
249            let handle = std::thread::Builder::new()
250                .name("byteflow-worker".into())
251                .spawn(move || worker::run_worker(shared, local))
252                .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
253            workers.push(handle);
254        }
255
256        let shared_timer = shared.clone();
257        let timer_thread = std::thread::Builder::new()
258            .name("byteflow-timer".into())
259            .spawn(move || {
260                shared_timer.timer.clone().drive(&shared_timer)
261            })
262            .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
263
264        Ok(Runtime {
265            shared,
266            chunk,
267            natives,
268            workers,
269            timer_thread: Some(timer_thread),
270            trust: config.trust,
271        })
272    }
273
274    /// Spawn a top-level flow starting at `function` in this runtime's
275    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
276    ///
277    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
278    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
279        spawn_on(
280            &self.shared,
281            &self.chunk,
282            &self.natives,
283            function,
284            args,
285            RestartPolicy::Never,
286            None,
287            None,
288            None,
289        )
290    }
291
292    /// A cheap, `Send + Sync` handle that can spawn processes into this
293    /// runtime from any thread, independent of `Runtime`'s own lifetime
294    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
295    pub fn spawner(&self) -> RuntimeSpawner {
296        RuntimeSpawner { shared: self.shared.clone(), chunk: self.chunk.clone(), natives: self.natives.clone() }
297    }
298
299    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
300    /// take supervised children (design notes §15).
301    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
302        super::supervisor::Supervisor::new(self.spawner())
303    }
304
305    /// Look up a function by name in the runtime's chunk — convenience for
306    /// callers that built their chunk with [`crate::Program`]
307    /// and don't want to thread raw indices through their own code.
308    pub fn function_index(&self, name: &str) -> Option<u32> {
309        self.chunk.functions.iter().position(|f| f.name == name).map(|i| i as u32)
310    }
311
312    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
313        self.shared.metrics.snapshot()
314    }
315
316    /// Number of flows currently registered in the directory — i.e.
317    /// alive (running, ready, sleeping, or waiting), not counting ones that
318    /// have already completed or failed.
319    pub fn live_flows(&self) -> usize {
320        self.shared.directory.len()
321    }
322
323    pub fn worker_count(&self) -> usize {
324        self.workers.len()
325    }
326
327    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
328    /// embedder (not from bytecode).
329    ///
330    /// # Host trust boundary
331    ///
332    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
333    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
334    /// `Ask`. The hop still goes through the same authentication choke-point
335    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
336    /// is minted when unset, and payload Caps are reissued to the recipient.
337    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
338    /// Bare scalars are rejected ([`SendError::NotAHop`]).
339    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
340        let Some(msg) = message.as_message().cloned() else {
341            return Err(SendError::NotAHop {
342                got: message.type_name(),
343            });
344        };
345        let mailbox = match self.shared.directory.lookup(target) {
346            Ok(Some(m)) => m,
347            Ok(None) => return Err(SendError::NoSuchFlow(target)),
348            Err(e) => {
349                super::error::report_fault(e);
350                return Err(SendError::Unavailable);
351            }
352        };
353        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
354            Ok(m) => Value::Message(m),
355            Err(_) => return Err(SendError::Capability),
356        };
357        match mailbox.push(stamped.clone()) {
358            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
359                Ok(())
360            }
361            Ok(Ok(Delivery::Handoff(flow))) => {
362                let _ = self.shared.ask_waits.remove_asker(flow.id);
363                match flow.last_receive_dest {
364                    Some(dest) => {
365                        let Some(flow) =
366                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
367                        else {
368                            return Err(SendError::Unavailable);
369                        };
370                        self.shared.injector.push(flow);
371                        wake_workers(&self.shared);
372                        Ok(())
373                    }
374                    None => {
375                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
376                            "Runtime::send handoff missing dest register",
377                        ));
378                        finalize_flow(
379                            &self.shared,
380                            *flow,
381                            FlowOutcome::Failed("handoff missing dest register".into()),
382                            FlowExitReason::Fault,
383                        );
384                        Err(SendError::Unavailable)
385                    }
386                }
387            }
388            Ok(Err(full)) => Err(SendError::MailboxFull {
389                flow: target,
390                reason: full.reason(),
391            }),
392            Err(e) => {
393                super::error::report_fault(e);
394                Err(SendError::Unavailable)
395            }
396        }
397    }
398
399    fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
400        match self.shared.directory.lookup(id) {
401            Ok(Some(_)) => Ok(()),
402            Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
403            Err(e) => Err(self.unavailable(e)),
404        }
405    }
406
407    fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
408        super::error::report_fault(err);
409        super::error::LifecycleError::Unavailable
410    }
411
412    /// Mint a SEND|ASK Cap for a live flow (host equivalent of `SelfPid`).
413    pub fn mint_cap(&self, flow: FlowId) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
414        self.require_live(flow)?;
415        self.shared
416            .caps
417            .mint(flow, flow, super::capability::CapRights::ADDRESSING)
418            .map_err(|e| self.unavailable(e))
419    }
420
421    /// Mint a Cap held by `holder` targeting `target` (host introduction).
422    pub fn grant_cap(
423        &self,
424        holder: FlowId,
425        target: FlowId,
426    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
427        self.require_live(holder)?;
428        self.require_live(target)?;
429        self.shared
430            .caps
431            .mint(holder, target, super::capability::CapRights::ADDRESSING)
432            .map_err(|e| self.unavailable(e))
433    }
434
435    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
436    ///
437    /// Both flows must be live. `owner == target` is [`LifecycleError::SelfRelation`].
438    pub fn monitor(
439        &self,
440        owner: FlowId,
441        target: FlowId,
442    ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
443        if owner == target {
444            return Err(super::error::LifecycleError::SelfRelation);
445        }
446        self.require_live(owner)?;
447        self.require_live(target)?;
448        let mon = self
449            .shared
450            .monitors
451            .create(owner, target)
452            .map_err(|e| self.unavailable(e))?;
453        // Target may have finalized between the live check and insert.
454        // Synthesize DOWN and drop the now-useless relation (owner still live).
455        if self.require_live(target).is_err() {
456            let _ = self.shared.monitors.remove_owned(owner, mon);
457            super::finalize::deliver_down(
458                &self.shared,
459                super::monitor::DownEvent {
460                    monitor: mon,
461                    owner,
462                    target,
463                    reason: super::monitor::FlowExitReason::Fault,
464                },
465            );
466        }
467        Ok(mon)
468    }
469
470    /// Drop `monitor` if `owner` still owns it.
471    pub fn demonitor(
472        &self,
473        owner: FlowId,
474        monitor: super::monitor::MonitorRef,
475    ) -> Result<(), super::error::LifecycleError> {
476        self.require_live(owner)?;
477        match self.shared.monitors.remove_owned(owner, monitor) {
478            Ok(inner) => inner,
479            Err(e) => Err(self.unavailable(e)),
480        }
481    }
482
483    /// Bidirectional link. Abnormal exit of either side kills the peer.
484    pub fn link(
485        &self,
486        a: FlowId,
487        b: FlowId,
488    ) -> Result<super::link::LinkId, super::error::LifecycleError> {
489        if a == b {
490            return Err(super::error::LifecycleError::SelfRelation);
491        }
492        self.require_live(a)?;
493        self.require_live(b)?;
494        match self.shared.links.link(a, b) {
495            Ok(inner) => inner,
496            Err(e) => Err(self.unavailable(e)),
497        }
498    }
499
500    /// Drop `link` if `owner` is one of the endpoints.
501    pub fn unlink(
502        &self,
503        owner: FlowId,
504        link: super::link::LinkId,
505    ) -> Result<(), super::error::LifecycleError> {
506        self.require_live(owner)?;
507        match self.shared.links.unlink_owned(owner, link) {
508            Ok(inner) => inner,
509            Err(e) => Err(self.unavailable(e)),
510        }
511    }
512
513    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
514    pub fn register_name(
515        &self,
516        name: &str,
517        cap: crate::bytecode::CapId,
518    ) -> Result<(), super::error::LifecycleError> {
519        let entry = match self.shared.caps.lookup(cap) {
520            Ok(Some(e)) => e,
521            Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
522            Err(e) => return Err(self.unavailable(e)),
523        };
524        let target = match entry.target() {
525            Some(id) => id,
526            None => return Err(super::error::LifecycleError::InvalidCapability),
527        };
528        self.require_live(target)?;
529        match self.shared.registry.register(
530            super::registry::RegistryName::from(name),
531            cap,
532            target,
533        ) {
534            Ok(inner) => inner,
535            Err(e) => Err(self.unavailable(e)),
536        }
537    }
538
539    /// Look up a registered Cap, or `None` if the name is free / was swept.
540    pub fn whereis(&self, name: &str) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
541        self.shared
542            .registry
543            .whereis(name)
544            .map_err(|e| self.unavailable(e))
545    }
546
547    /// Cooperative abort. Parked flows finalize immediately; a running flow
548    /// dies at the next quantum with [`super::monitor::FlowExitReason::Killed`].
549    pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
550        self.require_live(id)?;
551        super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
552        Ok(())
553    }
554
555    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
556    pub fn mint_admin_cap(
557        &self,
558        holder: FlowId,
559    ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
560        self.require_live(holder)?;
561        let cap = crate::bytecode::Cap::root(
562            crate::bytecode::CapTarget::Scheduler,
563            CapRights::ADMIN,
564            None,
565            self.shared.caps.scheduler_cell().as_ref(),
566        );
567        self.shared
568            .caps
569            .grant(holder, cap)
570            .map_err(|e| self.unavailable(e))
571    }
572
573    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
574    pub fn admin_kill(
575        &self,
576        holder: FlowId,
577        cap: crate::bytecode::CapId,
578        target: FlowId,
579    ) -> Result<(), super::error::LifecycleError> {
580        self.require_admin(holder, cap)?;
581        self.kill(target)
582    }
583
584    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
585    pub fn admin_top_up_cpu(
586        &self,
587        holder: FlowId,
588        cap: crate::bytecode::CapId,
589        target: FlowId,
590        extra: i64,
591    ) -> Result<(), super::error::LifecycleError> {
592        self.require_admin(holder, cap)?;
593        let quota = match self.shared.quotas.get(target) {
594            Ok(Some(q)) => q,
595            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
596            Err(e) => return Err(self.unavailable(e)),
597        };
598        quota.top_up_cpu(extra);
599        Ok(())
600    }
601
602    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
603    pub fn admin_top_up_mem(
604        &self,
605        holder: FlowId,
606        cap: crate::bytecode::CapId,
607        target: FlowId,
608        extra: usize,
609    ) -> Result<(), super::error::LifecycleError> {
610        self.require_admin(holder, cap)?;
611        let quota = match self.shared.quotas.get(target) {
612            Ok(Some(q)) => q,
613            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
614            Err(e) => return Err(self.unavailable(e)),
615        };
616        quota.top_up_mem(extra);
617        Ok(())
618    }
619
620    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
621    pub fn admin_top_up_send(
622        &self,
623        holder: FlowId,
624        cap: crate::bytecode::CapId,
625        target: FlowId,
626        extra: i64,
627    ) -> Result<(), super::error::LifecycleError> {
628        self.require_admin(holder, cap)?;
629        let quota = match self.shared.quotas.get(target) {
630            Ok(Some(q)) => q,
631            Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
632            Err(e) => return Err(self.unavailable(e)),
633        };
634        quota.top_up_send(extra);
635        Ok(())
636    }
637
638    fn require_admin(
639        &self,
640        holder: FlowId,
641        cap: crate::bytecode::CapId,
642    ) -> Result<(), super::error::LifecycleError> {
643        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
644            Ok(e) => e,
645            Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
646        };
647        super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
648            .map_err(|_| super::error::LifecycleError::InvalidCapability)
649    }
650
651    /// Remove a name without waiting for the flow to exit. `false` if unknown.
652    pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
653        self.shared
654            .registry
655            .unregister(name)
656            .map_err(|e| self.unavailable(e))
657    }
658
659    /// Replace the image used by **new host** [`Self::spawn`] calls and
660    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
661    /// existing `Vm` chunk.
662    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
663        crate::bytecode::verify_with(
664            &chunk,
665            crate::bytecode::VerifyConfig {
666                trust: self.trust,
667            },
668        )
669        .map_err(SpawnError::VerifyFailed)?;
670        let chunk = Arc::new(chunk);
671        self.chunk = chunk.clone();
672        #[cfg(feature = "jit")]
673        if let Some(jit) = &self.shared.jit {
674            jit.reload(chunk);
675        }
676        Ok(())
677    }
678
679    /// Signal workers and the timer to stop. Does **not** join threads —
680    /// use [`Self::shutdown`] for a deterministic join. [`Drop`] only signals.
681    fn request_shutdown(&self) {
682        self.shared.shutdown.store(true, Ordering::Release);
683        self.shared.timer.shutdown();
684        let (lock, cvar) = &self.shared.notify;
685        match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
686            Ok(_g) => cvar.notify_all(),
687            Err(e) => super::error::report_fault(e),
688        }
689    }
690
691    /// Stop accepting new scheduling work and join every worker + the timer
692    /// thread. Processes that are mid-quantum are allowed to reach their
693    /// next natural suspension point; this does **not** forcibly abort
694    /// running bytecode (there is no safe way to do that to an OS thread
695    /// mid-instruction — see design notes §11 on why preemption here is
696    /// cooperative/budgeted rather than signal-based).
697    pub fn shutdown(mut self) {
698        self.request_shutdown();
699        for w in self.workers.drain(..) {
700            let _ = w.join();
701        }
702        if let Some(t) = self.timer_thread.take() {
703            let _ = t.join();
704        }
705    }
706}
707
708impl Drop for Runtime {
709    fn drop(&mut self) {
710        if !self.shared.shutdown.load(Ordering::Acquire) {
711            self.request_shutdown();
712        }
713    }
714}
715
716/// A convenience Pid constructor for embedders that stored a raw `u64`
717/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
718/// call APIs that take one.
719pub fn flow_id_from_u64(raw: u64) -> FlowId {
720    FlowId(raw)
721}
722
723/// Why [`Runtime::send`] could not deliver a hop.
724#[derive(Debug, Clone, PartialEq, Eq)]
725pub enum SendError {
726    NoSuchFlow(FlowId),
727    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
728    NotAHop { got: &'static str },
729    /// Target inbox is at one of its logical bounds
730    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
731    /// [`MailboxFullReason`].
732    MailboxFull {
733        flow: FlowId,
734        reason: MailboxFullReason,
735    },
736    /// Host hop authentication failed (payload Cap reissue).
737    Capability,
738    /// Directory / mailbox mutex poisoned — not "no such flow".
739    Unavailable,
740}
741
742impl std::fmt::Display for SendError {
743    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
744        match self {
745            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
746            SendError::NotAHop { got } => {
747                write!(f, "atomic hop requires Value::Message, got {got}")
748            }
749            SendError::MailboxFull { flow, reason } => {
750                write!(f, "mailbox full for {flow} ({reason})")
751            }
752            SendError::Capability => {
753                write!(f, "host send could not reissue a capability in the hop")
754            }
755            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
756        }
757    }
758}
759
760impl std::error::Error for SendError {}
761
762/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
763/// the child. Host spawn passes `None` and mints a trusted root instead.
764pub(crate) struct BytecodeSpawn<'a> {
765    pub authority: &'a Cap,
766    pub cell: &'a crate::bytecode::RevocationCell,
767    pub quota: &'a super::quota::FlowQuota,
768    pub requested_rights: CapRights,
769}
770
771/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
772/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
773/// mailbox + completion channel), register it in the directory, and push
774/// it onto the global injector for any worker to pick up.
775///
776/// Returns [`SpawnError`] on bad function index / VM init / directory
777/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
778/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
779pub(crate) fn spawn_on(
780    shared: &Arc<Shared>,
781    chunk: &Arc<Chunk>,
782    natives: &Arc<NativeTable>,
783    function: u32,
784    args: &[Value],
785    restart_policy: RestartPolicy,
786    supervisor: Option<SupervisorLink>,
787    parent: Option<FlowId>,
788    bytecode: Option<BytecodeSpawn<'_>>,
789) -> Result<FlowHandle, SpawnError> {
790    if shared.max_flows > 0 {
791        let current = shared.directory.len();
792        if current >= shared.max_flows as usize {
793            return Err(SpawnError::FlowLimit {
794                current,
795                max: shared.max_flows,
796            });
797        }
798    }
799    let id = match super::process::try_next_flow_id() {
800        Ok(id) => id,
801        Err(super::error::RuntimeError::FlowIdExhausted) => {
802            return Err(SpawnError::FlowIdExhausted)
803        }
804        Err(_) => return Err(SpawnError::Unavailable),
805    };
806    let cell = shared
807        .caps
808        .bind_flow(id)
809        .map_err(|_| SpawnError::Unavailable)?;
810    let authority = match bytecode {
811        None => Cap::root(
812            CapTarget::Flow(id.as_u64()),
813            CapRights::ROOT,
814            Some(NativeMask::full(natives.len())),
815            cell.as_ref(),
816        ),
817        Some(ctx) => super::spawn::exec_spawn_authority(
818            ctx.authority,
819            ctx.cell,
820            ctx.quota,
821            id.as_u64(),
822            ctx.requested_rights,
823            None,
824            cell.as_ref(),
825        )
826        .map_err(SpawnError::from)?,
827    };
828    let args = grant_caps_in_args(shared, parent, id, args)?;
829    let gate = NativeGate::from_authority(
830        &authority,
831        Arc::clone(&cell),
832        shared.caps.native_cell(),
833        natives.len(),
834    );
835    let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
836    let mut vm = Vm::with_native_gate(chunk.clone(), natives.clone(), gate, function, args.as_slice())?;
837    vm.set_quota(Arc::clone(&quota))?;
838    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
839    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
840        super::error::report_fault(e);
841        return Err(SpawnError::Unavailable);
842    }
843    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
844        super::error::report_fault(e);
845        return Err(SpawnError::Unavailable);
846    }
847    let (tx, rx) = super::oneshot::channel();
848    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
849    flow.authority = authority;
850    flow.cell = cell;
851    flow.quota = quota;
852    flow.supervisor = supervisor;
853    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
854    shared.injector.push(flow);
855    wake_workers(shared);
856    Ok(FlowHandle { id, receiver: rx })
857}
858
859fn grant_caps_in_args(
860    shared: &Shared,
861    parent: Option<FlowId>,
862    child: FlowId,
863    args: &[Value],
864) -> Result<Vec<Value>, SpawnError> {
865    let mut out = Vec::with_capacity(args.len());
866    for arg in args {
867        match arg {
868            Value::Cap(id) => {
869                let granted = match parent {
870                    None => shared.caps.reissue_for(*id, child),
871                    Some(p) => shared.caps.delegate(*id, p, child),
872                };
873                match granted {
874                    Ok(cap) => out.push(Value::Cap(cap)),
875                    Err(_) => return Err(SpawnError::InvalidCapability),
876                }
877            }
878            other => out.push(other.clone()),
879        }
880    }
881    Ok(out)
882}
883
884pub(crate) fn wake_workers(shared: &Shared) {
885    let (lock, cvar) = &shared.notify;
886    match super::sync_lock::lock(lock, "wake_workers") {
887        Ok(_g) => cvar.notify_one(),
888        Err(e) => super::error::report_fault(e),
889    }
890}
891
892/// A `Send + Sync`, freely cloneable capability to spawn processes into a
893/// [`Runtime`], detached from the `Runtime` value itself. Exists because
894/// [`super::supervisor::Supervisor`] needs to respawn processes from a
895/// background monitor thread whose lifetime isn't tied to the `Runtime`
896/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
897#[derive(Clone)]
898pub struct RuntimeSpawner {
899    pub(crate) shared: Arc<Shared>,
900    pub(crate) chunk: Arc<Chunk>,
901    pub(crate) natives: Arc<NativeTable>,
902}
903
904impl RuntimeSpawner {
905    pub fn spawn(
906        &self,
907        function: u32,
908        args: &[Value],
909        restart_policy: RestartPolicy,
910    ) -> Result<FlowHandle, SpawnError> {
911        spawn_on(
912            &self.shared,
913            &self.chunk,
914            &self.natives,
915            function,
916            args,
917            restart_policy,
918            None,
919            None,
920            None,
921        )
922    }
923
924    pub(crate) fn spawn_linked(
925        &self,
926        function: u32,
927        args: &[Value],
928        restart_policy: RestartPolicy,
929        supervisor: SupervisorLink,
930    ) -> Result<FlowHandle, SpawnError> {
931        spawn_on(
932            &self.shared,
933            &self.chunk,
934            &self.natives,
935            function,
936            args,
937            restart_policy,
938            Some(supervisor),
939            None,
940            None,
941        )
942    }
943
944    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
945        self.shared.metrics.snapshot()
946    }
947
948    pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
949        super::finalize::request_kill(&self.shared, id, reason);
950    }
951}
952
953#[cfg(test)]
954mod tests {
955    use super::*;
956    use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
957    use crate::scheduler::FlowOutcome;
958    use std::time::Duration;
959
960    fn add_chunk() -> Chunk {
961        let mut b = ChunkBuilder::new("test");
962        b.begin_function("main", 0, 2);
963        b.emit_load_imm(0, 41);
964        b.emit_load_imm(1, 1);
965        b.emit_binop(Opcode::Add, 0, 0, 1);
966        b.emit_return(0);
967        b.finish()
968    }
969
970    /// Sleeps `millis` inside the flow, then returns 7. The sleep is what
971    /// makes "still running" an observable state from the host thread.
972    fn sleep_then_return_chunk(millis: i32) -> Chunk {
973        let mut b = ChunkBuilder::new("test");
974        b.begin_function("main", 0, 2);
975        b.emit_load_imm(0, millis);
976        b.emit_sleep(0);
977        b.emit_load_imm(0, 7);
978        b.emit_return(0);
979        b.finish()
980    }
981
982    /// The host thread must be able to ask "done yet?" and to wait under a
983    /// bound *it* chooses, instead of surrendering itself to `join` for
984    /// however long the bytecode decides to take.
985    #[test]
986    fn polling_and_bounded_waits_never_commit_the_host_thread() -> Result<(), Box<dyn std::error::Error>>
987    {
988        const FLOW_SLEEP: i32 = 150;
989        let rt = Runtime::with_config(
990            sleep_then_return_chunk(FLOW_SLEEP),
991            RuntimeConfig {
992                workers: 1,
993                quantum: 1_000,
994                mailbox: MailboxConfig::DEFAULT,
995                ..Default::default()
996            },
997        )?;
998        let handle = rt.spawn(0, &[])?;
999
1000        // The flow cannot possibly be finished yet: it has to be picked up
1001        // and then sleep. A poll must say so without waiting.
1002        if let Some(outcome) = handle.try_join() {
1003            rt.shutdown();
1004            return Err(format!("try_join answered too early: {outcome:?}").into());
1005        }
1006
1007        // A bound well below the flow's sleep must expire and hand control
1008        // back, not block until the flow happens to finish.
1009        if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1010            rt.shutdown();
1011            return Err(format!("join_timeout answered too early: {outcome:?}").into());
1012        }
1013
1014        // A generous bound collects the real outcome through the same
1015        // (non-consuming) handle.
1016        let outcome = handle.join_timeout(Duration::from_secs(10));
1017        rt.shutdown();
1018        match outcome {
1019            Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1020            other => Err(format!("unexpected outcome: {other:?}").into()),
1021        }
1022    }
1023
1024    #[test]
1025    fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1026        let rt = Runtime::with_config(
1027            add_chunk(),
1028            RuntimeConfig {
1029                workers: 1,
1030                quantum: 1_000,
1031                mailbox: MailboxConfig::DEFAULT,
1032                ..Default::default()
1033            },
1034        )?;
1035        let outcome = rt.spawn(0, &[])?.join();
1036        rt.shutdown();
1037        match outcome {
1038            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1039            other => Err(format!("unexpected outcome: {other:?}").into()),
1040        }
1041    }
1042
1043    fn receive_forever_chunk() -> Chunk {
1044        let mut b = ChunkBuilder::new("recv");
1045        b.begin_function("main", 0, 1);
1046        b.emit_receive(0);
1047        b.emit_return(0);
1048        b.finish()
1049    }
1050
1051    #[test]
1052    fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1053        let rt = Runtime::with_config(
1054            receive_forever_chunk(),
1055            RuntimeConfig {
1056                workers: 1,
1057                quantum: 1_000,
1058                mailbox: MailboxConfig::DEFAULT,
1059                ..Default::default()
1060            },
1061        )?;
1062        let handle = rt.spawn(0, &[])?;
1063        rt.kill(handle.id())?;
1064        let outcome = handle.join();
1065        rt.shutdown();
1066        assert!(
1067            matches!(outcome, FlowOutcome::Failed(_)),
1068            "kill must fail the joiner, got {outcome:?}"
1069        );
1070        Ok(())
1071    }
1072
1073    #[test]
1074    fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1075        let rt = Runtime::with_config(
1076            receive_forever_chunk(),
1077            RuntimeConfig {
1078                workers: 1,
1079                quantum: 1_000,
1080                mailbox: MailboxConfig::DEFAULT,
1081                max_flows: 1,
1082                ..Default::default()
1083            },
1084        )?;
1085        let first = rt.spawn(0, &[])?;
1086        let second = rt.spawn(0, &[]);
1087        rt.kill(first.id())?;
1088        let _ = first.join();
1089        rt.shutdown();
1090        match second {
1091            Err(SpawnError::FlowLimit { current, max }) => {
1092                assert_eq!(current, 1);
1093                assert_eq!(max, 1);
1094                Ok(())
1095            }
1096            other => Err(format!(
1097                "expected FlowLimit, got {}",
1098                match &other {
1099                    Ok(_) => "Ok(handle)".into(),
1100                    Err(e) => format!("Err({e})"),
1101                }
1102            )
1103            .into()),
1104        }
1105    }
1106
1107    #[cfg(feature = "jit")]
1108    #[test]
1109    fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1110        use crate::JitConfig;
1111
1112        let rt = Runtime::with_config(
1113            add_chunk(),
1114            RuntimeConfig {
1115                workers: 1,
1116                quantum: 1_000,
1117                mailbox: MailboxConfig::DEFAULT,
1118                jit: JitConfig {
1119                    enabled: true,
1120                    hot_threshold: 1,
1121                },
1122                ..Default::default()
1123            },
1124        )?;
1125        let outcome = rt.spawn(0, &[])?.join();
1126        rt.shutdown();
1127        match outcome {
1128            FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1129            other => Err(format!("unexpected outcome: {other:?}").into()),
1130        }
1131    }
1132}