Skip to main content

byteflow/scheduler/
runtime.rs

1//! The [`Runtime`]: M:N scheduler state shared by workers, host-facing
2//! spawn/send/deliver entry points, and shutdown.
3//!
4//! Split by concern: [`config`] (tunables), `control` (capabilities,
5//! monitors, links, names, admin, shutdown), `spawn` (the spawn path and
6//! [`RuntimeSpawner`]).
7
8// Docs ratchet: public items here predate `missing_docs`. Delete this
9// allow once they are documented; new files get the lint by default.
10#![allow(missing_docs)]
11
12use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
13use std::sync::{Arc, Condvar, Mutex};
14use std::thread::JoinHandle;
15
16use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
17use crate::vm::{NativeGate, NativeTable, Vm};
18
19use super::directory::Directory;
20use super::error::{RuntimeError, SpawnError};
21use super::finalize::finalize_flow;
22use super::handle::FlowHandle;
23use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
24use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot};
25use super::monitor::FlowExitReason;
26use super::process::{Flow, FlowId, FlowOutcome};
27use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
28use super::supervisor::SupervisorLink;
29use super::timer::TimerWheel;
30use super::worker;
31use crate::bytecode::RestartPolicy;
32
33mod config;
34mod control;
35mod spawn;
36#[cfg(test)]
37mod tests;
38
39#[cfg(feature = "jit")]
40pub use self::config::JitConfig;
41pub use self::config::{RootAuthorityPolicy, RuntimeConfig, DEFAULT_QUANTUM};
42#[cfg(test)]
43use self::spawn::bytecode_spawn_arity;
44pub use self::spawn::RuntimeSpawner;
45pub(crate) use self::spawn::{spawn_on, BytecodeSpawn};
46
47/// State shared by every worker thread and the timer thread. Everything in
48/// here is either internally synchronized (`Injector`, `Directory`,
49/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
50/// construction (`stealers`, `quantum`) — there is no top-level lock
51/// covering the whole runtime, by design: a global lock is exactly what an
52/// M:N scheduler exists to avoid.
53pub(crate) struct Shared {
54    pub(crate) injector: Injector<Box<Flow>>,
55    pub(crate) stealers: Vec<Stealer<Flow>>,
56    /// FlowId → mailbox (delivery after Cap resolution).
57    pub(crate) directory: Directory,
58    /// CapId → { holder, target, rights, native_mask, epoch } (FlowCap).
59    pub(crate) caps: super::capability::CapTable,
60    pub(crate) timer: Arc<TimerWheel>,
61    pub(crate) notify: (Mutex<()>, Condvar),
62    pub(crate) metrics: RuntimeMetrics,
63    pub(crate) shutdown: AtomicBool,
64    pub(crate) quantum: u32,
65    pub(crate) mailbox: MailboxConfig,
66    /// Atomic live-flow budget (`max_flows == 0` → unlimited).
67    pub(crate) flow_limit: super::flow_limit::FlowLimit,
68    pub(crate) memory: Arc<crate::MemoryBudget>,
69    pub(crate) quota: super::quota::QuotaConfig,
70    pub(crate) quotas: super::quota::QuotaTable,
71    pub(crate) monitors: super::monitor::MonitorStore,
72    pub(crate) links: super::link::LinkStore,
73    pub(crate) registry: super::registry::RegistryStore,
74    pub(crate) kill_signals: super::finalize::KillSignals,
75    pub(crate) trap_exits: super::finalize::TrapExitFlags,
76    pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
77    pub(crate) ask_waits: super::finalize::AskWaitIndex,
78    /// In-flight `Opcode::HostAwait` tickets. The flow stays on a worker
79    /// or in its mailbox; completion arrives as a host hop.
80    pub(crate) host_awaits: super::host_await::HostAwaitIndex,
81    /// Host async bridge (`None` ⇒ HostAwait fails closed).
82    pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
83    /// Recorded order for host completions. `None` delivers immediately.
84    pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
85    /// Host `fail` text the worker reads before committing a success.
86    pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
87    /// `SendRemote` queue. `None` fails the opcode.
88    pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
89    /// Optional replay filter for inbound remote frames.
90    pub(crate) remote_dedup: Option<Arc<super::distribution::RemoteFrameDedup>>,
91    /// Embedder copy of scheduler diagnostics. `None` leaves stderr gating
92    /// in [`crate::log`] unchanged.
93    pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
94    /// One named table per flow. Empty until `TableOpen`.
95    pub(crate) tables: super::table::FlowTables,
96    /// Supervisors started by bytecode `StartSupervisor`. Joined from
97    /// [`Runtime::shutdown`] after workers stop.
98    pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
99    /// Correlation ids for host `Runtime::send` when `request_id == 0`.
100    /// Starts at 1; `0` stays the unset sentinel.
101    pub(crate) host_next_request_id: AtomicU64,
102    /// Shared trace JIT state (`feature = "jit"`).
103    #[cfg(feature = "jit")]
104    pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
105    /// Sandbox observability (host-only; bytecode cannot mutate).
106    pub(crate) security: Arc<super::sandbox::SecurityCounters>,
107    pub(crate) security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
108    pub(crate) policy: super::sandbox::PolicyFingerprint,
109    pub(crate) trust: crate::bytecode::TrustLevel,
110    pub(crate) root_authority: RootAuthorityPolicy,
111}
112
113/// A running Byteflow runtime: worker pool + timer thread over one shared
114/// [`Chunk`].
115///
116/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
117/// FlowCap resolution, supervised restarts). Optional trace JIT when built
118/// with `feature = "jit"` and enabled in `RuntimeConfig`'s `jit` field.
119///
120/// Construct with [`Runtime::new`] (no natives) or
121/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
122/// [`crate::std_native_table`].
123pub struct Runtime {
124    shared: Arc<Shared>,
125    chunk: Arc<Chunk>,
126    natives: Arc<NativeTable>,
127    workers: Vec<JoinHandle<()>>,
128    timer_thread: Option<JoinHandle<()>>,
129    audit_worker: Option<super::sandbox::AuditWorkerHandle>,
130    trust: crate::bytecode::TrustLevel,
131}
132
133impl Runtime {
134    /// Convenience constructor for chunks that never call out through
135    /// `Opcode::CallNative`. Equivalent to
136    /// `Runtime::with_natives(chunk, NativeTable::empty())`.
137    ///
138    /// Returns [`SpawnError`] instead of panicking: verify failures and OS
139    /// thread-spawn refusals are category-A errors (see
140    /// [`docs::error_model`](crate::docs::error_model)).
141    pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
142        Self::with_config(chunk, RuntimeConfig::default())
143    }
144
145    /// Construct a runtime whose flows can call into `natives` via
146    /// `Opcode::CallNative` — the host FFI boundary.
147    pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
148        Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
149    }
150
151    pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
152        Self::with_natives_and_config(chunk, NativeTable::empty(), config)
153    }
154
155    /// Decode a `.bf` buffer only if its integrity fingerprint matches
156    /// `expected_digest`, then verify and start the runtime.
157    ///
158    /// Digest mismatch / decode failure → [`SpawnError::Attestation`].
159    /// Semantic verify failure → [`SpawnError::VerifyFailed`].
160    pub fn with_attested(
161        bytes: &[u8],
162        expected_digest: [u8; 32],
163        natives: Arc<NativeTable>,
164        config: RuntimeConfig,
165    ) -> Result<Self, SpawnError> {
166        let chunk =
167            crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
168        Self::with_natives_and_config(chunk, natives, config)
169    }
170
171    /// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
172    /// using [`RuntimeConfig::output`] for the `print` native.
173    pub fn with_std_natives_and_config(
174        chunk: Chunk,
175        config: RuntimeConfig,
176    ) -> Result<Self, SpawnError> {
177        Self::with_natives_and_config(
178            chunk,
179            crate::std_native_table_with(Arc::clone(&config.output)),
180            config,
181        )
182    }
183
184    /// Verify `chunk`, spawn the worker pool + timer thread, and return a
185    /// live [`Runtime`].
186    ///
187    /// Failures here mean the runtime was **never** started (no orphan
188    /// threads): either the bytecode is invalid
189    /// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
190    /// ([`SpawnError::ThreadSpawnFailed`]). Partial spawn failure rolls
191    /// back: already-started workers/timer are shut down and joined before
192    /// the error is returned.
193    pub fn with_natives_and_config(
194        chunk: Chunk,
195        natives: Arc<NativeTable>,
196        config: RuntimeConfig,
197    ) -> Result<Self, SpawnError> {
198        if let Err(err) = crate::bytecode::verify_with(
199            &chunk,
200            crate::bytecode::VerifyConfig {
201                trust: config.trust,
202            },
203        ) {
204            if let Some(sink) = config.security_audit.as_ref() {
205                // Sync notify before workers exist — verify never starts the pool.
206                sink.record(&super::sandbox::SecurityEvent::ModuleRejected {
207                    reason: "verify_failed",
208                });
209            }
210            return Err(SpawnError::VerifyFailed(err));
211        }
212        let chunk = Arc::new(chunk);
213        let workers_n = config.workers.max(1);
214        let quantum = config.quantum.max(1);
215
216        let (security_audit, audit_worker) = match config.security_audit.clone() {
217            Some(sink) => {
218                let (queued, handle) =
219                    super::sandbox::wrap_audit_sink(sink, super::sandbox::DEFAULT_AUDIT_QUEUE);
220                (Some(queued), Some(handle))
221            }
222            None => (None, None),
223        };
224
225        let locals: Vec<LocalDeque<Flow>> = (0..workers_n).map(|_| LocalDeque::new()).collect();
226        let stealers: Vec<Stealer<Flow>> = locals.iter().map(|l| l.stealer()).collect();
227
228        #[cfg(feature = "jit")]
229        let jit = if config.jit.enabled {
230            Some(super::jit::new_runtime(
231                chunk.clone(),
232                config.jit.hot_threshold,
233            ))
234        } else {
235            None
236        };
237
238        let shared = Arc::new(Shared {
239            injector: Injector::new(),
240            stealers,
241            directory: Directory::new(),
242            caps: super::capability::CapTable::new(),
243            timer: TimerWheel::new(),
244            notify: (Mutex::new(()), Condvar::new()),
245            metrics: RuntimeMetrics::default(),
246            shutdown: AtomicBool::new(false),
247            quantum,
248            mailbox: config.mailbox,
249            flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
250            memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
251            quota: config.quota,
252            quotas: super::quota::QuotaTable::new(),
253            monitors: super::monitor::MonitorStore::new(config.max_monitors),
254            links: super::link::LinkStore::new(config.max_links),
255            registry: super::registry::RegistryStore::new(config.max_registry_names),
256            kill_signals: super::finalize::KillSignals::new(),
257            trap_exits: super::finalize::TrapExitFlags::new(),
258            waiting_send_at: super::finalize::WaitingSendIndex::new(),
259            ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
260            host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
261            host_await_bridge: config.host_await.clone(),
262            host_replay: Mutex::new(None),
263            host_await_failures: super::host_await::HostAwaitFailures::new(),
264            distribution: config.distribution.clone(),
265            remote_dedup: if config.remote_dedup_window == 0 {
266                None
267            } else {
268                Some(super::distribution::RemoteFrameDedup::new(
269                    config.remote_dedup_window as usize,
270                ))
271            },
272            log_sink: config.log.clone(),
273            tables: super::table::FlowTables::new(),
274            flow_supervisors: Mutex::new(Vec::new()),
275            host_next_request_id: AtomicU64::new(1),
276            #[cfg(feature = "jit")]
277            jit,
278            security: Arc::new(super::sandbox::SecurityCounters::default()),
279            security_audit,
280            policy: config.policy_fingerprint(),
281            trust: config.trust,
282            root_authority: config.root_authority,
283        });
284
285        let mut workers = Vec::with_capacity(workers_n);
286        for local in locals {
287            let shared_w = shared.clone();
288            match std::thread::Builder::new()
289                .name("byteflow-worker".into())
290                .spawn(move || worker::run_worker(shared_w, local))
291            {
292                Ok(handle) => workers.push(handle),
293                Err(e) => {
294                    abort_startup(&shared, workers, None);
295                    return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
296                }
297            }
298        }
299
300        let shared_timer = shared.clone();
301        let timer_thread = match std::thread::Builder::new()
302            .name("byteflow-timer".into())
303            .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
304        {
305            Ok(handle) => handle,
306            Err(e) => {
307                abort_startup(&shared, workers, None);
308                return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
309            }
310        };
311
312        Ok(Runtime {
313            shared,
314            chunk,
315            natives,
316            workers,
317            timer_thread: Some(timer_thread),
318            audit_worker,
319            trust: config.trust,
320        })
321    }
322
323    /// Spawn a top-level flow starting at `function` in this runtime's
324    /// chunk, returning a [`FlowHandle`] the caller can `.join()`.
325    ///
326    /// Host authority follows [`RuntimeConfig::root_authority`] (default
327    /// trusted ROOT). For untrusted admission see [`Self::spawn_untrusted`].
328    ///
329    /// Returns [`SpawnError::BadFunction`] if `function` is out of range.
330    pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
331        spawn_on(
332            &self.shared,
333            &self.chunk,
334            &self.natives,
335            function,
336            args,
337            RestartPolicy::Never,
338            None,
339            None,
340            None,
341            None,
342        )
343    }
344
345    /// Like [`Self::spawn`], but forces [`RootAuthorityPolicy::Untrusted`]
346    /// (no Cap rights, empty native mask) regardless of config.
347    pub fn spawn_untrusted(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
348        spawn_on(
349            &self.shared,
350            &self.chunk,
351            &self.natives,
352            function,
353            args,
354            RestartPolicy::Never,
355            None,
356            None,
357            None,
358            Some(RootAuthorityPolicy::Untrusted),
359        )
360    }
361
362    /// A cheap, `Send + Sync` handle that can spawn flows into this
363    /// runtime from any thread, independent of `Runtime`'s own lifetime
364    /// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
365    pub fn spawner(&self) -> RuntimeSpawner {
366        RuntimeSpawner {
367            shared: self.shared.clone(),
368            chunk: self.chunk.clone(),
369            natives: self.natives.clone(),
370        }
371    }
372
373    /// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
374    /// take supervised children (design notes §15).
375    pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
376        super::supervisor::Supervisor::new(self.spawner())
377    }
378
379    /// Look up a function by name in the runtime's chunk — convenience for
380    /// callers that built their chunk with [`crate::Program`]
381    /// and don't want to thread raw indices through their own code.
382    pub fn function_index(&self, name: &str) -> Option<u32> {
383        self.chunk
384            .functions
385            .iter()
386            .position(|f| f.name == name)
387            .map(|i| i as u32)
388    }
389
390    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
391        self.shared.metrics.snapshot()
392    }
393
394    /// Sandbox security counters (host-only).
395    pub fn security_counters(&self) -> super::sandbox::SecurityCountersSnapshot {
396        self.shared.security.snapshot()
397    }
398
399    /// Policy fingerprint recorded at construction.
400    pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
401        self.shared.policy
402    }
403
404    /// Trust level used for constant-pool verification at construction.
405    pub fn trust_level(&self) -> crate::bytecode::TrustLevel {
406        self.trust
407    }
408
409    /// Host attestation of Caps currently held by `flow`.
410    pub fn attest_capabilities(
411        &self,
412        flow: FlowId,
413    ) -> Result<super::sandbox::CapabilityAttestation, RuntimeError> {
414        super::sandbox::CapabilityAttestation::from_table(
415            &self.shared.caps,
416            flow,
417            self.trust,
418            self.shared.policy,
419        )
420    }
421
422    /// Point-in-time view for dashboards and debug tooling.
423    pub fn snapshot(&self) -> RuntimeSnapshot {
424        RuntimeSnapshot {
425            metrics: self.metrics(),
426            live_flows: self.live_flows(),
427            flow_limit_live: self.shared.flow_limit.reserved_live(),
428            max_flows: self.shared.flow_limit.max_flows(),
429            distribution_pending: self
430                .shared
431                .distribution
432                .as_ref()
433                .and_then(|b| b.outbound_pending().ok()),
434            memory: self.memory_snapshot(),
435            workers: self.worker_count(),
436        }
437    }
438
439    /// Approximate number of flows currently registered in the directory.
440    ///
441    /// Sharded sum without a global snapshot — fine for dashboards
442    /// ([`Self::metrics`]), **not** for admission control (see
443    /// the flow limit / `max_flows`).
444    pub fn live_flows(&self) -> usize {
445        self.shared.directory.len()
446    }
447
448    /// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
449    pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
450        self.shared.memory.snapshot()
451    }
452
453    pub fn worker_count(&self) -> usize {
454        self.workers.len()
455    }
456
457    /// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
458    /// embedder (not from bytecode).
459    ///
460    /// # Host trust boundary
461    ///
462    /// This path takes a [`FlowId`] directly — **no Cap required**. The host
463    /// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
464    /// `Ask`. The hop still goes through the same authentication choke-point
465    /// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
466    /// is minted when unset, and payload Caps are reissued to the recipient.
467    /// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
468    /// Bare scalars are rejected ([`SendError::NotAHop`]).
469    pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
470        let Some(msg) = message.as_message().cloned() else {
471            return Err(SendError::NotAHop {
472                got: message.type_name(),
473            });
474        };
475        let mailbox = match self.shared.directory.lookup(target) {
476            Ok(Some(m)) => m,
477            Ok(None) => return Err(SendError::NoSuchFlow(target)),
478            Err(e) => {
479                super::error::report_fault(e);
480                return Err(SendError::Unavailable);
481            }
482        };
483        let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
484            Ok(m) => Value::Message(m),
485            Err(_) => return Err(SendError::Capability),
486        };
487        match mailbox.push(stamped.clone()) {
488            // Host `send` is fire-and-forget: DropNewest means the hop was
489            // intentionally discarded under policy, not an infrastructure
490            // error. Bytecode `Ask` treats DropNewest as hard failure in
491            // `worker::deliver` (must not park waiting for a reply).
492            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
493                Ok(())
494            }
495            Ok(Ok(Delivery::Handoff(flow))) => {
496                let _ = self.shared.ask_waits.remove_asker(flow.id);
497                match flow.last_receive_dest {
498                    Some(dest) => {
499                        let Some(flow) =
500                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
501                        else {
502                            return Err(SendError::Unavailable);
503                        };
504                        enqueue_flow(&self.shared, flow);
505                        wake_workers(&self.shared);
506                        Ok(())
507                    }
508                    None => {
509                        super::error::report_fault(super::error::RuntimeError::PoisonedLock(
510                            "Runtime::send handoff missing dest register",
511                        ));
512                        finalize_flow(
513                            &self.shared,
514                            *flow,
515                            FlowOutcome::Failed("handoff missing dest register".into()),
516                            FlowExitReason::Fault,
517                        );
518                        Err(SendError::Unavailable)
519                    }
520                }
521            }
522            Ok(Err(full)) => {
523                if full.reason() == MailboxFullReason::Closed {
524                    return Err(SendError::NoSuchFlow(target));
525                }
526                Err(SendError::MailboxFull {
527                    flow: target,
528                    reason: full.reason(),
529                })
530            }
531            Err(e) => {
532                super::error::report_fault(e);
533                Err(SendError::Unavailable)
534            }
535        }
536    }
537
538    /// Deliver a hop the host read off its own socket.
539    ///
540    /// The frame's sender is kept. This path does not restamp it as the local
541    /// host (`0`). A `Cap` or `Pid` in the frame is refused. The name must
542    /// already be registered on this node; the host still owns the socket.
543    ///
544    /// When [`RuntimeConfig::remote_dedup_window`] is set, acceptance is
545    /// transactional: a failed delivery (unknown name, full mailbox) rolls
546    /// back the reservation so the host may retransmit the same
547    /// `(sender, request_id)`.
548    pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
549        let hop = super::distribution::decode_frame(bytes)?;
550        let reservation = if hop.message.request_id != 0 {
551            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
552                match dedup
553                    .reserve(hop.sender.as_u64(), hop.message.request_id)
554                    .map_err(|_| super::distribution::RemoteFrameError::Unavailable)?
555                {
556                    super::distribution::DedupTicket::Duplicate => return Ok(()),
557                    super::distribution::DedupTicket::Fresh { sender, request_id } => {
558                        Some((sender, request_id))
559                    }
560                }
561            } else {
562                None
563            }
564        } else {
565            None
566        };
567
568        let outcome = self.deliver_frame_after_dedup(hop);
569        if let Some((sender, request_id)) = reservation {
570            if let Some(dedup) = self.shared.remote_dedup.as_ref() {
571                match &outcome {
572                    // Mailbox accepted the hop (queued or handoff taken).
573                    Ok(()) | Err(DeliverAcceptError::AfterAccept(_)) => {
574                        let _ = dedup.commit(sender, request_id);
575                    }
576                    Err(DeliverAcceptError::BeforeAccept(_)) => {
577                        let _ = dedup.rollback(sender, request_id);
578                    }
579                }
580            }
581        }
582        match outcome {
583            Ok(()) => Ok(()),
584            Err(DeliverAcceptError::BeforeAccept(e) | DeliverAcceptError::AfterAccept(e)) => Err(e),
585        }
586    }
587
588    fn deliver_frame_after_dedup(
589        &self,
590        hop: super::distribution::OutboundHop,
591    ) -> Result<(), DeliverAcceptError> {
592        let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
593            Ok(Some(cap)) => cap,
594            Ok(None) => {
595                return Err(DeliverAcceptError::BeforeAccept(
596                    super::distribution::RemoteFrameError::NoSuchName,
597                ))
598            }
599            Err(err) => {
600                super::error::report_fault(err);
601                return Err(DeliverAcceptError::BeforeAccept(
602                    super::distribution::RemoteFrameError::Unavailable,
603                ));
604            }
605        };
606        let target = match self.shared.caps.lookup(cap) {
607            Ok(Some(entry)) => match entry.target() {
608                Some(id) => id,
609                None => {
610                    return Err(DeliverAcceptError::BeforeAccept(
611                        super::distribution::RemoteFrameError::NoSuchName,
612                    ))
613                }
614            },
615            Ok(None) => {
616                return Err(DeliverAcceptError::BeforeAccept(
617                    super::distribution::RemoteFrameError::NoSuchName,
618                ))
619            }
620            Err(err) => {
621                super::error::report_fault(err);
622                return Err(DeliverAcceptError::BeforeAccept(
623                    super::distribution::RemoteFrameError::Unavailable,
624                ));
625            }
626        };
627        let mailbox = match self.shared.directory.lookup(target) {
628            Ok(Some(mailbox)) => mailbox,
629            Ok(None) => {
630                return Err(DeliverAcceptError::BeforeAccept(
631                    super::distribution::RemoteFrameError::NoSuchName,
632                ))
633            }
634            Err(err) => {
635                super::error::report_fault(err);
636                return Err(DeliverAcceptError::BeforeAccept(
637                    super::distribution::RemoteFrameError::Unavailable,
638                ));
639            }
640        };
641        let stamped = Value::Message(hop.message);
642        match mailbox.push(stamped.clone()) {
643            Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
644                Ok(())
645            }
646            Ok(Ok(Delivery::Handoff(flow))) => {
647                let _ = self.shared.ask_waits.remove_asker(flow.id);
648                match flow.last_receive_dest {
649                    Some(dest) => {
650                        let Some(flow) =
651                            super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
652                        else {
653                            return Err(DeliverAcceptError::AfterAccept(
654                                super::distribution::RemoteFrameError::Unavailable,
655                            ));
656                        };
657                        enqueue_flow(&self.shared, flow);
658                        wake_workers(&self.shared);
659                        Ok(())
660                    }
661                    None => {
662                        super::finalize::finalize_flow(
663                            &self.shared,
664                            *flow,
665                            FlowOutcome::Failed("handoff missing dest register".into()),
666                            FlowExitReason::Fault,
667                        );
668                        Err(DeliverAcceptError::AfterAccept(
669                            super::distribution::RemoteFrameError::Unavailable,
670                        ))
671                    }
672                }
673            }
674            Ok(Err(full)) => Err(DeliverAcceptError::BeforeAccept(
675                super::distribution::RemoteFrameError::Mailbox(full.reason()),
676            )),
677            Err(err) => {
678                super::error::report_fault(err);
679                Err(DeliverAcceptError::BeforeAccept(
680                    super::distribution::RemoteFrameError::Unavailable,
681                ))
682            }
683        }
684    }
685}
686
687/// Internal split for remote dedup: rollback only when the mailbox never
688/// accepted the hop.
689enum DeliverAcceptError {
690    BeforeAccept(super::distribution::RemoteFrameError),
691    AfterAccept(super::distribution::RemoteFrameError),
692}
693
694/// A convenience Pid constructor for embedders that stored a raw `u64`
695/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
696/// call APIs that take one.
697pub fn flow_id_from_u64(raw: u64) -> FlowId {
698    FlowId(raw)
699}
700
701/// Why [`Runtime::send`] could not deliver a hop.
702#[derive(Debug, Clone, PartialEq, Eq)]
703pub enum SendError {
704    NoSuchFlow(FlowId),
705    /// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
706    NotAHop {
707        got: &'static str,
708    },
709    /// Target inbox is at one of its logical bounds
710    /// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
711    /// [`MailboxFullReason`].
712    MailboxFull {
713        flow: FlowId,
714        reason: MailboxFullReason,
715    },
716    /// Host hop authentication failed (payload Cap reissue).
717    Capability,
718    /// Directory / mailbox mutex poisoned — not "no such flow".
719    Unavailable,
720}
721
722impl std::fmt::Display for SendError {
723    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
724        match self {
725            SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
726            SendError::NotAHop { got } => {
727                write!(f, "atomic hop requires Value::Message, got {got}")
728            }
729            SendError::MailboxFull { flow, reason } => {
730                write!(f, "mailbox full for {flow} ({reason})")
731            }
732            SendError::Capability => {
733                write!(f, "host send could not reissue a capability in the hop")
734            }
735            SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
736        }
737    }
738}
739
740impl std::error::Error for SendError {}
741
742/// Park `flow` on the global injector.
743///
744/// A poisoned injector is cleared inside [`Injector::push`]. The flow stays
745/// queued with whatever was already there.
746pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
747    shared.injector.push(flow);
748}
749
750pub(crate) fn wake_workers(shared: &Shared) {
751    let (lock, cvar) = &shared.notify;
752    match super::sync_lock::lock(lock, "wake_workers") {
753        Ok(_g) => cvar.notify_one(),
754        Err(e) => super::error::report_fault(e),
755    }
756}
757
758/// Signal shutdown and join any threads already started during construction
759/// failure — keeps the "no orphan threads" contract of
760/// [`Runtime::with_natives_and_config`].
761pub(crate) fn record_security_event(shared: &Shared, event: &super::sandbox::SecurityEvent) {
762    use super::sandbox::{SecurityCounters, SecurityEvent};
763    match event {
764        SecurityEvent::AccessDenied { .. } => {
765            SecurityCounters::inc(&shared.security.denied_operations);
766        }
767        SecurityEvent::QuotaExceeded { .. } => {
768            SecurityCounters::inc(&shared.security.quota_exceeded);
769        }
770        SecurityEvent::CapabilityCreated { .. } => {
771            SecurityCounters::inc(&shared.security.capabilities_created);
772        }
773        SecurityEvent::CapabilityRevoked { .. } => {
774            SecurityCounters::inc(&shared.security.capabilities_revoked);
775        }
776        SecurityEvent::ModuleRejected { .. } => {
777            SecurityCounters::inc(&shared.security.invalid_modules);
778        }
779        SecurityEvent::NativeDenied { .. } => {
780            SecurityCounters::inc(&shared.security.native_denied);
781        }
782        SecurityEvent::CapabilityDelegated { .. } | SecurityEvent::FlowFinalized { .. } => {}
783    }
784    if let Some(sink) = shared.security_audit.as_ref() {
785        // Queued: never blocks the worker on a slow host sink.
786        sink.record(event);
787    }
788}
789
790pub(crate) fn record_quota_exceeded(shared: &Shared, err: super::quota::QuotaError) {
791    record_security_event(
792        shared,
793        &super::sandbox::SecurityEvent::QuotaExceeded {
794            kind: err.audit_kind(),
795        },
796    );
797}
798
799fn abort_startup(
800    shared: &Arc<Shared>,
801    workers: Vec<std::thread::JoinHandle<()>>,
802    timer: Option<std::thread::JoinHandle<()>>,
803) {
804    shared.shutdown.store(true, Ordering::Release);
805    shared.timer.shutdown();
806    let (lock, cvar) = &shared.notify;
807    match super::sync_lock::lock(lock, "abort_startup") {
808        Ok(_g) => cvar.notify_all(),
809        Err(e) => super::error::report_fault(e),
810    }
811    for w in workers {
812        let _ = w.join();
813    }
814    if let Some(t) = timer {
815        let _ = t.join();
816    }
817}