byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Control plane of a running [`Runtime`]: capabilities, monitors, links,
//! names, admin top-ups, chunk reload, host-await replay and shutdown.
// 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::*;

impl Runtime {
    fn require_live(&self, id: FlowId) -> Result<(), crate::scheduler::error::LifecycleError> {
        match self.shared.directory.lookup(id) {
            Ok(Some(_)) => Ok(()),
            Ok(None) => Err(crate::scheduler::error::LifecycleError::NoSuchFlow(id)),
            Err(e) => Err(self.unavailable(e)),
        }
    }

    fn unavailable(
        &self,
        err: crate::scheduler::error::RuntimeError,
    ) -> crate::scheduler::error::LifecycleError {
        crate::scheduler::error::report_fault(err);
        crate::scheduler::error::LifecycleError::Unavailable
    }

    /// Mint an addressing Cap ([`CapRights::ADDRESSING`]) for a live flow
    /// (host equivalent of `SelfPid`).
    pub fn mint_cap(
        &self,
        flow: FlowId,
    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
        self.require_live(flow)?;
        self.shared
            .caps
            .mint(
                flow,
                flow,
                crate::scheduler::capability::CapRights::ADDRESSING,
            )
            .map_err(|e| self.unavailable(e))
    }

    /// Mint a Cap held by `holder` targeting `target` (host introduction).
    pub fn grant_cap(
        &self,
        holder: FlowId,
        target: FlowId,
    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
        self.require_live(holder)?;
        self.require_live(target)?;
        self.shared
            .caps
            .mint(
                holder,
                target,
                crate::scheduler::capability::CapRights::ADDRESSING,
            )
            .map_err(|e| self.unavailable(e))
    }

    /// Watch `target`; when it exits, `owner` receives a [`crate::TAG_SYS_DOWN`] hop.
    ///
    /// Both flows must be live. `owner == target` is `LifecycleError::SelfRelation`.
    pub fn monitor(
        &self,
        owner: FlowId,
        target: FlowId,
    ) -> Result<crate::scheduler::monitor::MonitorRef, crate::scheduler::error::LifecycleError>
    {
        if owner == target {
            return Err(crate::scheduler::error::LifecycleError::SelfRelation);
        }
        self.require_live(owner)?;
        self.require_live(target)?;
        let mon = self
            .shared
            .monitors
            .create(owner, target)
            .map_err(|e| self.unavailable(e))??;
        // Target may have finalized between the live check and insert.
        // Synthesize DOWN and drop the now-useless relation (owner still live).
        if self.require_live(target).is_err() {
            let _ = self.shared.monitors.remove_owned(owner, mon);
            crate::scheduler::finalize::deliver_down(
                &self.shared,
                crate::scheduler::monitor::DownEvent {
                    monitor: mon,
                    owner,
                    target,
                    reason: crate::scheduler::monitor::FlowExitReason::Fault,
                },
            );
        }
        Ok(mon)
    }

