Skip to main content

byteflow/scheduler/runtime/
control.rs

1//! Control plane of a running [`Runtime`]: capabilities, monitors, links,
2//! names, admin top-ups, chunk reload, host-await replay and shutdown.
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
9impl Runtime {
10    fn require_live(&self, id: FlowId) -> Result<(), crate::scheduler::error::LifecycleError> {
11        match self.shared.directory.lookup(id) {
12            Ok(Some(_)) => Ok(()),
13            Ok(None) => Err(crate::scheduler::error::LifecycleError::NoSuchFlow(id)),
14            Err(e) => Err(self.unavailable(e)),
15        }
16    }
17
18    fn unavailable(
19        &self,
20        err: crate::scheduler::error::RuntimeError,
21    ) -> crate::scheduler::error::LifecycleError {
22        crate::scheduler::error::report_fault(err);
23        crate::scheduler::error::LifecycleError::Unavailable
24    }
25
26    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
27    /// (host equivalent of `SelfPid`).
28    pub fn mint_cap(
29        &self,
30        flow: FlowId,
31    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
32        self.require_live(flow)?;
33        self.shared
34            .caps
35            .mint(
36                flow,
37                flow,
38                crate::scheduler::capability::CapRights::ADDRESSING,
39            )
40            .map_err(|e| self.unavailable(e))
41    }
42
43    /// Mint a Cap held by `holder` targeting `target` (host introduction).
44    pub fn grant_cap(
45        &self,
46        holder: FlowId,
47        target: FlowId,
48    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
49        self.require_live(holder)?;
50        self.require_live(target)?;
51        self.shared
52            .caps
53            .mint(
54                holder,
55                target,
56                crate::scheduler::capability::CapRights::ADDRESSING,
57            )
58            .map_err(|e| self.unavailable(e))
59    }
60
61    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
62    ///
63    /// Both flows must be live. `owner == target` is `LifecycleError::SelfRelation`.
64    pub fn monitor(
65        &self,
66        owner: FlowId,
67        target: FlowId,
68    ) -> Result<crate::scheduler::monitor::MonitorRef, crate::scheduler::error::LifecycleError>
69    {
70        if owner == target {
71            return Err(crate::scheduler::error::LifecycleError::SelfRelation);
72        }
73        self.require_live(owner)?;
74        self.require_live(target)?;
75        let mon = self
76            .shared
77            .monitors
78            .create(owner, target)
79            .map_err(|e| self.unavailable(e))??;
80        // Target may have finalized between the live check and insert.
81        // Synthesize DOWN and drop the now-useless relation (owner still live).
82        if self.require_live(target).is_err() {
83            let _ = self.shared.monitors.remove_owned(owner, mon);
84            crate::scheduler::finalize::deliver_down(
85                &self.shared,
86                crate::scheduler::monitor::DownEvent {
87                    monitor: mon,
88                    owner,
89                    target,
90                    reason: crate::scheduler::monitor::FlowExitReason::Fault,
91                },
92            );
93        }
94        Ok(mon)
95    }
96
97    /// Drop `monitor` if `owner` still owns it.
98    pub fn demonitor(
99        &self,
100        owner: FlowId,
101        monitor: crate::scheduler::monitor::MonitorRef,
102    ) -> Result<(), crate::scheduler::error::LifecycleError> {
103        self.require_live(owner)?;
104        match self.shared.monitors.remove_owned(owner, monitor) {
105            Ok(inner) => inner,
106            Err(e) => Err(self.unavailable(e)),
107        }
108    }
109
110    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
111    /// kills the peer (`Normal` only drops the link). With
112    /// [`Self::set_trap_exit`] on a peer, that peer receives a
113    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
114    pub fn link(
115        &self,
116        a: FlowId,
117        b: FlowId,
118    ) -> Result<crate::scheduler::link::LinkId, crate::scheduler::error::LifecycleError> {
119        if a == b {
120            return Err(crate::scheduler::error::LifecycleError::SelfRelation);
121        }
122        self.require_live(a)?;
123        self.require_live(b)?;
124        match self.shared.links.link_if_live(a, b, |id| {
125            self.shared.directory.lookup(id).map(|m| m.is_some())
126        }) {
127            Ok(Ok(crate::scheduler::link::LinkOutcome::Linked(id))) => Ok(id),
128            Ok(Ok(crate::scheduler::link::LinkOutcome::Consumed { dead })) => {
129                Err(crate::scheduler::error::LifecycleError::NoSuchFlow(dead))
130            }
131            Ok(Err(error)) => Err(error),
132            Err(e) => Err(self.unavailable(e)),
133        }
134    }
135
136    /// BEAM-style `process_flag(trap_exit, …)`.
137    ///
138    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
139    /// (including `Normal`) instead of killing this flow.
140    pub fn set_trap_exit(
141        &self,
142        id: FlowId,
143        enabled: bool,
144    ) -> Result<(), crate::scheduler::error::LifecycleError> {
145        self.require_live(id)?;
146        self.shared
147            .trap_exits
148            .set(id, enabled)
149            .map_err(|e| self.unavailable(e))
150    }
151
152    /// Drop `link` if `owner` is one of the endpoints.
153    pub fn unlink(
154        &self,
155        owner: FlowId,
156        link: crate::scheduler::link::LinkId,
157    ) -> Result<(), crate::scheduler::error::LifecycleError> {
158        self.require_live(owner)?;
159        match self.shared.links.unlink_owned(owner, link) {
160            Ok(inner) => inner,
161            Err(e) => Err(self.unavailable(e)),
162        }
163    }
164
165    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
166    pub fn register_name(
167        &self,
168        name: &str,
169        cap: crate::bytecode::CapId,
170    ) -> Result<(), crate::scheduler::error::LifecycleError> {
171        let entry = match self.shared.caps.lookup(cap) {
172            Ok(Some(e)) => e,
173            Ok(None) => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
174            Err(e) => return Err(self.unavailable(e)),
175        };
176        let target = match entry.target() {
177            Some(id) => id,
178            None => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
179        };
180        self.require_live(target)?;
181        match self.shared.registry.register(
182            crate::scheduler::registry::RegistryName::from(name),
183            cap,
184            target,
185        ) {
186            Ok(inner) => inner,
187            Err(e) => Err(self.unavailable(e)),
188        }
189    }
190
191    /// Look up a registered Cap, or `None` if the name is free / was swept.
192    pub fn whereis(
193        &self,
194        name: &str,
195    ) -> Result<Option<crate::bytecode::CapId>, crate::scheduler::error::LifecycleError> {
196        self.shared
197            .registry
198            .whereis(name)
199            .map_err(|e| self.unavailable(e))
200    }
201
202    /// Cooperative abort. Parked flows finalize immediately; a running flow
203    /// dies at the next quantum with [`crate::scheduler::monitor::FlowExitReason::Killed`].
204    pub fn kill(&self, id: FlowId) -> Result<(), crate::scheduler::error::LifecycleError> {
205        self.require_live(id)?;
206        crate::scheduler::finalize::request_kill(
207            &self.shared,
208            id,
209            crate::scheduler::monitor::FlowExitReason::Killed,
210        );
211        Ok(())
212    }
213
214    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
215    pub fn mint_admin_cap(
216        &self,
217        holder: FlowId,
218    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
219        self.require_live(holder)?;
220        let cap = crate::bytecode::Cap::root(
221            crate::bytecode::CapTarget::Scheduler,
222            CapRights::ADMIN,
223            None,
224            self.shared.caps.scheduler_cell().as_ref(),
225        );
226        self.shared
227            .caps
228            .grant(holder, cap)
229            .map_err(|e| self.unavailable(e))
230    }
231
232    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
233    pub fn admin_kill(
234        &self,
235        holder: FlowId,
236        cap: crate::bytecode::CapId,
237        target: FlowId,
238    ) -> Result<(), crate::scheduler::error::LifecycleError> {
239        self.require_admin(holder, cap)?;
240        self.kill(target)
241    }
242
243    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
244    pub fn admin_top_up_cpu(
245        &self,
246        holder: FlowId,
247        cap: crate::bytecode::CapId,
248        target: FlowId,
249        extra: i64,
250    ) -> Result<(), crate::scheduler::error::LifecycleError> {
251        self.require_admin(holder, cap)?;
252        let quota = match self.shared.quotas.get(target) {
253            Ok(Some(q)) => q,
254            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
255            Err(e) => return Err(self.unavailable(e)),
256        };
257        quota.top_up_cpu(extra);
258        Ok(())
259    }
260
261    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
262    pub fn admin_top_up_mem(
263        &self,
264        holder: FlowId,
265        cap: crate::bytecode::CapId,
266        target: FlowId,
267        extra: usize,
268    ) -> Result<(), crate::scheduler::error::LifecycleError> {
269        self.require_admin(holder, cap)?;
270        let quota = match self.shared.quotas.get(target) {
271            Ok(Some(q)) => q,
272            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
273            Err(e) => return Err(self.unavailable(e)),
274        };
275        quota.top_up_mem(extra);
276        Ok(())
277    }
278
279    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
280    pub fn admin_top_up_send(
281        &self,
282        holder: FlowId,
283        cap: crate::bytecode::CapId,
284        target: FlowId,
285        extra: i64,
286    ) -> Result<(), crate::scheduler::error::LifecycleError> {
287        self.require_admin(holder, cap)?;
288        let quota = match self.shared.quotas.get(target) {
289            Ok(Some(q)) => q,
290            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
291            Err(e) => return Err(self.unavailable(e)),
292        };
293        quota.top_up_send(extra);
294        Ok(())
295    }
296
297    fn require_admin(
298        &self,
299        holder: FlowId,
300        cap: crate::bytecode::CapId,
301    ) -> Result<(), crate::scheduler::error::LifecycleError> {
302        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
303            Ok(e) => e,
304            Err(_) => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
305        };
306        crate::scheduler::link_admin::check_admin(
307            &entry.cap,
308            self.shared.caps.scheduler_cell().as_ref(),
309        )
310        .map_err(|_| crate::scheduler::error::LifecycleError::InvalidCapability)
311    }
312
313    /// Remove a name without waiting for the flow to exit. `false` if unknown.
314    pub fn unregister_name(
315        &self,
316        name: &str,
317    ) -> Result<bool, crate::scheduler::error::LifecycleError> {
318        self.shared
319            .registry
320            .unregister(name)
321            .map_err(|e| self.unavailable(e))
322    }
323
324    /// Replace the image used by **new host** [`Self::spawn`] calls and
325    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
326    /// existing `Vm` chunk.
327    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
328        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
329            .map_err(SpawnError::VerifyFailed)?;
330        let chunk = Arc::new(chunk);
331        self.chunk = chunk.clone();
332        #[cfg(feature = "jit")]
333        if let Some(jit) = &self.shared.jit {
334            jit.reload(chunk);
335        }
336        Ok(())
337    }
338
339    /// Signal workers and the timer to stop. Does **not** join those threads.
340    /// [`Self::finish`] joins them and finalizes flows still parked.
341    fn request_shutdown(&self) {
342        self.shared.shutdown.store(true, Ordering::Release);
343        // Settle parked HostAwaits before joining workers: otherwise a bridge
344        // holding Completers could leave joiners blocked after OS threads exit.
345        finalize_host_awaits(&self.shared);
346        self.shared.timer.shutdown();
347        let (lock, cvar) = &self.shared.notify;
348        match crate::scheduler::sync_lock::lock(lock, "Runtime::request_shutdown") {
349            Ok(_g) => cvar.notify_all(),
350            Err(e) => crate::scheduler::error::report_fault(e),
351        }
352    }
353
354    /// Install the test-only host-completion replay gate.
355    ///
356    /// Production leaves the gate unset and delivers each completion at once.
357    /// Sequence numbers come from the test, not from arrival order.
358    #[cfg(test)]
359    pub(crate) fn enable_host_await_replay(
360        &self,
361    ) -> Result<(), crate::scheduler::error::RuntimeError> {
362        let mut gate = crate::scheduler::sync_lock::lock(
363            &self.shared.host_replay,
364            "Runtime::enable_host_await_replay",
365        )?;
366        *gate = Some(crate::scheduler::deterministic::HostReplayGate::default());
367        Ok(())
368    }
369
370    /// Bind a host-await ticket to a recorded sequence and deliver every
371    /// completion that is now the next event.
372    #[cfg(test)]
373    pub(crate) fn bind_host_await_replay(
374        &self,
375        ticket: u64,
376        sequence: u64,
377    ) -> Result<(), crate::scheduler::host_await::HostAwaitError> {
378        let ready = {
379            let mut gate = crate::scheduler::sync_lock::lock(
380                &self.shared.host_replay,
381                "Runtime::bind_host_await_replay",
382            )
383            .map_err(crate::scheduler::host_await::HostAwaitError::Runtime)?;
384            let Some(replay) = gate.as_mut() else {
385                return Err(crate::scheduler::host_await::HostAwaitError::Replay(
386                    "replay gate is not enabled",
387                ));
388            };
389            replay.bind(ticket, sequence).map_err(|err| {
390                crate::scheduler::host_await::HostAwaitError::Replay(
391                    crate::scheduler::deterministic::replay_label(err),
392                )
393            })?;
394            replay.drain_ready()
395        };
396        crate::scheduler::host_await::deliver_ready(&self.shared, ready)
397    }
398
399    /// Stop accepting new scheduling work, join every worker + the timer
400    /// thread, then finalize any flow still parked (mailbox, timer, injector,
401    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
402    /// instead of [`crate::scheduler::error::RuntimeError::Abandoned`].
403    ///
404    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
405    /// finalizes at the next loop check (cooperative preemption).
406    ///
407    /// [`Drop`] does the same work when it runs off a worker thread. On a
408    /// worker thread it only signals: joining that thread from itself would
409    /// deadlock the pool.
410    /// Register a process-wide (global) table under `name`.
411    ///
412    /// A flow that calls `TableOpen(name)` afterwards receives a Cap to this
413    /// table instead of opening its own per-flow table. The table survives
414    /// any single flow's exit; each opener's Cap is revoked when that flow
415    /// exits. Names must be 1..=256 bytes and unique.
416    pub fn register_table(&self, name: &str) -> Result<(), crate::scheduler::error::RuntimeError> {
417        self.shared
418            .tables
419            .register_global(&self.shared, name)
420            .map_err(crate::scheduler::error::RuntimeError::from)
421    }
422
423    /// Drop a previously registered global table and revoke every Cap that
424    /// still references it.
425    pub fn unregister_table(
426        &self,
427        name: &str,
428    ) -> Result<(), crate::scheduler::error::RuntimeError> {
429        self.shared
430            .tables
431            .unregister_global(&self.shared, name)
432            .map_err(crate::scheduler::error::RuntimeError::from)
433    }
434
435    /// Names of the currently registered global tables.
436    pub fn global_tables(&self) -> Vec<String> {
437        self.shared.tables.list_global()
438    }
439
440    pub fn shutdown(mut self) {
441        self.finish();
442    }
443
444    /// Join the threads started by [`Self::with_natives_and_config`] and
445    /// finalize every flow they did not finish. Safe to call again after
446    /// [`Self::shutdown`]: the handles are already taken and the second
447    /// sweep finds an empty directory.
448    fn finish(&mut self) {
449        if !self.shared.shutdown.load(Ordering::Acquire) {
450            self.request_shutdown();
451        }
452        for worker in self.workers.drain(..) {
453            let _ = worker.join();
454        }
455        crate::scheduler::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
456        if let Some(timer) = self.timer_thread.take() {
457            let _ = timer.join();
458        }
459        finalize_stranded(&self.shared);
460        if let Some(audit) = self.audit_worker.take() {
461            audit.stop();
462        }
463    }
464}
465
466fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
467    finalize_flow(
468        shared,
469        flow,
470        FlowOutcome::Failed("runtime shutdown".into()),
471        FlowExitReason::Shutdown,
472    );
473}
474
475fn finalize_host_awaits(shared: &Shared) {
476    match shared.host_awaits.cancel_all() {
477        Ok(notices) => crate::scheduler::host_await::notify_cancelled(shared, notices),
478        Err(e) => crate::scheduler::error::report_fault(e),
479    }
480}
481
482/// After workers and the timer have stopped, take every remaining flow
483/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
484///
485/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
486fn finalize_stranded(shared: &Shared) {
487    finalize_host_awaits(shared);
488    for flow in shared.timer.drain() {
489        finalize_shutdown_flow(shared, flow);
490    }
491    for _ in 0..8 {
492        let mut n = 0usize;
493        for flow in shared.injector.drain() {
494            finalize_shutdown_flow(shared, *flow);
495            n += 1;
496        }
497        for stealer in &shared.stealers {
498            for flow in stealer.drain() {
499                finalize_shutdown_flow(shared, *flow);
500                n += 1;
501            }
502        }
503        for (_id, mailbox) in shared.directory.snapshot() {
504            match mailbox.take_parked() {
505                Ok(Some(flow)) => {
506                    finalize_shutdown_flow(shared, *flow);
507                    n += 1;
508                }
509                Ok(None) => {}
510                Err(e) => crate::scheduler::error::report_fault(e),
511            }
512            match mailbox.close() {
513                Ok(senders) => {
514                    for sender in senders {
515                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
516                            crate::scheduler::error::report_fault(e);
517                        }
518                        finalize_shutdown_flow(shared, sender);
519                        n += 1;
520                    }
521                }
522                Err(e) => crate::scheduler::error::report_fault(e),
523            }
524        }
525        if n == 0 {
526            break;
527        }
528    }
529}
530
531impl Drop for Runtime {
532    fn drop(&mut self) {
533        if crate::scheduler::worker::is_on_worker() {
534            if !self.shared.shutdown.load(Ordering::Acquire) {
535                self.request_shutdown();
536            }
537            crate::scheduler::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
538            return;
539        }
540        self.finish();
541    }
542}