Skip to main content

byteflow/scheduler/runtime/
spawn.rs

1//! Spawning: the shared [`spawn_on`] path used by hosts and bytecode, and the
2//! detached [`RuntimeSpawner`] handle.
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/// Context for a bytecode `Spawn`: parent self-authority is attenuated into
10/// the child. Host spawn passes `None` and mints a trusted root instead.
11pub(crate) struct BytecodeSpawn<'a> {
12    pub authority: &'a Cap,
13    pub cell: &'a crate::bytecode::RevocationCell,
14    pub quota: &'a crate::scheduler::quota::FlowQuota,
15    pub requested_rights: CapRights,
16}
17
18/// Shared machinery behind `Runtime::spawn` and `RuntimeSpawner::spawn`
19/// (and, transitively, `Supervisor`): build a fresh `Flow` (VM +
20/// mailbox + completion channel), register it in the directory, and push
21/// it onto the global injector for any worker to pick up.
22///
23/// Returns [`SpawnError`] on bad function index / VM init / directory
24/// poison — never panics. Bytecode `Opcode::Spawn` that fails here turns
25/// into `FlowOutcome::Failed` for the *parent* (see `worker`).
26/// Bytecode `Spawn` must pass exactly the callee's arity. Host spawn is not
27/// checked here.
28pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
29    if argc != usize::from(arity) {
30        Err(crate::vm::Fault::BadArity {
31            passed: argc,
32            expected: arity,
33        })
34    } else {
35        Ok(())
36    }
37}
38
39#[allow(clippy::too_many_arguments)]
40pub(crate) fn spawn_on(
41    shared: &Arc<Shared>,
42    chunk: &Arc<Chunk>,
43    natives: &Arc<NativeTable>,
44    function: u32,
45    args: &[Value],
46    restart_policy: RestartPolicy,
47    supervisor: Option<SupervisorLink>,
48    parent: Option<FlowId>,
49    bytecode: Option<BytecodeSpawn<'_>>,
50    // When `bytecode` is `None`, overrides `Shared::root_authority`.
51    host_authority: Option<RootAuthorityPolicy>,
52) -> Result<FlowHandle, SpawnError> {
53    // Bytecode `Spawn` encodes argc. Host `Runtime::spawn` does not: a short
54    // host argument list still fills the rest with `Unit`. Only the bytecode
55    // path is rejected here, matching `VerifyError::CallArity` / `Fault::BadArity`.
56    if bytecode.is_some() {
57        match chunk.function(function) {
58            Some(def) => {
59                if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
60                    return Err(fault.into());
61                }
62            }
63            None => {
64                return Err(SpawnError::BadFunction {
65                    index: function,
66                    table_size: chunk.functions.len() as u32,
67                });
68            }
69        }
70    }
71    shared.flow_limit.try_reserve()?;
72    let id = match crate::scheduler::process::try_next_flow_id() {
73        Ok(id) => id,
74        Err(crate::scheduler::error::RuntimeError::FlowIdExhausted) => {
75            shared.flow_limit.release();
76            return Err(SpawnError::FlowIdExhausted);
77        }
78        Err(_) => {
79            shared.flow_limit.release();
80            return Err(SpawnError::Unavailable);
81        }
82    };
83    let cell = match shared.caps.bind_flow(id) {
84        Ok(c) => c,
85        Err(_) => {
86            shared.flow_limit.release();
87            return Err(SpawnError::Unavailable);
88        }
89    };
90    let authority = match bytecode {
91        None => {
92            let policy = host_authority.unwrap_or(shared.root_authority);
93            policy.mint(id.as_u64(), natives.len(), cell.as_ref())
94        }
95        Some(ctx) => match crate::scheduler::spawn::exec_spawn_authority(
96            ctx.authority,
97            ctx.cell,
98            ctx.quota,
99            id.as_u64(),
100            ctx.requested_rights,
101            None,
102            cell.as_ref(),
103        ) {
104            Ok(cap) => cap,
105            Err(e) => {
106                shared.flow_limit.release();
107                let _ = shared.caps.revoke_flow(id);
108                return Err(SpawnError::from(e));
109            }
110        },
111    };
112    let args = match grant_caps_in_args(shared, parent, id, args) {
113        Ok(a) => a,
114        Err(e) => {
115            shared.flow_limit.release();
116            let _ = shared.caps.revoke_flow(id);
117            return Err(e);
118        }
119    };
120    let gate = NativeGate::from_authority(
121        &authority,
122        Arc::clone(&cell),
123        shared.caps.native_cell(),
124        natives.len(),
125    );
126    let quota = Arc::new(crate::scheduler::quota::FlowQuota::from_config(
127        shared.quota,
128    ));
129    let mut vm = match Vm::with_native_gate(
130        chunk.clone(),
131        natives.clone(),
132        gate,
133        function,
134        args.as_slice(),
135    ) {
136        Ok(vm) => vm,
137        Err(e) => {
138            shared.flow_limit.release();
139            let _ = shared.caps.revoke_flow(id);
140            return Err(e.into());
141        }
142    };
143    vm.set_memory_budget(Arc::clone(&shared.memory));
144    if let Err(e) = vm.set_quota(Arc::clone(&quota)) {
145        shared.flow_limit.release();
146        let _ = shared.caps.revoke_flow(id);
147        return Err(e.into());
148    }
149    let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
150    if let Err(e) = shared.directory.register(id, mailbox.clone()) {
151        crate::scheduler::error::report_fault(e);
152        shared.flow_limit.release();
153        let _ = shared.caps.revoke_flow(id);
154        return Err(SpawnError::Unavailable);
155    }
156    if let Err(e) = shared.quotas.insert(id, Arc::clone(&quota)) {
157        crate::scheduler::error::report_fault(e);
158        let _ = shared.directory.unregister(id);
159        shared.flow_limit.release();
160        let _ = shared.caps.revoke_flow(id);
161        return Err(SpawnError::Unavailable);
162    }
163    let (tx, rx) = crate::scheduler::oneshot::channel();
164    let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
165    flow.authority = authority;
166    flow.cell = cell;
167    flow.quota = quota;
168    flow.supervisor = supervisor;
169    RuntimeMetrics::inc(&shared.metrics.processes_spawned);
170    record_security_event(
171        shared,
172        &crate::scheduler::sandbox::SecurityEvent::CapabilityCreated {
173            holder: id.as_u64(),
174        },
175    );
176    if matches!(
177        shared.trust,
178        crate::bytecode::TrustLevel::Untrusted | crate::bytecode::TrustLevel::Restricted
179    ) {
180        crate::scheduler::sandbox::SecurityCounters::inc(&shared.security.active_untrusted_flows);
181    }
182    enqueue_flow(shared, flow);
183    wake_workers(shared);
184    Ok(FlowHandle { id, receiver: rx })
185}
186
187fn grant_caps_in_args(
188    shared: &Shared,
189    parent: Option<FlowId>,
190    child: FlowId,
191    args: &[Value],
192) -> Result<Vec<Value>, SpawnError> {
193    let mut out = Vec::with_capacity(args.len());
194    for arg in args {
195        if !arg.within_nesting_limit() {
196            return Err(SpawnError::InvalidCapability);
197        }
198        let granted = arg.map_caps(
199            0,
200            &SpawnError::InvalidCapability,
201            &mut |id| match parent {
202                None => shared
203                    .caps
204                    .reissue_for(id, child)
205                    .map_err(|_| SpawnError::InvalidCapability),
206                Some(holder) => match shared.caps.delegate(id, holder, child) {
207                    Ok(granted) => {
208                        record_security_event(
209                            shared,
210                            &crate::scheduler::sandbox::SecurityEvent::CapabilityDelegated {
211                                from: holder.as_u64(),
212                                to: child.as_u64(),
213                            },
214                        );
215                        Ok(granted)
216                    }
217                    Err(_) => Err(SpawnError::InvalidCapability),
218                },
219            },
220            &mut |message| {
221                if let Some(holder) = parent {
222                    if message.sender == 0 {
223                        message.sender = holder.as_u64();
224                    }
225                }
226                if message.request_id == 0 {
227                    message.request_id =
228                        crate::scheduler::worker::mint_host_request_id(&shared.host_next_request_id)
229                            .ok_or(SpawnError::RequestIdsExhausted)?;
230                }
231                if !message.reply_cap.is_none() {
232                    message.reply_cap = match parent {
233                        None => shared
234                            .caps
235                            .reissue_for(message.reply_cap, child)
236                            .map_err(|_| SpawnError::InvalidCapability)?,
237                        Some(holder) => {
238                            match shared.caps.delegate(message.reply_cap, holder, child) {
239                                Ok(granted) => {
240                                    record_security_event(
241                                        shared,
242                                        &crate::scheduler::sandbox::SecurityEvent::CapabilityDelegated {
243                                            from: holder.as_u64(),
244                                            to: child.as_u64(),
245                                        },
246                                    );
247                                    granted
248                                }
249                                Err(_) => return Err(SpawnError::InvalidCapability),
250                            }
251                        }
252                    };
253                }
254                Ok(())
255            },
256        )?;
257        out.push(granted);
258    }
259    Ok(out)
260}
261
262/// A `Send + Sync`, freely cloneable capability to spawn flows into a
263/// [`Runtime`], detached from the `Runtime` value itself. Exists because
264/// [`crate::scheduler::supervisor::Supervisor`] needs to respawn flows from a
265/// background monitor thread whose lifetime isn't tied to the `Runtime`
266/// object's own (which owns non-`Sync` `JoinHandle`s for its workers).
267#[derive(Clone)]
268pub struct RuntimeSpawner {
269    pub(crate) shared: Arc<Shared>,
270    pub(crate) chunk: Arc<Chunk>,
271    pub(crate) natives: Arc<NativeTable>,
272}
273
274impl RuntimeSpawner {
275    pub fn spawn(
276        &self,
277        function: u32,
278        args: &[Value],
279        restart_policy: RestartPolicy,
280    ) -> Result<FlowHandle, SpawnError> {
281        spawn_on(
282            &self.shared,
283            &self.chunk,
284            &self.natives,
285            function,
286            args,
287            restart_policy,
288            None,
289            None,
290            None,
291            None,
292        )
293    }
294
295    /// Host spawn with [`RootAuthorityPolicy::Untrusted`].
296    pub fn spawn_untrusted(
297        &self,
298        function: u32,
299        args: &[Value],
300        restart_policy: RestartPolicy,
301    ) -> Result<FlowHandle, SpawnError> {
302        spawn_on(
303            &self.shared,
304            &self.chunk,
305            &self.natives,
306            function,
307            args,
308            restart_policy,
309            None,
310            None,
311            None,
312            Some(RootAuthorityPolicy::Untrusted),
313        )
314    }
315
316    pub(crate) fn spawn_linked(
317        &self,
318        function: u32,
319        args: &[Value],
320        restart_policy: RestartPolicy,
321        supervisor: SupervisorLink,
322    ) -> Result<FlowHandle, SpawnError> {
323        spawn_on(
324            &self.shared,
325            &self.chunk,
326            &self.natives,
327            function,
328            args,
329            restart_policy,
330            Some(supervisor),
331            None,
332            None,
333            None,
334        )
335    }
336
337    pub fn metrics(&self) -> RuntimeMetricsSnapshot {
338        self.shared.metrics.snapshot()
339    }
340
341    pub(crate) fn request_kill(
342        &self,
343        id: FlowId,
344        reason: crate::scheduler::monitor::FlowExitReason,
345    ) {
346        crate::scheduler::finalize::request_kill(&self.shared, id, reason);
347    }
348}