    /// Drop `monitor` if `owner` still owns it.
    pub fn demonitor(
        &self,
        owner: FlowId,
        monitor: crate::scheduler::monitor::MonitorRef,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_live(owner)?;
        match self.shared.monitors.remove_owned(owner, monitor) {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Bidirectional link. Without `trap_exit`, abnormal exit of either side
    /// kills the peer (`Normal` only drops the link). With
    /// [`Self::set_trap_exit`] on a peer, that peer receives a
    /// [`crate::TAG_SYS_EXIT`] hop for every linked exit (including `Normal`).
    pub fn link(
        &self,
        a: FlowId,
        b: FlowId,
    ) -> Result<crate::scheduler::link::LinkId, crate::scheduler::error::LifecycleError> {
        if a == b {
            return Err(crate::scheduler::error::LifecycleError::SelfRelation);
        }
        self.require_live(a)?;
        self.require_live(b)?;
        match self.shared.links.link_if_live(a, b, |id| {
            self.shared.directory.lookup(id).map(|m| m.is_some())
        }) {
            Ok(Ok(crate::scheduler::link::LinkOutcome::Linked(id))) => Ok(id),
            Ok(Ok(crate::scheduler::link::LinkOutcome::Consumed { dead })) => {
                Err(crate::scheduler::error::LifecycleError::NoSuchFlow(dead))
            }
            Ok(Err(error)) => Err(error),
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// BEAM-style `process_flag(trap_exit, …)`.
    ///
    /// When `enabled`, linked exits deliver a [`crate::TAG_SYS_EXIT`] hop
    /// (including `Normal`) instead of killing this flow.
    pub fn set_trap_exit(
        &self,
        id: FlowId,
        enabled: bool,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_live(id)?;
        self.shared
            .trap_exits
            .set(id, enabled)
            .map_err(|e| self.unavailable(e))
    }

    /// Drop `link` if `owner` is one of the endpoints.
    pub fn unlink(
        &self,
        owner: FlowId,
        link: crate::scheduler::link::LinkId,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_live(owner)?;
        match self.shared.links.unlink_owned(owner, link) {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Bind `name` to a live Cap (address). Names are swept when that flow exits.
    pub fn register_name(
        &self,
        name: &str,
        cap: crate::bytecode::CapId,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        let entry = match self.shared.caps.lookup(cap) {
            Ok(Some(e)) => e,
            Ok(None) => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
            Err(e) => return Err(self.unavailable(e)),
        };
        let target = match entry.target() {
            Some(id) => id,
            None => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
        };
        self.require_live(target)?;
        match self.shared.registry.register(
            crate::scheduler::registry::RegistryName::from(name),
            cap,
            target,
        ) {
            Ok(inner) => inner,
            Err(e) => Err(self.unavailable(e)),
        }
    }

    /// Look up a registered Cap, or `None` if the name is free / was swept.
    pub fn whereis(
        &self,
        name: &str,
    ) -> Result<Option<crate::bytecode::CapId>, crate::scheduler::error::LifecycleError> {
        self.shared
            .registry
            .whereis(name)
            .map_err(|e| self.unavailable(e))
    }

    /// Cooperative abort. Parked flows finalize immediately; a running flow
    /// dies at the next quantum with [`crate::scheduler::monitor::FlowExitReason::Killed`].
    pub fn kill(&self, id: FlowId) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_live(id)?;
        crate::scheduler::finalize::request_kill(
            &self.shared,
            id,
            crate::scheduler::monitor::FlowExitReason::Killed,
        );
        Ok(())
    }

    /// Mint a scheduler ADMIN cap for a live flow (host introduction).
    pub fn mint_admin_cap(
        &self,
        holder: FlowId,
    ) -> Result<crate::bytecode::CapId, crate::scheduler::error::LifecycleError> {
        self.require_live(holder)?;
        let cap = crate::bytecode::Cap::root(
            crate::bytecode::CapTarget::Scheduler,
            CapRights::ADMIN,
            None,
            self.shared.caps.scheduler_cell().as_ref(),
        );
        self.shared
            .caps
            .grant(holder, cap)
            .map_err(|e| self.unavailable(e))
    }

    /// Kill `target` only if `holder` presents a live ADMIN scheduler cap.
    pub fn admin_kill(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        self.kill(target)
    }

    /// Top up `target`'s CPU budget. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_cpu(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: i64,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_cpu(extra);
        Ok(())
    }

    /// Raise `target`'s heap limit. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_mem(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: usize,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_mem(extra);
        Ok(())
    }

    /// Credit `target`'s send bucket. Requires a live ADMIN scheduler cap.
    pub fn admin_top_up_send(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
        target: FlowId,
        extra: i64,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        self.require_admin(holder, cap)?;
        let quota = match self.shared.quotas.get(target) {
            Ok(Some(q)) => q,
            Ok(None) => return Err(crate::scheduler::error::LifecycleError::NoSuchFlow(target)),
            Err(e) => return Err(self.unavailable(e)),
        };
        quota.top_up_send(extra);
        Ok(())
    }

    fn require_admin(
        &self,
        holder: FlowId,
        cap: crate::bytecode::CapId,
    ) -> Result<(), crate::scheduler::error::LifecycleError> {
        let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
            Ok(e) => e,
            Err(_) => return Err(crate::scheduler::error::LifecycleError::InvalidCapability),
        };
        crate::scheduler::link_admin::check_admin(
            &entry.cap,
            self.shared.caps.scheduler_cell().as_ref(),
        )
        .map_err(|_| crate::scheduler::error::LifecycleError::InvalidCapability)
    }

    /// Remove a name without waiting for the flow to exit. `false` if unknown.
    pub fn unregister_name(
        &self,
        name: &str,
    ) -> Result<bool, crate::scheduler::error::LifecycleError> {
        self.shared
            .registry
            .unregister(name)
            .map_err(|e| self.unavailable(e))
    }

    /// Replace the image used by **new host** [`Self::spawn`] calls and
    /// drop JIT traces. Live flows and bytecode `Spawn` keep the parent's
    /// existing `Vm` chunk.
    pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
        crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
            .map_err(SpawnError::VerifyFailed)?;
        let chunk = Arc::new(chunk);
        self.chunk = chunk.clone();
        #[cfg(feature = "jit")]
        if let Some(jit) = &self.shared.jit {
            jit.reload(chunk);
        }
        Ok(())
    }

    /// Signal workers and the timer to stop. Does **not** join those threads.
    /// [`Self::finish`] joins them and finalizes flows still parked.
    fn request_shutdown(&self) {
        self.shared.shutdown.store(true, Ordering::Release);
        // Settle parked HostAwaits before joining workers: otherwise a bridge
        // holding Completers could leave joiners blocked after OS threads exit.
        finalize_host_awaits(&self.shared);
        self.shared.timer.shutdown();
        let (lock, cvar) = &self.shared.notify;
        match crate::scheduler::sync_lock::lock(lock, "Runtime::request_shutdown") {
            Ok(_g) => cvar.notify_all(),
            Err(e) => crate::scheduler::error::report_fault(e),
        }
    }

    /// Install the test-only host-completion replay gate.
    ///
    /// Production leaves the gate unset and delivers each completion at once.
    /// Sequence numbers come from the test, not from arrival order.
    #[cfg(test)]
    pub(crate) fn enable_host_await_replay(
        &self,
    ) -> Result<(), crate::scheduler::error::RuntimeError> {
        let mut gate = crate::scheduler::sync_lock::lock(
            &self.shared.host_replay,
            "Runtime::enable_host_await_replay",
        )?;
        *gate = Some(crate::scheduler::deterministic::HostReplayGate::default());
        Ok(())
    }

    /// Bind a host-await ticket to a recorded sequence and deliver every
    /// completion that is now the next event.
    #[cfg(test)]
    pub(crate) fn bind_host_await_replay(
        &self,
        ticket: u64,
        sequence: u64,
    ) -> Result<(), crate::scheduler::host_await::HostAwaitError> {
        let ready = {
            let mut gate = crate::scheduler::sync_lock::lock(
                &self.shared.host_replay,
                "Runtime::bind_host_await_replay",
            )
            .map_err(crate::scheduler::host_await::HostAwaitError::Runtime)?;
            let Some(replay) = gate.as_mut() else {
                return Err(crate::scheduler::host_await::HostAwaitError::Replay(
                    "replay gate is not enabled",
                ));
            };
            replay.bind(ticket, sequence).map_err(|err| {
                crate::scheduler::host_await::HostAwaitError::Replay(
                    crate::scheduler::deterministic::replay_label(err),
                )
            })?;
            replay.drain_ready()
        };
        crate::scheduler::host_await::deliver_ready(&self.shared, ready)
    }

    /// Stop accepting new scheduling work, join every worker + the timer
    /// thread, then finalize any flow still parked (mailbox, timer, injector,
    /// worker deques). Joiners see [`FlowOutcome::Failed`] (`runtime shutdown`)
    /// instead of [`crate::scheduler::error::RuntimeError::Abandoned`].
    ///
    /// Mid-quantum bytecode is not aborted mid-instruction — the worker
    /// finalizes at the next loop check (cooperative preemption).
    ///
    /// [`Drop`] does the same work when it runs off a worker thread. On a
    /// worker thread it only signals: joining that thread from itself would
    /// deadlock the pool.
    /// Register a process-wide (global) table under `name`.
    ///
    /// A flow that calls `TableOpen(name)` afterwards receives a Cap to this
    /// table instead of opening its own per-flow table. The table survives
    /// any single flow's exit; each opener's Cap is revoked when that flow
    /// exits. Names must be 1..=256 bytes and unique.
    pub fn register_table(&self, name: &str) -> Result<(), crate::scheduler::error::RuntimeError> {
        self.shared
            .tables
            .register_global(&self.shared, name)
            .map_err(crate::scheduler::error::RuntimeError::from)
    }

    /// Drop a previously registered global table and revoke every Cap that
    /// still references it.
    pub fn unregister_table(
        &self,
        name: &str,
    ) -> Result<(), crate::scheduler::error::RuntimeError> {
        self.shared
            .tables
            .unregister_global(&self.shared, name)
            .map_err(crate::scheduler::error::RuntimeError::from)
    }

    /// Names of the currently registered global tables.
    pub fn global_tables(&self) -> Vec<String> {
        self.shared.tables.list_global()
    }

    pub fn shutdown(mut self) {
        self.finish();
    }

    /// Join the threads started by [`Self::with_natives_and_config`] and
    /// finalize every flow they did not finish. Safe to call again after
    /// [`Self::shutdown`]: the handles are already taken and the second
    /// sweep finds an empty directory.
    fn finish(&mut self) {
        if !self.shared.shutdown.load(Ordering::Acquire) {
            self.request_shutdown();
        }
        for worker in self.workers.drain(..) {
            let _ = worker.join();
        }
        crate::scheduler::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
        if let Some(timer) = self.timer_thread.take() {
            let _ = timer.join();
        }
        finalize_stranded(&self.shared);
        if let Some(audit) = self.audit_worker.take() {
            audit.stop();
        }
    }
}

fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
    finalize_flow(
        shared,
        flow,
        FlowOutcome::Failed("runtime shutdown".into()),
        FlowExitReason::Shutdown,
    );
}

