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 max_runtime_bytes: usize,
79 pub trust: crate::bytecode::TrustLevel,
82 pub paranoid_jumps: bool,
87 pub output: Arc<dyn crate::OutputSink>,
90 pub quota: super::quota::QuotaConfig,
92 #[cfg(feature = "jit")]
94 pub jit: JitConfig,
95}
96
97#[cfg(feature = "jit")]
99#[derive(Clone, Debug)]
100pub struct JitConfig {
101 pub enabled: bool,
103 pub hot_threshold: u32,
105}
106
107#[cfg(feature = "jit")]
108impl Default for JitConfig {
109 fn default() -> Self {
110 JitConfig {
111 enabled: false,
112 hot_threshold: crate::jit::HOT_THRESHOLD,
113 }
114 }
115}
116
117fn default_worker_count() -> usize {
119 match std::thread::available_parallelism() {
120 Ok(n) => n.get().max(1),
121 Err(_) => 1,
122 }
123}
124
125impl Default for RuntimeConfig {
126 fn default() -> Self {
127 RuntimeConfig {
128 workers: default_worker_count(),
129 quantum: DEFAULT_QUANTUM,
130 mailbox: MailboxConfig::DEFAULT,
131 max_flows: 0,
132 max_ask_waits: 0,
133 max_host_awaits: 0,
134 max_links: 0,
135 max_monitors: 0,
136 max_registry_names: 0,
137 host_await: None,
138 max_runtime_bytes: 256 * 1024 * 1024,
139 trust: crate::bytecode::TrustLevel::Untrusted,
140 paranoid_jumps: false,
141 output: Arc::new(crate::output::NullSink),
142 quota: super::quota::QuotaConfig::default(),
143 #[cfg(feature = "jit")]
144 jit: JitConfig::default(),
145 }
146 }
147}
148
149impl RuntimeConfig {
150 pub fn sandbox() -> Self {
155 RuntimeConfig {
156 quota: super::quota::QuotaConfig::sandbox(),
157 max_flows: 256,
158 max_ask_waits: 128,
159 max_host_awaits: 128,
160 max_links: 1024,
161 max_monitors: 1024,
162 max_registry_names: 256,
163 max_runtime_bytes: 64 * 1024 * 1024,
164 paranoid_jumps: true,
165 ..Default::default()
166 }
167 }
168}
169
170pub struct Shared {
177 pub(crate) injector: Injector<Box<Flow>>,
178 pub(crate) stealers: Vec<Stealer<Box<Flow>>>,
179 pub(crate) directory: Directory,
181 pub(crate) caps: super::capability::CapTable,
183 pub(crate) timer: Arc<TimerWheel>,
184 pub(crate) notify: (Mutex<()>, Condvar),
185 pub(crate) metrics: RuntimeMetrics,
186 pub(crate) shutdown: AtomicBool,
187 pub(crate) quantum: u32,
188 pub(crate) mailbox: MailboxConfig,
189 pub(crate) flow_limit: super::flow_limit::FlowLimit,
191 pub(crate) memory: Arc<crate::MemoryBudget>,
192 pub(crate) quota: super::quota::QuotaConfig,
193 pub(crate) quotas: super::quota::QuotaTable,
194 pub(crate) monitors: super::monitor::MonitorStore,
195 pub(crate) links: super::link::LinkStore,
196 pub(crate) registry: super::registry::RegistryStore,
197 pub(crate) kill_signals: super::finalize::KillSignals,
198 pub(crate) trap_exits: super::finalize::TrapExitFlags,
199 pub(crate) waiting_send_at: super::finalize::WaitingSendIndex,
200 pub(crate) ask_waits: super::finalize::AskWaitIndex,
201 pub(crate) host_awaits: super::host_await::HostAwaitIndex,
203 pub(crate) host_await_bridge: Option<Arc<dyn super::host_await::HostAwaitBridge>>,
205 pub(crate) host_next_request_id: AtomicU64,
208 pub(crate) paranoid_jumps: bool,
210 #[cfg(feature = "jit")]
212 pub(crate) jit: Option<std::sync::Arc<crate::jit::JitRuntime>>,
213}
214
215pub struct Runtime {
226 shared: Arc<Shared>,
227 chunk: Arc<Chunk>,
228 natives: Arc<NativeTable>,
229 workers: Vec<JoinHandle<()>>,
230 timer_thread: Option<JoinHandle<()>>,
231 trust: crate::bytecode::TrustLevel,
232}
233
234impl Runtime {
235 pub fn new(chunk: Chunk) -> Result<Self, SpawnError> {
243 Self::with_config(chunk, RuntimeConfig::default())
244 }
245
246 pub fn with_natives(chunk: Chunk, natives: Arc<NativeTable>) -> Result<Self, SpawnError> {
249 Self::with_natives_and_config(chunk, natives, RuntimeConfig::default())
250 }
251
252 pub fn with_config(chunk: Chunk, config: RuntimeConfig) -> Result<Self, SpawnError> {
253 Self::with_natives_and_config(chunk, NativeTable::empty(), config)
254 }
255
256 pub fn with_attested(
262 bytes: &[u8],
263 expected_digest: [u8; 32],
264 natives: Arc<NativeTable>,
265 config: RuntimeConfig,
266 ) -> Result<Self, SpawnError> {
267 let chunk =
268 crate::decode_attested(bytes, &expected_digest).map_err(SpawnError::Attestation)?;
269 Self::with_natives_and_config(chunk, natives, config)
270 }
271
272 pub fn with_std_natives_and_config(
275 chunk: Chunk,
276 config: RuntimeConfig,
277 ) -> Result<Self, SpawnError> {
278 Self::with_natives_and_config(
279 chunk,
280 crate::std_native_table_with(Arc::clone(&config.output)),
281 config,
282 )
283 }
284
285 pub fn with_natives_and_config(
295 chunk: Chunk,
296 natives: Arc<NativeTable>,
297 config: RuntimeConfig,
298 ) -> Result<Self, SpawnError> {
299 crate::bytecode::verify_with(
300 &chunk,
301 crate::bytecode::VerifyConfig {
302 trust: config.trust,
303 },
304 )
305 .map_err(SpawnError::VerifyFailed)?;
306 let chunk = Arc::new(chunk);
307 let workers_n = config.workers.max(1);
308
309 let locals: Vec<LocalDeque<Box<Flow>>> =
310 (0..workers_n).map(|_| LocalDeque::new_fifo()).collect();
311 let stealers: Vec<Stealer<Box<Flow>>> = locals.iter().map(|l| l.stealer()).collect();
312
313 #[cfg(feature = "jit")]
314 let jit = if config.jit.enabled {
315 Some(super::jit::new_runtime(
316 chunk.clone(),
317 config.jit.hot_threshold,
318 ))
319 } else {
320 None
321 };
322
323 let paranoid_jumps =
324 config.paranoid_jumps || matches!(config.trust, crate::bytecode::TrustLevel::Untrusted);
325
326 let shared = Arc::new(Shared {
327 injector: Injector::new(),
328 stealers,
329 directory: Directory::new(),
330 caps: super::capability::CapTable::new(),
331 timer: TimerWheel::new(),
332 notify: (Mutex::new(()), Condvar::new()),
333 metrics: RuntimeMetrics::default(),
334 shutdown: AtomicBool::new(false),
335 quantum: config.quantum,
336 mailbox: config.mailbox,
337 flow_limit: super::flow_limit::FlowLimit::new(config.max_flows),
338 memory: Arc::new(crate::MemoryBudget::new(config.max_runtime_bytes)),
339 quota: config.quota,
340 quotas: super::quota::QuotaTable::new(),
341 monitors: super::monitor::MonitorStore::new(config.max_monitors),
342 links: super::link::LinkStore::new(config.max_links),
343 registry: super::registry::RegistryStore::new(config.max_registry_names),
344 kill_signals: super::finalize::KillSignals::new(),
345 trap_exits: super::finalize::TrapExitFlags::new(),
346 waiting_send_at: super::finalize::WaitingSendIndex::new(),
347 ask_waits: super::finalize::AskWaitIndex::new(config.max_ask_waits),
348 host_awaits: super::host_await::HostAwaitIndex::new(config.max_host_awaits),
349 host_await_bridge: config.host_await.clone(),
350 host_next_request_id: AtomicU64::new(1),
351 paranoid_jumps,
352 #[cfg(feature = "jit")]
353 jit,
354 });
355
356 let mut workers = Vec::with_capacity(workers_n);
357 for local in locals {
358 let shared_w = shared.clone();
359 match std::thread::Builder::new()
360 .name("byteflow-worker".into())
361 .spawn(move || worker::run_worker(shared_w, local))
362 {
363 Ok(handle) => workers.push(handle),
364 Err(e) => {
365 abort_startup(&shared, workers, None);
366 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
367 }
368 }
369 }
370
371 let shared_timer = shared.clone();
372 let timer_thread = match std::thread::Builder::new()
373 .name("byteflow-timer".into())
374 .spawn(move || shared_timer.timer.clone().drive(&shared_timer))
375 {
376 Ok(handle) => handle,
377 Err(e) => {
378 abort_startup(&shared, workers, None);
379 return Err(SpawnError::ThreadSpawnFailed(e.to_string()));
380 }
381 };
382
383 Ok(Runtime {
384 shared,
385 chunk,
386 natives,
387 workers,
388 timer_thread: Some(timer_thread),
389 trust: config.trust,
390 })
391 }
392
393 pub fn spawn(&self, function: u32, args: &[Value]) -> Result<FlowHandle, SpawnError> {
398 spawn_on(
399 &self.shared,
400 &self.chunk,
401 &self.natives,
402 function,
403 args,
404 RestartPolicy::Never,
405 None,
406 None,
407 None,
408 )
409 }
410
411 pub fn spawner(&self) -> RuntimeSpawner {
415 RuntimeSpawner {
416 shared: self.shared.clone(),
417 chunk: self.chunk.clone(),
418 natives: self.natives.clone(),
419 }
420 }
421
422 pub fn supervisor(&self) -> Result<super::supervisor::Supervisor, SpawnError> {
425 super::supervisor::Supervisor::new(self.spawner())
426 }
427
428 pub fn function_index(&self, name: &str) -> Option<u32> {
432 self.chunk
433 .functions
434 .iter()
435 .position(|f| f.name == name)
436 .map(|i| i as u32)
437 }
438
439 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
440 self.shared.metrics.snapshot()
441 }
442
443 pub fn live_flows(&self) -> usize {
449 self.shared.directory.len()
450 }
451
452 pub fn memory_snapshot(&self) -> crate::MemorySnapshot {
454 self.shared.memory.snapshot()
455 }
456
457 pub fn worker_count(&self) -> usize {
458 self.workers.len()
459 }
460
461 pub fn send(&self, target: FlowId, message: Value) -> Result<(), SendError> {
474 let Some(msg) = message.as_message().cloned() else {
475 return Err(SendError::NotAHop {
476 got: message.type_name(),
477 });
478 };
479 let mailbox = match self.shared.directory.lookup(target) {
480 Ok(Some(m)) => m,
481 Ok(None) => return Err(SendError::NoSuchFlow(target)),
482 Err(e) => {
483 super::error::report_fault(e);
484 return Err(SendError::Unavailable);
485 }
486 };
487 let stamped = match worker::authenticate_host_outgoing_message(&self.shared, target, msg) {
488 Ok(m) => Value::Message(m),
489 Err(_) => return Err(SendError::Capability),
490 };
491 match mailbox.push(stamped.clone()) {
492 Ok(Ok(Delivery::Queued | Delivery::QueuedDropOldest | Delivery::DroppedNewest)) => {
497 Ok(())
498 }
499 Ok(Ok(Delivery::Handoff(flow))) => {
500 let _ = self.shared.ask_waits.remove_asker(flow.id);
501 match flow.last_receive_dest {
502 Some(dest) => {
503 let Some(flow) =
504 super::finalize::resume_or_fail(&self.shared, flow, dest, stamped)
505 else {
506 return Err(SendError::Unavailable);
507 };
508 self.shared.injector.push(flow);
509 wake_workers(&self.shared);
510 Ok(())
511 }
512 None => {
513 super::error::report_fault(super::error::RuntimeError::PoisonedLock(
514 "Runtime::send handoff missing dest register",
515 ));
516 finalize_flow(
517 &self.shared,
518 *flow,
519 FlowOutcome::Failed("handoff missing dest register".into()),
520 FlowExitReason::Fault,
521 );
522 Err(SendError::Unavailable)
523 }
524 }
525 }
526 Ok(Err(full)) => {
527 if full.reason() == MailboxFullReason::Closed {
528 return Err(SendError::NoSuchFlow(target));
529 }
530 Err(SendError::MailboxFull {
531 flow: target,
532 reason: full.reason(),
533 })
534 }
535 Err(e) => {
536 super::error::report_fault(e);
537 Err(SendError::Unavailable)
538 }
539 }
540 }
541
542 fn require_live(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
543 match self.shared.directory.lookup(id) {
544 Ok(Some(_)) => Ok(()),
545 Ok(None) => Err(super::error::LifecycleError::NoSuchFlow(id)),
546 Err(e) => Err(self.unavailable(e)),
547 }
548 }
549
550 fn unavailable(&self, err: super::error::RuntimeError) -> super::error::LifecycleError {
551 super::error::report_fault(err);
552 super::error::LifecycleError::Unavailable
553 }
554
555 pub fn mint_cap(
558 &self,
559 flow: FlowId,
560 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
561 self.require_live(flow)?;
562 self.shared
563 .caps
564 .mint(flow, flow, super::capability::CapRights::ADDRESSING)
565 .map_err(|e| self.unavailable(e))
566 }
567
568 pub fn grant_cap(
570 &self,
571 holder: FlowId,
572 target: FlowId,
573 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
574 self.require_live(holder)?;
575 self.require_live(target)?;
576 self.shared
577 .caps
578 .mint(holder, target, super::capability::CapRights::ADDRESSING)
579 .map_err(|e| self.unavailable(e))
580 }
581
582 pub fn monitor(
586 &self,
587 owner: FlowId,
588 target: FlowId,
589 ) -> Result<super::monitor::MonitorRef, super::error::LifecycleError> {
590 if owner == target {
591 return Err(super::error::LifecycleError::SelfRelation);
592 }
593 self.require_live(owner)?;
594 self.require_live(target)?;
595 let mon = self
596 .shared
597 .monitors
598 .create(owner, target)
599 .map_err(|e| self.unavailable(e))??;
600 if self.require_live(target).is_err() {
603 let _ = self.shared.monitors.remove_owned(owner, mon);
604 super::finalize::deliver_down(
605 &self.shared,
606 super::monitor::DownEvent {
607 monitor: mon,
608 owner,
609 target,
610 reason: super::monitor::FlowExitReason::Fault,
611 },
612 );
613 }
614 Ok(mon)
615 }
616
617 pub fn demonitor(
619 &self,
620 owner: FlowId,
621 monitor: super::monitor::MonitorRef,
622 ) -> Result<(), super::error::LifecycleError> {
623 self.require_live(owner)?;
624 match self.shared.monitors.remove_owned(owner, monitor) {
625 Ok(inner) => inner,
626 Err(e) => Err(self.unavailable(e)),
627 }
628 }
629
630 pub fn link(
635 &self,
636 a: FlowId,
637 b: FlowId,
638 ) -> Result<super::link::LinkId, super::error::LifecycleError> {
639 if a == b {
640 return Err(super::error::LifecycleError::SelfRelation);
641 }
642 self.require_live(a)?;
643 self.require_live(b)?;
644 match self.shared.links.link_if_live(a, b, |id| {
645 self.shared.directory.lookup(id).map(|m| m.is_some())
646 }) {
647 Ok(inner) => inner,
648 Err(e) => Err(self.unavailable(e)),
649 }
650 }
651
652 pub fn set_trap_exit(
657 &self,
658 id: FlowId,
659 enabled: bool,
660 ) -> Result<(), super::error::LifecycleError> {
661 self.require_live(id)?;
662 self.shared
663 .trap_exits
664 .set(id, enabled)
665 .map_err(|e| self.unavailable(e))
666 }
667
668 pub fn unlink(
670 &self,
671 owner: FlowId,
672 link: super::link::LinkId,
673 ) -> Result<(), super::error::LifecycleError> {
674 self.require_live(owner)?;
675 match self.shared.links.unlink_owned(owner, link) {
676 Ok(inner) => inner,
677 Err(e) => Err(self.unavailable(e)),
678 }
679 }
680
681 pub fn register_name(
683 &self,
684 name: &str,
685 cap: crate::bytecode::CapId,
686 ) -> Result<(), super::error::LifecycleError> {
687 let entry = match self.shared.caps.lookup(cap) {
688 Ok(Some(e)) => e,
689 Ok(None) => return Err(super::error::LifecycleError::InvalidCapability),
690 Err(e) => return Err(self.unavailable(e)),
691 };
692 let target = match entry.target() {
693 Some(id) => id,
694 None => return Err(super::error::LifecycleError::InvalidCapability),
695 };
696 self.require_live(target)?;
697 match self
698 .shared
699 .registry
700 .register(super::registry::RegistryName::from(name), cap, target)
701 {
702 Ok(inner) => inner,
703 Err(e) => Err(self.unavailable(e)),
704 }
705 }
706
707 pub fn whereis(
709 &self,
710 name: &str,
711 ) -> Result<Option<crate::bytecode::CapId>, super::error::LifecycleError> {
712 self.shared
713 .registry
714 .whereis(name)
715 .map_err(|e| self.unavailable(e))
716 }
717
718 pub fn kill(&self, id: FlowId) -> Result<(), super::error::LifecycleError> {
721 self.require_live(id)?;
722 super::finalize::request_kill(&self.shared, id, super::monitor::FlowExitReason::Killed);
723 Ok(())
724 }
725
726 pub fn mint_admin_cap(
728 &self,
729 holder: FlowId,
730 ) -> Result<crate::bytecode::CapId, super::error::LifecycleError> {
731 self.require_live(holder)?;
732 let cap = crate::bytecode::Cap::root(
733 crate::bytecode::CapTarget::Scheduler,
734 CapRights::ADMIN,
735 None,
736 self.shared.caps.scheduler_cell().as_ref(),
737 );
738 self.shared
739 .caps
740 .grant(holder, cap)
741 .map_err(|e| self.unavailable(e))
742 }
743
744 pub fn admin_kill(
746 &self,
747 holder: FlowId,
748 cap: crate::bytecode::CapId,
749 target: FlowId,
750 ) -> Result<(), super::error::LifecycleError> {
751 self.require_admin(holder, cap)?;
752 self.kill(target)
753 }
754
755 pub fn admin_top_up_cpu(
757 &self,
758 holder: FlowId,
759 cap: crate::bytecode::CapId,
760 target: FlowId,
761 extra: i64,
762 ) -> Result<(), super::error::LifecycleError> {
763 self.require_admin(holder, cap)?;
764 let quota = match self.shared.quotas.get(target) {
765 Ok(Some(q)) => q,
766 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
767 Err(e) => return Err(self.unavailable(e)),
768 };
769 quota.top_up_cpu(extra);
770 Ok(())
771 }
772
773 pub fn admin_top_up_mem(
775 &self,
776 holder: FlowId,
777 cap: crate::bytecode::CapId,
778 target: FlowId,
779 extra: usize,
780 ) -> Result<(), super::error::LifecycleError> {
781 self.require_admin(holder, cap)?;
782 let quota = match self.shared.quotas.get(target) {
783 Ok(Some(q)) => q,
784 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
785 Err(e) => return Err(self.unavailable(e)),
786 };
787 quota.top_up_mem(extra);
788 Ok(())
789 }
790
791 pub fn admin_top_up_send(
793 &self,
794 holder: FlowId,
795 cap: crate::bytecode::CapId,
796 target: FlowId,
797 extra: i64,
798 ) -> Result<(), super::error::LifecycleError> {
799 self.require_admin(holder, cap)?;
800 let quota = match self.shared.quotas.get(target) {
801 Ok(Some(q)) => q,
802 Ok(None) => return Err(super::error::LifecycleError::NoSuchFlow(target)),
803 Err(e) => return Err(self.unavailable(e)),
804 };
805 quota.top_up_send(extra);
806 Ok(())
807 }
808
809 fn require_admin(
810 &self,
811 holder: FlowId,
812 cap: crate::bytecode::CapId,
813 ) -> Result<(), super::error::LifecycleError> {
814 let entry = match self.shared.caps.resolve(cap, holder, CapRights::ADMIN) {
815 Ok(e) => e,
816 Err(_) => return Err(super::error::LifecycleError::InvalidCapability),
817 };
818 super::link_admin::check_admin(&entry.cap, self.shared.caps.scheduler_cell().as_ref())
819 .map_err(|_| super::error::LifecycleError::InvalidCapability)
820 }
821
822 pub fn unregister_name(&self, name: &str) -> Result<bool, super::error::LifecycleError> {
824 self.shared
825 .registry
826 .unregister(name)
827 .map_err(|e| self.unavailable(e))
828 }
829
830 pub fn reload_chunk(&mut self, chunk: Chunk) -> Result<(), SpawnError> {
834 crate::bytecode::verify_with(&chunk, crate::bytecode::VerifyConfig { trust: self.trust })
835 .map_err(SpawnError::VerifyFailed)?;
836 let chunk = Arc::new(chunk);
837 self.chunk = chunk.clone();
838 #[cfg(feature = "jit")]
839 if let Some(jit) = &self.shared.jit {
840 jit.reload(chunk);
841 }
842 Ok(())
843 }
844
845 fn request_shutdown(&self) {
848 self.shared.shutdown.store(true, Ordering::Release);
849 finalize_host_awaits(&self.shared);
852 self.shared.timer.shutdown();
853 let (lock, cvar) = &self.shared.notify;
854 match super::sync_lock::lock(lock, "Runtime::request_shutdown") {
855 Ok(_g) => cvar.notify_all(),
856 Err(e) => super::error::report_fault(e),
857 }
858 }
859
860 pub fn shutdown(mut self) {
868 self.request_shutdown();
869 for w in self.workers.drain(..) {
870 let _ = w.join();
871 }
872 if let Some(t) = self.timer_thread.take() {
873 let _ = t.join();
874 }
875 finalize_stranded(&self.shared);
876 }
877}
878
879fn finalize_shutdown_flow(shared: &Shared, flow: Flow) {
880 finalize_flow(
881 shared,
882 flow,
883 FlowOutcome::Failed("runtime shutdown".into()),
884 FlowExitReason::Shutdown,
885 );
886}
887
888fn finalize_host_awaits(shared: &Shared) {
889 match shared.host_awaits.drain_all() {
890 Ok(parked) => {
891 for p in parked {
892 finalize_shutdown_flow(shared, *p.flow);
893 }
894 }
895 Err(e) => super::error::report_fault(e),
896 }
897}
898
899fn finalize_stranded(shared: &Shared) {
904 finalize_host_awaits(shared);
905 for flow in shared.timer.drain() {
906 finalize_shutdown_flow(shared, *flow);
907 }
908 for _ in 0..8 {
909 let mut n = 0usize;
910 for flow in shared.injector.drain() {
911 finalize_shutdown_flow(shared, *flow);
912 n += 1;
913 }
914 for stealer in &shared.stealers {
915 for flow in stealer.drain() {
916 finalize_shutdown_flow(shared, *flow);
917 n += 1;
918 }
919 }
920 for (_id, mailbox) in shared.directory.snapshot() {
921 match mailbox.take_parked() {
922 Ok(Some(flow)) => {
923 finalize_shutdown_flow(shared, *flow);
924 n += 1;
925 }
926 Ok(None) => {}
927 Err(e) => super::error::report_fault(e),
928 }
929 match mailbox.close() {
930 Ok(senders) => {
931 for sender in senders {
932 if let Err(e) = shared.waiting_send_at.remove(sender.id) {
933 super::error::report_fault(e);
934 }
935 finalize_shutdown_flow(shared, sender);
936 n += 1;
937 }
938 }
939 Err(e) => super::error::report_fault(e),
940 }
941 }
942 if n == 0 {
943 break;
944 }
945 }
946}
947
948impl Drop for Runtime {
949 fn drop(&mut self) {
950 if !self.shared.shutdown.load(Ordering::Acquire) {
951 self.request_shutdown();
952 }
953 }
954}
955
956pub fn flow_id_from_u64(raw: u64) -> FlowId {
960 FlowId(raw)
961}
962
963#[derive(Debug, Clone, PartialEq, Eq)]
965pub enum SendError {
966 NoSuchFlow(FlowId),
967 NotAHop {
969 got: &'static str,
970 },
971 MailboxFull {
975 flow: FlowId,
976 reason: MailboxFullReason,
977 },
978 Capability,
980 Unavailable,
982}
983
984impl std::fmt::Display for SendError {
985 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
986 match self {
987 SendError::NoSuchFlow(id) => write!(f, "no live flow {id}"),
988 SendError::NotAHop { got } => {
989 write!(f, "atomic hop requires Value::Message, got {got}")
990 }
991 SendError::MailboxFull { flow, reason } => {
992 write!(f, "mailbox full for {flow} ({reason})")
993 }
994 SendError::Capability => {
995 write!(f, "host send could not reissue a capability in the hop")
996 }
997 SendError::Unavailable => write!(f, "runtime table unavailable (poisoned lock)"),
998 }
999 }
1000}
1001
1002impl std::error::Error for SendError {}
1003
1004pub(crate) struct BytecodeSpawn<'a> {
1007 pub authority: &'a Cap,
1008 pub cell: &'a crate::bytecode::RevocationCell,
1009 pub quota: &'a super::quota::FlowQuota,
1010 pub requested_rights: CapRights,
1011}
1012
1013pub(crate) fn bytecode_spawn_arity(arity: u8, argc: usize) -> Result<(), crate::vm::Fault> {
1024 if argc != usize::from(arity) {
1025 Err(crate::vm::Fault::BadArity {
1026 passed: argc,
1027 expected: arity,
1028 })
1029 } else {
1030 Ok(())
1031 }
1032}
1033
1034#[allow(clippy::too_many_arguments)]
1035pub(crate) fn spawn_on(
1036 shared: &Arc<Shared>,
1037 chunk: &Arc<Chunk>,
1038 natives: &Arc<NativeTable>,
1039 function: u32,
1040 args: &[Value],
1041 restart_policy: RestartPolicy,
1042 supervisor: Option<SupervisorLink>,
1043 parent: Option<FlowId>,
1044 bytecode: Option<BytecodeSpawn<'_>>,
1045) -> Result<FlowHandle, SpawnError> {
1046 if bytecode.is_some() {
1050 match chunk.function(function) {
1051 Some(def) => {
1052 if let Err(fault) = bytecode_spawn_arity(def.arity, args.len()) {
1053 return Err(fault.into());
1054 }
1055 }
1056 None => {
1057 return Err(SpawnError::BadFunction {
1058 index: function,
1059 table_size: chunk.functions.len() as u32,
1060 });
1061 }
1062 }
1063 }
1064 shared.flow_limit.try_reserve()?;
1065 let id = match super::process::try_next_flow_id() {
1066 Ok(id) => id,
1067 Err(super::error::RuntimeError::FlowIdExhausted) => {
1068 shared.flow_limit.release();
1069 return Err(SpawnError::FlowIdExhausted);
1070 }
1071 Err(_) => {
1072 shared.flow_limit.release();
1073 return Err(SpawnError::Unavailable);
1074 }
1075 };
1076 let cell = match shared.caps.bind_flow(id) {
1077 Ok(c) => c,
1078 Err(_) => {
1079 shared.flow_limit.release();
1080 return Err(SpawnError::Unavailable);
1081 }
1082 };
1083 let authority = match bytecode {
1084 None => Cap::root(
1085 CapTarget::Flow(id.as_u64()),
1086 CapRights::ROOT,
1087 Some(NativeMask::full(natives.len())),
1088 cell.as_ref(),
1089 ),
1090 Some(ctx) => match super::spawn::exec_spawn_authority(
1091 ctx.authority,
1092 ctx.cell,
1093 ctx.quota,
1094 id.as_u64(),
1095 ctx.requested_rights,
1096 None,
1097 cell.as_ref(),
1098 ) {
1099 Ok(cap) => cap,
1100 Err(e) => {
1101 shared.flow_limit.release();
1102 let _ = shared.caps.revoke_flow(id);
1103 return Err(SpawnError::from(e));
1104 }
1105 },
1106 };
1107 let args = match grant_caps_in_args(shared, parent, id, args) {
1108 Ok(a) => a,
1109 Err(e) => {
1110 shared.flow_limit.release();
1111 let _ = shared.caps.revoke_flow(id);
1112 return Err(e);
1113 }
1114 };
1115 let gate = NativeGate::from_authority(
1116 &authority,
1117 Arc::clone(&cell),
1118 shared.caps.native_cell(),
1119 natives.len(),
1120 );
1121 let quota = Arc::new(super::quota::FlowQuota::from_config(shared.quota));
1122 let mut vm = match Vm::with_native_gate(
1123 chunk.clone(),
1124 natives.clone(),
1125 gate,
1126 function,
1127 args.as_slice(),
1128 ) {
1129 Ok(vm) => vm,
1130 Err(e) => {
1131 shared.flow_limit.release();
1132 let _ = shared.caps.revoke_flow(id);
1133 return Err(e.into());
1134 }
1135 };
1136 vm.set_paranoid_jumps(shared.paranoid_jumps);
1137 vm.set_memory_budget(Arc::clone(&shared.memory));
1138 if let Err(e) = vm.set_quota(Arc::clone("a)) {
1139 shared.flow_limit.release();
1140 let _ = shared.caps.revoke_flow(id);
1141 return Err(e.into());
1142 }
1143 let mailbox = Arc::new(Mailbox::with_config(shared.mailbox));
1144 if let Err(e) = shared.directory.register(id, mailbox.clone()) {
1145 super::error::report_fault(e);
1146 shared.flow_limit.release();
1147 let _ = shared.caps.revoke_flow(id);
1148 return Err(SpawnError::Unavailable);
1149 }
1150 if let Err(e) = shared.quotas.insert(id, Arc::clone("a)) {
1151 super::error::report_fault(e);
1152 let _ = shared.directory.unregister(id);
1153 shared.flow_limit.release();
1154 let _ = shared.caps.revoke_flow(id);
1155 return Err(SpawnError::Unavailable);
1156 }
1157 let (tx, rx) = super::oneshot::channel();
1158 let mut flow = Box::new(Flow::new(id, vm, mailbox, restart_policy, tx));
1159 flow.authority = authority;
1160 flow.cell = cell;
1161 flow.quota = quota;
1162 flow.supervisor = supervisor;
1163 RuntimeMetrics::inc(&shared.metrics.processes_spawned);
1164 shared.injector.push(flow);
1165 wake_workers(shared);
1166 Ok(FlowHandle { id, receiver: rx })
1167}
1168
1169fn grant_caps_in_args(
1170 shared: &Shared,
1171 parent: Option<FlowId>,
1172 child: FlowId,
1173 args: &[Value],
1174) -> Result<Vec<Value>, SpawnError> {
1175 let mut out = Vec::with_capacity(args.len());
1176 for arg in args {
1177 match arg {
1178 Value::Cap(id) => {
1179 let granted = match parent {
1180 None => shared.caps.reissue_for(*id, child),
1181 Some(p) => shared.caps.delegate(*id, p, child),
1182 };
1183 match granted {
1184 Ok(cap) => out.push(Value::Cap(cap)),
1185 Err(_) => return Err(SpawnError::InvalidCapability),
1186 }
1187 }
1188 other => out.push(other.clone()),
1189 }
1190 }
1191 Ok(out)
1192}
1193
1194pub(crate) fn wake_workers(shared: &Shared) {
1195 let (lock, cvar) = &shared.notify;
1196 match super::sync_lock::lock(lock, "wake_workers") {
1197 Ok(_g) => cvar.notify_one(),
1198 Err(e) => super::error::report_fault(e),
1199 }
1200}
1201
1202fn abort_startup(
1206 shared: &Arc<Shared>,
1207 workers: Vec<std::thread::JoinHandle<()>>,
1208 timer: Option<std::thread::JoinHandle<()>>,
1209) {
1210 shared.shutdown.store(true, Ordering::Release);
1211 shared.timer.shutdown();
1212 let (lock, cvar) = &shared.notify;
1213 match super::sync_lock::lock(lock, "abort_startup") {
1214 Ok(_g) => cvar.notify_all(),
1215 Err(e) => super::error::report_fault(e),
1216 }
1217 for w in workers {
1218 let _ = w.join();
1219 }
1220 if let Some(t) = timer {
1221 let _ = t.join();
1222 }
1223}
1224
1225#[derive(Clone)]
1231pub struct RuntimeSpawner {
1232 pub(crate) shared: Arc<Shared>,
1233 pub(crate) chunk: Arc<Chunk>,
1234 pub(crate) natives: Arc<NativeTable>,
1235}
1236
1237impl RuntimeSpawner {
1238 pub fn spawn(
1239 &self,
1240 function: u32,
1241 args: &[Value],
1242 restart_policy: RestartPolicy,
1243 ) -> Result<FlowHandle, SpawnError> {
1244 spawn_on(
1245 &self.shared,
1246 &self.chunk,
1247 &self.natives,
1248 function,
1249 args,
1250 restart_policy,
1251 None,
1252 None,
1253 None,
1254 )
1255 }
1256
1257 pub(crate) fn spawn_linked(
1258 &self,
1259 function: u32,
1260 args: &[Value],
1261 restart_policy: RestartPolicy,
1262 supervisor: SupervisorLink,
1263 ) -> Result<FlowHandle, SpawnError> {
1264 spawn_on(
1265 &self.shared,
1266 &self.chunk,
1267 &self.natives,
1268 function,
1269 args,
1270 restart_policy,
1271 Some(supervisor),
1272 None,
1273 None,
1274 )
1275 }
1276
1277 pub fn metrics(&self) -> RuntimeMetricsSnapshot {
1278 self.shared.metrics.snapshot()
1279 }
1280
1281 pub(crate) fn request_kill(&self, id: FlowId, reason: super::monitor::FlowExitReason) {
1282 super::finalize::request_kill(&self.shared, id, reason);
1283 }
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use super::*;
1289 use crate::bytecode::{builder::ChunkBuilder, Opcode, Value};
1290 use crate::scheduler::FlowOutcome;
1291 use std::time::Duration;
1292
1293 #[test]
1294 fn bytecode_spawn_rejects_an_argc_the_callee_did_not_declare() {
1295 assert!(super::bytecode_spawn_arity(2, 2).is_ok());
1296 assert!(matches!(
1297 super::bytecode_spawn_arity(2, 1),
1298 Err(crate::vm::Fault::BadArity {
1299 passed: 1,
1300 expected: 2,
1301 })
1302 ));
1303 }
1304
1305 fn add_chunk() -> Chunk {
1306 let mut b = ChunkBuilder::new("test");
1307 b.begin_function("main", 0, 2);
1308 b.emit_load_imm(0, 41);
1309 b.emit_load_imm(1, 1);
1310 b.emit_binop(Opcode::Add, 0, 0, 1);
1311 b.emit_return(0);
1312 b.finish()
1313 }
1314
1315 fn sleep_then_return_chunk(millis: i32) -> Chunk {
1318 let mut b = ChunkBuilder::new("test");
1319 b.begin_function("main", 0, 2);
1320 b.emit_load_imm(0, millis);
1321 b.emit_sleep(0);
1322 b.emit_load_imm(0, 7);
1323 b.emit_return(0);
1324 b.finish()
1325 }
1326
1327 #[test]
1331 fn polling_and_bounded_waits_never_commit_the_host_thread(
1332 ) -> Result<(), Box<dyn std::error::Error>> {
1333 const FLOW_SLEEP: i32 = 150;
1334 let rt = Runtime::with_config(
1335 sleep_then_return_chunk(FLOW_SLEEP),
1336 RuntimeConfig {
1337 workers: 1,
1338 quantum: 1_000,
1339 mailbox: MailboxConfig::DEFAULT,
1340 ..Default::default()
1341 },
1342 )?;
1343 let handle = rt.spawn(0, &[])?;
1344
1345 if let Some(outcome) = handle.try_join() {
1348 rt.shutdown();
1349 return Err(format!("try_join answered too early: {outcome:?}").into());
1350 }
1351
1352 if let Some(outcome) = handle.join_timeout(Duration::from_millis(20)) {
1355 rt.shutdown();
1356 return Err(format!("join_timeout answered too early: {outcome:?}").into());
1357 }
1358
1359 let outcome = handle.join_timeout(Duration::from_secs(10));
1362 rt.shutdown();
1363 match outcome {
1364 Some(FlowOutcome::Completed(Value::Int(7))) => Ok(()),
1365 other => Err(format!("unexpected outcome: {other:?}").into()),
1366 }
1367 }
1368
1369 #[test]
1370 fn spawn_and_join_add() -> Result<(), Box<dyn std::error::Error>> {
1371 let rt = Runtime::with_config(
1372 add_chunk(),
1373 RuntimeConfig {
1374 workers: 1,
1375 quantum: 1_000,
1376 mailbox: MailboxConfig::DEFAULT,
1377 ..Default::default()
1378 },
1379 )?;
1380 let outcome = rt.spawn(0, &[])?.join();
1381 rt.shutdown();
1382 match outcome {
1383 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1384 other => Err(format!("unexpected outcome: {other:?}").into()),
1385 }
1386 }
1387
1388 fn receive_forever_chunk() -> Chunk {
1389 let mut b = ChunkBuilder::new("recv");
1390 b.begin_function("main", 0, 1);
1391 b.emit_receive(0);
1392 b.emit_return(0);
1393 b.finish()
1394 }
1395
1396 #[test]
1397 fn kill_parked_flow_joins_failed() -> Result<(), Box<dyn std::error::Error>> {
1398 let rt = Runtime::with_config(
1399 receive_forever_chunk(),
1400 RuntimeConfig {
1401 workers: 1,
1402 quantum: 1_000,
1403 mailbox: MailboxConfig::DEFAULT,
1404 ..Default::default()
1405 },
1406 )?;
1407 let handle = rt.spawn(0, &[])?;
1408 rt.kill(handle.id())?;
1409 let outcome = handle.join();
1410 rt.shutdown();
1411 assert!(
1412 matches!(outcome, FlowOutcome::Failed(_)),
1413 "kill must fail the joiner, got {outcome:?}"
1414 );
1415 Ok(())
1416 }
1417
1418 #[test]
1419 fn shutdown_finalizes_parked_receive() -> Result<(), Box<dyn std::error::Error>> {
1420 let rt = Runtime::with_config(
1421 receive_forever_chunk(),
1422 RuntimeConfig {
1423 workers: 1,
1424 quantum: 1_000,
1425 mailbox: MailboxConfig::DEFAULT,
1426 ..Default::default()
1427 },
1428 )?;
1429 let handle = rt.spawn(0, &[])?;
1430 std::thread::sleep(Duration::from_millis(30));
1431 rt.shutdown();
1432 match handle.join() {
1433 FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1434 other => Err(format!("expected shutdown finalize, got {other:?}").into()),
1435 }
1436 }
1437
1438 #[test]
1439 fn shutdown_finalizes_sleeper() -> Result<(), Box<dyn std::error::Error>> {
1440 let rt = Runtime::with_config(
1441 sleep_then_return_chunk(60_000),
1442 RuntimeConfig {
1443 workers: 1,
1444 quantum: 1_000,
1445 mailbox: MailboxConfig::DEFAULT,
1446 ..Default::default()
1447 },
1448 )?;
1449 let handle = rt.spawn(0, &[])?;
1450 std::thread::sleep(Duration::from_millis(30));
1451 rt.shutdown();
1452 match handle.join() {
1453 FlowOutcome::Failed(msg) if msg.contains("runtime shutdown") => Ok(()),
1454 other => Err(format!("expected sleeper shutdown, got {other:?}").into()),
1455 }
1456 }
1457
1458 #[test]
1459 fn max_flows_rejects_extra_spawn() -> Result<(), Box<dyn std::error::Error>> {
1460 let rt = Runtime::with_config(
1461 receive_forever_chunk(),
1462 RuntimeConfig {
1463 workers: 1,
1464 quantum: 1_000,
1465 mailbox: MailboxConfig::DEFAULT,
1466 max_flows: 1,
1467 ..Default::default()
1468 },
1469 )?;
1470 let first = rt.spawn(0, &[])?;
1471 let second = rt.spawn(0, &[]);
1472 rt.kill(first.id())?;
1473 let _ = first.join();
1474 let third = rt.spawn(0, &[])?;
1476 rt.kill(third.id())?;
1477 let _ = third.join();
1478 rt.shutdown();
1479 match second {
1480 Err(SpawnError::FlowLimit { current, max }) => {
1481 assert_eq!(current, 1);
1482 assert_eq!(max, 1);
1483 Ok(())
1484 }
1485 other => Err(format!(
1486 "expected FlowLimit, got {}",
1487 match &other {
1488 Ok(_) => "Ok(handle)".into(),
1489 Err(e) => format!("Err({e})"),
1490 }
1491 )
1492 .into()),
1493 }
1494 }
1495
1496 #[test]
1498 fn ask_drop_newest_fails_closed() -> Result<(), Box<dyn std::error::Error>> {
1499 use crate::bytecode::{Message, Program};
1500 use crate::scheduler::mailbox::{MailboxCapacity, OverflowPolicy};
1501
1502 let mut program = Program::new("ask-drop-newest");
1503 let busy = program.function("busy", 0, |f| {
1504 let loop_lbl = f.label();
1506 f.bind(loop_lbl);
1507 let ms = f.load_i32(50);
1508 f.sleep(ms);
1509 f.jump(loop_lbl);
1510 });
1511 let asker = program.function("asker", 1, |f| {
1512 let server = f.reg(0);
1513 let z = f.load_i32(0);
1514 let req = f.hop_fresh(1, z);
1515 let reply = f.ask(server, req);
1516 f.return_(reply);
1517 });
1518 let chunk = program.build();
1519
1520 let cap = MailboxCapacity::new(1).ok_or("cap")?;
1521 let rt = Runtime::with_natives_and_config(
1522 chunk,
1523 crate::std_native_table(),
1524 RuntimeConfig {
1525 workers: 2,
1527 quantum: 1_000,
1528 mailbox: MailboxConfig::new(cap, OverflowPolicy::DropNewest),
1529 ..Default::default()
1530 },
1531 )?;
1532
1533 let server = rt.spawn(busy, &[])?;
1534 rt.send(
1536 server.id(),
1537 Value::Message(Message::request(1, 9, Value::Int(1))),
1538 )?;
1539 let server_cap = rt.mint_cap(server.id())?;
1540 let ask = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1541 let outcome = ask.join_timeout(Duration::from_secs(3));
1542 rt.kill(server.id())?;
1543 let _ = server.join_timeout(Duration::from_millis(500));
1544 rt.shutdown();
1545
1546 match outcome {
1547 Some(FlowOutcome::Failed(msg)) if msg.contains("DropNewest") => Ok(()),
1548 other => Err(format!("expected Ask DropNewest failure, got {other:?}").into()),
1549 }
1550 }
1551
1552 #[test]
1553 fn max_ask_waits_rejects_extra_park() -> Result<(), Box<dyn std::error::Error>> {
1554 use crate::bytecode::Program;
1555
1556 let mut program = Program::new("ask-limit");
1557 let silent = program.function("silent", 0, |f| {
1558 let _req = f.receive();
1560 let loop_lbl = f.label();
1561 f.bind(loop_lbl);
1562 let ms = f.load_i32(50);
1563 f.sleep(ms);
1564 f.jump(loop_lbl);
1565 });
1566 let asker = program.function("asker", 1, |f| {
1567 let server = f.reg(0);
1568 let z = f.load_i32(0);
1569 let req = f.hop_fresh(1, z);
1570 let reply = f.ask(server, req);
1571 f.return_(reply);
1572 });
1573 let chunk = program.build();
1574
1575 let rt = Runtime::with_natives_and_config(
1576 chunk,
1577 crate::std_native_table(),
1578 RuntimeConfig {
1579 workers: 2,
1580 quantum: 1_000,
1581 mailbox: MailboxConfig::DEFAULT,
1582 max_ask_waits: 1,
1583 ..Default::default()
1584 },
1585 )?;
1586
1587 let server = rt.spawn(silent, &[])?;
1588 let server_cap = rt.mint_cap(server.id())?;
1589 let first = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1590 std::thread::sleep(Duration::from_millis(30));
1592 let second = rt.spawn(asker, &[Value::Cap(server_cap)])?;
1593 let second_out = second.join_timeout(Duration::from_secs(2));
1594 rt.kill(server.id())?;
1595 let _ = first.join_timeout(Duration::from_millis(500));
1596 let _ = server.join_timeout(Duration::from_millis(500));
1597 rt.shutdown();
1598
1599 match second_out {
1600 Some(FlowOutcome::Failed(msg)) if msg.contains("Ask wait limit") => Ok(()),
1601 other => Err(format!("expected Ask wait limit failure, got {other:?}").into()),
1602 }
1603 }
1604
1605 #[cfg(feature = "jit")]
1608 #[test]
1609 fn runtime_with_jit_enabled_completes_add() -> Result<(), Box<dyn std::error::Error>> {
1610 use crate::JitConfig;
1611
1612 let rt = Runtime::with_config(
1613 add_chunk(),
1614 RuntimeConfig {
1615 workers: 1,
1616 quantum: 1_000,
1617 mailbox: MailboxConfig::DEFAULT,
1618 jit: JitConfig {
1619 enabled: true,
1620 hot_threshold: 1,
1621 },
1622 ..Default::default()
1623 },
1624 )?;
1625 let outcome = rt.spawn(0, &[])?.join();
1626 rt.shutdown();
1627 match outcome {
1628 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1629 other => Err(format!("unexpected outcome: {other:?}").into()),
1630 }
1631 }
1632
1633 #[test]
1634 fn sandbox_enables_process_wide_relation_caps() {
1635 let config = RuntimeConfig::sandbox();
1636 assert_eq!(config.max_flows, 256);
1637 assert_eq!(config.max_ask_waits, 128);
1638 assert_eq!(config.max_host_awaits, 128);
1639 assert_eq!(config.max_links, 1024);
1640 assert_eq!(config.max_monitors, 1024);
1641 assert_eq!(config.max_registry_names, 256);
1642 assert!(config.paranoid_jumps);
1643 assert_eq!(config.max_runtime_bytes, 64 * 1024 * 1024);
1644 }
1645
1646 #[test]
1647 fn default_remains_unlimited_for_relation_caps() {
1648 let config = RuntimeConfig::default();
1649 assert_eq!(config.max_links, 0);
1650 assert_eq!(config.max_monitors, 0);
1651 assert_eq!(config.max_registry_names, 0);
1652 assert!(!config.paranoid_jumps);
1653 }
1654
1655 #[test]
1656 fn with_attested_mismatch_is_attestation_error() -> Result<(), Box<dyn std::error::Error>> {
1657 use crate::bytecode::encode;
1658 use crate::{fingerprint_bf, AttestError};
1659
1660 let bytes = encode(&add_chunk());
1661 let mut bad = fingerprint_bf(&bytes);
1662 bad[0] ^= 0xff;
1663 match Runtime::with_attested(&bytes, bad, NativeTable::empty(), RuntimeConfig::default()) {
1664 Err(SpawnError::Attestation(AttestError::DigestMismatch { .. })) => Ok(()),
1665 Ok(_) => Err("expected Attestation error, got Ok(Runtime)".into()),
1666 Err(e) => Err(format!("expected Attestation(DigestMismatch), got Err({e})").into()),
1667 }
1668 }
1669
1670 #[test]
1671 fn with_attested_match_runs() -> Result<(), Box<dyn std::error::Error>> {
1672 use crate::bytecode::encode;
1673 use crate::fingerprint_bf;
1674
1675 let chunk = add_chunk();
1676 let bytes = encode(&chunk);
1677 let digest = fingerprint_bf(&bytes);
1678 let rt = Runtime::with_attested(
1679 &bytes,
1680 digest,
1681 NativeTable::empty(),
1682 RuntimeConfig {
1683 workers: 1,
1684 quantum: 1_000,
1685 mailbox: MailboxConfig::DEFAULT,
1686 ..Default::default()
1687 },
1688 )?;
1689 let outcome = rt.spawn(0, &[])?.join();
1690 rt.shutdown();
1691 match outcome {
1692 FlowOutcome::Completed(Value::Int(42)) => Ok(()),
1693 other => Err(format!("expected 42, got {other:?}").into()),
1694 }
1695 }
1696
1697 #[test]
1698 fn untrusted_enables_paranoid_jumps_on_shared() -> Result<(), Box<dyn std::error::Error>> {
1699 let rt = Runtime::with_config(
1702 add_chunk(),
1703 RuntimeConfig {
1704 workers: 1,
1705 quantum: 1_000,
1706 mailbox: MailboxConfig::DEFAULT,
1707 trust: crate::bytecode::TrustLevel::Untrusted,
1708 paranoid_jumps: false,
1709 ..Default::default()
1710 },
1711 )?;
1712 assert!(rt.shared.paranoid_jumps);
1713 rt.shutdown();
1714 Ok(())
1715 }
1716}