1#![allow(missing_docs)]
18
19use std::collections::VecDeque;
20use std::sync::atomic::{AtomicUsize, Ordering};
21use std::sync::{Arc, Condvar, Mutex};
22
23use crate::bytecode::{CapId, Message, Value};
24
25use super::error::RuntimeError;
26use super::process::FlowId;
27use super::sync_lock;
28
29pub const DEFAULT_MAX_PENDING_HOPS: usize = 1024;
31pub const DEFAULT_MAX_PENDING_BYTES: usize = 64 * 1024 * 1024;
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct DistributionConfig {
37 pub max_pending_hops: usize,
39 pub max_pending_bytes: usize,
41}
42
43impl Default for DistributionConfig {
44 fn default() -> Self {
45 Self {
46 max_pending_hops: DEFAULT_MAX_PENDING_HOPS,
47 max_pending_bytes: DEFAULT_MAX_PENDING_BYTES,
48 }
49 }
50}
51
52#[derive(Debug)]
57struct BridgeCharge {
58 accounts: Arc<BridgeAccounts>,
59 bytes: usize,
60}
61
62impl Drop for BridgeCharge {
63 fn drop(&mut self) {
64 self.accounts.release(self.bytes);
65 }
66}
67
68#[derive(Debug)]
69struct BridgeAccounts {
70 hops: AtomicUsize,
71 bytes: AtomicUsize,
72 max_hops: usize,
73 max_bytes: usize,
74}
75
76impl BridgeAccounts {
77 fn try_charge(self: &Arc<Self>, bytes: usize) -> Result<BridgeCharge, ()> {
78 loop {
79 let hops = self.hops.load(Ordering::Acquire);
80 if hops >= self.max_hops {
81 return Err(());
82 }
83 let used = self.bytes.load(Ordering::Acquire);
84 let Some(next_bytes) = used.checked_add(bytes) else {
85 return Err(());
86 };
87 if next_bytes > self.max_bytes {
88 return Err(());
89 }
90 if self
91 .hops
92 .compare_exchange_weak(hops, hops + 1, Ordering::AcqRel, Ordering::Acquire)
93 .is_err()
94 {
95 continue;
96 }
97 if self
98 .bytes
99 .compare_exchange_weak(used, next_bytes, Ordering::AcqRel, Ordering::Acquire)
100 .is_err()
101 {
102 self.hops.fetch_sub(1, Ordering::AcqRel);
103 continue;
104 }
105 return Ok(BridgeCharge {
106 accounts: Arc::clone(self),
107 bytes,
108 });
109 }
110 }
111
112 fn release(&self, bytes: usize) {
113 self.hops.fetch_sub(1, Ordering::AcqRel);
114 loop {
116 let cur = self.bytes.load(Ordering::Acquire);
117 let next = cur.saturating_sub(bytes);
118 if self
119 .bytes
120 .compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire)
121 .is_ok()
122 {
123 break;
124 }
125 }
126 }
127
128 fn pending_hops(&self) -> usize {
129 self.hops.load(Ordering::Relaxed)
130 }
131
132 fn pending_bytes(&self) -> usize {
133 self.bytes.load(Ordering::Relaxed)
134 }
135}
136
137#[derive(Debug)]
142pub struct OutboundHop {
143 pub sender: FlowId,
144 pub node: u64,
146 pub name: Arc<str>,
147 pub message: Message,
148 charge: Option<BridgeCharge>,
149}
150
151impl OutboundHop {
152 pub fn new(sender: FlowId, node: u64, name: Arc<str>, message: Message) -> Self {
154 Self {
155 sender,
156 node,
157 name,
158 message,
159 charge: None,
160 }
161 }
162}
163
164fn hop_byte_cost(hop: &OutboundHop) -> usize {
165 std::mem::size_of::<OutboundHop>()
166 .saturating_add(hop.name.len())
167 .saturating_add(Value::Message(hop.message.clone()).memory_size())
168}
169
170#[derive(Debug)]
177pub struct DistributionBridge {
178 queue: Mutex<VecDeque<OutboundHop>>,
179 ready: Condvar,
180 accounts: Arc<BridgeAccounts>,
181}
182
183impl DistributionBridge {
184 pub fn new() -> Arc<Self> {
185 Self::with_config(DistributionConfig::default())
186 }
187
188 pub fn with_config(cfg: DistributionConfig) -> Arc<Self> {
189 Arc::new(Self {
190 queue: Mutex::new(VecDeque::new()),
191 ready: Condvar::new(),
192 accounts: Arc::new(BridgeAccounts {
193 hops: AtomicUsize::new(0),
194 bytes: AtomicUsize::new(0),
195 max_hops: cfg.max_pending_hops.max(1),
196 max_bytes: cfg.max_pending_bytes.max(1),
197 }),
198 })
199 }
200
201 pub(crate) fn push(&self, mut hop: OutboundHop) -> Result<(), String> {
202 let bytes = hop_byte_cost(&hop);
203 let charge = self
204 .accounts
205 .try_charge(bytes)
206 .map_err(|()| "distribution bridge full".to_string())?;
207 hop.charge = Some(charge);
208 let mut queue =
209 sync_lock::lock(&self.queue, "DistributionBridge::push").map_err(|e| e.to_string())?;
210 queue.push_back(hop);
211 self.ready.notify_one();
212 Ok(())
213 }
214
215 pub fn try_recv(&self) -> Result<Option<OutboundHop>, RuntimeError> {
219 let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::try_recv")?;
220 Ok(queue.pop_front())
221 }
222
223 pub fn outbound_pending(&self) -> Result<usize, RuntimeError> {
225 let queue = sync_lock::lock(&self.queue, "DistributionBridge::outbound_pending")?;
226 Ok(queue.len())
227 }
228
229 pub fn pending_charged_hops(&self) -> usize {
231 self.accounts.pending_hops()
232 }
233
234 pub fn pending_charged_bytes(&self) -> usize {
236 self.accounts.pending_bytes()
237 }
238
239 pub fn recv_timeout(
241 &self,
242 timeout: std::time::Duration,
243 ) -> Result<Option<OutboundHop>, RuntimeError> {
244 let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::recv_timeout")?;
245 let start = std::time::Instant::now();
246 loop {
247 if let Some(hop) = queue.pop_front() {
248 return Ok(Some(hop));
249 }
250 let left = match timeout.checked_sub(start.elapsed()) {
251 Some(left) => left,
252 None => return Ok(None),
253 };
254 let (guard, status) =
255 sync_lock::wait_timeout(&self.ready, queue, left, "DistributionBridge::wait")?;
256 queue = guard;
257 if status.timed_out() && queue.is_empty() {
258 return Ok(None);
259 }
260 }
261 }
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub enum DedupState {
267 Pending,
269 Accepted,
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub enum DedupTicket {
276 Fresh { sender: u64, request_id: u64 },
278 Duplicate,
280}
281
282#[derive(Debug)]
289pub struct RemoteFrameDedup {
290 capacity: usize,
291 seen: Mutex<VecDeque<(u64, u64, DedupState)>>,
292 wait: Condvar,
293}
294
295impl RemoteFrameDedup {
296 pub fn new(capacity: usize) -> Arc<Self> {
297 Arc::new(RemoteFrameDedup {
298 capacity: capacity.max(1),
299 seen: Mutex::new(VecDeque::new()),
300 wait: Condvar::new(),
301 })
302 }
303
304 pub fn reserve(&self, sender: u64, request_id: u64) -> Result<DedupTicket, RuntimeError> {
309 let mut queue = sync_lock::lock(&self.seen, "RemoteFrameDedup::reserve")?;
310 loop {
311 if let Some(idx) = queue
312 .iter()
313 .position(|&(s, id, _)| s == sender && id == request_id)
314 {
315 match queue[idx].2 {
316 DedupState::Accepted => return Ok(DedupTicket::Duplicate),
317 DedupState::Pending => {
318 queue = sync_lock::wait(&self.wait, queue, "RemoteFrameDedup::wait")?;
319 continue;
320 }
321 }
322 }
323 queue.push_back((sender, request_id, DedupState::Pending));
324 Self::evict_accepted(&mut queue, self.capacity);
325 return Ok(DedupTicket::Fresh { sender, request_id });
326 }
327 }
328
329 pub fn commit(&self, sender: u64, request_id: u64) -> Result<(), RuntimeError> {
331 let mut queue = sync_lock::lock(&self.seen, "RemoteFrameDedup::commit")?;
332 if let Some(entry) = queue
333 .iter_mut()
334 .find(|&&mut (s, id, _)| s == sender && id == request_id)
335 {
336 entry.2 = DedupState::Accepted;
337 }
338 Self::evict_accepted(&mut queue, self.capacity);
339 self.wait.notify_all();
340 Ok(())
341 }
342
343 pub fn rollback(&self, sender: u64, request_id: u64) -> Result<(), RuntimeError> {
345 let mut queue = sync_lock::lock(&self.seen, "RemoteFrameDedup::rollback")?;
346 queue.retain(|&(s, id, state)| {
347 !(s == sender && id == request_id && state == DedupState::Pending)
348 });
349 self.wait.notify_all();
350 Ok(())
351 }
352
353 fn evict_accepted(queue: &mut VecDeque<(u64, u64, DedupState)>, capacity: usize) {
356 while queue.len() > capacity {
357 let Some(front) = queue.front() else {
358 break;
359 };
360 if front.2 == DedupState::Pending {
361 break;
362 }
363 queue.pop_front();
364 }
365 }
366}
367
368pub(crate) fn stamp(message: Message, sender: FlowId) -> Message {
370 message.authenticate(sender.as_u64(), CapId::NONE)
371}
372
373pub(crate) fn deliver(
375 shared: &super::runtime::Shared,
376 flow: &mut super::process::Flow,
377 node: u64,
378 name: Arc<str>,
379 message: Value,
380) -> Result<(), String> {
381 if !flow.authority.rights().contains(crate::CapRights::SEND) {
382 return Err("send_remote denied: flow lacks SEND right".into());
383 }
384 let Some(bridge) = shared.distribution.as_ref() else {
385 return Err("send_remote: no distribution bridge".into());
386 };
387 let Some(mut msg) = message.as_message().cloned() else {
388 return Err("send_remote: value is not a hop".into());
389 };
390 if !msg.payload.within_nesting_limit() {
391 return Err("send_remote: payload too nested".into());
392 }
393 if msg.payload.contains_live_cap(0) {
394 return Err("send_remote: payload contains a local capability".into());
395 }
396 if let Err(e) = flow.quota.check_send() {
397 return Err(e.to_string());
398 }
399 if msg.request_id == 0 {
400 msg.request_id = flow.vm.fresh_request_id();
401 }
402 let Some(payload) = msg
403 .payload
404 .stamp_unset_envelopes(0, flow.id.as_u64(), &mut || flow.vm.fresh_request_id())
405 else {
406 return Err("send_remote: payload too nested".into());
407 };
408 let stamped = stamp(msg.with_payload(payload), flow.id);
409 bridge.push(OutboundHop::new(flow.id, node, name, stamped))
410}
411
412const FRAME_MAGIC: [u8; 4] = *b"BFH1";
413const FRAME_VERSION: u8 = 1;
414const MAX_FRAME_NAME: usize = 256;
415
416#[derive(Debug, Clone, PartialEq, Eq)]
418pub enum RemoteFrameError {
419 BadMagic,
420 Truncated,
421 BadVersion,
422 BadUtf8,
423 LiveCapability,
425 SenderZero,
427 SenderMismatch,
429 Name,
430 Unsupported,
431 NoSuchName,
432 Mailbox(super::mailbox::MailboxFullReason),
433 Unavailable,
434}
435
436impl std::fmt::Display for RemoteFrameError {
437 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
438 match self {
439 Self::BadMagic => f.write_str("remote frame magic"),
440 Self::Truncated => f.write_str("remote frame truncated"),
441 Self::BadVersion => f.write_str("remote frame version"),
442 Self::BadUtf8 => f.write_str("remote frame name"),
443 Self::LiveCapability => f.write_str("remote frame carried a local capability"),
444 Self::SenderZero => f.write_str("remote frame sender is the local host"),
445 Self::SenderMismatch => f.write_str("remote frame sender does not match the envelope"),
446 Self::Name => f.write_str("remote frame name"),
447 Self::Unsupported => f.write_str("remote frame value"),
448 Self::NoSuchName => f.write_str("remote frame name is not registered"),
449 Self::Mailbox(reason) => write!(f, "remote frame mailbox ({reason})"),
450 Self::Unavailable => f.write_str("remote frame unavailable"),
451 }
452 }
453}
454
455impl std::error::Error for RemoteFrameError {}
456
457pub fn encode_frame(hop: &OutboundHop) -> Result<Vec<u8>, RemoteFrameError> {
459 if hop.sender.is_host() {
460 return Err(RemoteFrameError::SenderZero);
461 }
462 if hop.name.is_empty() || hop.name.len() > MAX_FRAME_NAME {
463 return Err(RemoteFrameError::Name);
464 }
465 if hop.message.sender != hop.sender.as_u64() {
466 return Err(frame_sender_error(hop.message.sender));
467 }
468 screen_message(&hop.message, 0)?;
469 let mut out = Vec::with_capacity(32 + hop.name.len());
470 out.extend_from_slice(&FRAME_MAGIC);
471 out.push(FRAME_VERSION);
472 out.extend_from_slice(&hop.node.to_le_bytes());
473 out.extend_from_slice(&(hop.name.len() as u16).to_le_bytes());
474 out.extend_from_slice(hop.name.as_bytes());
475 out.extend_from_slice(&hop.sender.as_u64().to_le_bytes());
476 out.extend_from_slice(&crate::bytecode::encode_value(&Value::Message(
477 hop.message.clone(),
478 )));
479 Ok(out)
480}
481
482pub fn decode_frame(bytes: &[u8]) -> Result<OutboundHop, RemoteFrameError> {
484 let mut pos = 0usize;
485 let magic: [u8; 4] = take(bytes, &mut pos)?;
486 if magic != FRAME_MAGIC {
487 return Err(RemoteFrameError::BadMagic);
488 }
489 let version: [u8; 1] = take(bytes, &mut pos)?;
490 if version[0] != FRAME_VERSION {
491 return Err(RemoteFrameError::BadVersion);
492 }
493 let node = u64::from_le_bytes(take(bytes, &mut pos)?);
494 let name_len = u16::from_le_bytes(take(bytes, &mut pos)?) as usize;
495 if name_len == 0 || name_len > MAX_FRAME_NAME {
496 return Err(RemoteFrameError::Name);
497 }
498 let name_bytes = take_slice(bytes, &mut pos, name_len)?;
499 let name = std::str::from_utf8(name_bytes).map_err(|_| RemoteFrameError::BadUtf8)?;
500 let sender = u64::from_le_bytes(take(bytes, &mut pos)?);
501 if sender == 0 {
502 return Err(RemoteFrameError::SenderZero);
503 }
504 let (value, consumed) =
505 crate::bytecode::decode_value(&bytes[pos..]).map_err(frame_format_error)?;
506 if consumed != bytes.len() - pos {
507 return Err(RemoteFrameError::Unsupported);
508 }
509 let Value::Message(message) = value else {
510 return Err(RemoteFrameError::Unsupported);
511 };
512 if message.sender != sender {
513 return Err(frame_sender_error(message.sender));
514 }
515 screen_message(&message, 0)?;
516 Ok(OutboundHop::new(
517 FlowId(sender),
518 node,
519 Arc::from(name),
520 message,
521 ))
522}
523
524fn frame_sender_error(message_sender: u64) -> RemoteFrameError {
525 if message_sender == 0 {
526 RemoteFrameError::SenderZero
527 } else {
528 RemoteFrameError::SenderMismatch
529 }
530}
531
532fn take<const N: usize>(data: &[u8], pos: &mut usize) -> Result<[u8; N], RemoteFrameError> {
533 let slice = take_slice(data, pos, N)?;
534 let mut out = [0u8; N];
535 out.copy_from_slice(slice);
536 Ok(out)
537}
538
539fn take_slice<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], RemoteFrameError> {
540 let end = pos.checked_add(n).ok_or(RemoteFrameError::Truncated)?;
541 if end > data.len() {
542 return Err(RemoteFrameError::Truncated);
543 }
544 let slice = &data[*pos..end];
545 *pos = end;
546 Ok(slice)
547}
548
549fn frame_format_error(err: crate::bytecode::FormatError) -> RemoteFrameError {
550 match err {
551 crate::bytecode::FormatError::Truncated => RemoteFrameError::Truncated,
552 crate::bytecode::FormatError::BadUtf8 => RemoteFrameError::BadUtf8,
553 crate::bytecode::FormatError::UnknownValueTag(4 | 6) => RemoteFrameError::LiveCapability,
554 _ => RemoteFrameError::Unsupported,
555 }
556}
557
558fn screen_message(message: &Message, depth: u32) -> Result<(), RemoteFrameError> {
559 if depth > crate::bytecode::MAX_VALUE_DEPTH {
560 return Err(RemoteFrameError::Unsupported);
561 }
562 if !message.reply_cap.is_none() {
563 return Err(RemoteFrameError::LiveCapability);
564 }
565 screen_value(message.payload.as_ref(), depth + 1)
566}
567
568fn screen_value(value: &Value, depth: u32) -> Result<(), RemoteFrameError> {
569 if depth > crate::bytecode::MAX_VALUE_DEPTH {
570 return Err(RemoteFrameError::Unsupported);
571 }
572 match value {
573 Value::Pid(_) | Value::Cap(_) => Err(RemoteFrameError::LiveCapability),
574 Value::Message(message) => screen_message(message, depth),
575 Value::List(items) => {
576 if items.len() > crate::bytecode::MAX_LIST_LEN {
577 return Err(RemoteFrameError::Unsupported);
578 }
579 items
580 .iter()
581 .try_for_each(|item| screen_value(item, depth + 1))
582 }
583 Value::Record(fields) => {
584 if fields.len() > crate::bytecode::MAX_RECORD_LEN {
585 return Err(RemoteFrameError::Unsupported);
586 }
587 fields
588 .iter()
589 .try_for_each(|field| screen_value(field, depth + 1))
590 }
591 Value::Map(entries) => {
592 if entries.len() > crate::bytecode::MAX_MAP_LEN {
593 return Err(RemoteFrameError::Unsupported);
594 }
595 entries
596 .iter()
597 .try_for_each(|(_, item)| screen_value(item, depth + 1))
598 }
599 Value::Unit
600 | Value::Bool(_)
601 | Value::Int(_)
602 | Value::Float(_)
603 | Value::Str(_)
604 | Value::Bytes(_) => Ok(()),
605 }
606}
607
608#[cfg(test)]
609#[allow(clippy::expect_used, clippy::unwrap_used)]
610mod tests {
611 use std::time::Duration;
612
613 use crate::{FlowOutcome, Program, Runtime, RuntimeConfig, Value};
614
615 use super::*;
616
617 #[test]
618 fn host_drains_a_remote_hop() -> Result<(), Box<dyn std::error::Error>> {
619 let bridge = DistributionBridge::new();
620 let mut program = Program::new("remote");
621 program.function("main", 0, |f| {
622 let node = f.load_i32(7);
623 let name = f.load_str("svc");
624 let payload = f.load_i32(41);
625 let msg = f.hop_fresh(3, payload);
626 f.send_remote(node, name, msg);
627 f.return_(payload);
628 });
629 let rt = Runtime::with_natives_and_config(
630 program.build(),
631 crate::std_native_table(),
632 RuntimeConfig {
633 distribution: Some(Arc::clone(&bridge)),
634 workers: 1,
635 ..RuntimeConfig::default()
636 },
637 )?;
638 let outcome = rt.spawn(0, &[])?.join();
639 rt.shutdown();
640 match outcome {
641 FlowOutcome::Completed(Value::Int(41)) => {}
642 other => return Err(format!("remote send failed: {other:?}").into()),
643 }
644 let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
645 Some(hop) => hop,
646 None => return Err("bridge empty".into()),
647 };
648 if hop.node != 7 || hop.name.as_ref() != "svc" {
649 return Err(format!("unexpected route {hop:?}").into());
650 }
651 if hop.message.reply_cap != CapId::NONE {
652 return Err("remote hop minted a local reply cap".into());
653 }
654 if !matches!(hop.message.payload.as_ref(), Value::Int(41)) {
655 return Err(format!("payload {:?}", hop.message.payload).into());
656 }
657 Ok(())
658 }
659
660 #[test]
661 fn a_live_cap_in_the_payload_does_not_leave_the_node() -> Result<(), Box<dyn std::error::Error>>
662 {
663 let bridge = DistributionBridge::new();
664 let mut program = Program::new("remote-cap");
665 program.function("main", 0, |f| {
666 let node = f.load_i32(7);
667 let name = f.load_str("svc");
668 let me = f.self_cap();
669 let msg = f.hop_fresh(3, me);
670 f.send_remote(node, name, msg);
671 f.return_(node);
672 });
673 let rt = Runtime::with_natives_and_config(
674 program.build(),
675 crate::std_native_table(),
676 RuntimeConfig {
677 distribution: Some(Arc::clone(&bridge)),
678 workers: 1,
679 ..RuntimeConfig::default()
680 },
681 )?;
682 let outcome = rt.spawn(0, &[])?.join();
683 rt.shutdown();
684 match outcome {
685 FlowOutcome::Failed(reason) if reason.contains("local capability") => {}
686 other => return Err(format!("expected a refused remote cap, got {other:?}").into()),
687 }
688 if bridge.try_recv()?.is_some() {
689 return Err("bridge accepted a hop that carried a capability".into());
690 }
691 Ok(())
692 }
693
694 #[test]
695 fn remote_nested_envelope_is_stamped_with_the_flow() -> Result<(), Box<dyn std::error::Error>> {
696 let bridge = DistributionBridge::new();
697 let mut program = Program::new("remote-nested");
698 program.function("main", 0, |f| {
699 let node = f.load_i32(7);
700 let name = f.load_str("svc");
701 let body = f.load_i32(1);
702 let inner = f.hop_fresh(1, body);
703 let outer = f.hop_fresh(2, inner);
704 f.send_remote(node, name, outer);
705 f.return_(node);
706 });
707 let rt = Runtime::with_natives_and_config(
708 program.build(),
709 crate::std_native_table(),
710 RuntimeConfig {
711 distribution: Some(Arc::clone(&bridge)),
712 workers: 1,
713 ..RuntimeConfig::default()
714 },
715 )?;
716 let outcome = rt.spawn(0, &[])?.join();
717 rt.shutdown();
718 if !matches!(outcome, FlowOutcome::Completed(Value::Int(7))) {
719 return Err(format!("remote nested send failed: {outcome:?}").into());
720 }
721 let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
722 Some(hop) => hop,
723 None => return Err("bridge empty".into()),
724 };
725 let Some(inner) = hop.message.payload.as_message() else {
726 return Err(format!("payload {:?}", hop.message.payload).into());
727 };
728 if inner.sender != hop.sender.as_u64() {
729 return Err(format!("nested sender {} hop {}", inner.sender, hop.sender).into());
730 }
731 if !inner.reply_cap.is_none() {
732 return Err("remote nested hop minted a local reply cap".into());
733 }
734 Ok(())
735 }
736
737 #[test]
738 fn frame_keeps_the_declared_sender() -> Result<(), RemoteFrameError> {
739 use crate::CapId;
740 let hop = OutboundHop::new(
741 FlowId(9),
742 3,
743 std::sync::Arc::from("svc"),
744 Message::new(9, 4, 1, Value::Int(5)).authenticate(9, CapId::NONE),
745 );
746 let back = decode_frame(&encode_frame(&hop)?)?;
747 if back.sender.as_u64() != 9 || back.node != 3 || back.message.tag != 1 {
748 return Err(RemoteFrameError::Unsupported);
749 }
750 if !matches!(back.message.payload.as_ref(), Value::Int(5)) {
751 return Err(RemoteFrameError::Unsupported);
752 }
753 Ok(())
754 }
755
756 #[test]
757 fn frame_round_trips_a_record_without_a_cap() -> Result<(), RemoteFrameError> {
758 use crate::CapId;
759 let record = Value::try_record(vec![Value::Int(1), Value::Int(2)])
760 .ok_or(RemoteFrameError::Unsupported)?;
761 let hop = OutboundHop::new(
762 FlowId(9),
763 3,
764 std::sync::Arc::from("svc"),
765 Message::new(9, 4, 1, record).authenticate(9, CapId::NONE),
766 );
767 let back = decode_frame(&encode_frame(&hop)?)?;
768 if back.sender.as_u64() != 9 || !back.message.reply_cap.is_none() {
769 return Err(RemoteFrameError::Unsupported);
770 }
771 match back.message.payload.as_ref() {
772 Value::Record(fields) if fields.len() == 2 => Ok(()),
773 _ => Err(RemoteFrameError::Unsupported),
774 }
775 }
776
777 #[test]
778 fn frame_rejects_a_live_cap() {
779 use crate::CapId;
780 let hop = OutboundHop::new(
781 FlowId(9),
782 1,
783 std::sync::Arc::from("svc"),
784 Message::new(9, 1, 1, Value::Cap(CapId::from_raw(1))).authenticate(9, CapId::NONE),
785 );
786 assert!(matches!(
787 encode_frame(&hop),
788 Err(RemoteFrameError::LiveCapability)
789 ));
790 }
791
792 #[test]
793 fn frame_rejects_a_list_past_the_cap() {
794 let hop = OutboundHop::new(
795 FlowId(9),
796 1,
797 std::sync::Arc::from("svc"),
798 Message::new(
799 9,
800 1,
801 1,
802 Value::List(std::sync::Arc::from(vec![Value::Int(1); 257])),
803 )
804 .authenticate(9, crate::CapId::NONE),
805 );
806 assert!(matches!(
807 encode_frame(&hop),
808 Err(RemoteFrameError::Unsupported)
809 ));
810 }
811
812 #[test]
813 fn frame_accepts_a_list_at_the_cap() -> Result<(), RemoteFrameError> {
814 let list =
815 Value::try_list(vec![Value::Int(1); 256]).ok_or(RemoteFrameError::Unsupported)?;
816 let hop = OutboundHop::new(
817 FlowId(9),
818 1,
819 std::sync::Arc::from("svc"),
820 Message::new(9, 1, 1, list).authenticate(9, crate::CapId::NONE),
821 );
822 encode_frame(&hop).map(|_| ())
823 }
824
825 #[test]
826 fn bridge_rejects_when_hop_count_exhausted() -> Result<(), Box<dyn std::error::Error>> {
827 let bridge = DistributionBridge::with_config(DistributionConfig {
828 max_pending_hops: 2,
829 max_pending_bytes: DEFAULT_MAX_PENDING_BYTES,
830 });
831 let mk = |rid| {
832 OutboundHop::new(
833 FlowId(1),
834 1,
835 Arc::from("svc"),
836 Message::new(1, rid, 1, Value::Int(1)).authenticate(1, CapId::NONE),
837 )
838 };
839 bridge.push(mk(1))?;
840 bridge.push(mk(2))?;
841 match bridge.push(mk(3)) {
842 Err(msg) if msg.contains("full") => {}
843 other => return Err(format!("expected full, got {other:?}").into()),
844 }
845 assert_eq!(bridge.pending_charged_hops(), 2);
846 let _ = bridge.try_recv()?;
847 assert_eq!(bridge.pending_charged_hops(), 1);
848 bridge.push(mk(4))?;
849 Ok(())
850 }
851
852 #[test]
853 fn bridge_rejects_when_byte_budget_exhausted() -> Result<(), Box<dyn std::error::Error>> {
854 let probe = OutboundHop::new(
855 FlowId(1),
856 1,
857 Arc::from("svc"),
858 Message::new(1, 1, 1, Value::Bytes(Arc::<[u8]>::from(vec![0u8; 400])))
859 .authenticate(1, CapId::NONE),
860 );
861 let one = hop_byte_cost(&probe);
862 let bridge = DistributionBridge::with_config(DistributionConfig {
863 max_pending_hops: 64,
864 max_pending_bytes: one,
866 });
867 bridge.push(probe)?;
868 let again = OutboundHop::new(
869 FlowId(1),
870 1,
871 Arc::from("svc"),
872 Message::new(1, 2, 1, Value::Bytes(Arc::<[u8]>::from(vec![0u8; 400])))
873 .authenticate(1, CapId::NONE),
874 );
875 match bridge.push(again) {
876 Err(msg) if msg.contains("full") => {}
877 other => return Err(format!("expected byte full, got {other:?}").into()),
878 }
879 let held = bridge.try_recv()?.ok_or("empty")?;
880 assert!(bridge.pending_charged_bytes() > 0);
881 drop(held);
882 assert_eq!(bridge.pending_charged_bytes(), 0);
883 assert_eq!(bridge.pending_charged_hops(), 0);
884 Ok(())
885 }
886
887 #[test]
888 fn bridge_charge_survives_after_recv_until_drop() -> Result<(), Box<dyn std::error::Error>> {
889 let bridge = DistributionBridge::with_config(DistributionConfig {
890 max_pending_hops: 1,
891 max_pending_bytes: DEFAULT_MAX_PENDING_BYTES,
892 });
893 bridge.push(OutboundHop::new(
894 FlowId(1),
895 1,
896 Arc::from("svc"),
897 Message::new(1, 1, 1, Value::Int(1)).authenticate(1, CapId::NONE),
898 ))?;
899 let hop = bridge.try_recv()?.ok_or("empty")?;
900 assert_eq!(bridge.outbound_pending()?, 0);
901 assert_eq!(bridge.pending_charged_hops(), 1);
902 match bridge.push(OutboundHop::new(
903 FlowId(1),
904 1,
905 Arc::from("svc"),
906 Message::new(1, 2, 1, Value::Int(2)).authenticate(1, CapId::NONE),
907 )) {
908 Err(msg) if msg.contains("full") => {}
909 other => return Err(format!("host-held hop should keep slot, got {other:?}").into()),
910 }
911 drop(hop);
912 bridge.push(OutboundHop::new(
913 FlowId(1),
914 1,
915 Arc::from("svc"),
916 Message::new(1, 3, 1, Value::Int(3)).authenticate(1, CapId::NONE),
917 ))?;
918 Ok(())
919 }
920
921 #[test]
922 fn remote_frame_dedup_commit_makes_replay_duplicate() -> Result<(), RuntimeError> {
923 let dedup = RemoteFrameDedup::new(4);
924 let DedupTicket::Fresh { sender, request_id } = dedup.reserve(1, 100)? else {
925 panic!("expected Fresh");
926 };
927 dedup.commit(sender, request_id)?;
928 assert_eq!(dedup.reserve(1, 100)?, DedupTicket::Duplicate);
929 assert!(matches!(dedup.reserve(1, 101)?, DedupTicket::Fresh { .. }));
930 Ok(())
931 }
932
933 #[test]
934 fn remote_frame_dedup_rollback_allows_retry() -> Result<(), RuntimeError> {
935 let dedup = RemoteFrameDedup::new(4);
936 let DedupTicket::Fresh { sender, request_id } = dedup.reserve(1, 100)? else {
937 panic!("expected Fresh");
938 };
939 dedup.rollback(sender, request_id)?;
940 assert!(matches!(dedup.reserve(1, 100)?, DedupTicket::Fresh { .. }));
941 Ok(())
942 }
943
944 #[test]
945 fn remote_frame_dedup_concurrent_pending_serializes() -> Result<(), RuntimeError> {
946 use std::sync::Barrier;
947 use std::thread;
948 let dedup = RemoteFrameDedup::new(8);
949 let barrier = Arc::new(Barrier::new(2));
950 let d1 = Arc::clone(&dedup);
951 let b1 = Arc::clone(&barrier);
952 let t1 = thread::spawn(move || -> Result<DedupTicket, RuntimeError> {
953 let ticket = d1.reserve(9, 42)?;
954 b1.wait();
955 thread::sleep(Duration::from_millis(30));
956 if let DedupTicket::Fresh { sender, request_id } = ticket {
957 d1.commit(sender, request_id)?;
958 }
959 Ok(ticket)
960 });
961 let d2 = Arc::clone(&dedup);
962 let b2 = Arc::clone(&barrier);
963 let t2 = thread::spawn(move || -> Result<DedupTicket, RuntimeError> {
964 b2.wait();
965 d2.reserve(9, 42)
966 });
967 let a = t1.join().expect("t1")?;
968 let b = t2.join().expect("t2")?;
969 let fresh = matches!(a, DedupTicket::Fresh { .. }) as u8
970 + matches!(b, DedupTicket::Fresh { .. }) as u8;
971 let dups =
972 matches!(a, DedupTicket::Duplicate) as u8 + matches!(b, DedupTicket::Duplicate) as u8;
973 assert_eq!(fresh, 1, "exactly one fresh reservation");
974 assert_eq!(dups, 1, "peer sees duplicate after commit");
975 Ok(())
976 }
977
978 #[test]
979 fn deliver_frame_retries_after_unknown_name() -> Result<(), Box<dyn std::error::Error>> {
980 use crate::CapId;
981 let mut program = Program::new("late");
982 program.function("main", 0, |f| {
983 let msg = f.receive();
984 let n = f.hop_payload(msg);
985 f.return_(n);
986 });
987 let rt = Runtime::with_natives_and_config(
988 program.build(),
989 crate::std_native_table(),
990 RuntimeConfig {
991 workers: 1,
992 remote_dedup_window: 32,
993 ..RuntimeConfig::default()
994 },
995 )?;
996 let handle = rt.spawn(0, &[])?;
997 let frame = encode_frame(&OutboundHop::new(
998 FlowId(44),
999 2,
1000 Arc::from("late"),
1001 Message::new(44, 1, 99, Value::Int(8)).authenticate(44, CapId::NONE),
1002 ))?;
1003 match rt.deliver_frame(&frame) {
1004 Err(RemoteFrameError::NoSuchName) => {}
1005 other => return Err(format!("expected NoSuchName, got {other:?}").into()),
1006 }
1007 let cap = rt.mint_cap(handle.id())?;
1008 rt.register_name("late", cap)?;
1009 rt.deliver_frame(&frame).map_err(|err| format!("{err:?}"))?;
1010 let outcome = handle
1011 .join_timeout(Duration::from_secs(2))
1012 .ok_or("retry after register timed out")?;
1013 rt.shutdown();
1014 match outcome {
1015 FlowOutcome::Completed(Value::Int(8)) => Ok(()),
1016 other => Err(format!("retry deliver: {other:?}").into()),
1017 }
1018 }
1019
1020 #[test]
1021 fn deliver_frame_retries_after_mailbox_full() -> Result<(), Box<dyn std::error::Error>> {
1022 use crate::scheduler::{MailboxCapacity, MailboxConfig, OverflowPolicy};
1023 use crate::CapId;
1024 let mut program = Program::new("full");
1025 program.function("main", 0, |f| {
1027 let delay = f.load_i32(500);
1028 f.sleep(delay);
1029 let _filler = f.receive();
1030 let msg = f.receive();
1031 let n = f.hop_payload(msg);
1032 f.return_(n);
1033 });
1034 let capacity = MailboxCapacity::new(1).ok_or("capacity")?;
1035 let rt = Runtime::with_natives_and_config(
1036 program.build(),
1037 crate::std_native_table(),
1038 RuntimeConfig {
1039 workers: 1,
1040 remote_dedup_window: 32,
1041 mailbox: MailboxConfig::new(capacity, OverflowPolicy::Reject),
1042 ..RuntimeConfig::default()
1043 },
1044 )?;
1045 let handle = rt.spawn(0, &[])?;
1046 let cap = rt.mint_cap(handle.id())?;
1047 rt.register_name("full", cap)?;
1048 std::thread::sleep(Duration::from_millis(50));
1049 let filler = encode_frame(&OutboundHop::new(
1051 FlowId(50),
1052 2,
1053 Arc::from("full"),
1054 Message::new(50, 1, 1, Value::Int(1)).authenticate(50, CapId::NONE),
1055 ))?;
1056 let target = encode_frame(&OutboundHop::new(
1057 FlowId(50),
1058 2,
1059 Arc::from("full"),
1060 Message::new(50, 99, 1, Value::Int(7)).authenticate(50, CapId::NONE),
1061 ))?;
1062 rt.deliver_frame(&filler)
1063 .map_err(|err| format!("filler: {err:?}"))?;
1064 match rt.deliver_frame(&target) {
1065 Err(RemoteFrameError::Mailbox(_)) => {}
1066 other => return Err(format!("expected Mailbox full, got {other:?}").into()),
1067 }
1068 std::thread::sleep(Duration::from_millis(600));
1070 rt.deliver_frame(&target)
1071 .map_err(|err| format!("retransmit: {err:?}"))?;
1072 let outcome = handle
1073 .join_timeout(Duration::from_secs(2))
1074 .ok_or("mailbox-full retry timed out")?;
1075 rt.shutdown();
1076 match outcome {
1077 FlowOutcome::Completed(Value::Int(7)) => Ok(()),
1078 other => Err(format!("mailbox-full retry: {other:?}").into()),
1079 }
1080 }
1081
1082 #[test]
1083 fn deliver_frame_accepted_replay_is_silent() -> Result<(), Box<dyn std::error::Error>> {
1084 use crate::CapId;
1085 let mut program = Program::new("once");
1086 program.function("main", 0, |f| {
1087 let msg = f.receive();
1088 let n = f.hop_payload(msg);
1089 f.return_(n);
1090 });
1091 let rt = Runtime::with_natives_and_config(
1092 program.build(),
1093 crate::std_native_table(),
1094 RuntimeConfig {
1095 workers: 1,
1096 remote_dedup_window: 32,
1097 ..RuntimeConfig::default()
1098 },
1099 )?;
1100 let handle = rt.spawn(0, &[])?;
1101 let cap = rt.mint_cap(handle.id())?;
1102 rt.register_name("once", cap)?;
1103 let frame = encode_frame(&OutboundHop::new(
1104 FlowId(44),
1105 2,
1106 Arc::from("once"),
1107 Message::new(44, 1, 7, Value::Int(8)).authenticate(44, CapId::NONE),
1108 ))?;
1109 rt.deliver_frame(&frame).map_err(|err| format!("{err:?}"))?;
1110 rt.deliver_frame(&frame)
1111 .map_err(|err| format!("replay: {err:?}"))?;
1112 let outcome = handle
1113 .join_timeout(Duration::from_secs(2))
1114 .ok_or("accepted replay timed out")?;
1115 rt.shutdown();
1116 match outcome {
1117 FlowOutcome::Completed(Value::Int(8)) => Ok(()),
1118 other => Err(format!("accepted replay: {other:?}").into()),
1119 }
1120 }
1121
1122 #[test]
1123 fn deliver_frame_lands_in_the_named_mailbox() -> Result<(), Box<dyn std::error::Error>> {
1124 use crate::CapId;
1125 let mut program = Program::new("inbox");
1126 program.function("main", 0, |f| {
1127 let msg = f.receive();
1128 let n = f.hop_payload(msg);
1129 f.return_(n);
1130 });
1131 let rt = Runtime::with_natives_and_config(
1132 program.build(),
1133 crate::std_native_table(),
1134 RuntimeConfig {
1135 workers: 1,
1136 ..RuntimeConfig::default()
1137 },
1138 )?;
1139 let handle = rt.spawn(0, &[])?;
1140 let cap = rt.mint_cap(handle.id())?;
1141 rt.register_name("inbox", cap)?;
1142 let frame = encode_frame(&OutboundHop::new(
1143 FlowId(44),
1144 2,
1145 std::sync::Arc::from("inbox"),
1146 Message::new(44, 1, 7, Value::Int(8)).authenticate(44, CapId::NONE),
1147 ))?;
1148 rt.deliver_frame(&frame).map_err(|err| format!("{err:?}"))?;
1149 let outcome = handle
1150 .join_timeout(Duration::from_secs(2))
1151 .ok_or("deliver frame timed out")?;
1152 rt.shutdown();
1153 match outcome {
1154 FlowOutcome::Completed(Value::Int(8)) => Ok(()),
1155 other => Err(format!("deliver frame: {other:?}").into()),
1156 }
1157 }
1158
1159 #[test]
1160 fn receive_match_cmp_keeps_the_failing_int_queued() -> Result<(), Box<dyn std::error::Error>> {
1161 use crate::bytecode::IntCmp;
1162 use crate::bytecode::Message;
1163 let mut program = Program::new("guard");
1164 program.function("main", 0, |f| {
1165 let tag = f.load_i32(1);
1166 let bound = f.load_i32(10);
1167 let msg = f.receive_match_cmp(tag, bound, IntCmp::Lt);
1168 let n = f.hop_payload(msg);
1169 f.return_(n);
1170 });
1171 let rt = Runtime::with_natives_and_config(
1172 program.build(),
1173 crate::std_native_table(),
1174 RuntimeConfig {
1175 workers: 1,
1176 ..RuntimeConfig::default()
1177 },
1178 )?;
1179 let handle = rt.spawn(0, &[])?;
1180 rt.send(
1181 handle.id(),
1182 Value::Message(Message::request(1, 1, Value::Int(20))),
1183 )?;
1184 rt.send(
1185 handle.id(),
1186 Value::Message(Message::request(2, 1, Value::Int(3))),
1187 )?;
1188 let outcome = handle
1189 .join_timeout(Duration::from_secs(2))
1190 .ok_or("guard timed out")?;
1191 rt.shutdown();
1192 match outcome {
1193 FlowOutcome::Completed(Value::Int(3)) => Ok(()),
1194 other => Err(format!("guard: {other:?}").into()),
1195 }
1196 }
1197
1198 #[test]
1199 fn table_put_get_and_read_only_delegate() -> Result<(), Box<dyn std::error::Error>> {
1200 use crate::bytecode::CapRights;
1201 let mut program = Program::new("table");
1202 program.function("main", 0, |f| {
1203 let name = f.load_str("box");
1204 let table = f.table_open(name);
1205 let key = f.load_i32(1);
1206 let value = f.load_i32(42);
1207 f.table_put(table, key, value);
1208 let got = f.table_get(table, key);
1209 f.return_(got);
1210 });
1211 let rt = Runtime::with_natives_and_config(
1212 program.build(),
1213 crate::std_native_table(),
1214 RuntimeConfig {
1215 workers: 1,
1216 ..RuntimeConfig::default()
1217 },
1218 )?;
1219 let handle = rt.spawn(0, &[])?;
1220 let outcome = handle
1221 .join_timeout(Duration::from_secs(2))
1222 .ok_or("table get timed out")?;
1223 rt.shutdown();
1224 if !matches!(outcome, FlowOutcome::Completed(Value::Int(42))) {
1225 return Err(format!("table get: {outcome:?}").into());
1226 }
1227
1228 let mut program = Program::new("table-ro");
1229 program.function("main", 0, |f| {
1230 let name = f.load_str("box");
1231 let table = f.table_open(name);
1232 let key = f.load_i32(1);
1233 let value = f.load_i32(42);
1234 f.table_put(table, key, value);
1235 let read_only = f.delegate(table, CapRights::RECV);
1236 f.table_put(read_only, key, value);
1237 f.return_(value);
1238 });
1239 let rt = Runtime::with_natives_and_config(
1240 program.build(),
1241 crate::std_native_table(),
1242 RuntimeConfig {
1243 workers: 1,
1244 ..RuntimeConfig::default()
1245 },
1246 )?;
1247 let handle = rt.spawn(0, &[])?;
1248 let outcome = handle
1249 .join_timeout(Duration::from_secs(2))
1250 .ok_or("read-only put timed out")?;
1251 rt.shutdown();
1252 match outcome {
1253 FlowOutcome::Failed(text) if text.contains("rights") => Ok(()),
1254 other => Err(format!("read-only put: {other:?}").into()),
1255 }
1256 }
1257
1258 #[test]
1259 fn frame_rejects_a_sender_that_is_not_the_envelope() -> Result<(), RemoteFrameError> {
1260 use crate::CapId;
1261 let agreed = OutboundHop::new(
1262 FlowId(9),
1263 1,
1264 std::sync::Arc::from("svc"),
1265 Message::new(9, 1, 1, Value::Int(1)).authenticate(9, CapId::NONE),
1266 );
1267 let bytes = encode_frame(&agreed)?;
1268 let host = OutboundHop::new(
1269 FlowId(9),
1270 1,
1271 std::sync::Arc::from("svc"),
1272 Message::new(0, 1, 1, Value::Int(1)).authenticate(0, CapId::NONE),
1273 );
1274 if !matches!(encode_frame(&host), Err(RemoteFrameError::SenderZero)) {
1275 return Err(RemoteFrameError::Unsupported);
1276 }
1277 let other = OutboundHop::new(
1278 FlowId(9),
1279 1,
1280 std::sync::Arc::from("svc"),
1281 Message::new(4, 1, 1, Value::Int(1)).authenticate(4, CapId::NONE),
1282 );
1283 if !matches!(encode_frame(&other), Err(RemoteFrameError::SenderMismatch)) {
1284 return Err(RemoteFrameError::Unsupported);
1285 }
1286 let envelope_at = 4 + 1 + 8 + 2 + agreed.name.len() + 8 + 1;
1288 let mut forged = bytes.clone();
1289 forged[envelope_at..envelope_at + 8].copy_from_slice(&0u64.to_le_bytes());
1290 if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderZero)) {
1291 return Err(RemoteFrameError::Unsupported);
1292 }
1293 forged[envelope_at..envelope_at + 8].copy_from_slice(&4u64.to_le_bytes());
1294 if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderMismatch)) {
1295 return Err(RemoteFrameError::Unsupported);
1296 }
1297 Ok(())
1298 }
1299
1300 #[test]
1301 fn table_overwrite_at_the_row_cap_keeps_the_row() -> Result<(), Box<dyn std::error::Error>> {
1302 use crate::bytecode::builder::ChunkBuilder;
1303 let mut b = ChunkBuilder::new("full");
1304 b.begin_function("main", 0, 6);
1305 let name = b.const_(Value::str("box"));
1306 b.emit_load_const(0, name);
1307 b.emit_table_open(1, 0);
1308 b.emit_load_imm(2, 0);
1309 b.emit_load_imm(3, 0);
1310 let again = b.new_label();
1311 let done = b.new_label();
1312 b.bind_label(again);
1313 b.emit_table_put(1, 2, 3);
1314 b.emit_add_imm(2, 2, 1);
1315 b.emit_lt_imm(4, 2, 256);
1316 b.emit_branch(4, done);
1317 b.emit_jump(again);
1318 b.bind_label(done);
1319 b.emit_load_imm(2, 0);
1320 b.emit_load_imm(3, 7);
1321 b.emit_table_put(1, 2, 3);
1322 b.emit_table_get(5, 1, 2);
1323 b.emit_return(5);
1324 let rt = Runtime::with_natives_and_config(
1325 b.finish(),
1326 crate::std_native_table(),
1327 RuntimeConfig {
1328 workers: 1,
1329 ..RuntimeConfig::default()
1330 },
1331 )?;
1332 let handle = rt.spawn(0, &[])?;
1333 let outcome = handle
1334 .join_timeout(Duration::from_secs(2))
1335 .ok_or("table fill timed out")?;
1336 rt.shutdown();
1337 match outcome {
1338 FlowOutcome::Completed(Value::Int(7)) => Ok(()),
1339 other => Err(format!("overwrite at cap: {other:?}").into()),
1340 }
1341 }
1342}