byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
//! [`RuntimeConfig`] and its parts: quantum, root authority, JIT knobs,
//! and the `sandbox` presets.
// Docs ratchet: public items here predate `missing_docs`. Delete this
// allow once they are documented; new files get the lint by default.
#![allow(missing_docs)]

use super::*;

/// Default instruction budget per scheduling turn (design notes §10).
/// Chosen as a middle ground: large enough that the per-yield bookkeeping
/// cost is amortized over meaningful work, small enough that a
/// pathological `loop {}` in one flow can't visibly stall the others —
/// at 10k simple instructions/turn and even a conservative tens-of-millions
/// of instructions/sec per core, worst-case added latency for a sibling
/// flow is sub-millisecond.
pub const DEFAULT_QUANTUM: u32 = 10_000;

/// Tunables for [`Runtime::new`]. Everything has a sensible default via
/// [`RuntimeConfig::default`] so the common case is `Runtime::new(chunk)`.
#[derive(Clone, Debug)]
pub struct RuntimeConfig {
    /// Number of worker OS threads. Defaults to the number of logical CPUs
    /// — one worker per core is the right starting point for a CPU-bound
    /// M:N scheduler; embedders running alongside other CPU-heavy work on
    /// the same machine may want fewer. `0` is raised to `1`: a runtime
    /// with no worker cannot run a flow.
    pub workers: usize,
    /// Instructions a flow runs before being preempted back to the
    /// scheduler even if it never hits `Yield`. `0` is raised to `1`.
    /// A zero slice returns `Yield` without executing anything, and the
    /// worker would requeue that flow forever.
    pub quantum: u32,
    /// Memory + overflow contract applied to **every** flow mailbox
    /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
    /// See [`MailboxConfig`] / `docs/mailbox.md`.
    pub mailbox: MailboxConfig,
    /// Hard cap on concurrently live flows (`0` = unlimited).
    /// Checked on every host and bytecode `spawn`.
    pub max_flows: u32,
    /// Hard cap on outstanding `Ask` / `AskTimeout` waiters process-wide
    /// (`0` = unlimited). Each asker holds at most one wait; this bounds the
    /// total index size when many flows park against a silent target.
    /// See [`crate::docs::security`] (DoS) and [`Self::sandbox`].
    pub max_ask_waits: u32,
    /// Hard cap on outstanding `HostAwait` parkers process-wide
    /// (`0` = unlimited). Each flow holds at most one await.
    pub max_host_awaits: u32,
    /// Hard cap on live process-wide links (`0` = unlimited).
    ///
    /// Accounting is performed by the link store itself, under
    /// the same synchronization that protects the link table.
    pub max_links: u32,
    /// Hard cap on live process-wide monitors (`0` = unlimited).
    ///
    /// Accounting is performed by the monitor store itself.
    pub max_monitors: u32,
    /// Hard cap on live process-wide registry names (`0` = unlimited).
    ///
    /// The registry store counts only successfully registered names.
    pub max_registry_names: u32,
    /// Host async bridge for [`crate::Opcode::HostAwait`]. `None` fails
    /// any `HostAwait` closed. Not a `CallNative` / std-native slot.
    pub host_await: Option<Arc<dyn crate::scheduler::host_await::HostAwaitBridge>>,
    /// `0` = disabled. When set, [`Runtime::deliver_frame`] ignores duplicate
    /// `(sender, request_id)` pairs within the window (at-least-once wire).
    pub remote_dedup_window: u32,
    /// Host queue for [`crate::Opcode::SendRemote`]. `None` fails that opcode.
    /// Byteflow does not open sockets; the embedder drains the bridge.
    pub distribution: Option<Arc<crate::scheduler::distribution::DistributionBridge>>,
    /// Process-wide memory ceiling for heap charges (`Str` / `Bytes`
    /// register stores and shared [`crate::HeapStr`] / [`crate::HeapBytes`]).
    /// Independent of per-flow [`crate::QuotaConfig::mem_limit`] and mailbox
    /// byte budgets. Default: 256 MiB.
    pub max_runtime_bytes: usize,
    /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
    /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
    pub trust: crate::bytecode::TrustLevel,
    /// Where bytecode `print` (native index 0) writes when using
    /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
    pub output: Arc<dyn crate::OutputSink>,
    /// Scheduler diagnostics (`ask`, `finalize`, …). `None` keeps the
    /// `BYTEFLOW_LOG` stderr path and adds no collector. The sink is called
    /// inline and must not block or panic.
    pub log: Option<Arc<dyn crate::log::LogSink>>,
    /// Per-flow CPU / memory / spawn-send rate budgets.
    pub quota: crate::scheduler::quota::QuotaConfig,
    /// Optional security audit sink (capability / quota / module denials).
    /// Independent of [`Self::log`]; never receives full CapId tokens.
    /// Delivery is **asynchronous** (bounded queue + dedicated thread) so a
    /// slow sink cannot stall scheduler workers.
    pub security_audit: Option<Arc<dyn crate::scheduler::sandbox::SecurityAuditSink>>,
    /// Authority minted for host [`Runtime::spawn`] (not bytecode `Spawn`).
    ///
    /// Default [`RootAuthorityPolicy::TrustedHost`] preserves historical
    /// ROOT + full native mask. [`Self::sandbox`] does **not** change this —
    /// use [`Runtime::spawn_untrusted`] or set this field explicitly.
    pub root_authority: RootAuthorityPolicy,
    /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
    #[cfg(feature = "jit")]
    pub jit: JitConfig,
}

/// Initial Cap rights for host-spawned root flows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RootAuthorityPolicy {
    /// [`CapRights::ROOT`] + full native mask (historical host spawn).
    #[default]
    TrustedHost,
    /// Flow rights without [`CapRights::NATIVE`]; empty native mask.
    Restricted,
    /// [`CapRights::NONE`] + empty native mask (minimum authority).
    Untrusted,
}

