Skip to main content

byteflow/scheduler/
runtime.rs

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