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_runtime_bytes: usize,
60 pub trust: crate::bytecode::TrustLevel,
63 pub output: Arc<dyn crate::OutputSink>,
66 pub quota: super::quota::QuotaConfig,
68 #[cfg(feature = "jit")]
70 pub jit: JitConfig,
71}
72
73#[cfg(feature = "jit")]
75#[derive(Clone, Debug)]
76pub struct JitConfig {
77 pub enabled: bool,
79 pub hot_threshold: u32,
81}
82
83#[cfg(feature = "jit")]
84impl Default for JitConfig {
85 fn default() -> Self {
86 JitConfig {
87 enabled: false,
88 hot_threshold: crate::jit::HOT_THRESHOLD,
89 }
90 }
91}
92
93fn default_worker_count() -> usize {
95 match std::thread::available_parallelism() {
96 Ok(n) => n.get().max(1),
97 Err(_) => 1,
98 }
99}
100
101impl Default for RuntimeConfig {
102 fn default() -> Self {
103 RuntimeConfig {
104 workers: default_worker_count(),
105 quantum: DEFAULT_QUANTUM,
106 mailbox: MailboxConfig::DEFAULT,
107 max_flows: 0,
108 max_ask_waits: 0,
109 max_runtime_bytes: 256 * 1024 * 1024,
110 trust: crate::bytecode::TrustLevel::Untrusted,
111 output: Arc::new(crate::output::NullSink),
112 quota: super::quota::QuotaConfig::default(),
113 #[cfg(feature = "jit")]
114 jit: JitConfig::default(),
115 }
116 }
117}
118
119impl RuntimeConfig {
120 pub fn sandbox() -> Self {
124 RuntimeConfig {
125 quota: super::quota::QuotaConfig::sandbox(),
126 max_flows: 256,
127 max_ask_waits: 128,
128 max_runtime_bytes: 64 * 1024 * 1024,
129 ..Default::default()
130 }
131 }
132}
133
134pub struct Shared {
141 pub(crate) injector: Injector<Box<Flow>>,
142 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
143 pub(crate) directory: Directory,
145 pub(crate) caps: super::capability::CapTable,
147 pub(crate) timer: Arc<TimerWheel>,
148 pub(crate) notify: (Mutex<()>, Condvar),
149 pub(crate) metrics: RuntimeMetrics,
150 pub(crate) shutdown: AtomicBool,
151 pub(crate) quantum: u32,
152 pub(crate) mailbox: MailboxConfig,
153 pub(crate) flow_limit: super::flow_limit::FlowLimit,
155 pub(crate) memory: Arc<crate::MemoryBudget>,
156 pub(crate) quota: super::quota::QuotaConfig,
157 pub(crate) quotas: super::quota::QuotaTable,
158 pub(crate) monitors: super::monitor::MonitorStore,
159 pub(crate) links: super::link::LinkStore,
160 pub(crate) registry: super::registry::RegistryStore,
161 pub(crate) kill_signals: super::finalize::KillSignals,
162 pub(crate) trap_exits: super::finalize::TrapExitFlags,
163 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
164 pub(crate) ask_waits: super::finalize::AskWaitIndex,
165 pub(crate) host_next_request_id: AtomicU64,
168 #[cfg(feature = "jit")]
170 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
171}
172
173pub struct Runtime {
184 shared: Arc<Shared>,
185 chunk: Arc<Chunk>,
186 natives: Arc<NativeTable>,
187 workers: Vec<JoinHandle<()>>,
188 timer_thread: Option<JoinHandle<()>>,
189 trust: crate::bytecode::TrustLevel,
190}
191
192impl Runtime {
193 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
201 Self::with_config(chunk, RuntimeConfig::default())
202 }
203
204 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
207 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
208 }
209
210 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
211 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
212 }
213
214 pub fn with_std_natives_and_config(
217 chunk: Chunk,
218 config: RuntimeConfig,
219 ) -> Result<Self, SpawnError> {
220 Self::with_natives_and_config(
221 chunk,
222 crate::std_native_table_with(Arc::clone(&config.output)),
223 config,
224 )
225 }
226
227 pub fn with_natives_and_config(
235 chunk: Chunk,
236 natives: Arc<NativeTable>,
237 config: RuntimeConfig,
238 ) -> Result<Self, SpawnError> {
239 crate::bytecode::verify_with(
240 &chunk,
241 crate::bytecode::VerifyConfig {
242 trust: config.trust,
243 },
244 )
245 .map_err(SpawnError::VerifyFailed)?;
246 let chunk = Arc::new(chunk);
247 let workers_n = config.workers.max(1);
248
249 let locals: Vec<LocalDeque<Box<Flow>>> =
250 (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
251 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
252
253 #[cfg(feature = "jit")]
254 let jit = if config.jit.enabled {
255 Some(super::jit::new_runtime(
256 chunk.clone(),
257 config.jit.hot_threshold,
258 ))
259 } else {
260 None
261 };
262
263 let shared = Arc::new(Shared {
264 injector: Injector::new(),
265 stealers,
266 directory: Directory::new(),
267 caps: super::capability::CapTable::new(),
268 timer: TimerWheel::new(),
269 notify: (Mutex::new(()), Condvar::new()),
270 metrics: RuntimeMetrics::default(),
271 shutdown: AtomicBool::new(false),
272 quantum: config.quantum,
273 mailbox: config.mailbox,
274 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
275 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
276 quota: config.quota,
277 quotas: super::quota::QuotaTable::new(),
278 monitors: super::monitor::MonitorStore::new(),
279 links: super::link::LinkStore::new(),
280 registry: super::registry::RegistryStore::new(),
281 kill_signals: super::finalize::KillSignals::new(),
282 trap_exits: super::finalize::TrapExitFlags::new(),
283 waiting_send_at: super::finalize::WaitingSendIndex::new(),
284 ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
285 host_next_request_id: AtomicU64::new(1),
286 #[cfg(feature = "jit")]
287 jit,
288 });
289
290 let mut workers = Vec::with_capacity(workers_n);
291 for local in locals {
292 let shared = shared.clone();
293 let handle = std::thread::Builder::new()
294 .name("byteflow-worker".into())
295 .spawn(move || worker::run_worker(shared, local))
296 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
297 workers.push(handle);
298 }
299
300 let shared_timer = shared.clone();
301 let timer_thread = std::thread::Builder::new()
302 .name("byteflow-timer".into())
303 .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
304 .map_err(|e| SpawnError::ThreadSpawnFailed(e.to_string()))?;
305
306 Ok(Runtime {
307 shared,
308 chunk,
309 natives,
310 workers,
311 timer_thread: Some(timer_thread),
312 trust: config.trust,
313 })
314 }
315
316 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
321 spawn_on(
322 &self.shared,
323 &self.chunk,
324 &self.natives,
325 function,
326 args,
327 RestartPolicy::Never,
328 None,
329 None,
330 None,
331 )
332 }
333
334 pub fn spawner(&self) -> RuntimeSpawner {
338 RuntimeSpawner {
339 shared: self.shared.clone(),
340 chunk: self.chunk.clone(),
341 natives: self.natives.clone(),
342 }
343 }
344
345 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
348 super::supervisor::Supervisor::new(self.spawner())
349 }
350
351 pub fn function_index(&self, name: &str) -> Option<u32> {
355 self.chunk
356 .functions
357 .iter()
358 .position(|f| f.name == name)
359 .map(|i| i as u32)
360 }
361
362 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
363 self.shared.metrics.snapshot()
364 }
365
366 pub fn live_flows(&self) -> usize {
372 self.shared.directory.len()
373 }
374
375 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
377 self.shared.memory.snapshot()
378 }
379
380 pub fn worker_count(&self) -> usize {
381 self.workers.len()
382 }
383
384 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
397 let Some(msg) = message.as_message().cloned() else {
398 return Err(SendError::NotAHop {
399 got: message.type_name(),
400 });
401 };
402 let mailbox = match self.shared.directory.lookup(target) {
403 Ok(Some(m)) => m,
404 Ok(None) => return Err(SendError::NoSuchFlow(target)),
405 Err(e) => {
406 super::error::report_fault(e);
407 return Err(SendError::Unavailable);
408 }
409 };
410 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
411 Ok(m) => Value::Message(m),
412 Err(_) => return Err(SendError::Capability),
413 };
414 match mailbox.push(stamped.clone()) {
415 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
420 Ok(())
421 }
422 Ok(Ok(Delivery::Handoff(flow))) => {
423 let _ = self.shared.ask_waits.remove_asker(flow.id);
424 match flow.last_receive_dest {
425 Some(dest) => {
426 let Some(flow) =
427 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
428 else {
429 return Err(SendError::Unavailable);
430 };
431 self.shared.injector.push(flow);
432 wake_workers(&self.shared);
433 Ok(())
434 }
435 None => {
436 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
437 "Runtime::send handoff missing dest register",
438 ));
439 finalize_flow(
440 &self.shared,
441 *flow,
442 FlowOutcome::Failed("handoff missing dest register".into()),
443 FlowExitReason::Fault,
444 );
445 Err(SendError::Unavailable)
446 }
447 }
448 }
449 Ok(Err(full)) => {
450 if full.reason() == MailboxFullReason::Closed {
451 return Err(SendError::NoSuchFlow(target));
452 }
453 Err(SendError::MailboxFull {
454 flow: target,
455 reason: full.reason(),
456 })
457 }
458 Err(e) => {
459 super::error::report_fault(e);
460 Err(SendError::Unavailable)
461 }
462 }
463 }
464
465 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
466 match self.shared.directory.lookup(id) {
467 Ok(Some(_)) => Ok(()),
468 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
469 Err(e) => Err(self.unavailable(e)),
470 }
471 }
472
473 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
474 super::error::report_fault(err);
475 super::error::LifecycleError::Unavailable
476 }
477
478 pub fn mint_cap(
481 &self,
482 flow: FlowId,
483 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
484 self.require_live(flow)?;
485 self.shared
486 .caps
487 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
488 .map_err(|e| self.unavailable(e))
489 }
490
491 pub fn grant_cap(
493 &self,
494 holder: FlowId,
495 target: FlowId,
496 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
497 self.require_live(holder)?;
498 self.require_live(target)?;
499 self.shared
500 .caps
501 .mint(holder, target, super::capability::CapRights::ADDRESSING)
502 .map_err(|e| self.unavailable(e))
503 }
504
505 pub fn monitor(
509 &self,
510 owner: FlowId,
511 target: FlowId,
512 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
513 if owner == target {
514 return Err(super::error::LifecycleError::SelfRelation);
515 }
516 self.require_live(owner)?;
517 self.require_live(target)?;
518 let mon = self
519 .shared
520 .monitors
521 .create(owner, target)
522 .map_err(|e| self.unavailable(e))?;
523 if self.require_live(target).is_err() {
526 let _ = self.shared.monitors.remove_owned(owner, mon);
527 super::finalize::deliver_down(
528 &self.shared,
529 super::monitor::DownEvent {
530 monitor: mon,
531 owner,
532 target,
533 reason: super::monitor::FlowExitReason::Fault,
534 },
535 );
536 }
537 Ok(mon)
538 }
539
540 pub fn demonitor(
542 &self,
543 owner: FlowId,
544 monitor: super::monitor::MonitorRef,
545 ) -> Result<(), super::error::LifecycleError> {
546 self.require_live(owner)?;
547 match self.shared.monitors.remove_owned(owner, monitor) {
548 Ok(inner) => inner,
549 Err(e) => Err(self.unavailable(e)),
550 }
551 }
552
553 pub fn link(
558 &self,
559 a: FlowId,
560 b: FlowId,
561 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
562 if a == b {
563 return Err(super::error::LifecycleError::SelfRelation);
564 }
565 self.require_live(a)?;
566 self.require_live(b)?;
567 match self.shared.links.link(a, b) {
568 Ok(inner) => inner,
569 Err(e) => Err(self.unavailable(e)),
570 }
571 }
572
573 pub fn set_trap_exit(
578 &self,
579 id: FlowId,
580 enabled: bool,
581 ) -> Result<(), super::error::LifecycleError> {
582 self.require_live(id)?;
583 self.shared
584 .trap_exits
585 .set(id, enabled)
586 .map_err(|e| self.unavailable(e))
587 }
588
589 pub fn unlink(
591 &self,
592 owner: FlowId,
593 link: super::link::LinkId,
594 ) -> Result<(), super::error::LifecycleError> {
595 self.require_live(owner)?;
596 match self.shared.links.unlink_owned(owner, link) {
597 Ok(inner) => inner,
598 Err(e) => Err(self.unavailable(e)),
599 }
600 }
601
602 pub fn register_name(
604 &self,
605 name: &str,
606 cap: crate::bytecode::CapId,
607 ) -> Result<(), super::error::LifecycleError> {
608 let entry = match self.shared.caps.lookup(cap) {
609 Ok(Some(e)) => e,
610 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
611 Err(e) => return Err(self.unavailable(e)),
612 };
613 let target = match entry.target() {
614 Some(id) => id,
615 None => return Err(super::error::LifecycleError::InvalidCapability),
616 };
617 self.require_live(target)?;
618 match self
619 .shared
620 .registry
621 .register(super::registry::RegistryName::from(name), cap, target)
622 {
623 Ok(inner) => inner,
624 Err(e) => Err(self.unavailable(e)),
625 }
626 }
627
628 pub fn whereis(
630 &self,
631 name: &str,
632 ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
633 self.shared
634 .registry
635 .whereis(name)
636 .map_err(|e| self.unavailable(e))
637 }
638
639 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
642 self.require_live(id)?;
643 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
644 Ok(())
645 }
646
647 pub fn mint_admin_cap(
649 &self,
650 holder: FlowId,
651 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
652 self.require_live(holder)?;
653 let cap = crate::bytecode::Cap::root(
654 crate::bytecode::CapTarget::Scheduler,
655 CapRights::ADMIN,
656 None,
657 self.shared.caps.scheduler_cell().as_ref(),
658 );
659 self.shared
660 .caps
661 .grant(holder, cap)
662 .map_err(|e| self.unavailable(e))
663 }
664
665 pub fn admin_kill(
667 &self,
668 holder: FlowId,
669 cap: crate::bytecode::CapId,
670 target: FlowId,
671 ) -> Result<(), super::error::LifecycleError> {
672 self.require_admin(holder, cap)?;
673 self.kill(target)
674 }
675
676 pub fn admin_top_up_cpu(
678 &self,
679 holder: FlowId,
680 cap: crate::bytecode::CapId,
681 target: FlowId,
682 extra: i64,
683 ) -> Result<(), super::error::LifecycleError> {
684 self.require_admin(holder, cap)?;
685 let quota = match self.shared.quotas.get(target) {
686 Ok(Some(q)) => q,
687 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
688 Err(e) => return Err(self.unavailable(e)),
689 };
690 quota.top_up_cpu(extra);
691 Ok(())
692 }
693
694 pub fn admin_top_up_mem(
696 &self,
697 holder: FlowId,
698 cap: crate::bytecode::CapId,
699 target: FlowId,
700 extra: usize,
701 ) -> Result<(), super::error::LifecycleError> {
702 self.require_admin(holder, cap)?;
703 let quota = match self.shared.quotas.get(target) {
704 Ok(Some(q)) => q,
705 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
706 Err(e) => return Err(self.unavailable(e)),
707 };
708 quota.top_up_mem(extra);
709 Ok(())
710 }
711
712 pub fn admin_top_up_send(
714 &self,
715 holder: FlowId,
716 cap: crate::bytecode::CapId,
717 target: FlowId,
718 extra: i64,
719 ) -> Result<(), super::error::LifecycleError> {
720 self.require_admin(holder, cap)?;
721 let quota = match self.shared.quotas.get(target) {
722 Ok(Some(q)) => q,
723 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
724 Err(e) => return Err(self.unavailable(e)),
725 };
726 quota.top_up_send(extra);
727 Ok(())
728 }
729
730 fn require_admin(
731 &self,
732 holder: FlowId,
733 cap: crate::bytecode::CapId,
734 ) -> Result<(), super::error::LifecycleError> {
735 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
736 Ok(e) => e,
737 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
738 };
739 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
740 .map_err(|_| super::error::LifecycleError::InvalidCapability)
741 }
742
743 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
745 self.shared
746 .registry
747 .unregister(name)
748 .map_err(|e| self.unavailable(e))
749 }
750
751 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
755 crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
756 .map_err(SpawnError::VerifyFailed)?;
757 let chunk = Arc::new(chunk);
758 self.chunk = chunk.clone();
759 #[cfg(feature = "jit")]
760 if let Some(jit) = &self.shared.jit {
761 jit.reload(chunk);
762 }
763 Ok(())
764 }
765
766 fn request_shutdown(&self) {
769 self.shared.shutdown.store(true, Ordering::Release);
770 self.shared.timer.shutdown();
771 let (lock, cvar) = &self.shared.notify;
772 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
773 Ok(_g) => cvar.notify_all(),
774 Err(e) => super::error::report_fault(e),
775 }
776 }
777
778 pub fn shutdown(mut self) {
785 self.request_shutdown();
786 for w in self.workers.drain(..) {
787 let _ = w.join();
788 }
789 if let Some(t) = self.timer_thread.take() {
790 let _ = t.join();
791 }
792 }
793}
794
795impl Drop for Runtime {
796 fn drop(&mut self) {
797 if !self.shared.shutdown.load(Ordering::Acquire) {
798 self.request_shutdown();
799 }
800 }
801}
802
803pub fn flow_id_from_u64(raw: u64) -> FlowId {
807 FlowId(raw)
808}
809
810#[derive(Debug, Clone, PartialEq, Eq)]
812pub enum SendError {
813 NoSuchFlow(FlowId),
814 NotAHop {
816 got: &'static str,
817 },
818 MailboxFull {
822 flow: FlowId,
823 reason: MailboxFullReason,
824 },
825 Capability,
827 Unavailable,
829}
830
831impl std::fmt::Display for SendError {
832 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833 match self {
834 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
835 SendError::NotAHop { got } => {
836 write!(f, "atomic hop requires Value::Message, got {got}")
837 }
838 SendError::MailboxFull { flow, reason } => {
839 write!(f, "mailbox full for {flow} ({reason})")
840 }
841 SendError::Capability => {
842 write!(f, "host send could not reissue a capability in the hop")
843 }
844 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
845 }
846 }
847}
848
849impl std::error::Error for SendError {}
850
851pub(crate) struct BytecodeSpawn<'a> {
854 pub authority: &'a Cap,
855 pub cell: &'a crate::bytecode::RevocationCell,
856 pub quota: &'a super::quota::FlowQuota,
857 pub requested_rights: CapRights,
858}
859
860#[allow(clippy::too_many_arguments)]
869pub(crate) fn spawn_on(
870 shared: &Arc<Shared>,
871 chunk: &Arc<Chunk>,
872 natives: &Arc<NativeTable>,
873 function: u32,
874 args: &[Value],
875 restart_policy: RestartPolicy,
876 supervisor: Option<SupervisorLink>,
877 parent: Option<FlowId>,
878 bytecode: Option<BytecodeSpawn<'_>>,
879) -> Result<FlowHandle, SpawnError> {
880 shared.flow_limit.try_reserve()?;
881 let id = match super::process::try_next_flow_id() {
882 Ok(id) => id,
883 Err(super::error::RuntimeError::FlowIdExhausted) => {
884 shared.flow_limit.release();
885 return Err(SpawnError::FlowIdExhausted);
886 }
887 Err(_) => {
888 shared.flow_limit.release();
889 return Err(SpawnError::Unavailable);
890 }
891 };
892 let cell = match shared.caps.bind_flow(id) {
893 Ok(c) => c,
894 Err(_) => {
895 shared.flow_limit.release();
896 return Err(SpawnError::Unavailable);
897 }
898 };
899 let authority = match bytecode {
900 None => Cap::root(
901 CapTarget::Flow(id.as_u64()),
902 CapRights::ROOT,
903 Some(NativeMask::full(natives.len())),
904 cell.as_ref(),
905 ),
906 Some(ctx) => match super::spawn::exec_spawn_authority(
907 ctx.authority,
908 ctx.cell,
909 ctx.quota,
910 id.as_u64(),
911 ctx.requested_rights,
912 None,
913 cell.as_ref(),
914 ) {
915 Ok(cap) => cap,
916 Err(e) => {
917 shared.flow_limit.release();
918 let _ = shared.caps.revoke_flow(id);
919 return Err(SpawnError::from(e));
920 }
921 },
922 };
923 let args = match grant_caps_in_args(shared, parent, id, args) {
924 Ok(a) => a,
925 Err(e) => {
926 shared.flow_limit.release();
927 let _ = shared.caps.revoke_flow(id);
928 return Err(e);
929 }
930 };
931 let gate = NativeGate::from_authority(
932 &authority,
933 Arc::clone(&cell),
934 shared.caps.native_cell(),
935 natives.len(),
936 );
937 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
938 let mut vm = match Vm::with_native_gate(
939 chunk.clone(),
940 natives.clone(),
941 gate,
942 function,
943 args.as_slice(),
944 ) {
945 Ok(vm) => vm,
946 Err(e) => {
947 shared.flow_limit.release();
948 let _ = shared.caps.revoke_flow(id);
949 return Err(e.into());
950 }
951 };
952 vm.set_memory_budget(Arc::clone(&shared.memory));
953 if let Err(e) = vm.set_quota(Arc::clone("a)) {
954 shared.flow_limit.release();
955 let _ = shared.caps.revoke_flow(id);
956 return Err(e.into());
957 }
958 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
959 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
960 super::error::report_fault(e);
961 shared.flow_limit.release();
962 let _ = shared.caps.revoke_flow(id);
963 return Err(SpawnError::Unavailable);
964 }
965 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
966 super::error::report_fault(e);
967 let _ = shared.directory.unregister(id);
968 shared.flow_limit.release();
969 let _ = shared.caps.revoke_flow(id);
970 return Err(SpawnError::Unavailable);
971 }
972 let (tx, rx) = super::oneshot::channel();
973 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
974 flow.authority = authority;
975 flow.cell = cell;
976 flow.quota = quota;
977 flow.supervisor = supervisor;
978 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
979 shared.injector.push(flow);
980 wake_workers(shared);
981 Ok(FlowHandle { id, receiver: rx })
982}
983
984fn grant_caps_in_args(
985 shared: &Shared,
986 parent: Option<FlowId>,
987 child: FlowId,
988 args: &[Value],
989) -> Result<Vec<Value>, SpawnError> {
990 let mut out = Vec::with_capacity(args.len());
991 for arg in args {
992 match arg {
993 Value::Cap(id) => {
994 let granted = match parent {
995 None => shared.caps.reissue_for(*id, child),
996 Some(p) => shared.caps.delegate(*id, p, child),
997 };
998 match granted {
999 Ok(cap) => out.push(Value::Cap(cap)),
1000 Err(_) => return Err(SpawnError::InvalidCapability),
1001 }
1002 }
1003 other => out.push(other.clone()),
1004 }
1005 }
1006 Ok(out)
1007}
1008
1009pub(crate) fn wake_workers(shared: &Shared) {
1010 let (lock, cvar) = &shared.notify;
1011 match super::sync_lock::lock(lock, "wake_workers") {
1012 Ok(_g) => cvar.notify_one(),
1013 Err(e) => super::error::report_fault(e),
1014 }
1015}
1016
1017#[derive(Clone)]
1023pub struct RuntimeSpawner {
1024 pub(crate) shared: Arc<Shared>,
1025 pub(crate) chunk: Arc<Chunk>,
1026 pub(crate) natives: Arc<NativeTable>,
1027}
1028
1029impl RuntimeSpawner {
1030 pub fn spawn(
1031 &self,
1032 function: u32,
1033 args: &[Value],
1034 restart_policy: RestartPolicy,
1035 ) -> Result<FlowHandle, SpawnError> {
1036 spawn_on(
1037 &self.shared,
1038 &self.chunk,
1039 &self.natives,
1040 function,
1041 args,
1042 restart_policy,
1043 None,
1044 None,
1045 None,
1046 )
1047 }
1048
1049 pub(crate) fn spawn_linked(
1050 &self,
1051 function: u32,
1052 args: &[Value],
1053 restart_policy: RestartPolicy,
1054 supervisor: SupervisorLink,
1055 ) -> Result<FlowHandle, SpawnError> {
1056 spawn_on(
1057 &self.shared,
1058 &self.chunk,
1059 &self.natives,
1060 function,
1061 args,
1062 restart_policy,
1063 Some(supervisor),
1064 None,
1065 None,
1066 )
1067 }
1068
1069 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1070 self.shared.metrics.snapshot()
1071 }
1072
1073 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1074 super::finalize::request_kill(&self.shared, id, reason);
1075 }
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080 use super::*;
1081 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1082 use crate::scheduler::FlowOutcome;
1083 use std::time::Duration;
1084
1085 fn add_chunk() -> Chunk {
1086 let mut b = ChunkBuilder::new("test");
1087 b.begin_function("main", 0, 2);
1088 b.emit_load_imm(0, 41);
1089 b.emit_load_imm(1, 1);
1090 b.emit_binop(Opcode::Add, 0, 0, 1);
1091 b.emit_return(0);
1092 b.finish()
1093 }
1094
1095 fn sleep_then_return_chunk(millis: i32) -> Chunk {
1098 let mut b = ChunkBuilder::new("test");
1099 b.begin_function("main", 0, 2);
1100 b.emit_load_imm(0, millis);
1101 b.emit_sleep(0);
1102 b.emit_load_imm(0, 7);
1103 b.emit_return(0);
1104 b.finish()
1105 }
1106
1107 #[test]
1111 fn polling_and_bounded_waits_never_commit_the_host_thread(
1112 ) -> Result<(), Box<dyn std::error::Error>> {
1113 const FLOW_SLEEP: i32 = 150;
1114 let rt = Runtime::with_config(
1115 sleep_then_return_chunk(FLOW_SLEEP),
1116 RuntimeConfig {
1117 workers: 1,
1118 quantum: 1_000,
1119 mailbox: MailboxConfig::DEFAULT,
1120 ..Default::default()
1121 },
1122 )?;
1123 let handle = rt.spawn(0, &[])?;
1124
1125 if let Some(outcome) = handle.try_join() {
1128 rt.shutdown();
1129 return Err(format!("try_join answered too early: {outcome:?}").into());
1130 }
1131
1132 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1135 rt.shutdown();
1136 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1137 }
1138
1139 let outcome = handle.join_timeout(Duration::from_secs(10));
1142 rt.shutdown();
1143 match outcome {
1144 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1145 other => Err(format!("unexpected outcome: {other:?}").into()),
1146 }
1147 }
1148
1149 #[test]
1150 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1151 let rt = Runtime::with_config(
1152 add_chunk(),
1153 RuntimeConfig {
1154 workers: 1,
1155 quantum: 1_000,
1156 mailbox: MailboxConfig::DEFAULT,
1157 ..Default::default()
1158 },
1159 )?;
1160 let outcome = rt.spawn(0, &[])?.join();
1161 rt.shutdown();
1162 match outcome {
1163 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1164 other => Err(format!("unexpected outcome: {other:?}").into()),
1165 }
1166 }
1167
1168 fn receive_forever_chunk() -> Chunk {
1169 let mut b = ChunkBuilder::new("recv");
1170 b.begin_function("main", 0, 1);
1171 b.emit_receive(0);
1172 b.emit_return(0);
1173 b.finish()
1174 }
1175
1176 #[test]
1177 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1178 let rt = Runtime::with_config(
1179 receive_forever_chunk(),
1180 RuntimeConfig {
1181 workers: 1,
1182 quantum: 1_000,
1183 mailbox: MailboxConfig::DEFAULT,
1184 ..Default::default()
1185 },
1186 )?;
1187 let handle = rt.spawn(0, &[])?;
1188 rt.kill(handle.id())?;
1189 let outcome = handle.join();
1190 rt.shutdown();
1191 assert!(
1192 matches!(outcome, FlowOutcome::Failed(_)),
1193 "kill must fail the joiner, got {outcome:?}"
1194 );
1195 Ok(())
1196 }
1197
1198 #[test]
1199 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1200 let rt = Runtime::with_config(
1201 receive_forever_chunk(),
1202 RuntimeConfig {
1203 workers: 1,
1204 quantum: 1_000,
1205 mailbox: MailboxConfig::DEFAULT,
1206 max_flows: 1,
1207 ..Default::default()
1208 },
1209 )?;
1210 let first = rt.spawn(0, &[])?;
1211 let second = rt.spawn(0, &[]);
1212 rt.kill(first.id())?;
1213 let _ = first.join();
1214 let third = rt.spawn(0, &[])?;
1216 rt.kill(third.id())?;
1217 let _ = third.join();
1218 rt.shutdown();
1219 match second {
1220 Err(SpawnError::FlowLimit { current, max }) => {
1221 assert_eq!(current, 1);
1222 assert_eq!(max, 1);
1223 Ok(())
1224 }
1225 other => Err(format!(
1226 "expected FlowLimit, got {}",
1227 match &other {
1228 Ok(_) => "Ok(handle)".into(),
1229 Err(e) => format!("Err({e})"),
1230 }
1231 )
1232 .into()),
1233 }
1234 }
1235
1236 #[test]
1238 fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1239 use crate::bytecode::{Message, Program};
1240 use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1241
1242 let mut program = Program::new("ask-drop-newest");
1243 let busy = program.function("busy", 0, |f| {
1244 let loop_lbl = f.label();
1246 f.bind(loop_lbl);
1247 let ms = f.load_i32(50);
1248 f.sleep(ms);
1249 f.jump(loop_lbl);
1250 });
1251 let asker = program.function("asker", 1, |f| {
1252 let server = f.reg(0);
1253 let z = f.load_i32(0);
1254 let req = f.hop_fresh(1, z);
1255 let reply = f.ask(server, req);
1256 f.return_(reply);
1257 });
1258 let chunk = program.build();
1259
1260 let cap = MailboxCapacity::new(1).ok_or("cap")?;
1261 let rt = Runtime::with_natives_and_config(
1262 chunk,
1263 crate::std_native_table(),
1264 RuntimeConfig {
1265 workers: 2,
1267 quantum: 1_000,
1268 mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1269 ..Default::default()
1270 },
1271 )?;
1272
1273 let server = rt.spawn(busy, &[])?;
1274 rt.send(
1276 server.id(),
1277 Value::Message(Message::request(1, 9, Value::Int(1))),
1278 )?;
1279 let server_cap = rt.mint_cap(server.id())?;
1280 let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1281 let outcome = ask.join_timeout(Duration::from_secs(3));
1282 rt.kill(server.id())?;
1283 let _ = server.join_timeout(Duration::from_millis(500));
1284 rt.shutdown();
1285
1286 match outcome {
1287 Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1288 other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1289 }
1290 }
1291
1292 #[test]
1293 fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1294 use crate::bytecode::Program;
1295
1296 let mut program = Program::new("ask-limit");
1297 let silent = program.function("silent", 0, |f| {
1298 let _req = f.receive();
1300 let loop_lbl = f.label();
1301 f.bind(loop_lbl);
1302 let ms = f.load_i32(50);
1303 f.sleep(ms);
1304 f.jump(loop_lbl);
1305 });
1306 let asker = program.function("asker", 1, |f| {
1307 let server = f.reg(0);
1308 let z = f.load_i32(0);
1309 let req = f.hop_fresh(1, z);
1310 let reply = f.ask(server, req);
1311 f.return_(reply);
1312 });
1313 let chunk = program.build();
1314
1315 let rt = Runtime::with_natives_and_config(
1316 chunk,
1317 crate::std_native_table(),
1318 RuntimeConfig {
1319 workers: 2,
1320 quantum: 1_000,
1321 mailbox: MailboxConfig::DEFAULT,
1322 max_ask_waits: 1,
1323 ..Default::default()
1324 },
1325 )?;
1326
1327 let server = rt.spawn(silent, &[])?;
1328 let server_cap = rt.mint_cap(server.id())?;
1329 let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1330 std::thread::sleep(Duration::from_millis(30));
1332 let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1333 let second_out = second.join_timeout(Duration::from_secs(2));
1334 rt.kill(server.id())?;
1335 let _ = first.join_timeout(Duration::from_millis(500));
1336 let _ = server.join_timeout(Duration::from_millis(500));
1337 rt.shutdown();
1338
1339 match second_out {
1340 Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1341 other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1342 }
1343 }
1344
1345 #[cfg(feature = "jit")]
1346 #[test]
1347 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1348 use crate::JitConfig;
1349
1350 let rt = Runtime::with_config(
1351 add_chunk(),
1352 RuntimeConfig {
1353 workers: 1,
1354 quantum: 1_000,
1355 mailbox: MailboxConfig::DEFAULT,
1356 jit: JitConfig {
1357 enabled: true,
1358 hot_threshold: 1,
1359 },
1360 ..Default::default()
1361 },
1362 )?;
1363 let outcome = rt.spawn(0, &[])?.join();
1364 rt.shutdown();
1365 match outcome {
1366 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1367 other => Err(format!("unexpected outcome: {other:?}").into()),
1368 }
1369 }
1370}