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::Map(entries) => {
315            if entries.len() > crate::bytecode::MAX_MAP_LEN {
316                return Err(RemoteFrameError::Unsupported);
317            }
318            entries
319                .iter()
320                .try_for_each(|(_, item)| screen_value(item, depth + 1))
321        }
322        Value::Unit
323        | Value::Bool(_)
324        | Value::Int(_)
325        | Value::Float(_)
326        | Value::Str(_)
327        | Value::Bytes(_) => Ok(()),
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use std::time::Duration;
334
335    use crate::{FlowOutcome, Program, Runtime, RuntimeConfig, Value};
336
337    use super::*;
338
339    #[test]
340    fn host_drains_a_remote_hop() -> Result<(), Box<dyn std::error::Error>> {
341        let bridge = DistributionBridge::new();
342        let mut program = Program::new("remote");
343        program.function("main", 0, |f| {
344            let node = f.load_i32(7);
345            let name = f.load_str("svc");
346            let payload = f.load_i32(41);
347            let msg = f.hop_fresh(3, payload);
348            f.send_remote(node, name, msg);
349            f.return_(payload);
350        });
351        let rt = Runtime::with_natives_and_config(
352            program.build(),
353            crate::std_native_table(),
354            RuntimeConfig {
355                distribution: Some(Arc::clone(&bridge)),
356                workers: 1,
357                ..RuntimeConfig::default()
358            },
359        )?;
360        let outcome = rt.spawn(0, &[])?.join();
361        rt.shutdown();
362        match outcome {
363            FlowOutcome::Completed(Value::Int(41)) => {}
364            other => return Err(format!("remote send failed: {other:?}").into()),
365        }
366        let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
367            Some(hop) => hop,
368            None => return Err("bridge empty".into()),
369        };
370        if hop.node != 7 || hop.name.as_ref() != "svc" {
371            return Err(format!("unexpected route {hop:?}").into());
372        }
373        if hop.message.reply_cap != CapId::NONE {
374            return Err("remote hop minted a local reply cap".into());
375        }
376        if !matches!(hop.message.payload.as_ref(), Value::Int(41)) {
377            return Err(format!("payload {:?}", hop.message.payload).into());
378        }
379        Ok(())
380    }
381
382    #[test]
383    fn a_live_cap_in_the_payload_does_not_leave_the_node() -> Result<(), Box<dyn std::error::Error>>
384    {
385        let bridge = DistributionBridge::new();
386        let mut program = Program::new("remote-cap");
387        program.function("main", 0, |f| {
388            let node = f.load_i32(7);
389            let name = f.load_str("svc");
390            let me = f.self_cap();
391            let msg = f.hop_fresh(3, me);
392            f.send_remote(node, name, msg);
393            f.return_(node);
394        });
395        let rt = Runtime::with_natives_and_config(
396            program.build(),
397            crate::std_native_table(),
398            RuntimeConfig {
399                distribution: Some(Arc::clone(&bridge)),
400                workers: 1,
401                ..RuntimeConfig::default()
402            },
403        )?;
404        let outcome = rt.spawn(0, &[])?.join();
405        rt.shutdown();
406        match outcome {
407            FlowOutcome::Failed(reason) if reason.contains("local capability") => {}
408            other => return Err(format!("expected a refused remote cap, got {other:?}").into()),
409        }
410        if bridge.try_recv()?.is_some() {
411            return Err("bridge accepted a hop that carried a capability".into());
412        }
413        Ok(())
414    }
415
416    #[test]
417    fn remote_nested_envelope_is_stamped_with_the_flow() -> Result<(), Box<dyn std::error::Error>> {
418        let bridge = DistributionBridge::new();
419        let mut program = Program::new("remote-nested");
420        program.function("main", 0, |f| {
421            let node = f.load_i32(7);
422            let name = f.load_str("svc");
423            let body = f.load_i32(1);
424            let inner = f.hop_fresh(1, body);
425            let outer = f.hop_fresh(2, inner);
426            f.send_remote(node, name, outer);
427            f.return_(node);
428        });
429        let rt = Runtime::with_natives_and_config(
430            program.build(),
431            crate::std_native_table(),
432            RuntimeConfig {
433                distribution: Some(Arc::clone(&bridge)),
434                workers: 1,
435                ..RuntimeConfig::default()
436            },
437        )?;
438        let outcome = rt.spawn(0, &[])?.join();
439        rt.shutdown();
440        if !matches!(outcome, FlowOutcome::Completed(Value::Int(7))) {
441            return Err(format!("remote nested send failed: {outcome:?}").into());
442        }
443        let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
444            Some(hop) => hop,
445            None => return Err("bridge empty".into()),
446        };
447        let Some(inner) = hop.message.payload.as_message() else {
448            return Err(format!("payload {:?}", hop.message.payload).into());
449        };
450        if inner.sender != hop.sender.as_u64() {
451            return Err(format!("nested sender {} hop {}", inner.sender, hop.sender).into());
452        }
453        if !inner.reply_cap.is_none() {
454            return Err("remote nested hop minted a local reply cap".into());
455        }
456        Ok(())
457    }
458
459    #[test]
460    fn frame_keeps_the_declared_sender() -> Result<(), RemoteFrameError> {
461        use crate::CapId;
462        let hop = OutboundHop {
463            sender: FlowId(9),
464            node: 3,
465            name: std::sync::Arc::from("svc"),
466            message: Message::new(9, 4, 1, Value::Int(5)).authenticate(9, CapId::NONE),
467        };
468        let back = decode_frame(&encode_frame(&hop)?)?;
469        if back.sender.as_u64() != 9 || back.node != 3 || back.message.tag != 1 {
470            return Err(RemoteFrameError::Unsupported);
471        }
472        if !matches!(back.message.payload.as_ref(), Value::Int(5)) {
473            return Err(RemoteFrameError::Unsupported);
474        }
475        Ok(())
476    }
477
478    #[test]
479    fn frame_rejects_a_live_cap() {
480        use crate::CapId;
481        let hop = OutboundHop {
482            sender: FlowId(9),
483            node: 1,
484            name: std::sync::Arc::from("svc"),
485            message: Message::new(9, 1, 1, Value::Cap(CapId::from_raw(1)))
486                .authenticate(9, CapId::NONE),
487        };
488        assert!(matches!(
489            encode_frame(&hop),
490            Err(RemoteFrameError::LiveCapability)
491        ));
492    }
493
494    #[test]
495    fn deliver_frame_lands_in_the_named_mailbox() -> Result<(), Box<dyn std::error::Error>> {
496        use crate::CapId;
497        let mut program = Program::new("inbox");
498        program.function("main", 0, |f| {
499            let msg = f.receive();
500            let n = f.hop_payload(msg);
501            f.return_(n);
502        });
503        let rt = Runtime::with_natives_and_config(
504            program.build(),
505            crate::std_native_table(),
506            RuntimeConfig {
507                workers: 1,
508                ..RuntimeConfig::default()
509            },
510        )?;
511        let handle = rt.spawn(0, &[])?;
512        let cap = rt.mint_cap(handle.id())?;
513        rt.register_name("inbox", cap)?;
514        let frame = encode_frame(&OutboundHop {
515            sender: FlowId(44),
516            node: 2,
517            name: std::sync::Arc::from("inbox"),
518            message: Message::new(44, 1, 7, Value::Int(8)).authenticate(44, CapId::NONE),
519        })?;
520        rt.deliver_frame(&frame).map_err(|err| format!("{err:?}"))?;
521        let outcome = handle
522            .join_timeout(Duration::from_secs(2))
523            .ok_or("deliver frame timed out")?;
524        rt.shutdown();
525        match outcome {
526            FlowOutcome::Completed(Value::Int(8)) => Ok(()),
527            other => Err(format!("deliver frame: {other:?}").into()),
528        }
529    }
530
531    #[test]
532    fn receive_match_cmp_keeps_the_failing_int_queued() -> Result<(), Box<dyn std::error::Error>> {
533        use crate::bytecode::IntCmp;
534        use crate::bytecode::Message;
535        let mut program = Program::new("guard");
536        program.function("main", 0, |f| {
537            let tag = f.load_i32(1);
538            let bound = f.load_i32(10);
539            let msg = f.receive_match_cmp(tag, bound, IntCmp::Lt);
540            let n = f.hop_payload(msg);
541            f.return_(n);
542        });
543        let rt = Runtime::with_natives_and_config(
544            program.build(),
545            crate::std_native_table(),
546            RuntimeConfig {
547                workers: 1,
548                ..RuntimeConfig::default()
549            },
550        )?;
551        let handle = rt.spawn(0, &[])?;
552        rt.send(
553            handle.id(),
554            Value::Message(Message::request(1, 1, Value::Int(20))),
555        )?;
556        rt.send(
557            handle.id(),
558            Value::Message(Message::request(2, 1, Value::Int(3))),
559        )?;
560        let outcome = handle
561            .join_timeout(Duration::from_secs(2))
562            .ok_or("guard timed out")?;
563        rt.shutdown();
564        match outcome {
565            FlowOutcome::Completed(Value::Int(3)) => Ok(()),
566            other => Err(format!("guard: {other:?}").into()),
567        }
568    }
569
570    #[test]
571    fn table_put_get_and_read_only_delegate() -> Result<(), Box<dyn std::error::Error>> {
572        use crate::bytecode::CapRights;
573        let mut program = Program::new("table");
574        program.function("main", 0, |f| {
575            let name = f.load_str("box");
576            let table = f.table_open(name);
577            let key = f.load_i32(1);
578            let value = f.load_i32(42);
579            f.table_put(table, key, value);
580            let got = f.table_get(table, key);
581            f.return_(got);
582        });
583        let rt = Runtime::with_natives_and_config(
584            program.build(),
585            crate::std_native_table(),
586            RuntimeConfig {
587                workers: 1,
588                ..RuntimeConfig::default()
589            },
590        )?;
591        let handle = rt.spawn(0, &[])?;
592        let outcome = handle
593            .join_timeout(Duration::from_secs(2))
594            .ok_or("table get timed out")?;
595        rt.shutdown();
596        if !matches!(outcome, FlowOutcome::Completed(Value::Int(42))) {
597            return Err(format!("table get: {outcome:?}").into());
598        }
599
600        let mut program = Program::new("table-ro");
601        program.function("main", 0, |f| {
602            let name = f.load_str("box");
603            let table = f.table_open(name);
604            let key = f.load_i32(1);
605            let value = f.load_i32(42);
606            f.table_put(table, key, value);
607            let read_only = f.delegate(table, CapRights::RECV);
608            f.table_put(read_only, key, value);
609            f.return_(value);
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 outcome = handle
621            .join_timeout(Duration::from_secs(2))
622            .ok_or("read-only put timed out")?;
623        rt.shutdown();
624        match outcome {
625            FlowOutcome::Failed(text) if text.contains("rights") => Ok(()),
626            other => Err(format!("read-only put: {other:?}").into()),
627        }
628    }
629
630    #[test]
631    fn frame_rejects_a_sender_that_is_not_the_envelope() -> Result<(), RemoteFrameError> {
632        use crate::CapId;
633        let agreed = OutboundHop {
634            sender: FlowId(9),
635            node: 1,
636            name: std::sync::Arc::from("svc"),
637            message: Message::new(9, 1, 1, Value::Int(1)).authenticate(9, CapId::NONE),
638        };
639        let bytes = encode_frame(&agreed)?;
640        let host = OutboundHop {
641            sender: FlowId(9),
642            node: 1,
643            name: std::sync::Arc::from("svc"),
644            message: Message::new(0, 1, 1, Value::Int(1)).authenticate(0, CapId::NONE),
645        };
646        if !matches!(encode_frame(&host), Err(RemoteFrameError::SenderZero)) {
647            return Err(RemoteFrameError::Unsupported);
648        }
649        let other = OutboundHop {
650            sender: FlowId(9),
651            node: 1,
652            name: std::sync::Arc::from("svc"),
653            message: Message::new(4, 1, 1, Value::Int(1)).authenticate(4, CapId::NONE),
654        };
655        if !matches!(encode_frame(&other), Err(RemoteFrameError::SenderMismatch)) {
656            return Err(RemoteFrameError::Unsupported);
657        }
658        // Header, then the `.bf` message tag, then the envelope sender.
659        let envelope_at = 4 + 1 + 8 + 2 + agreed.name.len() + 8 + 1;
660        let mut forged = bytes.clone();
661        forged[envelope_at..envelope_at + 8].copy_from_slice(&0u64.to_le_bytes());
662        if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderZero)) {
663            return Err(RemoteFrameError::Unsupported);
664        }
665        forged[envelope_at..envelope_at + 8].copy_from_slice(&4u64.to_le_bytes());
666        if !matches!(decode_frame(&forged), Err(RemoteFrameError::SenderMismatch)) {
667            return Err(RemoteFrameError::Unsupported);
668        }
669        Ok(())
670    }
671
672    #[test]
673    fn table_overwrite_at_the_row_cap_keeps_the_row() -> Result<(), Box<dyn std::error::Error>> {
674        use crate::bytecode::builder::ChunkBuilder;
675        let mut b = ChunkBuilder::new("full");
676        b.begin_function("main", 0, 6);
677        let name = b.const_(Value::str("box"));
678        b.emit_load_const(0, name);
679        b.emit_table_open(1, 0);
680        b.emit_load_imm(2, 0);
681        b.emit_load_imm(3, 0);
682        let again = b.new_label();
683        let done = b.new_label();
684        b.bind_label(again);
685        b.emit_table_put(1, 2, 3);
686        b.emit_add_imm(2, 2, 1);
687        b.emit_lt_imm(4, 2, 256);
688        b.emit_branch(4, done);
689        b.emit_jump(again);
690        b.bind_label(done);
691        b.emit_load_imm(2, 0);
692        b.emit_load_imm(3, 7);
693        b.emit_table_put(1, 2, 3);
694        b.emit_table_get(5, 1, 2);
695        b.emit_return(5);
696        let rt = Runtime::with_natives_and_config(
697            b.finish(),
698            crate::std_native_table(),
699            RuntimeConfig {
700                workers: 1,
701                ..RuntimeConfig::default()
702            },
703        )?;
704        let handle = rt.spawn(0, &[])?;
705        let outcome = handle
706            .join_timeout(Duration::from_secs(2))
707            .ok_or("table fill timed out")?;
708        rt.shutdown();
709        match outcome {
710            FlowOutcome::Completed(Value::Int(7)) => Ok(()),
711            other => Err(format!("overwrite at cap: {other:?}").into()),
712        }
713    }
714}