impl RootAuthorityPolicy {
    pub(super) fn mint(
        self,
        flow: u64,
        natives_len: usize,
        cell: &crate::bytecode::RevocationCell,
    ) -> Cap {
        match self {
            Self::TrustedHost => Cap::root(
                CapTarget::Flow(flow),
                CapRights::ROOT,
                Some(NativeMask::full(natives_len)),
                cell,
            ),
            Self::Restricted => Cap::root(
                CapTarget::Flow(flow),
                CapRights::from_bits(CapRights::FLOW.bits() & !CapRights::NATIVE.bits()),
                Some(NativeMask::empty(natives_len)),
                cell,
            ),
            Self::Untrusted => Cap::root(
                CapTarget::Flow(flow),
                CapRights::NONE,
                Some(NativeMask::empty(natives_len)),
                cell,
            ),
        }
    }
}

/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
#[cfg(feature = "jit")]
#[derive(Clone, Debug)]
pub struct JitConfig {
    /// When true, workers attempt compiled traces before interpreting.
    pub enabled: bool,
    /// How many times a `(function, pc)` pair must run before compilation.
    pub hot_threshold: u32,
}

#[cfg(feature = "jit")]
impl Default for JitConfig {
    fn default() -> Self {
        JitConfig {
            enabled: false,
            hot_threshold: crate::jit::HOT_THRESHOLD,
        }
    }
}

/// Logical CPU count for [`RuntimeConfig::default`], via `std` only.
fn default_worker_count() -> usize {
    match std::thread::available_parallelism() {
        Ok(n) => n.get().max(1),
        Err(_) => 1,
    }
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        RuntimeConfig {
            workers: default_worker_count(),
            quantum: DEFAULT_QUANTUM,
            mailbox: MailboxConfig::DEFAULT,
            max_flows: 0,
            max_ask_waits: 0,
            max_host_awaits: 0,
            max_links: 0,
            max_monitors: 0,
            max_registry_names: 0,
            host_await: None,
            remote_dedup_window: 0,
            distribution: None,
            max_runtime_bytes: 256 * 1024 * 1024,
            trust: crate::bytecode::TrustLevel::Untrusted,
            output: Arc::new(crate::output::NullSink),
            log: None,
            quota: crate::scheduler::quota::QuotaConfig::default(),
            security_audit: None,
            root_authority: RootAuthorityPolicy::TrustedHost,
            #[cfg(feature = "jit")]
            jit: JitConfig::default(),
        }
    }
}

impl RuntimeConfig {
    /// Opt-in sandbox profile for untrusted modules.
    ///
    /// Default [`RuntimeConfig`] stays permissive (`max_* = 0` unlimited,
    /// [`QuotaConfig::permissive`](crate::scheduler::quota::QuotaConfig::permissive)).
    /// This profile enables fail-closed process-wide caps and tight
    /// per-flow budgets. Trust defaults to [`crate::bytecode::TrustLevel::Untrusted`]
    /// (inherited from [`Default`]) so Cap/Pid/Message constants are
    /// rejected at verify time.
    ///
    /// Does **not** change [`Self::root_authority`]: host [`Runtime::spawn`]
    /// still mints trusted ROOT unless you set the policy or call
    /// [`Runtime::spawn_untrusted`].
    ///
    /// Limits (starting point — tune under load):
    /// - `max_flows = 128` live flows
    /// - `max_ask_waits = 64`, `max_host_awaits = 128`
    /// - `max_runtime_bytes = 64 MiB` process heap accounting
    /// - mailbox: 256 hops / 4 MiB / Reject ( [`MailboxConfig::DEFAULT`] )
    /// - per-flow: [`QuotaConfig::sandbox`](crate::scheduler::quota::QuotaConfig::sandbox)
    pub fn sandbox() -> Self {
        RuntimeConfig {
            quota: crate::scheduler::quota::QuotaConfig::sandbox(),
            max_flows: 128,
            max_ask_waits: 64,
            max_host_awaits: 128,
            max_links: 1024,
            max_monitors: 1024,
            max_registry_names: 256,
            max_runtime_bytes: 64 * 1024 * 1024,
            trust: crate::bytecode::TrustLevel::Untrusted,
            ..Default::default()
        }
    }

    /// Same process-wide caps as [`Self::sandbox`], but
    /// [`crate::bytecode::TrustLevel::Restricted`]: still no Cap/Pid/Message in the constant
    /// pool; host may grant Caps / natives after admission.
    pub fn sandbox_restricted() -> Self {
        RuntimeConfig {
            trust: crate::bytecode::TrustLevel::Restricted,
            ..Self::sandbox()
        }
    }

    /// Stable identity of the security-relevant knobs on this config.
    pub fn policy_fingerprint(&self) -> crate::scheduler::sandbox::PolicyFingerprint {
        crate::scheduler::sandbox::policy_fingerprint(self)
    }

    /// True when at least one process-wide sandbox ceiling is armed
    /// (`max_flows` / ask / host-await / runtime bytes tighter than the
    /// permissive defaults). Does not imply the chunk was verified as
    /// Untrusted — check [`Self::trust`] separately.
    pub fn applies_sandbox_caps(&self) -> bool {
        self.max_flows != 0
            || self.max_ask_waits != 0
            || self.max_host_awaits != 0
            || self.max_links != 0
            || self.max_monitors != 0
            || self.max_registry_names != 0
            || self.max_runtime_bytes < 256 * 1024 * 1024
            || self.quota.cpu_budget < crate::scheduler::quota::QuotaConfig::permissive().cpu_budget
    }
}