Skip to main content

byteflow/scheduler/
distribution.rs

1//! Outbound hops for another node.
2//!
3//! Byteflow does not open sockets and does not speak a cluster protocol.
4//! The host owns I/O. Bytecode [`crate::Opcode::SendRemote`] stamps the
5//! sender here and queues the hop on [`DistributionBridge`]; the embedder
6//! drains that queue and delivers it however it wants.
7//!
8//! Payload `Cap` tokens do not leave the node. A live cap, including one
9//! nested in a list or in another hop's `reply_cap`, fails the send before
10//! a send-quota token is spent. A nested envelope whose `sender` is still
11//! `0` is stamped with this flow. `reply_cap` on the outbound hop itself
12//! is [`crate::CapId::NONE`] — there is no local flow to mint a reply
13//! address for.
14
15use std::collections::VecDeque;
16use std::sync::{Arc, Condvar, Mutex};
17
18use crate::bytecode::{CapId, Message, Value};
19
20use super::error::RuntimeError;
21use super::process::FlowId;
22use super::sync_lock;
23
24/// How many outbound hops a bridge holds before `SendRemote` fails the flow.
25const MAX_OUTBOUND: usize = 1024;
26
27/// One authenticated hop waiting for the host to deliver it off-node.
28#[derive(Clone, Debug)]
29pub struct OutboundHop {
30    pub sender: FlowId,
31    /// Host-defined node number. `0` is not special.
32    pub node: u64,
33    pub name: Arc<str>,
34    pub message: Message,
35}
36
37/// Queue the host drains. Share one [`Arc`] via [`crate::RuntimeConfig::distribution`].
38#[derive(Debug)]
39pub struct DistributionBridge {
40    queue: Mutex<VecDeque<OutboundHop>>,
41    ready: Condvar,
42}
43
44impl DistributionBridge {
45    pub fn new() -> Arc<Self> {
46        Arc::new(Self {
47            queue: Mutex::new(VecDeque::new()),
48            ready: Condvar::new(),
49        })
50    }
51
52    pub(crate) fn push(&self, hop: OutboundHop) -> Result<(), String> {
53        let mut queue =
54            sync_lock::lock(&self.queue, "DistributionBridge::push").map_err(|e| e.to_string())?;
55        if queue.len() >= MAX_OUTBOUND {
56            return Err("distribution bridge full".into());
57        }
58        queue.push_back(hop);
59        self.ready.notify_one();
60        Ok(())
61    }
62
63    /// Next hop, if the host has not fallen behind.
64    pub fn try_recv(&self) -> Result<Option<OutboundHop>, RuntimeError> {
65        let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::try_recv")?;
66        Ok(queue.pop_front())
67    }
68
69    /// Hops waiting for the host to encode and send (`SendRemote` backpressure).
70    pub fn outbound_pending(&self) -> Result<usize, RuntimeError> {
71        let queue = sync_lock::lock(&self.queue, "DistributionBridge::outbound_pending")?;
72        Ok(queue.len())
73    }
74
75    /// Block until a hop arrives or `timeout` elapses.
76    pub fn recv_timeout(
77        &self,
78        timeout: std::time::Duration,
79    ) -> Result<Option<OutboundHop>, RuntimeError> {
80        let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::recv_timeout")?;
81        let start = std::time::Instant::now();
82        loop {
83            if let Some(hop) = queue.pop_front() {
84                return Ok(Some(hop));
85            }
86            let left = match timeout.checked_sub(start.elapsed()) {
87                Some(left) => left,
88                None => return Ok(None),
89            };
90            let (guard, status) =
91                sync_lock::wait_timeout(&self.ready, queue, left, "DistributionBridge::wait")?;
92            queue = guard;
93            if status.timed_out() && queue.is_empty() {
94                return Ok(None);
95            }
96        }
97    }
98}
99
100/// Sliding-window replay filter for [`crate::Runtime::deliver_frame`].
101#[derive(Debug)]
102pub struct RemoteFrameDedup {
103    capacity: usize,
104    seen: Mutex<VecDeque<(u64, u64)>>,
105}
106
107impl RemoteFrameDedup {
108    pub fn new(capacity: usize) -> Arc<Self> {
109        Arc::new(RemoteFrameDedup {
110            capacity: capacity.max(1),
111            seen: Mutex::new(VecDeque::new()),
112        })
113    }
114
115    /// `true` when this `(sender, request_id)` was already accepted in the window.
116    pub fn is_duplicate(&self, sender: u64, request_id: u64) -> Result<bool, RuntimeError> {
117        let mut queue = sync_lock::lock(&self.seen, "RemoteFrameDedup::is_duplicate")?;
118        for &(s, id) in queue.iter() {
119            if s == sender && id == request_id {
120                return Ok(true);
121            }
122        }
123        queue.push_back((sender, request_id));
124        while queue.len() > self.capacity {
125            queue.pop_front();
126        }
127        Ok(false)
128    }
129}
130
131/// Stamp `sender` and clear `reply_cap`. Does not mint a local reply Cap.
132pub(crate) fn stamp(message: Message, sender: FlowId) -> Message {
133    message.authenticate(sender.as_u64(), CapId::NONE)
134}
135
136/// `SendRemote` effect. `message` must already be a hop.
137pub(crate) fn deliver(
138    shared: &super::runtime::Shared,
139    flow: &mut super::process::Flow,
140    node: u64,
141    name: Arc<str>,
142    message: Value,
143) -> Result<(), String> {
144    if !flow.authority.rights().contains(crate::CapRights::SEND) {
145        return Err("send_remote denied: flow lacks SEND right".into());
146    }
147    let Some(bridge) = shared.distribution.as_ref() else {
148        return Err("send_remote: no distribution bridge".into());
149    };
150    let Some(mut msg) = message.as_message().cloned() else {
151        return Err("send_remote: value is not a hop".into());
152    };
153    if !msg.payload.within_nesting_limit() {
154        return Err("send_remote: payload too nested".into());
155    }
156    if msg.payload.contains_live_cap(0) {
157        return Err("send_remote: payload contains a local capability".into());
158    }
159    if let Err(e) = flow.quota.check_send() {
160        return Err(e.to_string());
161    }
162    if msg.request_id == 0 {
163        msg.request_id = flow.vm.fresh_request_id();
164    }
165    let Some(payload) = msg
166        .payload
167        .stamp_unset_envelopes(0, flow.id.as_u64(), &mut || flow.vm.fresh_request_id())
168    else {
169        return Err("send_remote: payload too nested".into());
170    };
171    let stamped = stamp(msg.with_payload(payload), flow.id);
172    bridge.push(OutboundHop {
173        sender: flow.id,
174        node,
175        name,
176        message: stamped,
177    })
178}
179
180const FRAME_MAGIC: [u8; 4] = *b"BFH1";
181const FRAME_VERSION: u8 = 1;
182const MAX_FRAME_NAME: usize = 256;
183
184/// Why a remote hop frame was refused.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub enum RemoteFrameError {
187    BadMagic,
188    Truncated,
189    BadVersion,
190    BadUtf8,
191    /// A `Cap` or `Pid` was on the wire, or a nested hop still had a reply cap.
192    LiveCapability,
193    /// Sender `0` is the local host. A remote frame must name another id.
194    SenderZero,
195    /// The frame header and the envelope name different senders.
196    SenderMismatch,
197    Name,
198    Unsupported,
199    NoSuchName,
200    Mailbox(super::mailbox::MailboxFullReason),
201    Unavailable,
202}
203
204impl std::fmt::Display for RemoteFrameError {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        match self {
207            Self::BadMagic => f.write_str("remote frame magic"),
208            Self::Truncated => f.write_str("remote frame truncated"),
209            Self::BadVersion => f.write_str("remote frame version"),
210            Self::BadUtf8 => f.write_str("remote frame name"),
211            Self::LiveCapability => f.write_str("remote frame carried a local capability"),
212            Self::SenderZero => f.write_str("remote frame sender is the local host"),
213            Self::SenderMismatch => f.write_str("remote frame sender does not match the envelope"),
214            Self::Name => f.write_str("remote frame name"),
215            Self::Unsupported => f.write_str("remote frame value"),
216            Self::NoSuchName => f.write_str("remote frame name is not registered"),
217            Self::Mailbox(reason) => write!(f, "remote frame mailbox ({reason})"),
218            Self::Unavailable => f.write_str("remote frame unavailable"),
219        }
220    }
221}
222
223impl std::error::Error for RemoteFrameError {}
224
225/// Bytes the host can write on its own socket. No capability leaves the node.
226pub fn encode_frame(hop: &OutboundHop) -> Result<Vec<u8>, RemoteFrameError> {
227    if hop.sender.is_host() {
228        return Err(RemoteFrameError::SenderZero);
229    }
230    if hop.name.is_empty() || hop.name.len() > MAX_FRAME_NAME {
231        return Err(RemoteFrameError::Name);
232    }
233    if hop.message.sender != hop.sender.as_u64() {
234        return Err(frame_sender_error(hop.message.sender));
235    }
236    screen_message(&hop.message, 0)?;
237    let mut out = Vec::with_capacity(32 + hop.name.len());
238    out.extend_from_slice(&FRAME_MAGIC);
239    out.push(FRAME_VERSION);
240    out.extend_from_slice(&hop.node.to_le_bytes());
241    out.extend_from_slice(&(hop.name.len() as u16).to_le_bytes());
242    out.extend_from_slice(hop.name.as_bytes());
243    out.extend_from_slice(&hop.sender.as_u64().to_le_bytes());
244    out.extend_from_slice(&crate::bytecode::encode_value(&Value::Message(
245        hop.message.clone(),
246    )));
247    Ok(out)
248}
249
250/// Inverse of [`encode_frame`]. The host still decides which bytes are trusted.
251pub fn decode_frame(bytes: &[u8]) -> Result<OutboundHop, RemoteFrameError> {
252    let mut pos = 0usize;
253    let magic: [u8; 4] = take(bytes, &mut pos)?;
254    if magic != FRAME_MAGIC {
255        return Err(RemoteFrameError::BadMagic);
256    }
257    let version: [u8; 1] = take(bytes, &mut pos)?;
258    if version[0] != FRAME_VERSION {
259        return Err(RemoteFrameError::BadVersion);
260    }
261    let node = u64::from_le_bytes(take(bytes, &mut pos)?);
262    let name_len = u16::from_le_bytes(take(bytes, &mut pos)?) as usize;
263    if name_len == 0 || name_len > MAX_FRAME_NAME {
264        return Err(RemoteFrameError::Name);
265    }
266    let name_bytes = take_slice(bytes, &mut pos, name_len)?;
267    let name = std::str::from_utf8(name_bytes).map_err(|_| RemoteFrameError::BadUtf8)?;
268    let sender = u64::from_le_bytes(take(bytes, &mut pos)?);
269    if sender == 0 {
270        return Err(RemoteFrameError::SenderZero);
271    }
272    let (value, consumed) =
273        crate::bytecode::decode_value(&bytes[pos..]).map_err(frame_format_error)?;
274    if consumed != bytes.len() - pos {
275        return Err(RemoteFrameError::Unsupported);
276    }
277    let Value::Message(message) = value else {
278        return Err(RemoteFrameError::Unsupported);
279    };
280    if message.sender != sender {
281        return Err(frame_sender_error(message.sender));
282    }
283    screen_message(&message, 0)?;
284    Ok(OutboundHop {
285        sender: FlowId(sender),
286        node,
287        name: Arc::from(name),
288        message,
289    })
290}
291
292fn frame_sender_error(message_sender: u64) -> RemoteFrameError {
293    if message_sender == 0 {
294        RemoteFrameError::SenderZero
295    } else {
296        RemoteFrameError::SenderMismatch
297    }
298}
299
300fn take<const N: usize>(data: &[u8], pos: &mut usize) -> Result<[u8; N], RemoteFrameError> {
301    let slice = take_slice(data, pos, N)?;
302    let mut out = [0u8; N];
303    out.copy_from_slice(slice);
304    Ok(out)
305}
306
307fn take_slice<'a>(data: &'a [u8], pos: &mut usize, n: usize) -> Result<&'a [u8], RemoteFrameError> {
308    let end = pos.checked_add(n).ok_or(RemoteFrameError::Truncated)?;
309    if end > data.len() {
310        return Err(RemoteFrameError::Truncated);
311    }
312    let slice = &data[*pos..end];
313    *pos = end;
314    Ok(slice)
315}
316
317fn frame_format_error(err: crate::bytecode::FormatError) -> RemoteFrameError {
318    match err {
319        crate::bytecode::FormatError::Truncated => RemoteFrameError::Truncated,
320        crate::bytecode::FormatError::BadUtf8 => RemoteFrameError::BadUtf8,
321        crate::bytecode::FormatError::UnknownValueTag(4 | 6) => RemoteFrameError::LiveCapability,
322        _ => RemoteFrameError::Unsupported,
323    }
324}
325
326fn screen_message(message: &Message, depth: u32) -> Result<(), RemoteFrameError> {
327    if depth > crate::bytecode::MAX_VALUE_DEPTH {
328        return Err(RemoteFrameError::Unsupported);
329    }
330    if !message.reply_cap.is_none() {
331        return Err(RemoteFrameError::LiveCapability);
332    }
333    screen_value(message.payload.as_ref(), depth + 1)
334}
335
336fn screen_value(value: &Value, depth: u32) -> Result<(), RemoteFrameError> {
337    if depth > crate::bytecode::MAX_VALUE_DEPTH {
338        return Err(RemoteFrameError::Unsupported);
339    }
340    match value {
341        Value::Pid(_) | Value::Cap(_) => Err(RemoteFrameError::LiveCapability),
342        Value::Message(message) => screen_message(message, depth),
343        Value::List(items) => {
344            if items.len() > crate::bytecode::MAX_LIST_LEN {
345                return Err(RemoteFrameError::Unsupported);
346            }
347            items
348                .iter()
349                .try_for_each(|item| screen_value(item, depth + 1))
350        }
351        Value::Record(fields) => {
352            if fields.len() > crate::bytecode::MAX_RECORD_LEN {
353                return Err(RemoteFrameError::Unsupported);
354            }
355            fields
356                .iter()
357                .try_for_each(|field| screen_value(field, depth + 1))
358        }
359        Value::Map(entries) => {
360            if entries.len() > crate::bytecode::MAX_MAP_LEN {
361                return Err(RemoteFrameError::Unsupported);
362            }
363            entries
364                .iter()
365                .try_for_each(|(_, item)| screen_value(item, depth + 1))
366        }
367        Value::Unit
368        | Value::Bool(_)
369        | Value::Int(_)
370        | Value::Float(_)
371        | Value::Str(_)
372        | Value::Bytes(_) => Ok(()),
373    }
374}
375
376#[cfg(test)]
377mod tests {
378    use std::time::Duration;
379
380    use crate::{FlowOutcome, Program, Runtime, RuntimeConfig, Value};
381
382    use super::*;
383
384    #[test]
385    fn host_drains_a_remote_hop() -> Result<(), Box<dyn std::error::Error>> {
386        let bridge = DistributionBridge::new();
387        let mut program = Program::new("remote");
388        program.function("main", 0, |f| {
389            let node = f.load_i32(7);
390            let name = f.load_str("svc");
391            let payload = f.load_i32(41);
392            let msg = f.hop_fresh(3, payload);
393            f.send_remote(node, name, msg);
394            f.return_(payload);
395        });
396        let rt = Runtime::with_natives_and_config(
397            program.build(),
398            crate::std_native_table(),
399            RuntimeConfig {
400                distribution: Some(Arc::clone(&bridge)),
401                workers: 1,
402                ..RuntimeConfig::default()
403            },
404        )?;
405        let outcome = rt.spawn(0, &[])?.join();
406        rt.shutdown();
407        match outcome {
408            FlowOutcome::Completed(Value::Int(41)) => {}
409            other => return Err(format!("remote send failed: {other:?}").into()),
410        }
411        let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
412            Some(hop) => hop,
413            None => return Err("bridge empty".into()),
414        };
415        if hop.node != 7 || hop.name.as_ref() != "svc" {
416            return Err(format!("unexpected route {hop:?}").into());
417        }
418        if hop.message.reply_cap != CapId::NONE {
419            return Err("remote hop minted a local reply cap".into());
420        }
421        if !matches!(hop.message.payload.as_ref(), Value::Int(41)) {
422            return Err(format!("payload {:?}", hop.message.payload).into());
423        }
424        Ok(())
425    }
426
427    #[test]
428    fn a_live_cap_in_the_payload_does_not_leave_the_node() -> Result<(), Box<dyn std::error::Error>>
429    {
430        let bridge = DistributionBridge::new();
431        let mut program = Program::new("remote-cap");
432        program.function("main", 0, |f| {
433            let node = f.load_i32(7);
434            let name = f.load_str("svc");
435            let me = f.self_cap();
436            let msg = f.hop_fresh(3, me);
437            f.send_remote(node, name, msg);
438            f.return_(node);
439        });
440        let rt = Runtime::with_natives_and_config(
441            program.build(),
442            crate::std_native_table(),
443            RuntimeConfig {
444                distribution: Some(Arc::clone(&bridge)),
445                workers: 1,
446                ..RuntimeConfig::default()
447            },
448        )?;
449        let outcome = rt.spawn(0, &[])?.join();
450        rt.shutdown();
451        match outcome {
452            FlowOutcome::Failed(reason) if reason.contains("local capability") => {}
453            other => return Err(format!("expected a refused remote cap, got {other:?}").into()),
454        }
455        if bridge.try_recv()?.is_some() {
456            return Err("bridge accepted a hop that carried a capability".into());
457        }
458        Ok(())
459    }
460
461    #[test]
462    fn remote_nested_envelope_is_stamped_with_the_flow() -> Result<(), Box<dyn std::error::Error>> {
463        let bridge = DistributionBridge::new();
464        let mut program = Program::new("remote-nested");
465        program.function("main", 0, |f| {
466            let node = f.load_i32(7);
467            let name = f.load_str("svc");
468            let body = f.load_i32(1);
469            let inner = f.hop_fresh(1, body);
470            let outer = f.hop_fresh(2, inner);
471            f.send_remote(node, name, outer);
472            f.return_(node);
473        });
474        let rt = Runtime::with_natives_and_config(
475            program.build(),
476            crate::std_native_table(),
477            RuntimeConfig {
478                distribution: Some(Arc::clone(&bridge)),
479                workers: 1,
480                ..RuntimeConfig::default()
481            },
482        )?;
483        let outcome = rt.spawn(0, &[])?.join();
484        rt.shutdown();
485        if !matches!(outcome, FlowOutcome::Completed(Value::Int(7))) {
486            return Err(format!("remote nested send failed: {outcome:?}").into());
487        }
488        let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
489            Some(hop) => hop,
490            None => return Err("bridge empty".into()),
491        };
492        let Some(inner) = hop.message.payload.as_message() else {
493            return Err(format!("payload {:?}", hop.message.payload).into());
494        };
495        if inner.sender != hop.sender.as_u64() {
496            return Err(format!("nested sender {} hop {}", inner.sender, hop.sender).into());
497        }
498        if !inner.reply_cap.is_none() {
499            return Err("remote nested hop minted a local reply cap".into());
500        }
501        Ok(())
502    }
503
504    #[test]
505    fn frame_keeps_the_declared_sender() -> Result<(), RemoteFrameError> {
506        use crate::CapId;
507        let hop = OutboundHop {
508            sender: FlowId(9),
509            node: 3,
510            name: std::sync::Arc::from("svc"),
511            message: Message::new(9, 4, 1, Value::Int(5)).authenticate(9, CapId::NONE),
512        };
513        let back = decode_frame(&encode_frame(&hop)?)?;
514        if back.sender.as_u64() != 9 || back.node != 3 || back.message.tag != 1 {
515            return Err(RemoteFrameError::Unsupported);
516        }
517        if !matches!(back.message.payload.as_ref(), Value::Int(5)) {
518            return Err(RemoteFrameError::Unsupported);
519        }
520        Ok(())
521    }
522
523    #[test]
524    fn frame_round_trips_a_record_without_a_cap() -> Result<(), RemoteFrameError> {
525        use crate::CapId;
526        let record = Value::try_record(vec![Value::Int(1), Value::Int(2)])
527            .ok_or(RemoteFrameError::Unsupported)?;
528        let hop = OutboundHop {
529            sender: FlowId(9),
530            node: 3,
531            name: std::sync::Arc::from("svc"),
532            message: Message::new(9, 4, 1, record).authenticate(9, CapId::NONE),
533        };
534        let back = decode_frame(&encode_frame(&hop)?)?;
535        if back.sender.as_u64() != 9 || !back.message.reply_cap.is_none() {
536            return Err(RemoteFrameError::Unsupported);
537        }
538        match back.message.payload.as_ref() {
539            Value::Record(fields) if fields.len() == 2 => Ok(()),
540            _ => Err(RemoteFrameError::Unsupported),
541        }
542    }
543
544    #[test]
545    fn frame_rejects_a_live_cap() {
546        use crate::CapId;
547        let hop = OutboundHop {
548            sender: FlowId(9),
549            node: 1,
550            name: std::sync::Arc::from("svc"),
551            message: Message::new(9, 1, 1, Value::Cap(CapId::from_raw(1)))
552                .authenticate(9, CapId::NONE),
553        };
554        assert!(matches!(
555            encode_frame(&hop),
556            Err(RemoteFrameError::LiveCapability)
557        ));
558    }
559
560    #[test]
561    fn frame_rejects_a_list_past_the_cap() {
562        let hop = OutboundHop {
563            sender: FlowId(9),
564            node: 1,
565            name: std::sync::Arc::from("svc"),
566            message: Message::new(
567                9,
568                1,
569                1,
570                Value::List(std::sync::Arc::from(vec![Value::Int(1); 257])),
571            )
572            .authenticate(9, crate::CapId::NONE),
573        };
574        assert!(matches!(
575            encode_frame(&hop),
576            Err(RemoteFrameError::Unsupported)
577        ));
578    }
579
580    #[test]
581    fn frame_accepts_a_list_at_the_cap() -> Result<(), RemoteFrameError> {
582        let list =
583            Value::try_list(vec![Value::Int(1); 256]).ok_or(RemoteFrameError::Unsupported)?;
584        let hop = OutboundHop {
585            sender: FlowId(9),
586            node: 1,
587            name: std::sync::Arc::from("svc"),
588            message: Message::new(9, 1, 1, list).authenticate(9, crate::CapId::NONE),
589        };
590        encode_frame(&hop).map(|_| ())
591    }
592
593    #[test]
594    fn remote_frame_dedup_detects_replay() -> Result<(), RuntimeError> {
595        let dedup = RemoteFrameDedup::new(4);
596        assert!(!dedup.is_duplicate(1, 100)?);
597        assert!(dedup.is_duplicate(1, 100)?);
598        assert!(!dedup.is_duplicate(1, 101)?);
599        Ok(())
600    }
601
602    #[test]
603    fn deliver_frame_lands_in_the_named_mailbox() -> Result<(), Box<dyn std::error::Error>> {
604        use crate::CapId;
605        let mut program = Program::new("inbox");
606        program.function("main", 0, |f| {
607            let msg = f.receive();
608            let n = f.hop_payload(msg);
609            f.return_(n);
610        });
611        let rt = Runtime::with_natives_and_config(
612            program.build(),
613            crate::std_native_table(),
614            RuntimeConfig {
615                workers: 1,
616                ..RuntimeConfig::default()
617            },
618        )?;
619        let handle = rt.spawn(0, &[])?;
620        let cap = rt.mint_cap(handle.id())?;
621        rt.register_name("inbox", cap)?;
622        let frame = encode_frame(&OutboundHop {
623            sender: FlowId(44),
624            node: 2,
625            name: std::sync::Arc::from("inbox"),
626            message: Message::new(44, 1, 7, Value::Int(8)).authenticate(44, CapId::NONE),
627        })?;
628        rt.deliver_frame(&frame).map_err(|err| format!("{err:?}"))?;
629        let outcome = handle
630            .join_timeout(Duration::from_secs(2))
631            .ok_or("deliver frame timed out")?;
632        rt.shutdown();
633        match outcome {
634            FlowOutcome::Completed(Value::Int(8)) => Ok(()),
635            other => Err(format!("deliver frame: {other:?}").into()),
636        }
637    }
638
639    #[test]
640    fn receive_match_cmp_keeps_the_failing_int_queued() -> Result<(), Box<dyn std::error::Error>> {
641        use crate::bytecode::IntCmp;
642        use crate::bytecode::Message;
643        let mut program = Program::new("guard");
644        program.function("main", 0, |f| {
645            let tag = f.load_i32(1);
646            let bound = f.load_i32(10);
647            let msg = f.receive_match_cmp(tag, bound, IntCmp::Lt);
648            let n = f.hop_payload(msg);
649            f.return_(n);
650        });
651        let rt = Runtime::with_natives_and_config(
652            program.build(),
653            crate::std_native_table(),
654            RuntimeConfig {
655                workers: 1,
656                ..RuntimeConfig::default()
657            },
658        )?;
659        let handle = rt.spawn(0, &[])?;
660        rt.send(
661            handle.id(),
662            Value::Message(Message::request(1, 1, Value::Int(20))),
663        )?;
664        rt.send(
665            handle.id(),
666            Value::Message(Message::request(2, 1, Value::Int(3))),
667        )?;
668        let outcome = handle
669            .join_timeout(Duration::from_secs(2))
670            .ok_or("guard timed out")?;
671        rt.shutdown();
672        match outcome {
673            FlowOutcome::Completed(Value::Int(3)) => Ok(()),
674            other => Err(format!("guard: {other:?}").into()),
675        }
676    }
677
678    #[test]
679    fn table_put_get_and_read_only_delegate() -> Result<(), Box<dyn std::error::Error>> {
680        use crate::bytecode::CapRights;
681        let mut program = Program::new("table");
682        program.function("main", 0, |f| {
683            let name = f.load_str("box");
684            let table = f.table_open(name);
685            let key = f.load_i32(1);
686            let value = f.load_i32(42);
687            f.table_put(table, key, value);
688            let got = f.table_get(table, key);
689            f.return_(got);
690        });
691        let rt = Runtime::with_natives_and_config(
692            program.build(),
693            crate::std_native_table(),
694            RuntimeConfig {
695                workers: 1,
696                ..RuntimeConfig::default()
697            },
698        )?;
699        let handle = rt.spawn(0, &[])?;
700        let outcome = handle
701            .join_timeout(Duration::from_secs(2))
702            .ok_or("table get timed out")?;
703        rt.shutdown();
704        if !matches!(outcome, FlowOutcome::Completed(Value::Int(42))) {
705            return Err(format!("table get: {outcome:?}").into());
706        }
707
708        let mut program = Program::new("table-ro");
709        program.function("main", 0, |f| {
710            let name = f.load_str("box");
711            let table = f.table_open(name);
712            let key = f.load_i32(1);
713            let value = f.load_i32(42);
714            f.table_put(table, key, value);
715            let read_only = f.delegate(table, CapRights::RECV);
716            f.table_put(read_only, key, value);
717            f.return_(value);
718        });
719        let rt = Runtime::with_natives_and_config(
720            program.build(),
721            crate::std_native_table(),
722            RuntimeConfig {
723                workers: 1,
724                ..RuntimeConfig::default()
725            },
726        )?;
727        let handle = rt.spawn(0, &[])?;
728        let outcome = handle
729            .join_timeout(Duration::from_secs(2))
730            .ok_or("read-only put timed out")?;
731        rt.shutdown();
732        match outcome {
733            FlowOutcome::Failed(text) if text.contains("rights") => Ok(()),
734            other => Err(format!("read-only put: {other:?}").into()),
735        }
736    }
737
738    #[test]
739    fn frame_rejects_a_sender_that_is_not_the_envelope() -> Result<(), RemoteFrameError> {
740        use crate::CapId;
741        let agreed = OutboundHop {
742            sender: FlowId(9),
743            node: 1,
744            name: std::sync::Arc::from("svc"),
745            message: Message::new(9, 1, 1, Value::Int(1)).authenticate(9, CapId::NONE),
746        };
747        let bytes = encode_frame(&agreed)?;
748        let host = OutboundHop {
749            sender: FlowId(9),
750            node: 1,
751            name: std::sync::Arc::from("svc"),
752            message: Message::new(0, 1, 1, Value::Int(1)).authenticate(0, CapId::NONE),
753        };
754        if !matches!(encode_frame(&host), Err(RemoteFrameError::SenderZero)) {
755            return Err(RemoteFrameError::Unsupported);
756        }
757        let other = OutboundHop {
758            sender: FlowId(9),
759            node: 1,
760            name: std::sync::Arc::from("svc"),
761            message: Message::new(4, 1, 1, Value::Int(1)).authenticate(4, CapId::NONE),
762        };
763        if !matches!(encode_frame(&other), Err(RemoteFrameError::SenderMismatch)) {
764            return Err(RemoteFrameError::Unsupported);
765        }
766        // Header, then the `.bf` message tag, then the envelope sender.
767        let envelope_at = 4 + 1 + 8 + 2 + agreed.name.len() + 8 + 1;
768        let mut forged = bytes.clone();
769        forged[envelope_at..envelope_at + 8].copy_from_slice(&0u64.to_le_bytes());
770        if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderZero)) {
771            return Err(RemoteFrameError::Unsupported);
772        }
773        forged[envelope_at..envelope_at + 8].copy_from_slice(&4u64.to_le_bytes());
774        if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderMismatch)) {
775            return Err(RemoteFrameError::Unsupported);
776        }
777        Ok(())
778    }
779
780    #[test]
781    fn table_overwrite_at_the_row_cap_keeps_the_row() -> Result<(), Box<dyn std::error::Error>> {
782        use crate::bytecode::builder::ChunkBuilder;
783        let mut b = ChunkBuilder::new("full");
784        b.begin_function("main", 0, 6);
785        let name = b.const_(Value::str("box"));
786        b.emit_load_const(0, name);
787        b.emit_table_open(1, 0);
788        b.emit_load_imm(2, 0);
789        b.emit_load_imm(3, 0);
790        let again = b.new_label();
791        let done = b.new_label();
792        b.bind_label(again);
793        b.emit_table_put(1, 2, 3);
794        b.emit_add_imm(2, 2, 1);
795        b.emit_lt_imm(4, 2, 256);
796        b.emit_branch(4, done);
797        b.emit_jump(again);
798        b.bind_label(done);
799        b.emit_load_imm(2, 0);
800        b.emit_load_imm(3, 7);
801        b.emit_table_put(1, 2, 3);
802        b.emit_table_get(5, 1, 2);
803        b.emit_return(5);
804        let rt = Runtime::with_natives_and_config(
805            b.finish(),
806            crate::std_native_table(),
807            RuntimeConfig {
808                workers: 1,
809                ..RuntimeConfig::default()
810            },
811        )?;
812        let handle = rt.spawn(0, &[])?;
813        let outcome = handle
814            .join_timeout(Duration::from_secs(2))
815            .ok_or("table fill timed out")?;
816        rt.shutdown();
817        match outcome {
818            FlowOutcome::Completed(Value::Int(7)) => Ok(()),
819            other => Err(format!("overwrite at cap: {other:?}").into()),
820        }
821    }
822}