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