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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! The [`Runtime`]: M:N scheduler state shared by workers, host-facing
//! spawn/send/deliver entry points, and shutdown.
//!
//! Split by concern: [`config`] (tunables), `control` (capabilities,
//! monitors, links, names, admin, shutdown), `spawn` (the spawn path and
//! [`RuntimeSpawner`]).
// 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 std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread::JoinHandle;
use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
use crate::vm::{NativeGate, NativeTable, Vm};
use super::directory::Directory;
use super::error::{RuntimeError, SpawnError};
use super::finalize::finalize_flow;
use super::handle::FlowHandle;
use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSnapshot};
use super::monitor::FlowExitReason;
use super::process::{Flow, FlowId, FlowOutcome};
use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
use super::supervisor::SupervisorLink;
use super::timer::TimerWheel;
use super::worker;
use crate::bytecode::RestartPolicy;
mod config;
mod control;
mod spawn;
#[cfg(test)]
mod tests;
#[cfg(feature = "jit")]
pub use self::config::JitConfig;
pub use self::config::{RootAuthorityPolicy, RuntimeConfig, DEFAULT_QUANTUM};
#[cfg(test)]
use self::spawn::bytecode_spawn_arity;
pub use self::spawn::RuntimeSpawner;
pub(crate) use self::spawn::{spawn_on, BytecodeSpawn};
/// State shared by every worker thread and the timer thread. Everything in
/// here is either internally synchronized (`Injector`, `Directory`,
/// `CapTable`, `TimerWheel`, the `RuntimeMetrics` atomics) or immutable after
/// construction (`stealers`, `quantum`) — there is no top-level lock
/// covering the whole runtime, by design: a global lock is exactly what an
/// M:N scheduler exists to avoid.
pub(crate) struct Shared {
pub(crate) injector: Injector<Box<Flow>>,
pub(crate) stealers: Vec<Stealer<Flow>>,
/// FlowId → mailbox (delivery after Cap resolution).
pub(crate) directory: Directory,
/// CapId → { holder, target, rights, native_mask, epoch } (FlowCap).
pub(crate) caps: super::capability::CapTable,
pub(crate) timer: Arc<TimerWheel>,
pub(crate) notify: (Mutex<()>, Condvar),
pub(crate) metrics: RuntimeMetrics,
pub(crate) shutdown: AtomicBool,
pub(crate) quantum: u32,
pub(crate) mailbox: MailboxConfig,
/// Atomic live-flow budget (`max_flows == 0` → unlimited).
pub(crate) flow_limit: super::flow_limit::FlowLimit,
pub(crate) memory: Arc<crate::MemoryBudget>,
pub(crate) quota: super::quota::QuotaConfig,
pub(crate) quotas: super::quota::QuotaTable,
pub(crate) monitors: super::monitor::MonitorStore,
pub(crate) links: super::link::LinkStore,
pub(crate) registry: super::registry::RegistryStore,
pub(crate) kill_signals: super::finalize::KillSignals,
pub(crate) trap_exits: super::finalize::TrapExitFlags,
pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
pub(crate) ask_waits: super::finalize::AskWaitIndex,
/// In-flight `Opcode::HostAwait` tickets. The flow stays on a worker
/// or in its mailbox; completion arrives as a host hop.
pub(crate) host_awaits: super::host_await::HostAwaitIndex,
/// Host async bridge (`None` ⇒ HostAwait fails closed).
pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
/// Recorded order for host completions. `None` delivers immediately.
pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
/// Host `fail` text the worker reads before committing a success.
pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
/// `SendRemote` queue. `None` fails the opcode.
pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
/// Optional replay filter for inbound remote frames.
pub(crate) remote_dedup: Option<Arc<super::distribution::RemoteFrameDedup>>,
/// Embedder copy of scheduler diagnostics. `None` leaves stderr gating
/// in [`crate::log`] unchanged.
pub(crate) log_sink: Option<Arc<dyn crate::log::LogSink>>,
/// One named table per flow. Empty until `TableOpen`.
pub(crate) tables: super::table::FlowTables,
/// Supervisors started by bytecode `StartSupervisor`. Joined from
/// [`Runtime::shutdown`] after workers stop.
pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
/// Correlation ids for host `Runtime::send` when `request_id == 0`.
/// Starts at 1; `0` stays the unset sentinel.
pub(crate) host_next_request_id: AtomicU64,
/// Shared trace JIT state (`feature = "jit"`).
#[cfg(feature = "jit")]
pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
/// Sandbox observability (host-only; bytecode cannot mutate).
pub(crate) security: Arc<super::sandbox::SecurityCounters>,
pub(crate) security_audit: Option<Arc<dyn super::sandbox::SecurityAuditSink>>,
pub(crate) policy: super::sandbox::PolicyFingerprint,
pub(crate) trust: crate::bytecode::TrustLevel,
pub(crate) root_authority: RootAuthorityPolicy,
}
/// A running Byteflow runtime: worker pool + timer thread over one shared
/// [`Chunk`].
///
/// Owns M:N scheduling for **flows** (spawn, yield, sleep, mailboxes,
/// FlowCap resolution, supervised restarts). Optional trace JIT when built
/// with `feature = "jit"` and enabled in `RuntimeConfig`'s `jit` field.
///
/// Construct with [`Runtime::new`] (no natives) or
/// [`Runtime::with_natives`] when the chunk uses `CallNative` /
/// [`crate::std_native_table`].
pub struct Runtime {
shared: Arc<Shared>,
chunk: Arc<Chunk>,
natives: Arc<NativeTable>,
workers: Vec<JoinHandle<()>>,
timer_thread: Option<JoinHandle<()>>,
audit_worker: Option<super::sandbox::AuditWorkerHandle>,
trust: crate::bytecode::TrustLevel,
}
impl Runtime {
/// Convenience constructor for chunks that never call out through
/// `Opcode::CallNative`. Equivalent to
/// `Runtime::with_natives(chunk, NativeTable::empty())`.
///
/// Returns [`SpawnError`] instead of panicking: verify failures and OS
/// thread-spawn refusals are category-A errors (see
/// [`docs::error_model`](crate::docs::error_model)).
pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
Self::with_config(chunk, RuntimeConfig::default())
}
/// Construct a runtime whose flows can call into `natives` via
/// `Opcode::CallNative` — the host FFI boundary.
pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
}
pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
Self::with_natives_and_config(chunk, NativeTable::empty(), config)
}
/// Decode a `.bf` buffer only if its integrity fingerprint matches
/// `expected_digest`, then verify and start the runtime.
///
/// Digest mismatch / decode failure → [`SpawnError::Attestation`].
/// Semantic verify failure → [`SpawnError::VerifyFailed`].
pub fn with_attested(
bytes: &[u8],
expected_digest: [u8; 32],
natives: Arc<NativeTable>,
config: RuntimeConfig,
) -> Result<Self, SpawnError> {
let chunk =
crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
Self::with_natives_and_config(chunk, natives, config)
}
/// Like [`Runtime::with_config`] but wires [`crate::std_native_table_with`]
/// using [`RuntimeConfig::output`] for the `print` native.
pub fn with_std_natives_and_config(
chunk: Chunk,
config: RuntimeConfig,
) -> Result<Self, SpawnError> {
Self::with_natives_and_config(
chunk,
crate::std_native_table_with(Arc::clone(&config.output)),
config,
)
}
/// Verify `chunk`, spawn the worker pool + timer thread, and return a
/// live [`Runtime`].
///
/// Failures here mean the runtime was **never** started (no orphan
/// threads): either the bytecode is invalid
/// ([`SpawnError::VerifyFailed`]) or the OS refused a thread
/// ([`SpawnError::ThreadSpawnFailed`]). Partial spawn failure rolls
/// back: already-started workers/timer are shut down and joined before
/// the error is returned.
pub fn with_natives_and_config(
chunk: Chunk,
natives: Arc<NativeTable>,
config: RuntimeConfig,
) -> Result<Self, SpawnError> {
if let Err(err) = crate::bytecode::verify_with(
&chunk,
crate::bytecode::VerifyConfig {
trust: config.trust,
},
) {
if let Some(sink) = config.security_audit.as_ref() {
// Sync notify before workers exist — verify never starts the pool.
sink.record(&super::sandbox::SecurityEvent::ModuleRejected {
reason: "verify_failed",
});
}
return Err(SpawnError::VerifyFailed(err));
}
let chunk = Arc::new(chunk);
let workers_n = config.workers.max(1);
let quantum = config.quantum.max(1);
let (security_audit, audit_worker) = match config.security_audit.clone() {
Some(sink) => {
let (queued, handle) =
super::sandbox::wrap_audit_sink(sink, super::sandbox::DEFAULT_AUDIT_QUEUE);
(Some(queued), Some(handle))
}
None => (None, None),
};
let locals: Vec<LocalDeque<Flow>> = (0..workers_n).map(|_| LocalDeque::new()).collect();
let stealers: Vec<Stealer<Flow>> = locals.iter().map(|l| l.stealer()).collect();
#[cfg(feature = "jit")]
let jit = if config.jit.enabled {
Some(super::jit::new_runtime(
chunk.clone(),
config.jit.hot_threshold,
))
} else {
None
};
let shared = Arc::new(Shared {
injector: Injector::new(),
stealers,
directory: Directory::new(),
caps: super::capability::CapTable::new(),
timer: TimerWheel::new(),
notify: (Mutex::new(()), Condvar::new()),
metrics: RuntimeMetrics::default(),
shutdown: AtomicBool::new(false),
quantum,
mailbox: config.mailbox,
flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
quota: config.quota,
quotas: super::quota::QuotaTable::new(),
monitors: super::monitor::MonitorStore::new(config.max_monitors),
links: super::link::LinkStore::new(config.max_links),
registry: super::registry::RegistryStore::new(config.max_registry_names),
kill_signals: super::finalize::KillSignals::new(),
trap_exits: super::finalize::TrapExitFlags::new(),
waiting_send_at: super::finalize::WaitingSendIndex::new(),
ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
host_await_bridge: config.host_await.clone(),
host_replay: Mutex::new(None),
host_await_failures: super::host_await::HostAwaitFailures::new(),
distribution: config.distribution.clone(),
remote_dedup: if config.remote_dedup_window == 0 {
None
} else {
Some(super::distribution::RemoteFrameDedup::new(
config.remote_dedup_window as usize,
))
},
log_sink: config.log.clone(),
tables: super::table::FlowTables::new(),
flow_supervisors: Mutex::new(Vec::new()),
host_next_request_id: AtomicU64::new(1),
#[cfg(feature = "jit")]
jit,
security: Arc::new(super::sandbox::SecurityCounters::default()),
security_audit,
policy: config.policy_fingerprint(),
trust: config.trust,
root_authority: config.root_authority,
});
let mut workers = Vec::with_capacity(workers_n);
for local in locals {
let shared_w = shared.clone();
match std::thread::Builder::new()
.name("byteflow-worker".into())
.spawn(move || worker::run_worker(shared_w, local))
{
Ok(handle) => workers.push(handle),
Err(e) => {
abort_startup(&shared, workers, None);
return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
}
}
}
let shared_timer = shared.clone();
let timer_thread = match std::thread::Builder::new()
.name("byteflow-timer".into())
.spawn(move || shared_timer.timer.clone().drive(&shared_timer))
{
Ok(handle) => handle,
Err(e) => {
abort_startup(&shared, workers, None);
return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
}
};
Ok(Runtime {
shared,
chunk,
natives,
workers,
timer_thread: Some(timer_thread),
audit_worker,
trust: config.trust,
})
}
/// Spawn a top-level flow starting at `function` in this runtime's
/// chunk, returning a [`FlowHandle`] the caller can `.join()`.
///
/// Host authority follows [`RuntimeConfig::root_authority`] (default
/// trusted ROOT). For untrusted admission see [`Self::spawn_untrusted`].
///
/// Returns [`SpawnError::BadFunction`] if `function` is out of range.
pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
spawn_on(
&self.shared,
&self.chunk,
&self.natives,
function,
args,
RestartPolicy::Never,
None,
None,
None,
None,
)
}
/// Like [`Self::spawn`], but forces [`RootAuthorityPolicy::Untrusted`]
/// (no Cap rights, empty native mask) regardless of config.
pub fn spawn_untrusted(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
spawn_on(
&self.shared,
&self.chunk,
&self.natives,
function,
args,
RestartPolicy::Never,
None,
None,
None,
Some(RootAuthorityPolicy::Untrusted),
)
}
/// A cheap, `Send + Sync` handle that can spawn flows into this
/// runtime from any thread, independent of `Runtime`'s own lifetime
/// bookkeeping (worker `JoinHandle`s). Used by [`super::supervisor::Supervisor`].
pub fn spawner(&self) -> RuntimeSpawner {
RuntimeSpawner {
shared: self.shared.clone(),
chunk: self.chunk.clone(),
natives: self.natives.clone(),
}
}
/// A [`super::supervisor::Supervisor`] bound to this runtime, ready to
/// take supervised children (design notes §15).
pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
super::supervisor::Supervisor::new(self.spawner())
}
/// Look up a function by name in the runtime's chunk — convenience for
/// callers that built their chunk with [`crate::Program`]
/// and don't want to thread raw indices through their own code.
pub fn function_index(&self, name: &str) -> Option<u32> {
self.chunk
.functions
.iter()
.position(|f| f.name == name)
.map(|i| i as u32)
}
pub fn metrics(&self) -> RuntimeMetricsSnapshot {
self.shared.metrics.snapshot()
}
/// Sandbox security counters (host-only).
pub fn security_counters(&self) -> super::sandbox::SecurityCountersSnapshot {
self.shared.security.snapshot()
}
/// Policy fingerprint recorded at construction.
pub fn policy_fingerprint(&self) -> super::sandbox::PolicyFingerprint {
self.shared.policy
}
/// Trust level used for constant-pool verification at construction.
pub fn trust_level(&self) -> crate::bytecode::TrustLevel {
self.trust
}
/// Host attestation of Caps currently held by `flow`.
pub fn attest_capabilities(
&self,
flow: FlowId,
) -> Result<super::sandbox::CapabilityAttestation, RuntimeError> {
super::sandbox::CapabilityAttestation::from_table(
&self.shared.caps,
flow,
self.trust,
self.shared.policy,
)
}
/// Point-in-time view for dashboards and debug tooling.
pub fn snapshot(&self) -> RuntimeSnapshot {
RuntimeSnapshot {
metrics: self.metrics(),
live_flows: self.live_flows(),
flow_limit_live: self.shared.flow_limit.reserved_live(),
max_flows: self.shared.flow_limit.max_flows(),
distribution_pending: self
.shared
.distribution
.as_ref()
.and_then(|b| b.outbound_pending().ok()),
memory: self.memory_snapshot(),
workers: self.worker_count(),
}
}
/// Approximate number of flows currently registered in the directory.
///
/// Sharded sum without a global snapshot — fine for dashboards
/// ([`Self::metrics`]), **not** for admission control (see
/// the flow limit / `max_flows`).
pub fn live_flows(&self) -> usize {
self.shared.directory.len()
}
/// Process-wide heap accounting snapshot (`max_runtime_bytes` ceiling).
pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
self.shared.memory.snapshot()
}
pub fn worker_count(&self) -> usize {
self.workers.len()
}
/// Deliver an **Atomic Hop** (`Value::Message`) to `target` from the
/// embedder (not from bytecode).
///
/// # Host trust boundary
///
/// This path takes a [`FlowId`] directly — **no Cap required**. The host
/// is trusted; bytecode must use `Value::Cap` via `Opcode::Send` /
/// `Ask`. The hop still goes through the same authentication choke-point
/// as bytecode: `sender` is stamped [`FlowId::HOST`] (`0`), `request_id`
/// is minted when unset, and payload Caps are reissued to the recipient.
/// The host has no mailbox, so `reply_cap` is [`crate::bytecode::CapId::NONE`].
/// Bare scalars are rejected ([`SendError::NotAHop`]).
pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
let Some(msg) = message.as_message().cloned() else {
return Err(SendError::NotAHop {
got: message.type_name(),
});
};
let mailbox = match self.shared.directory.lookup(target) {
Ok(Some(m)) => m,
Ok(None) => return Err(SendError::NoSuchFlow(target)),
Err(e) => {
super::error::report_fault(e);
return Err(SendError::Unavailable);
}
};
let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
Ok(m) => Value::Message(m),
Err(_) => return Err(SendError::Capability),
};
match mailbox.push(stamped.clone()) {
// Host `send` is fire-and-forget: DropNewest means the hop was
// intentionally discarded under policy, not an infrastructure
// error. Bytecode `Ask` treats DropNewest as hard failure in
// `worker::deliver` (must not park waiting for a reply).
Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
Ok(())
}
Ok(Ok(Delivery::Handoff(flow))) => {
let _ = self.shared.ask_waits.remove_asker(flow.id);
match flow.last_receive_dest {
Some(dest) => {
let Some(flow) =
super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
else {
return Err(SendError::Unavailable);
};
enqueue_flow(&self.shared, flow);
wake_workers(&self.shared);
Ok(())
}
None => {
super::error::report_fault(super::error::RuntimeError::PoisonedLock(
"Runtime::send handoff missing dest register",
));
finalize_flow(
&self.shared,
*flow,
FlowOutcome::Failed("handoff missing dest register".into()),
FlowExitReason::Fault,
);
Err(SendError::Unavailable)
}
}
}
Ok(Err(full)) => {
if full.reason() == MailboxFullReason::Closed {
return Err(SendError::NoSuchFlow(target));
}
Err(SendError::MailboxFull {
flow: target,
reason: full.reason(),
})
}
Err(e) => {
super::error::report_fault(e);
Err(SendError::Unavailable)
}
}
}
/// Deliver a hop the host read off its own socket.
///
/// The frame's sender is kept. This path does not restamp it as the local
/// host (`0`). A `Cap` or `Pid` in the frame is refused. The name must
/// already be registered on this node; the host still owns the socket.
///
/// When [`RuntimeConfig::remote_dedup_window`] is set, acceptance is
/// transactional: a failed delivery (unknown name, full mailbox) rolls
/// back the reservation so the host may retransmit the same
/// `(sender, request_id)`.
pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
let hop = super::distribution::decode_frame(bytes)?;
let reservation = if hop.message.request_id != 0 {
if let Some(dedup) = self.shared.remote_dedup.as_ref() {
match dedup
.reserve(hop.sender.as_u64(), hop.message.request_id)
.map_err(|_| super::distribution::RemoteFrameError::Unavailable)?
{
super::distribution::DedupTicket::Duplicate => return Ok(()),
super::distribution::DedupTicket::Fresh { sender, request_id } => {
Some((sender, request_id))
}
}
} else {
None
}
} else {
None
};
let outcome = self.deliver_frame_after_dedup(hop);
if let Some((sender, request_id)) = reservation {
if let Some(dedup) = self.shared.remote_dedup.as_ref() {
match &outcome {
// Mailbox accepted the hop (queued or handoff taken).
Ok(()) | Err(DeliverAcceptError::AfterAccept(_)) => {
let _ = dedup.commit(sender, request_id);
}
Err(DeliverAcceptError::BeforeAccept(_)) => {
let _ = dedup.rollback(sender, request_id);
}
}
}
}
match outcome {
Ok(()) => Ok(()),
Err(DeliverAcceptError::BeforeAccept(e) | DeliverAcceptError::AfterAccept(e)) => Err(e),
}
}
fn deliver_frame_after_dedup(
&self,
hop: super::distribution::OutboundHop,
) -> Result<(), DeliverAcceptError> {
let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
Ok(Some(cap)) => cap,
Ok(None) => {
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::NoSuchName,
))
}
Err(err) => {
super::error::report_fault(err);
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::Unavailable,
));
}
};
let target = match self.shared.caps.lookup(cap) {
Ok(Some(entry)) => match entry.target() {
Some(id) => id,
None => {
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::NoSuchName,
))
}
},
Ok(None) => {
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::NoSuchName,
))
}
Err(err) => {
super::error::report_fault(err);
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::Unavailable,
));
}
};
let mailbox = match self.shared.directory.lookup(target) {
Ok(Some(mailbox)) => mailbox,
Ok(None) => {
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::NoSuchName,
))
}
Err(err) => {
super::error::report_fault(err);
return Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::Unavailable,
));
}
};
let stamped = Value::Message(hop.message);
match mailbox.push(stamped.clone()) {
Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
Ok(())
}
Ok(Ok(Delivery::Handoff(flow))) => {
let _ = self.shared.ask_waits.remove_asker(flow.id);
match flow.last_receive_dest {
Some(dest) => {
let Some(flow) =
super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
else {
return Err(DeliverAcceptError::AfterAccept(
super::distribution::RemoteFrameError::Unavailable,
));
};
enqueue_flow(&self.shared, flow);
wake_workers(&self.shared);
Ok(())
}
None => {
super::finalize::finalize_flow(
&self.shared,
*flow,
FlowOutcome::Failed("handoff missing dest register".into()),
FlowExitReason::Fault,
);
Err(DeliverAcceptError::AfterAccept(
super::distribution::RemoteFrameError::Unavailable,
))
}
}
}
Ok(Err(full)) => Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::Mailbox(full.reason()),
)),
Err(err) => {
super::error::report_fault(err);
Err(DeliverAcceptError::BeforeAccept(
super::distribution::RemoteFrameError::Unavailable,
))
}
}
}
}
/// Internal split for remote dedup: rollback only when the mailbox never
/// accepted the hop.
enum DeliverAcceptError {
BeforeAccept(super::distribution::RemoteFrameError),
AfterAccept(super::distribution::RemoteFrameError),
}
/// A convenience Pid constructor for embedders that stored a raw `u64`
/// (e.g. round-tripped through `Value::Pid`) and need a [`FlowId`] to
/// call APIs that take one.
pub fn flow_id_from_u64(raw: u64) -> FlowId {
FlowId(raw)
}
/// Why [`Runtime::send`] could not deliver a hop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SendError {
NoSuchFlow(FlowId),
/// Atomic Hop rule: only [`crate::Value::Message`] may cross `Send`.
NotAHop {
got: &'static str,
},
/// Target inbox is at one of its logical bounds
/// ([`OverflowPolicy::Reject`](crate::OverflowPolicy::Reject)). `reason` says which — see
/// [`MailboxFullReason`].
MailboxFull {
flow: FlowId,
reason: MailboxFullReason,
},
/// Host hop authentication failed (payload Cap reissue).
Capability,
/// Directory / mailbox mutex poisoned — not "no such flow".
Unavailable,
}
impl std::fmt::Display for SendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
SendError::NotAHop { got } => {
write!(f, "atomic hop requires Value::Message, got {got}")
}
SendError::MailboxFull { flow, reason } => {
write!(f, "mailbox full for {flow} ({reason})")
}
SendError::Capability => {
write!(f, "host send could not reissue a capability in the hop")
}
SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
}
}
}
impl std::error::Error for SendError {}
/// Park `flow` on the global injector.
///
/// A poisoned injector is cleared inside [`Injector::push`]. The flow stays
/// queued with whatever was already there.
pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
shared.injector.push(flow);
}
pub(crate) fn wake_workers(shared: &Shared) {
let (lock, cvar) = &shared.notify;
match super::sync_lock::lock(lock, "wake_workers") {
Ok(_g) => cvar.notify_one(),
Err(e) => super::error::report_fault(e),
}
}
/// Signal shutdown and join any threads already started during construction
/// failure — keeps the "no orphan threads" contract of
/// [`Runtime::with_natives_and_config`].
pub(crate) fn record_security_event(shared: &Shared, event: &super::sandbox::SecurityEvent) {
use super::sandbox::{SecurityCounters, SecurityEvent};
match event {
SecurityEvent::AccessDenied { .. } => {
SecurityCounters::inc(&shared.security.denied_operations);
}
SecurityEvent::QuotaExceeded { .. } => {
SecurityCounters::inc(&shared.security.quota_exceeded);
}
SecurityEvent::CapabilityCreated { .. } => {
SecurityCounters::inc(&shared.security.capabilities_created);
}
SecurityEvent::CapabilityRevoked { .. } => {
SecurityCounters::inc(&shared.security.capabilities_revoked);
}
SecurityEvent::ModuleRejected { .. } => {
SecurityCounters::inc(&shared.security.invalid_modules);
}
SecurityEvent::NativeDenied { .. } => {
SecurityCounters::inc(&shared.security.native_denied);
}
SecurityEvent::CapabilityDelegated { .. } | SecurityEvent::FlowFinalized { .. } => {}
}
if let Some(sink) = shared.security_audit.as_ref() {
// Queued: never blocks the worker on a slow host sink.
sink.record(event);
}
}
pub(crate) fn record_quota_exceeded(shared: &Shared, err: super::quota::QuotaError) {
record_security_event(
shared,
&super::sandbox::SecurityEvent::QuotaExceeded {
kind: err.audit_kind(),
},
);
}
fn abort_startup(
shared: &Arc<Shared>,
workers: Vec<std::thread::JoinHandle<()>>,
timer: Option<std::thread::JoinHandle<()>>,
) {
shared.shutdown.store(true, Ordering::Release);
shared.timer.shutdown();
let (lock, cvar) = &shared.notify;
match super::sync_lock::lock(lock, "abort_startup") {
Ok(_g) => cvar.notify_all(),
Err(e) => super::error::report_fault(e),
}
for w in workers {
let _ = w.join();
}
if let Some(t) = timer {
let _ = t.join();
}
}