fn finalize_host_awaits(shared: &Shared) {
    match shared.host_awaits.cancel_all() {
        Ok(notices) => crate::scheduler::host_await::notify_cancelled(shared, notices),
        Err(e) => crate::scheduler::error::report_fault(e),
    }
}

/// After workers and the timer have stopped, take every remaining flow
/// and run it through [`finalize_flow`] so links, monitors and joiners fire.
///
/// A few passes: finalize can hand off a `trap_exit` peer onto the injector.
fn finalize_stranded(shared: &Shared) {
    finalize_host_awaits(shared);
    for flow in shared.timer.drain() {
        finalize_shutdown_flow(shared, flow);
    }
    for _ in 0..8 {
        let mut n = 0usize;
        for flow in shared.injector.drain() {
            finalize_shutdown_flow(shared, *flow);
            n += 1;
        }
        for stealer in &shared.stealers {
            for flow in stealer.drain() {
                finalize_shutdown_flow(shared, *flow);
                n += 1;
            }
        }
        for (_id, mailbox) in shared.directory.snapshot() {
            match mailbox.take_parked() {
                Ok(Some(flow)) => {
                    finalize_shutdown_flow(shared, *flow);
                    n += 1;
                }
                Ok(None) => {}
                Err(e) => crate::scheduler::error::report_fault(e),
            }
            match mailbox.close() {
                Ok(senders) => {
                    for sender in senders {
                        if let Err(e) = shared.waiting_send_at.remove(sender.id) {
                            crate::scheduler::error::report_fault(e);
                        }
                        finalize_shutdown_flow(shared, sender);
                        n += 1;
                    }
                }
                Err(e) => crate::scheduler::error::report_fault(e),
            }
        }
        if n == 0 {
            break;
        }
    }
}

impl Drop for Runtime {
    fn drop(&mut self) {
        if crate::scheduler::worker::is_on_worker() {
            if !self.shared.shutdown.load(Ordering::Acquire) {
                self.request_shutdown();
            }
            crate::scheduler::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
            return;
        }
        self.finish();
    }
}