byteflow/scheduler/runtime/config.rs
1//! [`RuntimeConfig`] and its parts: quantum, root authority, JIT knobs,
2//! and the `sandbox` presets.
3// Docs ratchet: public items here predate `missing_docs`. Delete this
4// allow once they are documented; new files get the lint by default.
5#![allow(missing_docs)]
6
7use super::*;
8
9/// Default instruction budget per scheduling turn (design notes §10).
10/// Chosen as a middle ground: large enough that the per-yield bookkeeping
11/// cost is amortized over meaningful work, small enough that a
12/// pathological `loop {}` in one flow can't visibly stall the others —
13/// at 10k simple instructions/turn and even a conservative tens-of-millions
14/// of instructions/sec per core, worst-case added latency for a sibling
15/// flow is sub-millisecond.
16pub const DEFAULT_QUANTUM: u32 = 10_000;
17
18/// Tunables for [`Runtime::new`]. Everything has a sensible default via
19/// [`RuntimeConfig::default`] so the common case is `Runtime::new(chunk)`.
20#[derive(Clone, Debug)]
21pub struct RuntimeConfig {
22 /// Number of worker OS threads. Defaults to the number of logical CPUs
23 /// — one worker per core is the right starting point for a CPU-bound
24 /// M:N scheduler; embedders running alongside other CPU-heavy work on
25 /// the same machine may want fewer. `0` is raised to `1`: a runtime
26 /// with no worker cannot run a flow.
27 pub workers: usize,
28 /// Instructions a flow runs before being preempted back to the
29 /// scheduler even if it never hits `Yield`. `0` is raised to `1`.
30 /// A zero slice returns `Yield` without executing anything, and the
31 /// worker would requeue that flow forever.
32 pub quantum: u32,
33 /// Memory + overflow contract applied to **every** flow mailbox
34 /// spawned by this runtime (bytecode `Spawn` and host `spawn`).
35 /// See [`MailboxConfig`] / `docs/mailbox.md`.
36 pub mailbox: MailboxConfig,
37 /// Hard cap on concurrently live flows (`0` = unlimited).
38 /// Checked on every host and bytecode `spawn`.
39 pub max_flows: u32,
40 /// Hard cap on outstanding `Ask` / `AskTimeout` waiters process-wide
41 /// (`0` = unlimited). Each asker holds at most one wait; this bounds the
42 /// total index size when many flows park against a silent target.
43 /// See [`crate::docs::security`] (DoS) and [`Self::sandbox`].
44 pub max_ask_waits: u32,
45 /// Hard cap on outstanding `HostAwait` parkers process-wide
46 /// (`0` = unlimited). Each flow holds at most one await.
47 pub max_host_awaits: u32,
48 /// Hard cap on live process-wide links (`0` = unlimited).
49 ///
50 /// Accounting is performed by the link store itself, under
51 /// the same synchronization that protects the link table.
52 pub max_links: u32,
53 /// Hard cap on live process-wide monitors (`0` = unlimited).
54 ///
55 /// Accounting is performed by the monitor store itself.
56 pub max_monitors: u32,
57 /// Hard cap on live process-wide registry names (`0` = unlimited).
58 ///
59 /// The registry store counts only successfully registered names.
60 pub max_registry_names: u32,
61 /// Host async bridge for [`crate::Opcode::HostAwait`]. `None` fails
62 /// any `HostAwait` closed. Not a `CallNative` / std-native slot.
63 pub host_await: Option<Arc<dyn crate::scheduler::host_await::HostAwaitBridge>>,
64 /// `0` = disabled. When set, [`Runtime::deliver_frame`] ignores duplicate
65 /// `(sender, request_id)` pairs within the window (at-least-once wire).
66 pub remote_dedup_window: u32,
67 /// Host queue for [`crate::Opcode::SendRemote`]. `None` fails that opcode.
68 /// Byteflow does not open sockets; the embedder drains the bridge.
69 pub distribution: Option<Arc<crate::scheduler::distribution::DistributionBridge>>,
70 /// Process-wide memory ceiling for heap charges (`Str` / `Bytes`
71 /// register stores and shared [`crate::HeapStr`] / [`crate::HeapBytes`]).
72 /// Independent of per-flow [`crate::QuotaConfig::mem_limit`] and mailbox
73 /// byte budgets. Default: 256 MiB.
74 pub max_runtime_bytes: usize,
75 /// Constant-pool trust for [`crate::verify_with`] at runtime construction.
76 /// Default is [`crate::TrustLevel::Untrusted`] (fail closed).
77 pub trust: crate::bytecode::TrustLevel,
78 /// Where bytecode `print` (native index 0) writes when using
79 /// [`crate::std_native_table_with`]. Ignored if you supply your own table.
80 pub output: Arc<dyn crate::OutputSink>,
81 /// Scheduler diagnostics (`ask`, `finalize`, …). `None` keeps the
82 /// `BYTEFLOW_LOG` stderr path and adds no collector. The sink is called
83 /// inline and must not block or panic.
84 pub log: Option<Arc<dyn crate::log::LogSink>>,
85 /// Per-flow CPU / memory / spawn-send rate budgets.
86 pub quota: crate::scheduler::quota::QuotaConfig,
87 /// Optional security audit sink (capability / quota / module denials).
88 /// Independent of [`Self::log`]; never receives full CapId tokens.
89 /// Delivery is **asynchronous** (bounded queue + dedicated thread) so a
90 /// slow sink cannot stall scheduler workers.
91 pub security_audit: Option<Arc<dyn crate::scheduler::sandbox::SecurityAuditSink>>,
92 /// Authority minted for host [`Runtime::spawn`] (not bytecode `Spawn`).
93 ///
94 /// Default [`RootAuthorityPolicy::TrustedHost`] preserves historical
95 /// ROOT + full native mask. [`Self::sandbox`] does **not** change this —
96 /// use [`Runtime::spawn_untrusted`] or set this field explicitly.
97 pub root_authority: RootAuthorityPolicy,
98 /// Trace JIT settings (`feature = "jit"`). Ignored when the feature is off.
99 #[cfg(feature = "jit")]
100 pub jit: JitConfig,
101}
102
103/// Initial Cap rights for host-spawned root flows.
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
105pub enum RootAuthorityPolicy {
106 /// [`CapRights::ROOT`] + full native mask (historical host spawn).
107 #[default]
108 TrustedHost,
109 /// Flow rights without [`CapRights::NATIVE`]; empty native mask.
110 Restricted,
111 /// [`CapRights::NONE`] + empty native mask (minimum authority).
112 Untrusted,
113}
114
115impl RootAuthorityPolicy {
116 pub(super) fn mint(
117 self,
118 flow: u64,
119 natives_len: usize,
120 cell: &crate::bytecode::RevocationCell,
121 ) -> Cap {
122 match self {
123 Self::TrustedHost => Cap::root(
124 CapTarget::Flow(flow),
125 CapRights::ROOT,
126 Some(NativeMask::full(natives_len)),
127 cell,
128 ),
129 Self::Restricted => Cap::root(
130 CapTarget::Flow(flow),
131 CapRights::from_bits(CapRights::FLOW.bits() & !CapRights::NATIVE.bits()),
132 Some(NativeMask::empty(natives_len)),
133 cell,
134 ),
135 Self::Untrusted => Cap::root(
136 CapTarget::Flow(flow),
137 CapRights::NONE,
138 Some(NativeMask::empty(natives_len)),
139 cell,
140 ),
141 }
142 }
143}
144
145/// Trace JIT toggles for [`RuntimeConfig`] (`feature = "jit"`).
146#[cfg(feature = "jit")]
147#[derive(Clone, Debug)]
148pub struct JitConfig {
149 /// When true, workers attempt compiled traces before interpreting.
150 pub enabled: bool,
151 /// How many times a `(function, pc)` pair must run before compilation.
152 pub hot_threshold: u32,
153}
154
155#[cfg(feature = "jit")]
156impl Default for JitConfig {
157 fn default() -> Self {
158 JitConfig {
159 enabled: false,
160 hot_threshold: crate::jit::HOT_THRESHOLD,
161 }
162 }
163}
164
165/// Logical CPU count for [`RuntimeConfig::default`], via `std` only.
166fn default_worker_count() -> usize {
167 match std::thread::available_parallelism() {
168 Ok(n) => n.get().max(1),
169 Err(_) => 1,
170 }
171}
172
173impl Default for RuntimeConfig {
174 fn default() -> Self {
175 RuntimeConfig {
176 workers: default_worker_count(),
177 quantum: DEFAULT_QUANTUM,
178 mailbox: MailboxConfig::DEFAULT,
179 max_flows: 0,
180 max_ask_waits: 0,
181 max_host_awaits: 0,
182 max_links: 0,
183 max_monitors: 0,
184 max_registry_names: 0,
185 host_await: None,
186 remote_dedup_window: 0,
187 distribution: None,
188 max_runtime_bytes: 256 * 1024 * 1024,
189 trust: crate::bytecode::TrustLevel::Untrusted,
190 output: Arc::new(crate::output::NullSink),
191 log: None,
192 quota: crate::scheduler::quota::QuotaConfig::default(),
193 security_audit: None,
194 root_authority: RootAuthorityPolicy::TrustedHost,
195 #[cfg(feature = "jit")]
196 jit: JitConfig::default(),
197 }
198 }
199}
200
201impl RuntimeConfig {
202 /// Opt-in sandbox profile for untrusted modules.
203 ///
204 /// Default [`RuntimeConfig`] stays permissive (`max_* = 0` unlimited,
205 /// [`QuotaConfig::permissive`](crate::scheduler::quota::QuotaConfig::permissive)).
206 /// This profile enables fail-closed process-wide caps and tight
207 /// per-flow budgets. Trust defaults to [`crate::bytecode::TrustLevel::Untrusted`]
208 /// (inherited from [`Default`]) so Cap/Pid/Message constants are
209 /// rejected at verify time.
210 ///
211 /// Does **not** change [`Self::root_authority`]: host [`Runtime::spawn`]
212 /// still mints trusted ROOT unless you set the policy or call
213 /// [`Runtime::spawn_untrusted`].
214 ///
215 /// Limits (starting point — tune under load):
216 /// - `max_flows = 128` live flows
217 /// - `max_ask_waits = 64`, `max_host_awaits = 128`
218 /// - `max_runtime_bytes = 64 MiB` process heap accounting
219 /// - mailbox: 256 hops / 4 MiB / Reject ( [`MailboxConfig::DEFAULT`] )
220 /// - per-flow: [`QuotaConfig::sandbox`](crate::scheduler::quota::QuotaConfig::sandbox)
221 pub fn sandbox() -> Self {
222 RuntimeConfig {
223 quota: crate::scheduler::quota::QuotaConfig::sandbox(),
224 max_flows: 128,
225 max_ask_waits: 64,
226 max_host_awaits: 128,
227 max_links: 1024,
228 max_monitors: 1024,
229 max_registry_names: 256,
230 max_runtime_bytes: 64 * 1024 * 1024,
231 trust: crate::bytecode::TrustLevel::Untrusted,
232 ..Default::default()
233 }
234 }
235
236 /// Same process-wide caps as [`Self::sandbox`], but
237 /// [`crate::bytecode::TrustLevel::Restricted`]: still no Cap/Pid/Message in the constant
238 /// pool; host may grant Caps / natives after admission.
239 pub fn sandbox_restricted() -> Self {
240 RuntimeConfig {
241 trust: crate::bytecode::TrustLevel::Restricted,
242 ..Self::sandbox()
243 }
244 }
245
246 /// Stable identity of the security-relevant knobs on this config.
247 pub fn policy_fingerprint(&self) -> crate::scheduler::sandbox::PolicyFingerprint {
248 crate::scheduler::sandbox::policy_fingerprint(self)
249 }
250
251 /// True when at least one process-wide sandbox ceiling is armed
252 /// (`max_flows` / ask / host-await / runtime bytes tighter than the
253 /// permissive defaults). Does not imply the chunk was verified as
254 /// Untrusted — check [`Self::trust`] separately.
255 pub fn applies_sandbox_caps(&self) -> bool {
256 self.max_flows != 0
257 || self.max_ask_waits != 0
258 || self.max_host_awaits != 0
259 || self.max_links != 0
260 || self.max_monitors != 0
261 || self.max_registry_names != 0
262 || self.max_runtime_bytes < 256 * 1024 * 1024
263 || self.quota.cpu_budget < crate::scheduler::quota::QuotaConfig::permissive().cpu_budget
264 }
265}