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