1use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
2use std::sync::{Arc, Condvar, Mutex};
3use std::thread::JoinHandle;
4
5use crate::bytecode::{Cap, CapRights, CapTarget, Chunk, NativeMask, Value};
6use crate::vm::{NativeGate, NativeTable, Vm};
7
8use super::directory::Directory;
9use super::error::SpawnError;
10use super::finalize::finalize_flow;
11use super::handle::FlowHandle;
12use super::mailbox::{Delivery, Mailbox, MailboxConfig, MailboxFullReason};
13use super::metrics::{RuntimeMetrics, RuntimeMetricsSnapshot};
14use super::monitor::FlowExitReason;
15use super::process::{Flow, FlowId, FlowOutcome};
16use super::runqueue::{Injector, Stealer, Worker as LocalDeque};
17use super::supervisor::SupervisorLink;
18use super::timer::TimerWheel;
19use super::worker;
20use crate::bytecode::RestartPolicy;
21
22pub const DEFAULT_QUANTUM: u32 = 10_000;
30
31#[derive(Clone, Debug)]
34pub struct RuntimeConfig {
35 pub workers: usize,
40 pub quantum: u32,
43 pub mailbox: MailboxConfig,
47 pub max_flows: u32,
50 pub max_ask_waits: u32,
55 pub max_host_awaits: u32,
58 pub max_links: u32,
63 pub max_monitors: u32,
67 pub max_registry_names: u32,
71 pub host_await: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
74 pub distribution: Option<Arc<super::distribution::DistributionBridge>>,
77 pub max_runtime_bytes: usize,
82 pub trust: crate::bytecode::TrustLevel,
85 pub output: Arc<dyn crate::OutputSink>,
88 pub quota: super::quota::QuotaConfig,
90 #[cfg(feature = "jit")]
92 pub jit: JitConfig,
93}
94
95#[cfg(feature = "jit")]
97#[derive(Clone, Debug)]
98pub struct JitConfig {
99 pub enabled: bool,
101 pub hot_threshold: u32,
103}
104
105#[cfg(feature = "jit")]
106impl Default for JitConfig {
107 fn default() -> Self {
108 JitConfig {
109 enabled: false,
110 hot_threshold: crate::jit::HOT_THRESHOLD,
111 }
112 }
113}
114
115fn default_worker_count() -> usize {
117 match std::thread::available_parallelism() {
118 Ok(n) => n.get().max(1),
119 Err(_) => 1,
120 }
121}
122
123impl Default for RuntimeConfig {
124 fn default() -> Self {
125 RuntimeConfig {
126 workers: default_worker_count(),
127 quantum: DEFAULT_QUANTUM,
128 mailbox: MailboxConfig::DEFAULT,
129 max_flows: 0,
130 max_ask_waits: 0,
131 max_host_awaits: 0,
132 max_links: 0,
133 max_monitors: 0,
134 max_registry_names: 0,
135 host_await: None,
136 distribution: None,
137 max_runtime_bytes: 256 * 1024 * 1024,
138 trust: crate::bytecode::TrustLevel::Untrusted,
139 output: Arc::new(crate::output::NullSink),
140 quota: super::quota::QuotaConfig::default(),
141 #[cfg(feature = "jit")]
142 jit: JitConfig::default(),
143 }
144 }
145}
146
147impl RuntimeConfig {
148 pub fn sandbox() -> Self {
153 RuntimeConfig {
154 quota: super::quota::QuotaConfig::sandbox(),
155 max_flows: 256,
156 max_ask_waits: 128,
157 max_host_awaits: 128,
158 max_links: 1024,
159 max_monitors: 1024,
160 max_registry_names: 256,
161 max_runtime_bytes: 64 * 1024 * 1024,
162 ..Default::default()
163 }
164 }
165}
166
167pub struct Shared {
174 pub(crate) injector: Injector<Box<Flow>>,
175 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
176 pub(crate) directory: Directory,
178 pub(crate) caps: super::capability::CapTable,
180 pub(crate) timer: Arc<TimerWheel>,
181 pub(crate) notify: (Mutex<()>, Condvar),
182 pub(crate) metrics: RuntimeMetrics,
183 pub(crate) shutdown: AtomicBool,
184 pub(crate) quantum: u32,
185 pub(crate) mailbox: MailboxConfig,
186 pub(crate) flow_limit: super::flow_limit::FlowLimit,
188 pub(crate) memory: Arc<crate::MemoryBudget>,
189 pub(crate) quota: super::quota::QuotaConfig,
190 pub(crate) quotas: super::quota::QuotaTable,
191 pub(crate) monitors: super::monitor::MonitorStore,
192 pub(crate) links: super::link::LinkStore,
193 pub(crate) registry: super::registry::RegistryStore,
194 pub(crate) kill_signals: super::finalize::KillSignals,
195 pub(crate) trap_exits: super::finalize::TrapExitFlags,
196 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
197 pub(crate) ask_waits: super::finalize::AskWaitIndex,
198 pub(crate) host_awaits: super::host_await::HostAwaitIndex,
201 pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
203 pub(crate) host_replay: Mutex<Option<super::deterministic::HostReplayGate>>,
205 pub(crate) host_await_failures: super::host_await::HostAwaitFailures,
207 pub(crate) distribution: Option<Arc<super::distribution::DistributionBridge>>,
209 pub(crate) tables: super::table::FlowTables,
211 pub(crate) flow_supervisors: Mutex<Vec<super::supervisor::Supervisor>>,
214 pub(crate) host_next_request_id: AtomicU64,
217 #[cfg(feature = "jit")]
219 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
220}
221
222pub struct Runtime {
233 shared: Arc<Shared>,
234 chunk: Arc<Chunk>,
235 natives: Arc<NativeTable>,
236 workers: Vec<JoinHandle<()>>,
237 timer_thread: Option<JoinHandle<()>>,
238 trust: crate::bytecode::TrustLevel,
239}
240
241impl Runtime {
242 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
250 Self::with_config(chunk, RuntimeConfig::default())
251 }
252
253 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
256 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
257 }
258
259 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
260 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
261 }
262
263 pub fn with_attested(
269 bytes: &[u8],
270 expected_digest: [u8; 32],
271 natives: Arc<NativeTable>,
272 config: RuntimeConfig,
273 ) -> Result<Self, SpawnError> {
274 let chunk =
275 crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
276 Self::with_natives_and_config(chunk, natives, config)
277 }
278
279 pub fn with_std_natives_and_config(
282 chunk: Chunk,
283 config: RuntimeConfig,
284 ) -> Result<Self, SpawnError> {
285 Self::with_natives_and_config(
286 chunk,
287 crate::std_native_table_with(Arc::clone(&config.output)),
288 config,
289 )
290 }
291
292 pub fn with_natives_and_config(
302 chunk: Chunk,
303 natives: Arc<NativeTable>,
304 config: RuntimeConfig,
305 ) -> Result<Self, SpawnError> {
306 crate::bytecode::verify_with(
307 &chunk,
308 crate::bytecode::VerifyConfig {
309 trust: config.trust,
310 },
311 )
312 .map_err(SpawnError::VerifyFailed)?;
313 let chunk = Arc::new(chunk);
314 let workers_n = config.workers.max(1);
315
316 let locals: Vec<LocalDeque<Box<Flow>>> =
317 (0..workers_n).map(|_| LocalDeque::new()).collect();
318 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
319
320 #[cfg(feature = "jit")]
321 let jit = if config.jit.enabled {
322 Some(super::jit::new_runtime(
323 chunk.clone(),
324 config.jit.hot_threshold,
325 ))
326 } else {
327 None
328 };
329
330 let shared = Arc::new(Shared {
331 injector: Injector::new(),
332 stealers,
333 directory: Directory::new(),
334 caps: super::capability::CapTable::new(),
335 timer: TimerWheel::new(),
336 notify: (Mutex::new(()), Condvar::new()),
337 metrics: RuntimeMetrics::default(),
338 shutdown: AtomicBool::new(false),
339 quantum: config.quantum,
340 mailbox: config.mailbox,
341 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
342 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
343 quota: config.quota,
344 quotas: super::quota::QuotaTable::new(),
345 monitors: super::monitor::MonitorStore::new(config.max_monitors),
346 links: super::link::LinkStore::new(config.max_links),
347 registry: super::registry::RegistryStore::new(config.max_registry_names),
348 kill_signals: super::finalize::KillSignals::new(),
349 trap_exits: super::finalize::TrapExitFlags::new(),
350 waiting_send_at: super::finalize::WaitingSendIndex::new(),
351 ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
352 host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
353 host_await_bridge: config.host_await.clone(),
354 host_replay: Mutex::new(None),
355 host_await_failures: super::host_await::HostAwaitFailures::new(),
356 distribution: config.distribution.clone(),
357 tables: super::table::FlowTables::new(),
358 flow_supervisors: Mutex::new(Vec::new()),
359 host_next_request_id: AtomicU64::new(1),
360 #[cfg(feature = "jit")]
361 jit,
362 });
363
364 let mut workers = Vec::with_capacity(workers_n);
365 for local in locals {
366 let shared_w = shared.clone();
367 match std::thread::Builder::new()
368 .name("byteflow-worker".into())
369 .spawn(move || worker::run_worker(shared_w, local))
370 {
371 Ok(handle) => workers.push(handle),
372 Err(e) => {
373 abort_startup(&shared, workers, None);
374 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
375 }
376 }
377 }
378
379 let shared_timer = shared.clone();
380 let timer_thread = match std::thread::Builder::new()
381 .name("byteflow-timer".into())
382 .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
383 {
384 Ok(handle) => handle,
385 Err(e) => {
386 abort_startup(&shared, workers, None);
387 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
388 }
389 };
390
391 Ok(Runtime {
392 shared,
393 chunk,
394 natives,
395 workers,
396 timer_thread: Some(timer_thread),
397 trust: config.trust,
398 })
399 }
400
401 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
406 spawn_on(
407 &self.shared,
408 &self.chunk,
409 &self.natives,
410 function,
411 args,
412 RestartPolicy::Never,
413 None,
414 None,
415 None,
416 )
417 }
418
419 pub fn spawner(&self) -> RuntimeSpawner {
423 RuntimeSpawner {
424 shared: self.shared.clone(),
425 chunk: self.chunk.clone(),
426 natives: self.natives.clone(),
427 }
428 }
429
430 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
433 super::supervisor::Supervisor::new(self.spawner())
434 }
435
436 pub fn function_index(&self, name: &str) -> Option<u32> {
440 self.chunk
441 .functions
442 .iter()
443 .position(|f| f.name == name)
444 .map(|i| i as u32)
445 }
446
447 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
448 self.shared.metrics.snapshot()
449 }
450
451 pub fn live_flows(&self) -> usize {
457 self.shared.directory.len()
458 }
459
460 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
462 self.shared.memory.snapshot()
463 }
464
465 pub fn worker_count(&self) -> usize {
466 self.workers.len()
467 }
468
469 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
482 let Some(msg) = message.as_message().cloned() else {
483 return Err(SendError::NotAHop {
484 got: message.type_name(),
485 });
486 };
487 let mailbox = match self.shared.directory.lookup(target) {
488 Ok(Some(m)) => m,
489 Ok(None) => return Err(SendError::NoSuchFlow(target)),
490 Err(e) => {
491 super::error::report_fault(e);
492 return Err(SendError::Unavailable);
493 }
494 };
495 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
496 Ok(m) => Value::Message(m),
497 Err(_) => return Err(SendError::Capability),
498 };
499 match mailbox.push(stamped.clone()) {
500 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
505 Ok(())
506 }
507 Ok(Ok(Delivery::Handoff(flow))) => {
508 let _ = self.shared.ask_waits.remove_asker(flow.id);
509 match flow.last_receive_dest {
510 Some(dest) => {
511 let Some(flow) =
512 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
513 else {
514 return Err(SendError::Unavailable);
515 };
516 enqueue_flow(&self.shared, flow);
517 wake_workers(&self.shared);
518 Ok(())
519 }
520 None => {
521 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
522 "Runtime::send handoff missing dest register",
523 ));
524 finalize_flow(
525 &self.shared,
526 *flow,
527 FlowOutcome::Failed("handoff missing dest register".into()),
528 FlowExitReason::Fault,
529 );
530 Err(SendError::Unavailable)
531 }
532 }
533 }
534 Ok(Err(full)) => {
535 if full.reason() == MailboxFullReason::Closed {
536 return Err(SendError::NoSuchFlow(target));
537 }
538 Err(SendError::MailboxFull {
539 flow: target,
540 reason: full.reason(),
541 })
542 }
543 Err(e) => {
544 super::error::report_fault(e);
545 Err(SendError::Unavailable)
546 }
547 }
548 }
549
550 pub fn deliver_frame(&self, bytes: &[u8]) -> Result<(), super::distribution::RemoteFrameError> {
556 let hop = super::distribution::decode_frame(bytes)?;
557 let cap = match self.shared.registry.whereis(hop.name.as_ref()) {
558 Ok(Some(cap)) => cap,
559 Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
560 Err(err) => {
561 super::error::report_fault(err);
562 return Err(super::distribution::RemoteFrameError::Unavailable);
563 }
564 };
565 let target = match self.shared.caps.lookup(cap) {
566 Ok(Some(entry)) => match entry.target() {
567 Some(id) => id,
568 None => return Err(super::distribution::RemoteFrameError::NoSuchName),
569 },
570 Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
571 Err(err) => {
572 super::error::report_fault(err);
573 return Err(super::distribution::RemoteFrameError::Unavailable);
574 }
575 };
576 let mailbox = match self.shared.directory.lookup(target) {
577 Ok(Some(mailbox)) => mailbox,
578 Ok(None) => return Err(super::distribution::RemoteFrameError::NoSuchName),
579 Err(err) => {
580 super::error::report_fault(err);
581 return Err(super::distribution::RemoteFrameError::Unavailable);
582 }
583 };
584 let stamped = Value::Message(hop.message);
585 match mailbox.push(stamped.clone()) {
586 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
587 Ok(())
588 }
589 Ok(Ok(Delivery::Handoff(flow))) => {
590 let _ = self.shared.ask_waits.remove_asker(flow.id);
591 match flow.last_receive_dest {
592 Some(dest) => {
593 let Some(flow) =
594 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
595 else {
596 return Err(super::distribution::RemoteFrameError::Unavailable);
597 };
598 enqueue_flow(&self.shared, flow);
599 wake_workers(&self.shared);
600 Ok(())
601 }
602 None => {
603 super::finalize::finalize_flow(
604 &self.shared,
605 *flow,
606 FlowOutcome::Failed("handoff missing dest register".into()),
607 FlowExitReason::Fault,
608 );
609 Err(super::distribution::RemoteFrameError::Unavailable)
610 }
611 }
612 }
613 Ok(Err(full)) => Err(super::distribution::RemoteFrameError::Mailbox(
614 full.reason(),
615 )),
616 Err(err) => {
617 super::error::report_fault(err);
618 Err(super::distribution::RemoteFrameError::Unavailable)
619 }
620 }
621 }
622
623 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
624 match self.shared.directory.lookup(id) {
625 Ok(Some(_)) => Ok(()),
626 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
627 Err(e) => Err(self.unavailable(e)),
628 }
629 }
630
631 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
632 super::error::report_fault(err);
633 super::error::LifecycleError::Unavailable
634 }
635
636 pub fn mint_cap(
639 &self,
640 flow: FlowId,
641 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
642 self.require_live(flow)?;
643 self.shared
644 .caps
645 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
646 .map_err(|e| self.unavailable(e))
647 }
648
649 pub fn grant_cap(
651 &self,
652 holder: FlowId,
653 target: FlowId,
654 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
655 self.require_live(holder)?;
656 self.require_live(target)?;
657 self.shared
658 .caps
659 .mint(holder, target, super::capability::CapRights::ADDRESSING)
660 .map_err(|e| self.unavailable(e))
661 }
662
663 pub fn monitor(
667 &self,
668 owner: FlowId,
669 target: FlowId,
670 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
671 if owner == target {
672 return Err(super::error::LifecycleError::SelfRelation);
673 }
674 self.require_live(owner)?;
675 self.require_live(target)?;
676 let mon = self
677 .shared
678 .monitors
679 .create(owner, target)
680 .map_err(|e| self.unavailable(e))??;
681 if self.require_live(target).is_err() {
684 let _ = self.shared.monitors.remove_owned(owner, mon);
685 super::finalize::deliver_down(
686 &self.shared,
687 super::monitor::DownEvent {
688 monitor: mon,
689 owner,
690 target,
691 reason: super::monitor::FlowExitReason::Fault,
692 },
693 );
694 }
695 Ok(mon)
696 }
697
698 pub fn demonitor(
700 &self,
701 owner: FlowId,
702 monitor: super::monitor::MonitorRef,
703 ) -> Result<(), super::error::LifecycleError> {
704 self.require_live(owner)?;
705 match self.shared.monitors.remove_owned(owner, monitor) {
706 Ok(inner) => inner,
707 Err(e) => Err(self.unavailable(e)),
708 }
709 }
710
711 pub fn link(
716 &self,
717 a: FlowId,
718 b: FlowId,
719 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
720 if a == b {
721 return Err(super::error::LifecycleError::SelfRelation);
722 }
723 self.require_live(a)?;
724 self.require_live(b)?;
725 match self.shared.links.link_if_live(a, b, |id| {
726 self.shared.directory.lookup(id).map(|m| m.is_some())
727 }) {
728 Ok(inner) => inner,
729 Err(e) => Err(self.unavailable(e)),
730 }
731 }
732
733 pub fn set_trap_exit(
738 &self,
739 id: FlowId,
740 enabled: bool,
741 ) -> Result<(), super::error::LifecycleError> {
742 self.require_live(id)?;
743 self.shared
744 .trap_exits
745 .set(id, enabled)
746 .map_err(|e| self.unavailable(e))
747 }
748
749 pub fn unlink(
751 &self,
752 owner: FlowId,
753 link: super::link::LinkId,
754 ) -> Result<(), super::error::LifecycleError> {
755 self.require_live(owner)?;
756 match self.shared.links.unlink_owned(owner, link) {
757 Ok(inner) => inner,
758 Err(e) => Err(self.unavailable(e)),
759 }
760 }
761
762 pub fn register_name(
764 &self,
765 name: &str,
766 cap: crate::bytecode::CapId,
767 ) -> Result<(), super::error::LifecycleError> {
768 let entry = match self.shared.caps.lookup(cap) {
769 Ok(Some(e)) => e,
770 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
771 Err(e) => return Err(self.unavailable(e)),
772 };
773 let target = match entry.target() {
774 Some(id) => id,
775 None => return Err(super::error::LifecycleError::InvalidCapability),
776 };
777 self.require_live(target)?;
778 match self
779 .shared
780 .registry
781 .register(super::registry::RegistryName::from(name), cap, target)
782 {
783 Ok(inner) => inner,
784 Err(e) => Err(self.unavailable(e)),
785 }
786 }
787
788 pub fn whereis(
790 &self,
791 name: &str,
792 ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
793 self.shared
794 .registry
795 .whereis(name)
796 .map_err(|e| self.unavailable(e))
797 }
798
799 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
802 self.require_live(id)?;
803 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
804 Ok(())
805 }
806
807 pub fn mint_admin_cap(
809 &self,
810 holder: FlowId,
811 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
812 self.require_live(holder)?;
813 let cap = crate::bytecode::Cap::root(
814 crate::bytecode::CapTarget::Scheduler,
815 CapRights::ADMIN,
816 None,
817 self.shared.caps.scheduler_cell().as_ref(),
818 );
819 self.shared
820 .caps
821 .grant(holder, cap)
822 .map_err(|e| self.unavailable(e))
823 }
824
825 pub fn admin_kill(
827 &self,
828 holder: FlowId,
829 cap: crate::bytecode::CapId,
830 target: FlowId,
831 ) -> Result<(), super::error::LifecycleError> {
832 self.require_admin(holder, cap)?;
833 self.kill(target)
834 }
835
836 pub fn admin_top_up_cpu(
838 &self,
839 holder: FlowId,
840 cap: crate::bytecode::CapId,
841 target: FlowId,
842 extra: i64,
843 ) -> Result<(), super::error::LifecycleError> {
844 self.require_admin(holder, cap)?;
845 let quota = match self.shared.quotas.get(target) {
846 Ok(Some(q)) => q,
847 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
848 Err(e) => return Err(self.unavailable(e)),
849 };
850 quota.top_up_cpu(extra);
851 Ok(())
852 }
853
854 pub fn admin_top_up_mem(
856 &self,
857 holder: FlowId,
858 cap: crate::bytecode::CapId,
859 target: FlowId,
860 extra: usize,
861 ) -> Result<(), super::error::LifecycleError> {
862 self.require_admin(holder, cap)?;
863 let quota = match self.shared.quotas.get(target) {
864 Ok(Some(q)) => q,
865 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
866 Err(e) => return Err(self.unavailable(e)),
867 };
868 quota.top_up_mem(extra);
869 Ok(())
870 }
871
872 pub fn admin_top_up_send(
874 &self,
875 holder: FlowId,
876 cap: crate::bytecode::CapId,
877 target: FlowId,
878 extra: i64,
879 ) -> Result<(), super::error::LifecycleError> {
880 self.require_admin(holder, cap)?;
881 let quota = match self.shared.quotas.get(target) {
882 Ok(Some(q)) => q,
883 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
884 Err(e) => return Err(self.unavailable(e)),
885 };
886 quota.top_up_send(extra);
887 Ok(())
888 }
889
890 fn require_admin(
891 &self,
892 holder: FlowId,
893 cap: crate::bytecode::CapId,
894 ) -> Result<(), super::error::LifecycleError> {
895 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
896 Ok(e) => e,
897 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
898 };
899 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
900 .map_err(|_| super::error::LifecycleError::InvalidCapability)
901 }
902
903 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
905 self.shared
906 .registry
907 .unregister(name)
908 .map_err(|e| self.unavailable(e))
909 }
910
911 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
915 crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
916 .map_err(SpawnError::VerifyFailed)?;
917 let chunk = Arc::new(chunk);
918 self.chunk = chunk.clone();
919 #[cfg(feature = "jit")]
920 if let Some(jit) = &self.shared.jit {
921 jit.reload(chunk);
922 }
923 Ok(())
924 }
925
926 fn request_shutdown(&self) {
930 self.shared.shutdown.store(true, Ordering::Release);
931 finalize_host_awaits(&self.shared);
934 self.shared.timer.shutdown();
935 let (lock, cvar) = &self.shared.notify;
936 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
937 Ok(_g) => cvar.notify_all(),
938 Err(e) => super::error::report_fault(e),
939 }
940 }
941
942 #[cfg(test)]
947 pub(crate) fn enable_host_await_replay(&self) -> Result<(), super::error::RuntimeError> {
948 let mut gate = super::sync_lock::lock(
949 &self.shared.host_replay,
950 "Runtime::enable_host_await_replay",
951 )?;
952 *gate = Some(super::deterministic::HostReplayGate::default());
953 Ok(())
954 }
955
956 #[cfg(test)]
959 pub(crate) fn bind_host_await_replay(
960 &self,
961 ticket: u64,
962 sequence: u64,
963 ) -> Result<(), super::host_await::HostAwaitError> {
964 let ready = {
965 let mut gate =
966 super::sync_lock::lock(&self.shared.host_replay, "Runtime::bind_host_await_replay")
967 .map_err(super::host_await::HostAwaitError::Runtime)?;
968 let Some(replay) = gate.as_mut() else {
969 return Err(super::host_await::HostAwaitError::Replay(
970 "replay gate is not enabled",
971 ));
972 };
973 replay.bind(ticket, sequence).map_err(|err| {
974 super::host_await::HostAwaitError::Replay(super::deterministic::replay_label(err))
975 })?;
976 replay.drain_ready()
977 };
978 super::host_await::deliver_ready(&self.shared, ready)
979 }
980
981 pub fn shutdown(mut self) {
989 self.request_shutdown();
990 for w in self.workers.drain(..) {
991 let _ = w.join();
992 }
993 super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
994 if let Some(t) = self.timer_thread.take() {
995 let _ = t.join();
996 }
997 finalize_stranded(&self.shared);
998 }
999}
1000
1001fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
1002 finalize_flow(
1003 shared,
1004 flow,
1005 FlowOutcome::Failed("runtime shutdown".into()),
1006 FlowExitReason::Shutdown,
1007 );
1008}
1009
1010fn finalize_host_awaits(shared: &Shared) {
1011 match shared.host_awaits.cancel_all() {
1012 Ok(notices) => super::host_await::notify_cancelled(shared, notices),
1013 Err(e) => super::error::report_fault(e),
1014 }
1015}
1016
1017fn finalize_stranded(shared: &Shared) {
1022 finalize_host_awaits(shared);
1023 for flow in shared.timer.drain() {
1024 finalize_shutdown_flow(shared, flow);
1025 }
1026 for _ in 0..8 {
1027 let mut n = 0usize;
1028 for flow in shared.injector.drain() {
1029 finalize_shutdown_flow(shared, *flow);
1030 n += 1;
1031 }
1032 for stealer in &shared.stealers {
1033 for flow in stealer.drain() {
1034 finalize_shutdown_flow(shared, *flow);
1035 n += 1;
1036 }
1037 }
1038 for (_id, mailbox) in shared.directory.snapshot() {
1039 match mailbox.take_parked() {
1040 Ok(Some(flow)) => {
1041 finalize_shutdown_flow(shared, *flow);
1042 n += 1;
1043 }
1044 Ok(None) => {}
1045 Err(e) => super::error::report_fault(e),
1046 }
1047 match mailbox.close() {
1048 Ok(senders) => {
1049 for sender in senders {
1050 if let Err(e) = shared.waiting_send_at.remove(sender.id) {
1051 super::error::report_fault(e);
1052 }
1053 finalize_shutdown_flow(shared, sender);
1054 n += 1;
1055 }
1056 }
1057 Err(e) => super::error::report_fault(e),
1058 }
1059 }
1060 if n == 0 {
1061 break;
1062 }
1063 }
1064}
1065
1066impl Drop for Runtime {
1067 fn drop(&mut self) {
1068 if !self.shared.shutdown.load(Ordering::Acquire) {
1069 self.request_shutdown();
1070 }
1071 super::flow_supervisor::shutdown_all(&self.shared.flow_supervisors);
1072 }
1073}
1074
1075pub fn flow_id_from_u64(raw: u64) -> FlowId {
1079 FlowId(raw)
1080}
1081
1082#[derive(Debug, Clone, PartialEq, Eq)]
1084pub enum SendError {
1085 NoSuchFlow(FlowId),
1086 NotAHop {
1088 got: &'static str,
1089 },
1090 MailboxFull {
1094 flow: FlowId,
1095 reason: MailboxFullReason,
1096 },
1097 Capability,
1099 Unavailable,
1101}
1102
1103impl std::fmt::Display for SendError {
1104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1105 match self {
1106 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
1107 SendError::NotAHop { got } => {
1108 write!(f, "atomic hop requires Value::Message, got {got}")
1109 }
1110 SendError::MailboxFull { flow, reason } => {
1111 write!(f, "mailbox full for {flow} ({reason})")
1112 }
1113 SendError::Capability => {
1114 write!(f, "host send could not reissue a capability in the hop")
1115 }
1116 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
1117 }
1118 }
1119}
1120
1121impl std::error::Error for SendError {}
1122
1123pub(crate) struct BytecodeSpawn<'a> {
1126 pub authority: &'a Cap,
1127 pub cell: &'a crate::bytecode::RevocationCell,
1128 pub quota: &'a super::quota::FlowQuota,
1129 pub requested_rights: CapRights,
1130}
1131
1132pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
1143 if argc != usize::from(arity) {
1144 Err(crate::vm::Fault::BadArity {
1145 passed: argc,
1146 expected: arity,
1147 })
1148 } else {
1149 Ok(())
1150 }
1151}
1152
1153#[allow(clippy::too_many_arguments)]
1154pub(crate) fn spawn_on(
1155 shared: &Arc<Shared>,
1156 chunk: &Arc<Chunk>,
1157 natives: &Arc<NativeTable>,
1158 function: u32,
1159 args: &[Value],
1160 restart_policy: RestartPolicy,
1161 supervisor: Option<SupervisorLink>,
1162 parent: Option<FlowId>,
1163 bytecode: Option<BytecodeSpawn<'_>>,
1164) -> Result<FlowHandle, SpawnError> {
1165 if bytecode.is_some() {
1169 match chunk.function(function) {
1170 Some(def) => {
1171 if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
1172 return Err(fault.into());
1173 }
1174 }
1175 None => {
1176 return Err(SpawnError::BadFunction {
1177 index: function,
1178 table_size: chunk.functions.len() as u32,
1179 });
1180 }
1181 }
1182 }
1183 shared.flow_limit.try_reserve()?;
1184 let id = match super::process::try_next_flow_id() {
1185 Ok(id) => id,
1186 Err(super::error::RuntimeError::FlowIdExhausted) => {
1187 shared.flow_limit.release();
1188 return Err(SpawnError::FlowIdExhausted);
1189 }
1190 Err(_) => {
1191 shared.flow_limit.release();
1192 return Err(SpawnError::Unavailable);
1193 }
1194 };
1195 let cell = match shared.caps.bind_flow(id) {
1196 Ok(c) => c,
1197 Err(_) => {
1198 shared.flow_limit.release();
1199 return Err(SpawnError::Unavailable);
1200 }
1201 };
1202 let authority = match bytecode {
1203 None => Cap::root(
1204 CapTarget::Flow(id.as_u64()),
1205 CapRights::ROOT,
1206 Some(NativeMask::full(natives.len())),
1207 cell.as_ref(),
1208 ),
1209 Some(ctx) => match super::spawn::exec_spawn_authority(
1210 ctx.authority,
1211 ctx.cell,
1212 ctx.quota,
1213 id.as_u64(),
1214 ctx.requested_rights,
1215 None,
1216 cell.as_ref(),
1217 ) {
1218 Ok(cap) => cap,
1219 Err(e) => {
1220 shared.flow_limit.release();
1221 let _ = shared.caps.revoke_flow(id);
1222 return Err(SpawnError::from(e));
1223 }
1224 },
1225 };
1226 let args = match grant_caps_in_args(shared, parent, id, args) {
1227 Ok(a) => a,
1228 Err(e) => {
1229 shared.flow_limit.release();
1230 let _ = shared.caps.revoke_flow(id);
1231 return Err(e);
1232 }
1233 };
1234 let gate = NativeGate::from_authority(
1235 &authority,
1236 Arc::clone(&cell),
1237 shared.caps.native_cell(),
1238 natives.len(),
1239 );
1240 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1241 let mut vm = match Vm::with_native_gate(
1242 chunk.clone(),
1243 natives.clone(),
1244 gate,
1245 function,
1246 args.as_slice(),
1247 ) {
1248 Ok(vm) => vm,
1249 Err(e) => {
1250 shared.flow_limit.release();
1251 let _ = shared.caps.revoke_flow(id);
1252 return Err(e.into());
1253 }
1254 };
1255 vm.set_memory_budget(Arc::clone(&shared.memory));
1256 if let Err(e) = vm.set_quota(Arc::clone("a)) {
1257 shared.flow_limit.release();
1258 let _ = shared.caps.revoke_flow(id);
1259 return Err(e.into());
1260 }
1261 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1262 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1263 super::error::report_fault(e);
1264 shared.flow_limit.release();
1265 let _ = shared.caps.revoke_flow(id);
1266 return Err(SpawnError::Unavailable);
1267 }
1268 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
1269 super::error::report_fault(e);
1270 let _ = shared.directory.unregister(id);
1271 shared.flow_limit.release();
1272 let _ = shared.caps.revoke_flow(id);
1273 return Err(SpawnError::Unavailable);
1274 }
1275 let (tx, rx) = super::oneshot::channel();
1276 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1277 flow.authority = authority;
1278 flow.cell = cell;
1279 flow.quota = quota;
1280 flow.supervisor = supervisor;
1281 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1282 enqueue_flow(shared, flow);
1283 wake_workers(shared);
1284 Ok(FlowHandle { id, receiver: rx })
1285}
1286
1287fn grant_caps_in_args(
1288 shared: &Shared,
1289 parent: Option<FlowId>,
1290 child: FlowId,
1291 args: &[Value],
1292) -> Result<Vec<Value>, SpawnError> {
1293 let mut out = Vec::with_capacity(args.len());
1294 for arg in args {
1295 if !arg.within_nesting_limit() {
1296 return Err(SpawnError::InvalidCapability);
1297 }
1298 let granted = arg.map_caps(
1299 0,
1300 &SpawnError::InvalidCapability,
1301 &mut |id| {
1302 let next = match parent {
1303 None => shared.caps.reissue_for(id, child),
1304 Some(holder) => shared.caps.delegate(id, holder, child),
1305 };
1306 next.map_err(|_| SpawnError::InvalidCapability)
1307 },
1308 &mut |message| {
1309 if let Some(holder) = parent {
1310 if message.sender == 0 {
1311 message.sender = holder.as_u64();
1312 }
1313 }
1314 if message.request_id == 0 {
1315 message.request_id =
1316 super::worker::mint_host_request_id(&shared.host_next_request_id);
1317 }
1318 if !message.reply_cap.is_none() {
1319 message.reply_cap = match parent {
1320 None => shared.caps.reissue_for(message.reply_cap, child),
1321 Some(holder) => shared.caps.delegate(message.reply_cap, holder, child),
1322 }
1323 .map_err(|_| SpawnError::InvalidCapability)?;
1324 }
1325 Ok(())
1326 },
1327 )?;
1328 out.push(granted);
1329 }
1330 Ok(out)
1331}
1332
1333pub(crate) fn enqueue_flow(shared: &Shared, flow: Box<Flow>) {
1338 shared.injector.push(flow);
1339}
1340
1341pub(crate) fn wake_workers(shared: &Shared) {
1342 let (lock, cvar) = &shared.notify;
1343 match super::sync_lock::lock(lock, "wake_workers") {
1344 Ok(_g) => cvar.notify_one(),
1345 Err(e) => super::error::report_fault(e),
1346 }
1347}
1348
1349fn abort_startup(
1353 shared: &Arc<Shared>,
1354 workers: Vec<std::thread::JoinHandle<()>>,
1355 timer: Option<std::thread::JoinHandle<()>>,
1356) {
1357 shared.shutdown.store(true, Ordering::Release);
1358 shared.timer.shutdown();
1359 let (lock, cvar) = &shared.notify;
1360 match super::sync_lock::lock(lock, "abort_startup") {
1361 Ok(_g) => cvar.notify_all(),
1362 Err(e) => super::error::report_fault(e),
1363 }
1364 for w in workers {
1365 let _ = w.join();
1366 }
1367 if let Some(t) = timer {
1368 let _ = t.join();
1369 }
1370}
1371
1372#[derive(Clone)]
1378pub struct RuntimeSpawner {
1379 pub(crate) shared: Arc<Shared>,
1380 pub(crate) chunk: Arc<Chunk>,
1381 pub(crate) natives: Arc<NativeTable>,
1382}
1383
1384impl RuntimeSpawner {
1385 pub fn spawn(
1386 &self,
1387 function: u32,
1388 args: &[Value],
1389 restart_policy: RestartPolicy,
1390 ) -> Result<FlowHandle, SpawnError> {
1391 spawn_on(
1392 &self.shared,
1393 &self.chunk,
1394 &self.natives,
1395 function,
1396 args,
1397 restart_policy,
1398 None,
1399 None,
1400 None,
1401 )
1402 }
1403
1404 pub(crate) fn spawn_linked(
1405 &self,
1406 function: u32,
1407 args: &[Value],
1408 restart_policy: RestartPolicy,
1409 supervisor: SupervisorLink,
1410 ) -> Result<FlowHandle, SpawnError> {
1411 spawn_on(
1412 &self.shared,
1413 &self.chunk,
1414 &self.natives,
1415 function,
1416 args,
1417 restart_policy,
1418 Some(supervisor),
1419 None,
1420 None,
1421 )
1422 }
1423
1424 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1425 self.shared.metrics.snapshot()
1426 }
1427
1428 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1429 super::finalize::request_kill(&self.shared, id, reason);
1430 }
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435 use super::*;
1436 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1437 use crate::scheduler::FlowOutcome;
1438 use std::time::Duration;
1439
1440 #[test]
1441 fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
1442 assert!(super::bytecode_spawn_arity(2, 2).is_ok());
1443 assert!(matches!(
1444 super::bytecode_spawn_arity(2, 1),
1445 Err(crate::vm::Fault::BadArity {
1446 passed: 1,
1447 expected: 2,
1448 })
1449 ));
1450 }
1451
1452 fn add_chunk() -> Chunk {
1453 let mut b = ChunkBuilder::new("test");
1454 b.begin_function("main", 0, 2);
1455 b.emit_load_imm(0, 41);
1456 b.emit_load_imm(1, 1);
1457 b.emit_binop(Opcode::Add, 0, 0, 1);
1458 b.emit_return(0);
1459 b.finish()
1460 }
1461
1462 fn sleep_then_return_chunk(millis: i32) -> Chunk {
1465 let mut b = ChunkBuilder::new("test");
1466 b.begin_function("main", 0, 2);
1467 b.emit_load_imm(0, millis);
1468 b.emit_sleep(0);
1469 b.emit_load_imm(0, 7);
1470 b.emit_return(0);
1471 b.finish()
1472 }
1473
1474 #[test]
1478 fn polling_and_bounded_waits_never_commit_the_host_thread(
1479 ) -> Result<(), Box<dyn std::error::Error>> {
1480 const FLOW_SLEEP: i32 = 150;
1481 let rt = Runtime::with_config(
1482 sleep_then_return_chunk(FLOW_SLEEP),
1483 RuntimeConfig {
1484 workers: 1,
1485 quantum: 1_000,
1486 mailbox: MailboxConfig::DEFAULT,
1487 ..Default::default()
1488 },
1489 )?;
1490 let handle = rt.spawn(0, &[])?;
1491
1492 if let Some(outcome) = handle.try_join() {
1495 rt.shutdown();
1496 return Err(format!("try_join answered too early: {outcome:?}").into());
1497 }
1498
1499 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1502 rt.shutdown();
1503 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1504 }
1505
1506 let outcome = handle.join_timeout(Duration::from_secs(10));
1509 rt.shutdown();
1510 match outcome {
1511 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1512 other => Err(format!("unexpected outcome: {other:?}").into()),
1513 }
1514 }
1515
1516 #[test]
1517 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1518 let rt = Runtime::with_config(
1519 add_chunk(),
1520 RuntimeConfig {
1521 workers: 1,
1522 quantum: 1_000,
1523 mailbox: MailboxConfig::DEFAULT,
1524 ..Default::default()
1525 },
1526 )?;
1527 let outcome = rt.spawn(0, &[])?.join();
1528 rt.shutdown();
1529 match outcome {
1530 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1531 other => Err(format!("unexpected outcome: {other:?}").into()),
1532 }
1533 }
1534
1535 fn receive_forever_chunk() -> Chunk {
1536 let mut b = ChunkBuilder::new("recv");
1537 b.begin_function("main", 0, 1);
1538 b.emit_receive(0);
1539 b.emit_return(0);
1540 b.finish()
1541 }
1542
1543 #[test]
1544 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1545 let rt = Runtime::with_config(
1546 receive_forever_chunk(),
1547 RuntimeConfig {
1548 workers: 1,
1549 quantum: 1_000,
1550 mailbox: MailboxConfig::DEFAULT,
1551 ..Default::default()
1552 },
1553 )?;
1554 let handle = rt.spawn(0, &[])?;
1555 rt.kill(handle.id())?;
1556 let outcome = handle.join();
1557 rt.shutdown();
1558 assert!(
1559 matches!(outcome, FlowOutcome::Failed(_)),
1560 "kill must fail the joiner, got {outcome:?}"
1561 );
1562 Ok(())
1563 }
1564
1565 #[test]
1566 fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
1567 let rt = Runtime::with_config(
1568 receive_forever_chunk(),
1569 RuntimeConfig {
1570 workers: 1,
1571 quantum: 1_000,
1572 mailbox: MailboxConfig::DEFAULT,
1573 ..Default::default()
1574 },
1575 )?;
1576 let handle = rt.spawn(0, &[])?;
1577 std::thread::sleep(Duration::from_millis(30));
1578 rt.shutdown();
1579 match handle.join() {
1580 FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1581 other => Err(format!("expected shutdown finalize, got {other:?}").into()),
1582 }
1583 }
1584
1585 #[test]
1586 fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1587 let rt = Runtime::with_config(
1588 sleep_then_return_chunk(60_000),
1589 RuntimeConfig {
1590 workers: 1,
1591 quantum: 1_000,
1592 mailbox: MailboxConfig::DEFAULT,
1593 ..Default::default()
1594 },
1595 )?;
1596 let handle = rt.spawn(0, &[])?;
1597 std::thread::sleep(Duration::from_millis(30));
1598 rt.shutdown();
1599 match handle.join() {
1600 FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1601 other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
1602 }
1603 }
1604
1605 #[test]
1606 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1607 let rt = Runtime::with_config(
1608 receive_forever_chunk(),
1609 RuntimeConfig {
1610 workers: 1,
1611 quantum: 1_000,
1612 mailbox: MailboxConfig::DEFAULT,
1613 max_flows: 1,
1614 ..Default::default()
1615 },
1616 )?;
1617 let first = rt.spawn(0, &[])?;
1618 let second = rt.spawn(0, &[]);
1619 rt.kill(first.id())?;
1620 let _ = first.join();
1621 let third = rt.spawn(0, &[])?;
1623 rt.kill(third.id())?;
1624 let _ = third.join();
1625 rt.shutdown();
1626 match second {
1627 Err(SpawnError::FlowLimit { current, max }) => {
1628 assert_eq!(current, 1);
1629 assert_eq!(max, 1);
1630 Ok(())
1631 }
1632 other => Err(format!(
1633 "expected FlowLimit, got {}",
1634 match &other {
1635 Ok(_) => "Ok(handle)".into(),
1636 Err(e) => format!("Err({e})"),
1637 }
1638 )
1639 .into()),
1640 }
1641 }
1642
1643 #[test]
1645 fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1646 use crate::bytecode::{Message, Program};
1647 use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1648
1649 let mut program = Program::new("ask-drop-newest");
1650 let busy = program.function("busy", 0, |f| {
1651 let loop_lbl = f.label();
1653 f.bind(loop_lbl);
1654 let ms = f.load_i32(50);
1655 f.sleep(ms);
1656 f.jump(loop_lbl);
1657 });
1658 let asker = program.function("asker", 1, |f| {
1659 let server = f.reg(0);
1660 let z = f.load_i32(0);
1661 let req = f.hop_fresh(1, z);
1662 let reply = f.ask(server, req);
1663 f.return_(reply);
1664 });
1665 let chunk = program.build();
1666
1667 let cap = MailboxCapacity::new(1).ok_or("cap")?;
1668 let rt = Runtime::with_natives_and_config(
1669 chunk,
1670 crate::std_native_table(),
1671 RuntimeConfig {
1672 workers: 2,
1674 quantum: 1_000,
1675 mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1676 ..Default::default()
1677 },
1678 )?;
1679
1680 let server = rt.spawn(busy, &[])?;
1681 rt.send(
1683 server.id(),
1684 Value::Message(Message::request(1, 9, Value::Int(1))),
1685 )?;
1686 let server_cap = rt.mint_cap(server.id())?;
1687 let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1688 let outcome = ask.join_timeout(Duration::from_secs(3));
1689 rt.kill(server.id())?;
1690 let _ = server.join_timeout(Duration::from_millis(500));
1691 rt.shutdown();
1692
1693 match outcome {
1694 Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1695 other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1696 }
1697 }
1698
1699 #[test]
1700 fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1701 use crate::bytecode::Program;
1702
1703 let mut program = Program::new("ask-limit");
1704 let silent = program.function("silent", 0, |f| {
1705 let _req = f.receive();
1707 let loop_lbl = f.label();
1708 f.bind(loop_lbl);
1709 let ms = f.load_i32(50);
1710 f.sleep(ms);
1711 f.jump(loop_lbl);
1712 });
1713 let asker = program.function("asker", 1, |f| {
1714 let server = f.reg(0);
1715 let z = f.load_i32(0);
1716 let req = f.hop_fresh(1, z);
1717 let reply = f.ask(server, req);
1718 f.return_(reply);
1719 });
1720 let chunk = program.build();
1721
1722 let rt = Runtime::with_natives_and_config(
1723 chunk,
1724 crate::std_native_table(),
1725 RuntimeConfig {
1726 workers: 2,
1727 quantum: 1_000,
1728 mailbox: MailboxConfig::DEFAULT,
1729 max_ask_waits: 1,
1730 ..Default::default()
1731 },
1732 )?;
1733
1734 let server = rt.spawn(silent, &[])?;
1735 let server_cap = rt.mint_cap(server.id())?;
1736 let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1737 std::thread::sleep(Duration::from_millis(30));
1739 let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1740 let second_out = second.join_timeout(Duration::from_secs(2));
1741 rt.kill(server.id())?;
1742 let _ = first.join_timeout(Duration::from_millis(500));
1743 let _ = server.join_timeout(Duration::from_millis(500));
1744 rt.shutdown();
1745
1746 match second_out {
1747 Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1748 other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1749 }
1750 }
1751
1752 #[cfg(feature = "jit")]
1755 #[test]
1756 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1757 use crate::JitConfig;
1758
1759 let rt = Runtime::with_config(
1760 add_chunk(),
1761 RuntimeConfig {
1762 workers: 1,
1763 quantum: 1_000,
1764 mailbox: MailboxConfig::DEFAULT,
1765 jit: JitConfig {
1766 enabled: true,
1767 hot_threshold: 1,
1768 },
1769 ..Default::default()
1770 },
1771 )?;
1772 let outcome = rt.spawn(0, &[])?.join();
1773 rt.shutdown();
1774 match outcome {
1775 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1776 other => Err(format!("unexpected outcome: {other:?}").into()),
1777 }
1778 }
1779
1780 #[test]
1781 fn sandbox_enables_process_wide_relation_caps() {
1782 let config = RuntimeConfig::sandbox();
1783 assert_eq!(config.max_flows, 256);
1784 assert_eq!(config.max_ask_waits, 128);
1785 assert_eq!(config.max_host_awaits, 128);
1786 assert_eq!(config.max_links, 1024);
1787 assert_eq!(config.max_monitors, 1024);
1788 assert_eq!(config.max_registry_names, 256);
1789 assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1790 }
1791
1792 #[test]
1793 fn default_remains_unlimited_for_relation_caps() {
1794 let config = RuntimeConfig::default();
1795 assert_eq!(config.max_links, 0);
1796 assert_eq!(config.max_monitors, 0);
1797 assert_eq!(config.max_registry_names, 0);
1798 }
1799
1800 #[test]
1801 fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1802 use crate::bytecode::encode;
1803 use crate::{fingerprint_bf, AttestError};
1804
1805 let bytes = encode(&add_chunk());
1806 let mut bad = fingerprint_bf(&bytes);
1807 bad[0] ^= 0xff;
1808 match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1809 Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1810 Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1811 Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1812 }
1813 }
1814
1815 #[test]
1816 fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1817 use crate::bytecode::encode;
1818 use crate::fingerprint_bf;
1819
1820 let chunk = add_chunk();
1821 let bytes = encode(&chunk);
1822 let digest = fingerprint_bf(&bytes);
1823 let rt = Runtime::with_attested(
1824 &bytes,
1825 digest,
1826 NativeTable::empty(),
1827 RuntimeConfig {
1828 workers: 1,
1829 quantum: 1_000,
1830 mailbox: MailboxConfig::DEFAULT,
1831 ..Default::default()
1832 },
1833 )?;
1834 let outcome = rt.spawn(0, &[])?.join();
1835 rt.shutdown();
1836 match outcome {
1837 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1838 other => Err(format!("expected 42, got {other:?}").into()),
1839 }
1840 }
1841
1842 #[test]
1843 fn poisoned_injector_still_runs_the_flow() -> Result<(), Box<dyn std::error::Error>> {
1844 let rt = Runtime::new(add_chunk())?;
1845 rt.shared.injector.poison_for_test();
1846 let outcome = rt.spawn(0, &[])?.join_timeout(Duration::from_secs(2));
1847 rt.shutdown();
1848 match outcome {
1849 Some(FlowOutcome::Completed(Value::Int(42))) => Ok(()),
1850 other => Err(format!("expected 42 after a poisoned injector, got {other:?}").into()),
1851 }
1852 }
1853}