Skip to main content

byteflow/vm/
machine.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3use std::time::Duration;
4
5use crate::bytecode::{CapId, Chunk, Instruction, Opcode, Value};
6use crate::scheduler::FlowQuota;
7
8use super::fault::{Fault, NativeCallError};
9use super::frame::Frame;
10use super::native::{check_native_gate, NativeGate, NativeTable};
11use super::result::VmResult;
12
13/// Bytes a dictionary slot owns. Scalars are free. `Str` / `Bytes` charge
14/// their length even when a register still holds the same `Arc`: the
15/// dictionary keeps the buffer after that register is overwritten.
16fn dict_owned_bytes(value: &Value) -> Result<usize, Fault> {
17    match value {
18        Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Float(_) => Ok(0),
19        Value::Str(s) => Ok(s.len()),
20        Value::Bytes(b) => Ok(b.len()),
21        other => Err(Fault::TypeMismatch {
22            expected: "dict value (scalar, str, or bytes)",
23            got: other.type_name(),
24        }),
25    }
26}
27
28/// Hard limit on call nesting. Frames are heap-allocated, so
29/// unbounded recursion would grow the Flow's memory instead of crashing
30/// the worker thread's native stack — which is worse, not better, without a
31/// limit. `4096` comfortably covers real recursive algorithms while keeping
32/// a runaway `fn f() { f() }` a `Fault`, not an OOM.
33pub const MAX_CALL_DEPTH: usize = 4096;
34
35/// One virtual Flow's execution state: call stack + registers. Cheap
36/// enough to construct that spawning a Flow is a handful of small heap
37/// allocations, not a native thread/stack (contrast: a `std::thread` reserves
38/// megabytes of stack whether it uses them or not).
39///
40/// `Vm` owns no scheduler, mailbox, or thread handle — see [`VmResult`] for
41/// why that separation is the whole point.
42pub struct Vm {
43    chunk: Arc<Chunk>,
44    natives: Arc<NativeTable>,
45    native_gate: NativeGate,
46    frames: Vec<Frame>,
47    /// Lifetime instruction counter, exposed for `FlowMetrics` (design
48    /// notes §26).
49    instructions_executed: u64,
50    /// Next `Message.request_id` for [`Opcode::FreshRequestId`] and for
51    /// hops that still carry `0` (“unset”) at the Send/Ask boundary.
52    next_request_id: u64,
53    /// Per-flow heap charge for `Str`/`Bytes` written into registers.
54    quota: Option<Arc<FlowQuota>>,
55    /// Process-wide memory ceiling (optional; set by the runtime).
56    memory: Option<Arc<crate::MemoryBudget>>,
57    /// Retained for API / `RuntimeConfig` wiring. Out-of-range jumps always
58    /// trap with [`Fault::BadJump`] (fail-closed); this flag no longer gates
59    /// the check.
60    #[allow(dead_code)]
61    paranoid_jumps: bool,
62    /// BEAM process dictionary. Allocated on first `DictPut` so the common
63    /// flow that never touches the dict pays nothing.
64    dict: Option<HashMap<i64, Value>>,
65    /// Heap bytes charged for `Str` / `Bytes` stored in [`Self::dict`].
66    /// Separate from frame charges: overwriting the source register must not
67    /// free a buffer the dictionary still owns.
68    dict_bytes: usize,
69}
70
71impl Vm {
72    /// Construct a `Vm` ready to run `function` (an index into
73    /// `chunk.functions`) with the given arguments loaded into `r0..argc`.
74    /// `natives` is the FFI table `Opcode::CallNative` dispatches through —
75    /// pass [`NativeTable::empty`] if the chunk never calls out to Rust.
76    ///
77    /// Native calls are **denied** until [`Self::with_native_gate`] installs
78    /// an allowlist (the runtime does this from the flow's attenuated Cap).
79    pub fn new(
80        chunk: Arc<Chunk>,
81        natives: Arc<NativeTable>,
82        function: u32,
83        args: &[Value],
84    ) -> Result<Self, Fault> {
85        let gate = NativeGate::deny(natives.len());
86        Self::with_native_gate(chunk, natives, gate, function, args)
87    }
88
89    pub fn with_native_gate(
90        chunk: Arc<Chunk>,
91        natives: Arc<NativeTable>,
92        native_gate: NativeGate,
93        function: u32,
94        args: &[Value],
95    ) -> Result<Self, Fault> {
96        let def = chunk.function(function).ok_or(Fault::BadFunction {
97            index: function,
98            table_size: chunk.functions.len() as u32,
99        })?;
100        let mut frame = Frame::new(function, def.num_registers, None);
101        frame.set_pc(def.entry as usize);
102        load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
103        Ok(Vm {
104            chunk,
105            natives,
106            native_gate,
107            frames: vec![frame],
108            instructions_executed: 0,
109            next_request_id: 1,
110            quota: None,
111            memory: None,
112            paranoid_jumps: false,
113            dict: None,
114            dict_bytes: 0,
115        })
116    }
117
118    /// Historical API: out-of-range `Jump` / `Branch` always trap with
119    /// [`Fault::BadJump`]. The flag is retained for `RuntimeConfig` compatibility
120    /// but does not change jump semantics.
121    pub fn set_paranoid_jumps(&mut self, enabled: bool) {
122        self.paranoid_jumps = enabled;
123    }
124
125    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
126    ///
127    /// Charges the **total** current register heap in one reservation, then
128    /// installs the quota. A failed reservation leaves `self.quota` unset and
129    /// does not partially inflate the budget. Same `Arc` rewritten into the
130    /// same slot is not charged twice on later stores.
131    pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
132        let mut per_frame: Vec<usize> = Vec::with_capacity(self.frames.len());
133        let mut total = 0usize;
134        for frame in &self.frames {
135            let mut bytes = 0usize;
136            for value in frame.registers() {
137                let part = heap_charge_of(value)?;
138                bytes = match bytes.checked_add(part) {
139                    Some(sum) => sum,
140                    None => {
141                        return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
142                    }
143                };
144            }
145            total = match total.checked_add(bytes) {
146                Some(sum) => sum,
147                None => return Err(Fault::QuotaExceeded("heap charge does not fit".into())),
148            };
149            per_frame.push(bytes);
150        }
151        total = match total.checked_add(self.dict_bytes) {
152            Some(sum) => sum,
153            None => return Err(Fault::QuotaExceeded("heap charge does not fit".into())),
154        };
155        charge_pair(&quota, self.memory.as_deref(), total)?;
156        for (frame, bytes) in self.frames.iter_mut().zip(per_frame) {
157            frame.set_heap_charge(bytes);
158        }
159        self.quota = Some(quota);
160        Ok(())
161    }
162
163    /// Attach the process-wide memory ceiling (call before or with [`Self::set_quota`]).
164    pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
165        self.memory = Some(memory);
166    }
167
168    /// Mint a per-flow correlation id.
169    ///
170    /// Stays in the `Value::Int` (`i64`) domain so
171    /// `FreshRequestId` → `Int` → [`request_id_from_value`] never produces a
172    /// negative id. Never returns `0` (`next_request_id` starts at 1).
173    pub fn fresh_request_id(&mut self) -> u64 {
174        let id = self.next_request_id;
175        if self.next_request_id < i64::MAX as u64 {
176            self.next_request_id += 1;
177        }
178        id
179    }
180
181    #[cfg(test)]
182    fn set_next_request_id_for_test(&mut self, id: u64) {
183        self.next_request_id = id;
184    }
185
186    pub fn instructions_executed(&self) -> u64 {
187        self.instructions_executed
188    }
189
190    /// Index into `chunk.functions` for the active (top) call frame.
191    /// Useful for diagnostics / supervisor logs when a Flow traps.
192    pub fn current_function(&self) -> u32 {
193        // Category D: frames must be non-empty while the VM is runnable.
194        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
195        // broken invariant cannot panic a worker; the next `run` will trap.
196        debug_assert!(!self.frames.is_empty(), "frames empty while running");
197        match self.frames.last() {
198            Some(frame) => frame.function(),
199            None => 0,
200        }
201    }
202
203    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
204    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
205    /// needing to know anything about `Chunk`'s internals — every Flow
206    /// spawned (transitively) from the same top-level `spawn()` call shares
207    /// one immutable chunk in memory, never copies it.
208    pub fn chunk_arc(&self) -> Arc<Chunk> {
209        self.chunk.clone()
210    }
211
212    /// A cheap `Arc` clone of this VM's native function table, for the same
213    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
214    /// `CallNative` through the identical table its parent uses.
215    pub fn natives_arc(&self) -> Arc<NativeTable> {
216        self.natives.clone()
217    }
218
219    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
220    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
221    /// into the register the instruction that suspended us was targeting,
222    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
223    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
224    /// destination register holding its previous (stale) value.
225    #[inline]
226    pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
227        self.set_reg(dest_reg, value)
228    }
229
230    /// Program counter of the active frame — used by the optional JIT hook.
231    pub fn current_pc(&self) -> Option<usize> {
232        self.frames.last().map(|f| f.pc())
233    }
234
235    /// Number of registers in the active frame.
236    pub fn current_num_registers(&self) -> Option<u8> {
237        self.frames.last().map(|f| f.registers().len() as u8)
238    }
239
240    /// Read-only view of the active register file.
241    pub fn top_registers(&self) -> Option<&[Value]> {
242        self.frames.last().map(|f| f.registers())
243    }
244
245    /// Mutable view of the active register file (JIT sync path).
246    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
247        self.frames.last_mut().map(|f| f.registers_mut())
248    }
249
250    /// Set the active frame's program counter.
251    pub fn set_pc(&mut self, pc: usize) {
252        if let Some(frame) = self.frames.last_mut() {
253            frame.set_pc(pc);
254        }
255    }
256
257    /// Write one register in the active frame (JIT sync path).
258    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
259        self.set_reg(reg, value)
260    }
261
262    /// Deliver a return value through the call stack.
263    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
264        self.pop_frame(value)
265    }
266
267    /// Top call frame. Empty stack is a broken invariant (category D) —
268    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
269    #[inline]
270    fn current(&mut self) -> Result<&mut Frame, Fault> {
271        debug_assert!(!self.frames.is_empty(), "frames empty while running");
272        self.frames
273            .last_mut()
274            .ok_or(Fault::Invariant("empty frame stack while running"))
275    }
276
277    #[inline]
278    fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
279        let frame = self
280            .frames
281            .last()
282            .ok_or(Fault::Invariant("empty frame stack while running"))?;
283        frame
284            .registers()
285            .get(reg as usize)
286            .cloned()
287            .ok_or(Fault::RegisterOutOfRange {
288                reg,
289                frame_size: frame.registers().len() as u8,
290            })
291    }
292
293    /// Write a register. Bounds-check the slot **before** any heap charge so
294    /// a failed store cannot inflate FlowQuota / MemoryBudget.
295    #[inline]
296    fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
297        let frame = self
298            .frames
299            .last()
300            .ok_or(Fault::Invariant("empty frame stack while running"))?;
301        let frame_size = frame.registers().len() as u8;
302        let old = frame
303            .registers()
304            .get(reg as usize)
305            .ok_or(Fault::RegisterOutOfRange { reg, frame_size })?;
306
307        // `old` is `&Value`; keep both sides as references for the helper.
308        let old_bytes = heap_charge_of(old)?;
309        let new_bytes = heap_charge_of(&value)?;
310
311        match (&value, old) {
312            (Value::Str(s), Value::Str(prev)) if Arc::ptr_eq(s, prev) => return Ok(()),
313            (Value::Bytes(b), Value::Bytes(prev)) if Arc::ptr_eq(b, prev) => return Ok(()),
314            _ => {}
315        }
316
317        if let Some(quota) = self.quota.as_ref() {
318            if new_bytes > old_bytes {
319                charge_pair(quota, self.memory.as_deref(), new_bytes - old_bytes)?;
320            } else if old_bytes > new_bytes {
321                release_pair(quota, self.memory.as_deref(), old_bytes - new_bytes);
322            }
323        }
324
325        let frame = self.current()?;
326        if new_bytes > old_bytes {
327            let delta = new_bytes - old_bytes;
328            if !frame.try_add_heap_charge(delta) {
329                if let Some(quota) = self.quota.as_ref() {
330                    release_pair(quota, self.memory.as_deref(), delta);
331                }
332                return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
333            }
334        } else if old_bytes > new_bytes {
335            frame.sub_heap_charge(old_bytes - new_bytes);
336        }
337        match frame.registers_mut().get_mut(reg as usize) {
338            Some(slot) => {
339                *slot = value;
340                Ok(())
341            }
342            None => Err(Fault::RegisterOutOfRange {
343                reg,
344                frame_size: frame.registers().len() as u8,
345            }),
346        }
347    }
348
349    /// Fetch the next instruction and advance `pc`.
350    ///
351    /// `Ok(None)` if control fell off the end of the function body without an
352    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
353    /// (friendlier to hand-written bytecode that omits a trailing return).
354    /// `Err` if the frame stack is empty (invariant break).
355    ///
356    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
357    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
358    /// compile.
359    #[inline]
360    fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
361        let pc = self.current()?.pc();
362        let instr = self.chunk.code.get(pc).copied();
363        if instr.is_some() {
364            self.current()?.set_pc(pc + 1);
365        }
366        Ok(instr)
367    }
368
369    fn add_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
370        let src_val = self.get_reg(src)?;
371        let addend = i64::from(imm);
372        let result = match src_val {
373            Value::Int(x) => Value::Int(x.wrapping_add(addend)),
374            Value::Float(x) => Value::Float(x + (addend as f64)),
375            other => {
376                return Err(Fault::TypeMismatch {
377                    expected: "int or float",
378                    got: other.type_name(),
379                })
380            }
381        };
382        self.set_reg(dst, result)
383    }
384
385    fn sub_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
386        let src_val = self.get_reg(src)?;
387        let subtrahend = i64::from(imm);
388        let result = match src_val {
389            Value::Int(x) => Value::Int(x.wrapping_sub(subtrahend)),
390            Value::Float(x) => Value::Float(x - (subtrahend as f64)),
391            other => {
392                return Err(Fault::TypeMismatch {
393                    expected: "int or float",
394                    got: other.type_name(),
395                })
396            }
397        };
398        self.set_reg(dst, result)
399    }
400
401    fn lt_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
402        let src_val = self.get_reg(src)?;
403        let rhs = i64::from(imm);
404        let result = match src_val {
405            Value::Int(x) => Value::Bool(x < rhs),
406            Value::Float(x) => Value::Bool(x < (rhs as f64)),
407            other => {
408                return Err(Fault::TypeMismatch {
409                    expected: "int or float",
410                    got: other.type_name(),
411                })
412            }
413        };
414        self.set_reg(dst, result)
415    }
416
417    fn list_pack(&mut self, dst: u8, base: u8, count: i32) -> Result<(), Fault> {
418        if !(0..=crate::bytecode::MAX_LIST_LEN as i32).contains(&count) {
419            return Err(Fault::TypeMismatch {
420                expected: "list length 0..=32",
421                got: "imm-out-of-range",
422            });
423        }
424        let mut items = Vec::with_capacity(count as usize);
425        for offset in 0..count {
426            let reg = reg_at(base, offset as u16)?;
427            items.push(self.get_reg(reg)?);
428        }
429        let list = match Value::try_list(items) {
430            Some(list) => list,
431            None => return Err(Fault::QuotaExceeded("value nesting exceeds limit".into())),
432        };
433        self.set_reg(dst, list)
434    }
435
436    fn list_get(&mut self, dst: u8, src: u8, index: i32) -> Result<(), Fault> {
437        let value = self.get_reg(src)?;
438        let Value::List(items) = value else {
439            return Err(Fault::TypeMismatch {
440                expected: "list",
441                got: value.type_name(),
442            });
443        };
444        if index < 0 {
445            return Err(Fault::TypeMismatch {
446                expected: "list index",
447                got: "negative-int",
448            });
449        }
450        match items.get(index as usize) {
451            Some(item) => self.set_reg(dst, item.clone()),
452            None => Err(Fault::TypeMismatch {
453                expected: "list index",
454                got: "out-of-range",
455            }),
456        }
457    }
458
459    fn list_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
460        let value = self.get_reg(src)?;
461        let Value::List(items) = value else {
462            return Err(Fault::TypeMismatch {
463                expected: "list",
464                got: value.type_name(),
465            });
466        };
467        self.set_reg(dst, Value::Int(items.len() as i64))
468    }
469
470    fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
471        let a = self.get_reg(lhs)?;
472        let b = self.get_reg(rhs)?;
473        let result = match (op, &a, &b) {
474            (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
475            (Opcode::Add, _, _) => Value::Float(as_f64(&a)? + as_f64(&b)?),
476            (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
477            (Opcode::Sub, _, _) => Value::Float(as_f64(&a)? - as_f64(&b)?),
478            (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
479            (Opcode::Mul, _, _) => Value::Float(as_f64(&a)? * as_f64(&b)?),
480            (Opcode::Div, Value::Int(x), Value::Int(y)) => {
481                if *y == 0 {
482                    return Err(Fault::DivideByZero);
483                }
484                Value::Int(x.wrapping_div(*y))
485            }
486            (Opcode::Div, _, _) => {
487                let denom = as_f64(&b)?;
488                Value::Float(as_f64(&a)? / denom)
489            }
490            (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
491                if *y == 0 {
492                    return Err(Fault::DivideByZero);
493                }
494                Value::Int(x.wrapping_rem(*y))
495            }
496            (Opcode::Mod, _, _) => {
497                let got = if !matches!(a, Value::Int(_)) {
498                    a.type_name()
499                } else {
500                    b.type_name()
501                };
502                return Err(Fault::TypeMismatch {
503                    expected: "int",
504                    got,
505                });
506            }
507            (Opcode::Eq, _, _) => Value::Bool(a == b),
508            (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
509            (Opcode::Lt, _, _) => Value::Bool(as_f64(&a)? < as_f64(&b)?),
510            (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
511            (Opcode::Le, _, _) => Value::Bool(as_f64(&a)? <= as_f64(&b)?),
512            _ => {
513                return Err(Fault::Invariant(
514                    "numeric_binop called with a non-arithmetic opcode",
515                ))
516            }
517        };
518        self.set_reg(dst, result)
519    }
520
521    #[inline]
522    fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
523        let v = self.get_reg(reg)?;
524        v.as_cap().ok_or(Fault::TypeMismatch {
525            expected: "cap",
526            got: v.type_name(),
527        })
528    }
529
530    #[inline]
531    fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
532        let v = self.get_reg(reg)?;
533        if v.as_message().is_none() {
534            return Err(Fault::TypeMismatch {
535                expected: "message",
536                got: v.type_name(),
537            });
538        }
539        Ok(v)
540    }
541
542    #[inline]
543    fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
544        match self.get_reg(reg)? {
545            Value::Str(s) => Ok(s),
546            other => Err(Fault::TypeMismatch {
547                expected: "str",
548                got: other.type_name(),
549            }),
550        }
551    }
552
553    #[inline]
554    fn int_from_reg(&self, reg: u8) -> Result<i64, Fault> {
555        match self.get_reg(reg)? {
556            Value::Int(n) => Ok(n),
557            other => Err(Fault::TypeMismatch {
558                expected: "int",
559                got: other.type_name(),
560            }),
561        }
562    }
563
564    #[inline]
565    fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
566        tag_from_value(&self.get_reg(reg)?)
567    }
568
569    #[inline]
570    fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
571        request_id_from_value(&self.get_reg(reg)?)
572    }
573
574    fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
575        let mut args = Vec::with_capacity(argc as usize);
576        for i in 0..argc {
577            let reg = reg_at(base, first_offset + u16::from(i))?;
578            args.push(self.get_reg(reg)?);
579        }
580        Ok(args)
581    }
582
583    /// Move `old_bytes` of dictionary charge to `new_bytes`.
584    ///
585    /// The counter is not the register frame. `pop_frame` must not release it.
586    fn adjust_dict_quota(&mut self, old_bytes: usize, new_bytes: usize) -> Result<(), Fault> {
587        if new_bytes > old_bytes {
588            let delta = new_bytes - old_bytes;
589            if let Some(quota) = self.quota.as_ref() {
590                charge_pair(quota, self.memory.as_deref(), delta)?;
591            }
592            self.dict_bytes = match self.dict_bytes.checked_add(delta) {
593                Some(next) => next,
594                None => {
595                    if let Some(quota) = self.quota.as_ref() {
596                        release_pair(quota, self.memory.as_deref(), delta);
597                    }
598                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
599                }
600            };
601        } else if old_bytes > new_bytes {
602            let delta = old_bytes - new_bytes;
603            if let Some(quota) = self.quota.as_ref() {
604                release_pair(quota, self.memory.as_deref(), delta);
605            }
606            self.dict_bytes = self.dict_bytes.saturating_sub(delta);
607        }
608        Ok(())
609    }
610
611    /// Non-negative `Int` only. `Bool` is not a duration.
612    fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
613        let millis = self.get_reg(reg)?;
614        match require_int(&millis) {
615            Ok(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
616            Ok(_) => Err(Fault::TypeMismatch {
617                expected: "non-negative int",
618                got: "negative-int",
619            }),
620            Err(fault) => Err(fault),
621        }
622    }
623
624    /// Apply a relative jump from the current (post-fetch) `pc`.
625    ///
626    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
627    /// Out-of-range targets always trap with [`Fault::BadJump`] (fail-closed).
628    fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
629        let code_len = self.chunk.code.len();
630        let frame = self.current()?;
631        let target_i = frame.pc() as i64 + i64::from(imm);
632        if target_i < 0 || target_i as usize > code_len {
633            let target = if target_i < 0 {
634                usize::MAX
635            } else {
636                target_i as usize
637            };
638            return Err(Fault::BadJump { target, code_len });
639        }
640        frame.set_pc(target_i as usize);
641        Ok(())
642    }
643
644    /// Run at most `budget` instructions (cooperative-preemption quantum,
645    /// design notes §10-11), or until the Flow completes / needs an
646    /// effect the scheduler must perform / faults.
647    ///
648    /// Every exit path is captured by [`VmResult`] — this function itself
649    /// never panics on malformed *verified* bytecode; faults are returned,
650    /// not thrown, so a buggy Flow can't take a worker thread down.
651    pub fn run(&mut self, budget: u32) -> VmResult {
652        macro_rules! trap {
653            ($e:expr) => {
654                match $e {
655                    Ok(v) => v,
656                    Err(fault) => return VmResult::Trap(fault),
657                }
658            };
659        }
660
661        for _ in 0..budget {
662            self.instructions_executed += 1;
663            let instr = match self.fetch() {
664                Ok(Some(i)) => i,
665                Ok(None) => {
666                    // Fell off the end of a function: implicit `return Unit`.
667                    match self.pop_frame(Value::Unit) {
668                        Ok(Some(result)) => return result,
669                        Ok(None) => continue,
670                        Err(fault) => return VmResult::Trap(fault),
671                    }
672                }
673                Err(fault) => return VmResult::Trap(fault),
674            };
675
676            match instr.op {
677                Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
678                Opcode::Nop => {}
679                Opcode::LoadConst => {
680                    let idx = instr.imm as u32;
681                    let konst = match self.chunk.constant(idx) {
682                        Some(v) => v.clone(),
683                        None => {
684                            return VmResult::Trap(Fault::BadConstant {
685                                index: idx,
686                                pool_size: self.chunk.constants.len() as u32,
687                            })
688                        }
689                    };
690                    trap!(self.set_reg(instr.a, konst));
691                }
692                Opcode::LoadImm => {
693                    trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
694                }
695                Opcode::AddImm => {
696                    trap!(self.add_imm(instr.a, instr.b, instr.imm));
697                }
698                Opcode::SubImm => {
699                    trap!(self.sub_imm(instr.a, instr.b, instr.imm));
700                }
701                Opcode::LtImm => {
702                    trap!(self.lt_imm(instr.a, instr.b, instr.imm));
703                }
704                Opcode::ListPack => {
705                    trap!(self.list_pack(instr.a, instr.b, instr.imm));
706                }
707                Opcode::ListGet => {
708                    trap!(self.list_get(instr.a, instr.b, instr.imm));
709                }
710                Opcode::ListLen => {
711                    trap!(self.list_len(instr.a, instr.b));
712                }
713                Opcode::Move => {
714                    let v = trap!(self.get_reg(instr.b));
715                    trap!(self.set_reg(instr.a, v));
716                }
717                Opcode::Add
718                | Opcode::Sub
719                | Opcode::Mul
720                | Opcode::Div
721                | Opcode::Mod
722                | Opcode::Eq
723                | Opcode::Lt
724                | Opcode::Le => {
725                    trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
726                }
727                Opcode::Neg => {
728                    let v = trap!(self.get_reg(instr.b));
729                    let negated = match v {
730                        Value::Int(x) => Value::Int(x.wrapping_neg()),
731                        Value::Float(x) => Value::Float(-x),
732                        other => {
733                            return VmResult::Trap(Fault::TypeMismatch {
734                                expected: "int or float",
735                                got: other.type_name(),
736                            })
737                        }
738                    };
739                    trap!(self.set_reg(instr.a, negated));
740                }
741                Opcode::Jump => {
742                    trap!(self.apply_relative_jump(instr.imm));
743                }
744                Opcode::Branch => {
745                    let cond = trap!(self.get_reg(instr.a));
746                    if !cond.is_truthy() {
747                        trap!(self.apply_relative_jump(instr.imm));
748                    }
749                }
750                Opcode::Call => {
751                    let function = instr.imm as u32;
752                    let argc = instr.b;
753                    let dst = instr.a;
754                    if self.frames.len() >= MAX_CALL_DEPTH {
755                        return VmResult::Trap(Fault::CallStackOverflow {
756                            depth: self.frames.len(),
757                        });
758                    }
759                    let (num_registers, arity, entry) = match self.chunk.function(function) {
760                        Some(d) => (d.num_registers, d.arity, d.entry as usize),
761                        None => {
762                            return VmResult::Trap(Fault::BadFunction {
763                                index: function,
764                                table_size: self.chunk.functions.len() as u32,
765                            })
766                        }
767                    };
768                    // `verify` rejects this statically. Direct `Vm::run` on an
769                    // unverified chunk must not drop extras or fill holes with
770                    // `Unit` — both hide a wrong call.
771                    if argc != arity {
772                        return VmResult::Trap(Fault::BadArity {
773                            passed: usize::from(argc),
774                            expected: arity,
775                        });
776                    }
777                    let args = trap!(self.gather_regs(dst, argc, 0));
778                    let mut new_frame = Frame::new(function, num_registers, Some(dst));
779                    new_frame.set_pc(entry);
780                    trap!(self.load_frame_args_charged(&mut new_frame, args, arity));
781                    self.frames.push(new_frame);
782                }
783                Opcode::CallNative | Opcode::CallNativeFrom => {
784                    let native_index = instr.imm as u32;
785                    // `CallNative` reads and writes `r[a]`. `CallNativeFrom`
786                    // reads `r[b]` and writes `r[a]`, so a one-arg unpack does
787                    // not destroy the source.
788                    let (arg_base, argc) = if instr.op == Opcode::CallNativeFrom {
789                        (instr.b, 1)
790                    } else {
791                        (instr.a, instr.b)
792                    };
793                    let dst = instr.a;
794                    if let Err(err) =
795                        check_native_gate(&self.native_gate, &self.natives, native_index)
796                    {
797                        return VmResult::Trap(match err {
798                            NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
799                                index,
800                                table_size: self.natives.len() as u32,
801                            },
802                            other => Fault::NativeDenied(other),
803                        });
804                    }
805                    let args = trap!(self.gather_regs(arg_base, argc, 0));
806                    // Runs inline on this worker thread — see
807                    // `NativeFn`'s doc comment on why natives must not
808                    // block. This is the actual FFI boundary (design
809                    // notes §30-31): plain Rust on one side, bytecode
810                    // registers on the other, with `Fault::NativeError`
811                    // as the only channel for a native-side failure to
812                    // become a Flow fault instead of a host panic.
813                    let result = match self.natives.get(native_index) {
814                        Some(native_fn) => native_fn(&args),
815                        None => {
816                            return VmResult::Trap(Fault::BadNative {
817                                index: native_index,
818                                table_size: self.natives.len() as u32,
819                            })
820                        }
821                    };
822                    match result {
823                        Ok(value) => trap!(self.set_reg(dst, value)),
824                        Err(fault) => return VmResult::Trap(fault),
825                    }
826                }
827                Opcode::Return => {
828                    let v = trap!(self.get_reg(instr.a));
829                    match self.pop_frame(v) {
830                        Ok(Some(result)) => return result,
831                        Ok(None) => {}
832                        Err(fault) => return VmResult::Trap(fault),
833                    }
834                }
835                Opcode::Spawn => {
836                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
837                    // child Cap. `a = 255` overflows on the first gather.
838                    let args = trap!(self.gather_regs(instr.a, instr.b, 1));
839                    return VmResult::Spawn {
840                        function: instr.imm as u32,
841                        args,
842                        dest_reg: instr.a,
843                        requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
844                    };
845                }
846                Opcode::Yield => return VmResult::Yield,
847                Opcode::Sleep => {
848                    return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
849                }
850                Opcode::Exit => {
851                    let v = trap!(self.get_reg(instr.a));
852                    return VmResult::Complete(v);
853                }
854                Opcode::SelfPid => {
855                    return VmResult::SelfPid { dest_reg: instr.a };
856                }
857                Opcode::Send => {
858                    let target_cap = trap!(self.expect_cap_reg(instr.a));
859                    let message = trap!(self.expect_message_value(instr.b));
860                    return VmResult::Send {
861                        target_cap,
862                        message,
863                    };
864                }
865                Opcode::Receive => {
866                    return VmResult::Receive {
867                        dest_reg: instr.a,
868                        timeout: None,
869                        match_tag: None,
870                        match_request_id: None,
871                        match_payload_kind: None,
872                        match_payload_eq: None,
873                        match_payload_value: None,
874                    };
875                }
876                Opcode::ReceiveTimeout => {
877                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
878                    return VmResult::Receive {
879                        dest_reg: instr.a,
880                        timeout: Some(timeout),
881                        match_tag: None,
882                        match_request_id: None,
883                        match_payload_kind: None,
884                        match_payload_eq: None,
885                        match_payload_value: None,
886                    };
887                }
888                Opcode::ReceiveMatch => {
889                    let tag = trap!(self.tag_from_reg(instr.b));
890                    return VmResult::Receive {
891                        dest_reg: instr.a,
892                        timeout: None,
893                        match_tag: Some(tag),
894                        match_request_id: None,
895                        match_payload_kind: None,
896                        match_payload_eq: None,
897                        match_payload_value: None,
898                    };
899                }
900                Opcode::ReceiveMatchImm => {
901                    let tag = trap!(tag_from_imm(instr.imm));
902                    return VmResult::Receive {
903                        dest_reg: instr.a,
904                        timeout: None,
905                        match_tag: Some(tag),
906                        match_request_id: None,
907                        match_payload_kind: None,
908                        match_payload_eq: None,
909                        match_payload_value: None,
910                    };
911                }
912                Opcode::ReceiveMatchTimeout => {
913                    let tag = trap!(self.tag_from_reg(instr.b));
914                    let timeout = trap!(self.duration_millis_from_reg(instr.c));
915                    return VmResult::Receive {
916                        dest_reg: instr.a,
917                        timeout: Some(timeout),
918                        match_tag: Some(tag),
919                        match_request_id: None,
920                        match_payload_kind: None,
921                        match_payload_eq: None,
922                        match_payload_value: None,
923                    };
924                }
925                Opcode::ReceiveMatchImmTimeout => {
926                    let tag = trap!(tag_from_imm(instr.imm));
927                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
928                    return VmResult::Receive {
929                        dest_reg: instr.a,
930                        timeout: Some(timeout),
931                        match_tag: Some(tag),
932                        match_request_id: None,
933                        match_payload_kind: None,
934                        match_payload_eq: None,
935                        match_payload_value: None,
936                    };
937                }
938                Opcode::IsAlive => {
939                    let target_cap = trap!(self.expect_cap_reg(instr.b));
940                    return VmResult::IsAlive {
941                        dest_reg: instr.a,
942                        target_cap,
943                    };
944                }
945                Opcode::ExitSignal => {
946                    let target_cap = trap!(self.expect_cap_reg(instr.a));
947                    let reason = trap!(self.int_from_reg(instr.b));
948                    let Ok(reason_u) = u64::try_from(reason) else {
949                        return VmResult::Trap(Fault::TypeMismatch {
950                            expected: "FlowExitReason 0..=6",
951                            got: "imm-out-of-range",
952                        });
953                    };
954                    if crate::FlowExitReason::from_u64(reason_u).is_none() {
955                        return VmResult::Trap(Fault::TypeMismatch {
956                            expected: "FlowExitReason 0..=6",
957                            got: "imm-out-of-range",
958                        });
959                    }
960                    return VmResult::ExitSignal {
961                        target_cap,
962                        reason: reason_u,
963                    };
964                }
965                Opcode::DictPut => {
966                    let key = trap!(self.int_from_reg(instr.b));
967                    let value = trap!(self.get_reg(instr.c));
968                    let new_bytes = trap!(dict_owned_bytes(&value));
969                    let previous = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
970                        Some(prev) => prev,
971                        None => Value::Unit,
972                    };
973                    let old_bytes = trap!(dict_owned_bytes(&previous));
974                    // Charge first, write the register second, and only then
975                    // replace the slot. `set_reg` of the previous value can
976                    // refuse (the old buffer moves into `ra` while `rc` and
977                    // the dictionary both still hold the new one). Rolling
978                    // the charge back leaves the slot untouched.
979                    if let Err(fault) = self.adjust_dict_quota(old_bytes, new_bytes) {
980                        return VmResult::Trap(fault);
981                    }
982                    if let Err(fault) = self.set_reg(instr.a, previous) {
983                        if let Err(rollback) = self.adjust_dict_quota(new_bytes, old_bytes) {
984                            return VmResult::Trap(rollback);
985                        }
986                        return VmResult::Trap(fault);
987                    }
988                    self.dict
989                        .get_or_insert_with(HashMap::new)
990                        .insert(key, value);
991                }
992                Opcode::DictGet => {
993                    let key = trap!(self.int_from_reg(instr.b));
994                    let value = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
995                        Some(v) => v,
996                        None => Value::Unit,
997                    };
998                    trap!(self.set_reg(instr.a, value));
999                }
1000                Opcode::DictErase => {
1001                    let key = trap!(self.int_from_reg(instr.b));
1002                    // A bad destination must not drop the entry on the way out.
1003                    trap!(self.get_reg(instr.a));
1004                    let old = match self.dict.as_mut().and_then(|d| d.remove(&key)) {
1005                        Some(v) => v,
1006                        None => Value::Unit,
1007                    };
1008                    let old_bytes = trap!(dict_owned_bytes(&old));
1009                    trap!(self.adjust_dict_quota(old_bytes, 0));
1010                    trap!(self.set_reg(instr.a, old));
1011                }
1012                Opcode::ReceiveMatchEq => {
1013                    let tag = trap!(self.tag_from_reg(instr.b));
1014                    let payload = trap!(self.int_from_reg(instr.c));
1015                    return VmResult::Receive {
1016                        dest_reg: instr.a,
1017                        timeout: None,
1018                        match_tag: Some(tag),
1019                        match_request_id: None,
1020                        match_payload_kind: None,
1021                        match_payload_eq: Some(payload),
1022                        match_payload_value: None,
1023                    };
1024                }
1025                Opcode::ReceiveMatchValue => {
1026                    let tag = trap!(self.tag_from_reg(instr.b));
1027                    let payload = trap!(self.get_reg(instr.c));
1028                    return VmResult::Receive {
1029                        dest_reg: instr.a,
1030                        timeout: None,
1031                        match_tag: Some(tag),
1032                        match_request_id: None,
1033                        match_payload_kind: None,
1034                        match_payload_eq: None,
1035                        match_payload_value: Some(Arc::new(payload)),
1036                    };
1037                }
1038                Opcode::SendRemote => {
1039                    let node = trap!(self.int_from_reg(instr.a));
1040                    if node < 0 {
1041                        return VmResult::Trap(Fault::TypeMismatch {
1042                            expected: "node id >= 0",
1043                            got: "negative",
1044                        });
1045                    }
1046                    let name = match trap!(self.get_reg(instr.b)) {
1047                        Value::Str(name) => name,
1048                        _ => {
1049                            return VmResult::Trap(Fault::TypeMismatch {
1050                                expected: "str",
1051                                got: "not-str",
1052                            })
1053                        }
1054                    };
1055                    let message = trap!(self.expect_message_value(instr.c));
1056                    let Ok(node) = u64::try_from(node) else {
1057                        return VmResult::Trap(Fault::TypeMismatch {
1058                            expected: "node id",
1059                            got: "imm-out-of-range",
1060                        });
1061                    };
1062                    return VmResult::SendRemote {
1063                        node,
1064                        name,
1065                        message,
1066                    };
1067                }
1068                Opcode::StartSupervisor => {
1069                    let Ok(strategy) = u8::try_from(instr.imm) else {
1070                        return VmResult::Trap(Fault::TypeMismatch {
1071                            expected: "strategy 0..=2",
1072                            got: "imm-out-of-range",
1073                        });
1074                    };
1075                    if strategy > 2 {
1076                        return VmResult::Trap(Fault::TypeMismatch {
1077                            expected: "strategy 0..=2",
1078                            got: "imm-out-of-range",
1079                        });
1080                    }
1081                    return VmResult::StartSupervisor { strategy };
1082                }
1083                Opcode::StartChild => {
1084                    let function = match u32::try_from(instr.imm) {
1085                        Ok(f) => f,
1086                        Err(_) => u32::MAX,
1087                    };
1088                    if self.chunk.function(function).is_none() {
1089                        return VmResult::Trap(Fault::BadFunction {
1090                            index: function,
1091                            table_size: self.chunk.functions.len() as u32,
1092                        });
1093                    }
1094                    if crate::RestartPolicy::from_u8(instr.b).is_none() {
1095                        return VmResult::Trap(Fault::TypeMismatch {
1096                            expected: "restart policy 0..=2",
1097                            got: "imm-out-of-range",
1098                        });
1099                    }
1100                    return VmResult::StartChild {
1101                        dest_reg: instr.a,
1102                        function,
1103                        policy: instr.b,
1104                    };
1105                }
1106                Opcode::ReceiveMatchKind => {
1107                    // Selective receive by payload wire-tag (`Value::wire_tag`,
1108                    // 0..=8). Non-matching hops stay queued (FIFO skip).
1109                    let kind = match u8::try_from(instr.imm) {
1110                        Ok(k) if k <= 9 => k,
1111                        _ => {
1112                            return VmResult::Trap(Fault::TypeMismatch {
1113                                expected: "payload kind 0..=9",
1114                                got: "imm-out-of-range",
1115                            })
1116                        }
1117                    };
1118                    return VmResult::Receive {
1119                        dest_reg: instr.a,
1120                        timeout: None,
1121                        match_tag: None,
1122                        match_request_id: None,
1123                        match_payload_kind: Some(kind),
1124                        match_payload_eq: None,
1125                        match_payload_value: None,
1126                    };
1127                }
1128                Opcode::FreshRequestId => {
1129                    let id = self.fresh_request_id();
1130                    trap!(self.set_reg(instr.a, Value::Int(id as i64)));
1131                }
1132                Opcode::ReceiveMatchCorr => {
1133                    let tag = trap!(self.tag_from_reg(instr.b));
1134                    let rid = trap!(self.request_id_from_reg(instr.c));
1135                    return VmResult::Receive {
1136                        dest_reg: instr.a,
1137                        timeout: None,
1138                        match_tag: Some(tag),
1139                        match_request_id: Some(rid),
1140                        match_payload_kind: None,
1141                        match_payload_eq: None,
1142                        match_payload_value: None,
1143                    };
1144                }
1145                Opcode::ReceiveMatchCorrImm => {
1146                    let tag = trap!(tag_from_imm(instr.imm));
1147                    let rid = trap!(self.request_id_from_reg(instr.b));
1148                    return VmResult::Receive {
1149                        dest_reg: instr.a,
1150                        timeout: None,
1151                        match_tag: Some(tag),
1152                        match_request_id: Some(rid),
1153                        match_payload_kind: None,
1154                        match_payload_eq: None,
1155                        match_payload_value: None,
1156                    };
1157                }
1158                Opcode::Ask => {
1159                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1160                    let request = trap!(self.expect_message_value(instr.c));
1161                    return VmResult::Ask {
1162                        dest_reg: instr.a,
1163                        target_cap,
1164                        request,
1165                        timeout: None,
1166                    };
1167                }
1168                Opcode::AskTimeout => {
1169                    let millis_reg = match u8::try_from(instr.imm) {
1170                        Ok(r) => r,
1171                        Err(_) => {
1172                            return VmResult::Trap(Fault::TypeMismatch {
1173                                expected: "millis register",
1174                                got: "imm-out-of-range",
1175                            })
1176                        }
1177                    };
1178                    let timeout = trap!(self.duration_millis_from_reg(millis_reg));
1179                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1180                    let request = trap!(self.expect_message_value(instr.c));
1181                    return VmResult::Ask {
1182                        dest_reg: instr.a,
1183                        target_cap,
1184                        request,
1185                        timeout: Some(timeout),
1186                    };
1187                }
1188                Opcode::Monitor => {
1189                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1190                    return VmResult::Monitor {
1191                        dest_reg: instr.a,
1192                        target_cap,
1193                    };
1194                }
1195                Opcode::Demonitor => {
1196                    return VmResult::Demonitor {
1197                        monitor_reg: instr.a,
1198                    };
1199                }
1200                Opcode::Link => {
1201                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1202                    return VmResult::Link {
1203                        dest_reg: instr.a,
1204                        target_cap,
1205                    };
1206                }
1207                Opcode::Unlink => {
1208                    return VmResult::Unlink { link_reg: instr.a };
1209                }
1210                Opcode::SetTrapExit => {
1211                    let enabled = trap!(self.get_reg(instr.a)).is_truthy();
1212                    return VmResult::SetTrapExit { enabled };
1213                }
1214                Opcode::SetRestartPolicy => {
1215                    // Flow-local OTP restart policy for the host Supervisor
1216                    // (`0` Always / `1` OnFailure / `2` Never).
1217                    let policy = match instr.imm {
1218                        0..=2 => instr.imm as u8,
1219                        _ => {
1220                            return VmResult::Trap(Fault::TypeMismatch {
1221                                expected: "restart policy 0..=2",
1222                                got: "imm-out-of-range",
1223                            })
1224                        }
1225                    };
1226                    return VmResult::SetRestartPolicy { policy };
1227                }
1228                Opcode::HostAwait => {
1229                    let args = trap!(self.get_reg(instr.b));
1230                    let op = if instr.imm < 0 {
1231                        return VmResult::Trap(Fault::TypeMismatch {
1232                            expected: "HostAwait op >= 0",
1233                            got: "imm-negative",
1234                        });
1235                    } else {
1236                        instr.imm as u32
1237                    };
1238                    return VmResult::HostAwait {
1239                        dest_reg: instr.a,
1240                        op,
1241                        args,
1242                    };
1243                }
1244                Opcode::RegisterName => {
1245                    return VmResult::RegisterName {
1246                        name: trap!(self.expect_str_reg(instr.a)),
1247                    };
1248                }
1249                Opcode::Whereis => {
1250                    return VmResult::Whereis {
1251                        dest_reg: instr.a,
1252                        name: trap!(self.expect_str_reg(instr.b)),
1253                    };
1254                }
1255                Opcode::Delegate => {
1256                    let src_cap = trap!(self.expect_cap_reg(instr.b));
1257                    let want_native_cap = if instr.c == 255 {
1258                        None
1259                    } else {
1260                        Some(trap!(self.expect_cap_reg(instr.c)))
1261                    };
1262                    return VmResult::Delegate {
1263                        dest_reg: instr.a,
1264                        src_cap,
1265                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
1266                        want_native_cap,
1267                    };
1268                }
1269                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
1270            }
1271        }
1272        VmResult::Yield
1273    }
1274
1275    /// Pop the current frame, delivering `value` to the caller (or
1276    /// finishing the Flow if this was the outermost frame). Returns
1277    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
1278    ///
1279    /// Releases the finished frame's heap charge (except the escaping
1280    /// return value on the outermost `Complete` path, which stays charged
1281    /// until flow finalize — matching prior MemoryBudget semantics).
1282    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
1283        let escaping = self
1284            .frames
1285            .last()
1286            .ok_or(Fault::Invariant("pop_frame on empty stack"))?
1287            .dest_reg()
1288            .is_none();
1289        // Charge the escaping value before the pop, so a chain past the
1290        // decoder ceiling fails without dropping the frame first.
1291        let keep = if escaping { heap_charge_of(&value)? } else { 0 };
1292        let finished = self
1293            .frames
1294            .pop()
1295            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
1296        match finished.dest_reg() {
1297            Some(dest) => {
1298                if let Some(quota) = self.quota.as_ref() {
1299                    release_pair(quota, self.memory.as_deref(), finished.heap_charge());
1300                }
1301                self.set_reg(dest, value)?;
1302                Ok(None)
1303            }
1304            None => {
1305                if let Some(quota) = self.quota.as_ref() {
1306                    let release = finished.heap_charge().saturating_sub(keep);
1307                    release_pair(quota, self.memory.as_deref(), release);
1308                }
1309                Ok(Some(VmResult::Complete(value)))
1310            }
1311        }
1312    }
1313
1314    /// Load call arguments into a not-yet-pushed frame, charging heap for
1315    /// any `Str`/`Bytes`. Rolls back a partial charge if a later arg fails.
1316    fn load_frame_args_charged(
1317        &self,
1318        frame: &mut Frame,
1319        args: impl IntoIterator<Item = Value>,
1320        arity: u8,
1321    ) -> Result<(), Fault> {
1322        let frame_size = frame.registers().len() as u8;
1323        let mut charged = 0usize;
1324        for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1325            let bytes = heap_charge_of(&a)?;
1326            if bytes > 0 {
1327                if let Some(quota) = self.quota.as_ref() {
1328                    if let Err(e) = charge_pair(quota, self.memory.as_deref(), bytes) {
1329                        if charged > 0 {
1330                            release_pair(quota, self.memory.as_deref(), charged);
1331                        }
1332                        frame.set_heap_charge(0);
1333                        return Err(e);
1334                    }
1335                }
1336                let Some(next) = charged.checked_add(bytes) else {
1337                    if let Some(quota) = self.quota.as_ref() {
1338                        release_pair(quota, self.memory.as_deref(), charged);
1339                        release_pair(quota, self.memory.as_deref(), bytes);
1340                    }
1341                    frame.set_heap_charge(0);
1342                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
1343                };
1344                if !frame.try_add_heap_charge(bytes) {
1345                    if let Some(quota) = self.quota.as_ref() {
1346                        release_pair(quota, self.memory.as_deref(), next);
1347                    }
1348                    frame.set_heap_charge(0);
1349                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
1350                }
1351                charged = next;
1352            }
1353            match frame.registers_mut().get_mut(i) {
1354                Some(slot) => *slot = a,
1355                None => {
1356                    if charged > 0 {
1357                        if let Some(quota) = self.quota.as_ref() {
1358                            release_pair(quota, self.memory.as_deref(), charged);
1359                        }
1360                        frame.set_heap_charge(0);
1361                    }
1362                    return Err(Fault::RegisterOutOfRange {
1363                        reg: i as u8,
1364                        frame_size,
1365                    });
1366                }
1367            }
1368        }
1369        Ok(())
1370    }
1371}
1372
1373/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
1374/// if that sum leaves the register index space.
1375///
1376/// Every multi-operand opcode gathers its arguments from consecutive
1377/// registers. Written as a plain `base + offset` on `u8`, that addition
1378/// panics in debug and **wraps** in release — so a release build silently
1379/// reads the wrong register instead of failing, which is the worst of the
1380/// two outcomes and the one a debug-mode test suite never sees. The sum is
1381/// therefore computed in a wider type and narrowed explicitly.
1382#[inline]
1383fn load_frame_args(
1384    frame: &mut Frame,
1385    args: impl IntoIterator<Item = Value>,
1386    arity: u8,
1387) -> Result<(), Fault> {
1388    let frame_size = frame.registers().len() as u8;
1389    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1390        match frame.registers_mut().get_mut(i) {
1391            Some(slot) => *slot = a,
1392            None => {
1393                return Err(Fault::RegisterOutOfRange {
1394                    reg: i as u8,
1395                    frame_size,
1396                })
1397            }
1398        }
1399    }
1400    Ok(())
1401}
1402
1403fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
1404    match u8::try_from(u32::from(base) + u32::from(offset)) {
1405        Ok(reg) => Ok(reg),
1406        Err(_) => Err(Fault::RegisterIndexOverflow {
1407            base,
1408            offset: match u8::try_from(offset) {
1409                Ok(o) => o,
1410                Err(_) => u8::MAX,
1411            },
1412        }),
1413    }
1414}
1415
1416/// Bytes charged for a register-resident heap value.
1417///
1418/// `Str` / `Bytes` charge their length. A [`Value::Message`] charges the
1419/// payload, down to the same ceiling as the `.bf` decoder. Stopping at that
1420/// ceiling and still storing the value would leave the tail unpaid.
1421#[inline]
1422fn heap_charge_of(value: &Value) -> Result<usize, Fault> {
1423    fn walk(value: &Value, depth: u32) -> Result<usize, Fault> {
1424        if depth > crate::bytecode::MAX_VALUE_DEPTH {
1425            return Err(Fault::QuotaExceeded("value nesting exceeds limit".into()));
1426        }
1427        match value {
1428            Value::Str(s) => Ok(s.len()),
1429            Value::Bytes(b) => Ok(b.len()),
1430            Value::Message(message) => walk(message.payload.as_ref(), depth + 1),
1431            Value::List(items) => {
1432                let mut sum = items
1433                    .len()
1434                    .checked_mul(std::mem::size_of::<Value>())
1435                    .ok_or_else(|| Fault::QuotaExceeded("heap charge does not fit".into()))?;
1436                for item in items.iter() {
1437                    let part = walk(item, depth + 1)?;
1438                    sum = match sum.checked_add(part) {
1439                        Some(total) => total,
1440                        None => {
1441                            return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
1442                        }
1443                    };
1444                }
1445                Ok(sum)
1446            }
1447            Value::Unit
1448            | Value::Bool(_)
1449            | Value::Int(_)
1450            | Value::Float(_)
1451            | Value::Pid(_)
1452            | Value::Cap(_) => Ok(0),
1453        }
1454    }
1455    walk(value, 0)
1456}
1457
1458/// Bytes to reserve on the sender quota while `value` is in flight.
1459///
1460/// The hop is still in a register, and that register already pays for the
1461/// `Str` / `Bytes` inside it. Charging [`Value::memory_size`] on top of that
1462/// counts the same buffers twice and rejects a send the quota can hold.
1463#[inline]
1464pub(crate) fn in_flight_hop_charge(value: &Value) -> usize {
1465    match heap_charge_of(value) {
1466        Ok(held) => value.memory_size().saturating_sub(held),
1467        Err(_) => value.memory_size(),
1468    }
1469}
1470
1471/// Reserve `bytes` on the flow quota and optional runtime budget.
1472/// Rolls back the flow charge if the global budget refuses.
1473fn charge_pair(
1474    quota: &FlowQuota,
1475    memory: Option<&crate::MemoryBudget>,
1476    bytes: usize,
1477) -> Result<(), Fault> {
1478    if bytes == 0 {
1479        return Ok(());
1480    }
1481    quota
1482        .alloc(bytes)
1483        .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
1484    if let Some(mem) = memory {
1485        if let Err(e) = mem.try_charge(bytes) {
1486            quota.free(bytes);
1487            return Err(Fault::QuotaExceeded(e.to_string()));
1488        }
1489    }
1490    Ok(())
1491}
1492
1493fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
1494    if bytes == 0 {
1495        return;
1496    }
1497    quota.free(bytes);
1498    if let Some(mem) = memory {
1499        mem.release(bytes);
1500    }
1501}
1502
1503fn as_f64(v: &Value) -> Result<f64, Fault> {
1504    match v {
1505        Value::Int(i) => Ok(*i as f64),
1506        Value::Float(f) => Ok(*f),
1507        other => Err(Fault::TypeMismatch {
1508            expected: "int or float",
1509            got: other.type_name(),
1510        }),
1511    }
1512}
1513
1514/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
1515#[inline]
1516fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
1517    match u16::try_from(imm) {
1518        Ok(t) if imm >= 0 => Ok(t),
1519        _ => Err(Fault::TypeMismatch {
1520            expected: "tag u16",
1521            got: "imm-out-of-range",
1522        }),
1523    }
1524}
1525
1526/// `Int` only. [`Value::as_int`] still coerces `Bool` for natives.
1527fn require_int(v: &Value) -> Result<i64, Fault> {
1528    match v {
1529        Value::Int(n) => Ok(*n),
1530        other => Err(Fault::TypeMismatch {
1531            expected: "int",
1532            got: other.type_name(),
1533        }),
1534    }
1535}
1536
1537fn tag_from_value(v: &Value) -> Result<u16, Fault> {
1538    match require_int(v) {
1539        Ok(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
1540        Ok(_) => Err(Fault::TypeMismatch {
1541            expected: "tag u16",
1542            got: "int-out-of-range",
1543        }),
1544        Err(fault) => Err(fault),
1545    }
1546}
1547
1548/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
1549#[inline]
1550fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
1551    match require_int(v) {
1552        Ok(i) if i >= 0 => Ok(i as u64),
1553        Ok(_) => Err(Fault::TypeMismatch {
1554            expected: "request_id u64",
1555            got: "negative-int",
1556        }),
1557        Err(fault) => Err(fault),
1558    }
1559}
1560
1561#[cfg(test)]
1562mod tests {
1563    use super::*;
1564    use crate::bytecode::builder::ChunkBuilder;
1565
1566    type TestResult = Result<(), Box<dyn std::error::Error>>;
1567
1568    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
1569    /// already leaves the register space. This used to panic in debug and —
1570    /// far worse — wrap around to `r0` in release, silently spawning with the
1571    /// wrong argument.
1572    #[test]
1573    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1574        let mut b = ChunkBuilder::new("t");
1575        b.begin_function("main", 0, 2);
1576        b.emit_spawn(255, 0, 1);
1577        b.emit_return(0);
1578        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1579        match vm.run(10) {
1580            VmResult::Trap(Fault::RegisterIndexOverflow {
1581                base: 255,
1582                offset: 1,
1583            }) => Ok(()),
1584            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1585        }
1586    }
1587
1588    /// `Vm::new` is public and reachable without `verify`, and its panic
1589    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
1590    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
1591    #[test]
1592    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1593        let mut b = ChunkBuilder::new("t");
1594        b.begin_function("main", 3, 1);
1595        b.emit_return(0);
1596        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1597        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1598            Err(Fault::RegisterOutOfRange {
1599                reg: 1,
1600                frame_size: 1,
1601            }) => Ok(()),
1602            Err(e) => Err(format!("unexpected fault: {e}").into()),
1603            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1604        }
1605    }
1606
1607    #[test]
1608    fn call_with_the_wrong_argc_traps_instead_of_padding() -> TestResult {
1609        let mut b = ChunkBuilder::new("t");
1610        let callee = b.begin_function("callee", 0, 1);
1611        b.emit_load_imm(0, 1);
1612        b.emit_return(0);
1613        let main = b.begin_function("main", 0, 2);
1614        b.emit_load_imm(0, 7);
1615        b.emit_call(0, callee, 1);
1616        b.emit_return(0);
1617        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1618        match vm.run(20) {
1619            VmResult::Trap(Fault::BadArity {
1620                passed: 1,
1621                expected: 0,
1622            }) => Ok(()),
1623            other => Err(format!("expected BadArity, got {other:?}").into()),
1624        }
1625    }
1626
1627    #[test]
1628    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1629        let mut b = ChunkBuilder::new("t");
1630        let callee = b.begin_function("callee", 3, 1);
1631        b.emit_return(0);
1632        let main = b.begin_function("main", 0, 4);
1633        b.emit_load_imm(0, 7);
1634        b.emit_load_imm(1, 8);
1635        b.emit_load_imm(2, 9);
1636        b.emit_call(0, callee, 3);
1637        b.emit_return(0);
1638        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1639        match vm.run(50) {
1640            VmResult::Trap(Fault::RegisterOutOfRange {
1641                reg: 1,
1642                frame_size: 1,
1643            }) => Ok(()),
1644            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1645        }
1646    }
1647
1648    /// The boundary case that must keep working: gathering right up to the
1649    /// last register is legal, it is only going *past* it that faults.
1650    #[test]
1651    fn gathering_up_to_the_last_register_still_works() -> TestResult {
1652        let mut b = ChunkBuilder::new("t");
1653        let callee = b.begin_function("callee", 1, 1);
1654        b.emit_return(0);
1655        let main = b.begin_function("main", 0, 255);
1656        b.emit_load_imm(254, 5);
1657        // Argument at r254 — the highest index a 255-register frame has.
1658        b.emit_call(254, callee, 1);
1659        b.emit_return(254);
1660        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1661        match vm.run(100) {
1662            VmResult::Complete(_) => Ok(()),
1663            other => Err(format!("expected completion, got {other:?}").into()),
1664        }
1665    }
1666
1667    #[test]
1668    fn neg_i64_min_wrapping() -> TestResult {
1669        let mut b = ChunkBuilder::new("t");
1670        b.begin_function("main", 0, 1);
1671        let k = b.const_(Value::Int(i64::MIN));
1672        b.emit_load_const(0, k);
1673        b.emit_neg(0, 0);
1674        b.emit_return(0);
1675        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1676        match vm.run(10) {
1677            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1678            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1679        }
1680    }
1681
1682    #[test]
1683    fn mod_non_int_type_mismatch() -> TestResult {
1684        let mut b = ChunkBuilder::new("t");
1685        b.begin_function("main", 0, 3);
1686        b.emit_load_imm(0, 10);
1687        let kf = b.const_(Value::Float(3.0));
1688        b.emit_load_const(1, kf);
1689        b.emit_binop(Opcode::Mod, 2, 0, 1);
1690        b.emit_return(2);
1691        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1692        match vm.run(20) {
1693            VmResult::Trap(Fault::TypeMismatch {
1694                expected: "int",
1695                got: "float",
1696            }) => Ok(()),
1697            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1698        }
1699    }
1700
1701    #[test]
1702    fn receive_timeout_negative_traps() -> TestResult {
1703        let mut b = ChunkBuilder::new("t");
1704        b.begin_function("main", 0, 2);
1705        b.emit_load_imm(1, -1);
1706        b.emit_receive_timeout(0, 1);
1707        b.emit_return(0);
1708        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1709        match vm.run(10) {
1710            VmResult::Trap(Fault::TypeMismatch {
1711                expected: "non-negative int",
1712                ..
1713            }) => Ok(()),
1714            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1715        }
1716    }
1717
1718    #[test]
1719    fn ask_timeout_negative_traps() -> TestResult {
1720        let mut b = ChunkBuilder::new("t");
1721        b.begin_function("main", 0, 4);
1722        b.emit_load_imm(3, -5);
1723        // Cap/message regs are garbage; millis is checked first.
1724        b.emit_ask_timeout(0, 1, 2, 3);
1725        b.emit_return(0);
1726        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1727        match vm.run(10) {
1728            VmResult::Trap(Fault::TypeMismatch {
1729                expected: "non-negative int",
1730                ..
1731            }) => Ok(()),
1732            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1733        }
1734    }
1735
1736    #[test]
1737    fn paranoid_jump_out_of_range_traps() -> TestResult {
1738        let mut b = ChunkBuilder::new("t");
1739        b.begin_function("main", 0, 1);
1740        b.emit_load_imm(0, 0);
1741        b.emit_return(0);
1742        let mut chunk = b.finish();
1743        let code_len = chunk.code.len();
1744        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1745        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1746        vm.set_paranoid_jumps(true);
1747        match vm.run(10) {
1748            VmResult::Trap(Fault::BadJump {
1749                target: 101,
1750                code_len: len,
1751            }) if len == code_len => Ok(()),
1752            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1753        }
1754    }
1755
1756    #[test]
1757    fn overwrite_releases_previous_heap_charge() -> TestResult {
1758        let mut b = ChunkBuilder::new("t");
1759        let k1 = b.const_(Value::Str("a".repeat(100).into()));
1760        let k2 = b.const_(Value::Str("b".repeat(100).into()));
1761        b.begin_function("main", 0, 1);
1762        b.emit_load_const(0, k1);
1763        b.emit_load_const(0, k2);
1764        b.emit_return(0);
1765        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1766        // Limit 150: first 100 fits; without release the second 100 would fail.
1767        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1768            crate::QuotaConfig {
1769                mem_limit: 150,
1770                ..crate::QuotaConfig::permissive()
1771            },
1772        ));
1773        let memory = Arc::new(crate::MemoryBudget::new(10_000));
1774        vm.set_memory_budget(Arc::clone(&memory));
1775        vm.set_quota(Arc::clone(&quota))?;
1776        match vm.run(20) {
1777            VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1778                assert_eq!(quota.mem_used(), 100);
1779                assert_eq!(memory.used(), 100);
1780                Ok(())
1781            }
1782            other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1783        }
1784    }
1785
1786    #[test]
1787    fn return_releases_callee_heap_before_caller_writeback() -> TestResult {
1788        let mut b = ChunkBuilder::new("t");
1789        let k = b.const_(Value::Str("x".repeat(200).into()));
1790        let callee = b.begin_function("callee", 0, 1);
1791        b.emit_load_const(0, k);
1792        b.emit_return(0);
1793        let main = b.begin_function("main", 0, 1);
1794        b.emit_call(0, callee, 0);
1795        b.emit_return(0);
1796        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1797        // Old bug: callee charged 200 and return writeback charged again without
1798        // release → QuotaExceeded at 250. Correct path releases then recharges.
1799        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1800        vm.set_quota(Arc::clone(&quota))?;
1801        match vm.run(50) {
1802            VmResult::Complete(Value::Str(s)) if s.len() == 200 => {
1803                assert_eq!(quota.mem_used(), 200);
1804                Ok(())
1805            }
1806            other => Err(format!("expected Complete(200-byte Str), got {other:?}").into()),
1807        }
1808    }
1809
1810    #[test]
1811    fn set_reg_out_of_range_does_not_charge() -> TestResult {
1812        let mut b = ChunkBuilder::new("t");
1813        b.begin_function("main", 0, 1);
1814        b.emit_return(0);
1815        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1816        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1817            crate::QuotaConfig {
1818                mem_limit: 10_000,
1819                ..crate::QuotaConfig::permissive()
1820            },
1821        ));
1822        vm.set_quota(Arc::clone(&quota))?;
1823        let big = Value::Str("z".repeat(500).into());
1824        match vm.set_register(255, big) {
1825            Err(Fault::RegisterOutOfRange {
1826                reg: 255,
1827                frame_size: 1,
1828            }) => {
1829                assert_eq!(quota.mem_used(), 0);
1830                Ok(())
1831            }
1832            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1833        }
1834    }
1835
1836    #[test]
1837    fn set_quota_is_transactional() -> TestResult {
1838        let mut b = ChunkBuilder::new("t");
1839        b.begin_function("main", 0, 2);
1840        b.emit_return(0);
1841        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1842        // Two 100-byte Strs already in registers; limit 150 must refuse the
1843        // whole attach without leaving a partial charge on the quota object.
1844        vm.set_register(0, Value::Str("a".repeat(100).into()))?;
1845        vm.set_register(1, Value::Str("b".repeat(100).into()))?;
1846        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1847            crate::QuotaConfig {
1848                mem_limit: 150,
1849                ..crate::QuotaConfig::permissive()
1850            },
1851        ));
1852        match vm.set_quota(Arc::clone(&quota)) {
1853            Err(Fault::QuotaExceeded(_)) => {
1854                assert_eq!(
1855                    quota.mem_used(),
1856                    0,
1857                    "failed set_quota must not leave a partial charge"
1858                );
1859                Ok(())
1860            }
1861            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
1862        }
1863    }
1864
1865    #[test]
1866    fn message_payload_counts_against_the_heap_quota() -> TestResult {
1867        let mut b = ChunkBuilder::new("t");
1868        b.begin_function("main", 0, 1);
1869        b.emit_return(0);
1870        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1871        let quota = Arc::new(FlowQuota::new(10_000, 64, 1, 1, 1, 1));
1872        vm.set_quota(Arc::clone(&quota))?;
1873        let hop = Value::Message(crate::bytecode::Message::new(
1874            0,
1875            1,
1876            1,
1877            Value::str("x".repeat(200)),
1878        ));
1879        match vm.set_register(0, hop) {
1880            Err(Fault::QuotaExceeded(_)) => {
1881                assert_eq!(quota.mem_used(), 0);
1882                Ok(())
1883            }
1884            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
1885        }
1886    }
1887
1888    #[test]
1889    fn overwriting_a_message_releases_the_payload_charge() -> TestResult {
1890        let mut b = ChunkBuilder::new("t");
1891        b.begin_function("main", 0, 1);
1892        b.emit_return(0);
1893        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1894        let quota = Arc::new(FlowQuota::new(10_000, 10_000, 1, 1, 1, 1));
1895        vm.set_quota(Arc::clone(&quota))?;
1896        vm.set_register(
1897            0,
1898            Value::Message(crate::bytecode::Message::new(
1899                0,
1900                1,
1901                1,
1902                Value::str("x".repeat(200)),
1903            )),
1904        )?;
1905        assert_eq!(quota.mem_used(), 200);
1906        vm.set_register(0, Value::Int(1))?;
1907        assert_eq!(quota.mem_used(), 0);
1908        Ok(())
1909    }
1910
1911    #[test]
1912    fn a_message_past_the_decoder_ceiling_is_not_stored() -> TestResult {
1913        let mut b = ChunkBuilder::new("t");
1914        b.begin_function("main", 0, 1);
1915        b.emit_return(0);
1916        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1917        let quota = Arc::new(FlowQuota::new(10_000, 10_000, 1, 1, 1, 1));
1918        vm.set_quota(Arc::clone(&quota))?;
1919        let mut value = Value::str("x".repeat(200));
1920        for _ in 0..17 {
1921            value = Value::Message(crate::bytecode::Message::new(0, 1, 1, value));
1922        }
1923        match vm.set_register(0, value) {
1924            Err(Fault::QuotaExceeded(_)) => {
1925                assert_eq!(quota.mem_used(), 0);
1926                Ok(())
1927            }
1928            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
1929        }
1930    }
1931
1932    #[test]
1933    fn in_flight_hop_does_not_recount_the_held_payload() {
1934        let hop = Value::Message(crate::bytecode::Message::new(
1935            0,
1936            1,
1937            1,
1938            Value::str("x".repeat(200)),
1939        ));
1940        let inflight = in_flight_hop_charge(&hop);
1941        assert_eq!(inflight + 200, hop.memory_size());
1942        assert!(inflight < hop.memory_size());
1943    }
1944
1945    #[test]
1946    fn sleep_rejects_a_bool() -> TestResult {
1947        let mut b = ChunkBuilder::new("t");
1948        let flag = b.const_(Value::Bool(true));
1949        b.begin_function("main", 0, 1);
1950        b.emit_load_const(0, flag);
1951        b.emit_sleep(0);
1952        b.emit_return(0);
1953        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1954        match vm.run(10) {
1955            VmResult::Trap(Fault::TypeMismatch {
1956                expected: "int",
1957                got: "bool",
1958            }) => Ok(()),
1959            other => Err(format!("expected TypeMismatch(bool), got {other:?}").into()),
1960        }
1961    }
1962
1963    #[test]
1964    fn tag_and_request_id_reject_a_bool() -> TestResult {
1965        let mut b = ChunkBuilder::new("t");
1966        let flag = b.const_(Value::Bool(false));
1967        b.begin_function("main", 0, 3);
1968        b.emit_load_const(0, flag);
1969        b.emit_receive_match(1, 0);
1970        b.emit_return(0);
1971        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1972        match vm.run(10) {
1973            VmResult::Trap(Fault::TypeMismatch {
1974                expected: "int",
1975                got: "bool",
1976            }) => {}
1977            other => return Err(format!("tag bool: {other:?}").into()),
1978        }
1979        let mut b = ChunkBuilder::new("t");
1980        let flag = b.const_(Value::Bool(true));
1981        b.begin_function("main", 0, 3);
1982        b.emit_load_imm(0, 1);
1983        b.emit_load_const(1, flag);
1984        b.emit_receive_match_corr(2, 0, 1);
1985        b.emit_return(0);
1986        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1987        match vm.run(10) {
1988            VmResult::Trap(Fault::TypeMismatch {
1989                expected: "int",
1990                got: "bool",
1991            }) => Ok(()),
1992            other => Err(format!("request_id bool: {other:?}").into()),
1993        }
1994    }
1995
1996    #[test]
1997    fn sleep_accepts_zero_and_rejects_a_float() -> TestResult {
1998        let mut b = ChunkBuilder::new("t");
1999        b.begin_function("main", 0, 1);
2000        b.emit_load_imm(0, 0);
2001        b.emit_sleep(0);
2002        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2003        match vm.run(10) {
2004            VmResult::Sleep(d) if d.is_zero() => {}
2005            other => return Err(format!("expected Sleep(0), got {other:?}").into()),
2006        }
2007        let mut b = ChunkBuilder::new("t");
2008        let n = b.const_(Value::Float(1.0));
2009        b.begin_function("main", 0, 1);
2010        b.emit_load_const(0, n);
2011        b.emit_sleep(0);
2012        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2013        match vm.run(10) {
2014            VmResult::Trap(Fault::TypeMismatch {
2015                expected: "int",
2016                got: "float",
2017            }) => Ok(()),
2018            other => Err(format!("expected float rejection, got {other:?}").into()),
2019        }
2020    }
2021
2022    #[test]
2023    fn dict_str_stays_charged_after_the_register_is_cleared() -> TestResult {
2024        let mut b = ChunkBuilder::new("t");
2025        let text = b.const_(Value::Str("x".repeat(100).into()));
2026        b.begin_function("main", 0, 3);
2027        b.emit_load_const(0, text);
2028        b.emit_load_imm(1, 7);
2029        b.emit_dict_put(2, 1, 0);
2030        b.emit_load_imm(0, 0);
2031        b.emit_halt();
2032        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2033        let quota = Arc::new(FlowQuota::new(10_000, 500, 1, 1, 1, 1));
2034        vm.set_quota(Arc::clone(&quota))?;
2035        match vm.run(20) {
2036            VmResult::Complete(_) => {
2037                assert_eq!(quota.mem_used(), 100);
2038                Ok(())
2039            }
2040            other => Err(format!("expected Complete, got {other:?}").into()),
2041        }
2042    }
2043
2044    #[test]
2045    fn dict_bytes_round_trip_charges_the_buffer() -> TestResult {
2046        let mut b = ChunkBuilder::new("t");
2047        let blob = b.const_(Value::bytes(vec![1u8; 60]));
2048        b.begin_function("main", 0, 3);
2049        b.emit_load_const(0, blob);
2050        b.emit_load_imm(1, 4);
2051        b.emit_dict_put(2, 1, 0);
2052        b.emit_load_imm(0, 0);
2053        b.emit_dict_get(0, 1);
2054        b.emit_halt();
2055        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2056        let quota = Arc::new(FlowQuota::new(10_000, 500, 1, 1, 1, 1));
2057        vm.set_quota(Arc::clone(&quota))?;
2058        match vm.run(30) {
2059            VmResult::Complete(Value::Bytes(buf)) if buf.len() == 60 => {
2060                // Register and dictionary each hold the buffer.
2061                assert_eq!(quota.mem_used(), 120);
2062                Ok(())
2063            }
2064            other => Err(format!("expected bytes, got {other:?}").into()),
2065        }
2066    }
2067
2068    #[test]
2069    fn dict_put_rejects_a_second_copy_that_does_not_fit() -> TestResult {
2070        let mut b = ChunkBuilder::new("t");
2071        let text = b.const_(Value::Str("x".repeat(100).into()));
2072        b.begin_function("main", 0, 3);
2073        b.emit_load_const(0, text);
2074        b.emit_load_imm(1, 1);
2075        b.emit_dict_put(2, 1, 0);
2076        b.emit_halt();
2077        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2078        let quota = Arc::new(FlowQuota::new(10_000, 150, 1, 1, 1, 1));
2079        vm.set_quota(Arc::clone(&quota))?;
2080        match vm.run(20) {
2081            VmResult::Trap(Fault::QuotaExceeded(_)) => {
2082                assert_eq!(quota.mem_used(), 100);
2083                Ok(())
2084            }
2085            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
2086        }
2087    }
2088
2089    #[test]
2090    fn dict_replace_that_cannot_park_the_old_string_keeps_it() -> TestResult {
2091        let mut b = ChunkBuilder::new("t");
2092        let first = b.const_(Value::Str("a".repeat(100).into()));
2093        let second = b.const_(Value::Str("b".repeat(80).into()));
2094        b.begin_function("main", 0, 4);
2095        b.emit_load_const(0, first);
2096        b.emit_load_imm(1, 1);
2097        b.emit_dict_put(2, 1, 0);
2098        b.emit_load_imm(0, 0);
2099        b.emit_load_const(0, second);
2100        b.emit_dict_put(3, 1, 0);
2101        b.emit_halt();
2102        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2103        // 200 admits the original string in both the register and the
2104        // dictionary. Returning that string to r3 while r0 and the
2105        // dictionary both hold the 80-byte replacement needs 260.
2106        let quota = Arc::new(FlowQuota::new(10_000, 200, 1, 1, 1, 1));
2107        vm.set_quota(Arc::clone(&quota))?;
2108        match vm.run(30) {
2109            VmResult::Trap(Fault::QuotaExceeded(_)) => {
2110                // r0 still holds 80 and the dictionary still holds 100.
2111                assert_eq!(quota.mem_used(), 180);
2112                Ok(())
2113            }
2114            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
2115        }
2116    }
2117
2118    #[test]
2119    fn dict_erase_moves_the_charge_back_to_the_register() -> TestResult {
2120        let mut b = ChunkBuilder::new("t");
2121        let text = b.const_(Value::Str("y".repeat(80).into()));
2122        b.begin_function("main", 0, 4);
2123        b.emit_load_const(0, text);
2124        b.emit_load_imm(1, 3);
2125        b.emit_dict_put(2, 1, 0);
2126        b.emit_load_imm(0, 0);
2127        b.emit_dict_erase(0, 1);
2128        b.emit_halt();
2129        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2130        let quota = Arc::new(FlowQuota::new(10_000, 1_000, 1, 1, 1, 1));
2131        vm.set_quota(Arc::clone(&quota))?;
2132        match vm.run(30) {
2133            VmResult::Complete(Value::Str(s)) if s.len() == 80 => {
2134                assert_eq!(quota.mem_used(), 80);
2135                Ok(())
2136            }
2137            other => Err(format!("expected the erased string, got {other:?}").into()),
2138        }
2139    }
2140
2141    #[test]
2142    fn dict_rejects_a_message_and_an_empty_string_is_free() -> TestResult {
2143        let mut b = ChunkBuilder::new("t");
2144        let hop = b.const_(Value::Message(crate::bytecode::Message::new(0, 1, 1, 1i64)));
2145        b.begin_function("main", 0, 3);
2146        b.emit_load_const(0, hop);
2147        b.emit_load_imm(1, 1);
2148        b.emit_dict_put(2, 1, 0);
2149        b.emit_halt();
2150        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2151        match vm.run(10) {
2152            VmResult::Trap(Fault::TypeMismatch {
2153                expected: "dict value (scalar, str, or bytes)",
2154                got: "message",
2155            }) => {}
2156            other => return Err(format!("message dict: {other:?}").into()),
2157        }
2158        let mut b = ChunkBuilder::new("t");
2159        let empty = b.const_(Value::Str("".into()));
2160        b.begin_function("main", 0, 3);
2161        b.emit_load_const(0, empty);
2162        b.emit_load_imm(1, 1);
2163        b.emit_dict_put(2, 1, 0);
2164        b.emit_halt();
2165        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2166        let quota = Arc::new(FlowQuota::new(10_000, 64, 1, 1, 1, 1));
2167        vm.set_quota(Arc::clone(&quota))?;
2168        match vm.run(20) {
2169            VmResult::Complete(_) => {
2170                assert_eq!(quota.mem_used(), 0);
2171                Ok(())
2172            }
2173            other => Err(format!("empty str: {other:?}").into()),
2174        }
2175    }
2176
2177    #[test]
2178    fn dict_replace_releases_the_previous_string() -> TestResult {
2179        let mut b = ChunkBuilder::new("t");
2180        let first = b.const_(Value::Str("a".repeat(100).into()));
2181        let second = b.const_(Value::Str("b".repeat(40).into()));
2182        b.begin_function("main", 0, 4);
2183        b.emit_load_const(0, first);
2184        b.emit_load_imm(1, 1);
2185        b.emit_dict_put(2, 1, 0);
2186        b.emit_load_imm(0, 0);
2187        b.emit_load_const(0, second);
2188        b.emit_dict_put(2, 1, 0);
2189        b.emit_load_imm(2, 0);
2190        b.emit_halt();
2191        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2192        let quota = Arc::new(FlowQuota::new(10_000, 1_000, 1, 1, 1, 1));
2193        vm.set_quota(Arc::clone(&quota))?;
2194        match vm.run(40) {
2195            VmResult::Complete(_) => {
2196                // r0 still holds the 40-byte replacement; the dict holds the
2197                // same buffer; the 100-byte previous value was overwritten.
2198                assert_eq!(quota.mem_used(), 80);
2199                Ok(())
2200            }
2201            other => Err(format!("expected Complete, got {other:?}").into()),
2202        }
2203    }
2204
2205    #[test]
2206    fn dictionaries_are_isolated_between_vms() -> TestResult {
2207        let mut writer = ChunkBuilder::new("t");
2208        writer.begin_function("main", 0, 3);
2209        writer.emit_load_imm(0, 9);
2210        writer.emit_load_imm(1, 1);
2211        writer.emit_dict_put(2, 1, 0);
2212        writer.emit_halt();
2213        let mut vm = Vm::new(Arc::new(writer.finish()), NativeTable::empty(), 0, &[])?;
2214        match vm.run(20) {
2215            VmResult::Complete(_) => {}
2216            other => return Err(format!("writer: {other:?}").into()),
2217        }
2218        let mut reader = ChunkBuilder::new("t");
2219        reader.begin_function("main", 0, 2);
2220        reader.emit_load_imm(1, 1);
2221        reader.emit_dict_get(0, 1);
2222        reader.emit_halt();
2223        let mut other_vm = Vm::new(Arc::new(reader.finish()), NativeTable::empty(), 0, &[])?;
2224        match other_vm.run(20) {
2225            VmResult::Complete(Value::Unit) => Ok(()),
2226            other => Err(format!("reader saw {other:?}").into()),
2227        }
2228    }
2229
2230    #[test]
2231    fn tag_bounds_and_non_integers_stay_strict() -> TestResult {
2232        let mut b = ChunkBuilder::new("t");
2233        b.begin_function("main", 0, 2);
2234        b.emit_load_imm(0, i32::from(u16::MAX));
2235        b.emit_receive_match(1, 0);
2236        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2237        match vm.run(10) {
2238            VmResult::Receive {
2239                match_tag: Some(tag),
2240                ..
2241            } if tag == u16::MAX => {}
2242            other => return Err(format!("u16::MAX tag: {other:?}").into()),
2243        }
2244        let mut b = ChunkBuilder::new("t");
2245        b.begin_function("main", 0, 2);
2246        b.emit_load_imm(0, i32::from(u16::MAX) + 1);
2247        b.emit_receive_match(1, 0);
2248        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2249        match vm.run(10) {
2250            VmResult::Trap(Fault::TypeMismatch {
2251                expected: "tag u16",
2252                got: "int-out-of-range",
2253            }) => {}
2254            other => return Err(format!("tag overflow: {other:?}").into()),
2255        }
2256        let mut b = ChunkBuilder::new("t");
2257        let text = b.const_(Value::str("nope"));
2258        b.begin_function("main", 0, 1);
2259        b.emit_load_const(0, text);
2260        b.emit_sleep(0);
2261        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2262        match vm.run(10) {
2263            VmResult::Trap(Fault::TypeMismatch {
2264                expected: "int",
2265                got: "str",
2266            }) => Ok(()),
2267            other => Err(format!("str sleep: {other:?}").into()),
2268        }
2269    }
2270
2271    #[test]
2272    fn sub_imm_and_lt_imm_follow_integer_and_float_rules() -> TestResult {
2273        let mut b = ChunkBuilder::new("t");
2274        b.begin_function("main", 0, 2);
2275        b.emit_load_imm(0, 10);
2276        b.emit_sub_imm(1, 0, 3);
2277        b.emit_return(1);
2278        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2279        match vm.run(10) {
2280            VmResult::Complete(Value::Int(7)) => {}
2281            other => return Err(format!("10 - 3: {other:?}").into()),
2282        }
2283        let mut b = ChunkBuilder::new("t");
2284        let big = b.const_(Value::Int(i64::MAX));
2285        b.begin_function("main", 0, 2);
2286        b.emit_load_const(0, big);
2287        b.emit_sub_imm(1, 0, -1);
2288        b.emit_return(1);
2289        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2290        match vm.run(10) {
2291            VmResult::Complete(Value::Int(n)) if n == i64::MIN => {}
2292            other => return Err(format!("wrap: {other:?}").into()),
2293        }
2294        let mut b = ChunkBuilder::new("t");
2295        let flag = b.const_(Value::Bool(true));
2296        b.begin_function("main", 0, 2);
2297        b.emit_load_const(0, flag);
2298        b.emit_sub_imm(1, 0, 1);
2299        b.emit_return(1);
2300        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2301        match vm.run(10) {
2302            VmResult::Trap(Fault::TypeMismatch {
2303                expected: "int or float",
2304                got: "bool",
2305            }) => {}
2306            other => return Err(format!("bool sub: {other:?}").into()),
2307        }
2308        let mut b = ChunkBuilder::new("t");
2309        let num = b.const_(Value::Float(1.5));
2310        b.begin_function("main", 0, 2);
2311        b.emit_load_const(0, num);
2312        b.emit_lt_imm(1, 0, 2);
2313        b.emit_return(1);
2314        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2315        match vm.run(10) {
2316            VmResult::Complete(Value::Bool(true)) => {}
2317            other => return Err(format!("1.5 < 2: {other:?}").into()),
2318        }
2319        let mut b = ChunkBuilder::new("t");
2320        let nan = b.const_(Value::Float(f64::NAN));
2321        b.begin_function("main", 0, 2);
2322        b.emit_load_const(0, nan);
2323        b.emit_lt_imm(1, 0, 0);
2324        b.emit_return(1);
2325        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2326        match vm.run(10) {
2327            VmResult::Complete(Value::Bool(false)) => Ok(()),
2328            other => Err(format!("nan < 0: {other:?}").into()),
2329        }
2330    }
2331
2332    #[test]
2333    fn list_pack_get_len_and_quota() -> TestResult {
2334        let mut b = ChunkBuilder::new("t");
2335        b.begin_function("main", 0, 4);
2336        b.emit_load_imm(0, 7);
2337        b.emit_load_imm(1, 8);
2338        b.emit_list_pack(2, 0, 2);
2339        b.emit_list_get(3, 2, 1);
2340        b.emit_return(3);
2341        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2342        match vm.run(20) {
2343            VmResult::Complete(Value::Int(8)) => {}
2344            other => return Err(format!("list get: {other:?}").into()),
2345        }
2346        let mut b = ChunkBuilder::new("t");
2347        let text = b.const_(Value::Str("z".repeat(100).into()));
2348        b.begin_function("main", 0, 2);
2349        b.emit_load_const(0, text);
2350        b.emit_list_pack(1, 0, 1);
2351        b.emit_halt();
2352        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2353        let quota = Arc::new(FlowQuota::new(10_000, 1_000, 1, 1, 1, 1));
2354        vm.set_quota(Arc::clone(&quota))?;
2355        let slot = std::mem::size_of::<Value>();
2356        match vm.run(10) {
2357            VmResult::Complete(_) => {
2358                assert_eq!(quota.mem_used(), 100 + slot + 100);
2359                Ok(())
2360            }
2361            other => Err(format!("list quota: {other:?}").into()),
2362        }
2363    }
2364
2365    #[test]
2366    fn fresh_request_id_stays_in_i64_domain() -> TestResult {
2367        let mut b = ChunkBuilder::new("t");
2368        b.begin_function("main", 0, 1);
2369        b.emit_return(0);
2370        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
2371        vm.set_next_request_id_for_test(i64::MAX as u64);
2372        let id = vm.fresh_request_id();
2373        assert_eq!(id, i64::MAX as u64);
2374        assert_eq!(vm.fresh_request_id(), i64::MAX as u64);
2375        assert!((id as i64) >= 0);
2376        Ok(())
2377    }
2378
2379    #[test]
2380    fn call_native_without_gate_is_typed_denied() -> TestResult {
2381        let mut b = ChunkBuilder::new("t");
2382        b.begin_function("main", 0, 1);
2383        b.emit_call_native(0, 0, 0);
2384        b.emit_return(0);
2385        let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
2386        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
2387        match vm.run(10) {
2388            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
2389            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
2390        }
2391    }
2392
2393    #[test]
2394    fn bad_jump_fail_closes_even_without_paranoid_flag() -> TestResult {
2395        let mut b = ChunkBuilder::new("t");
2396        b.begin_function("main", 0, 1);
2397        b.emit_load_imm(0, 7);
2398        b.emit_return(0);
2399        let mut chunk = b.finish();
2400        let code_len = chunk.code.len();
2401        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
2402        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
2403        // Flag retained for API compat; jumps always fail closed.
2404        vm.set_paranoid_jumps(false);
2405        match vm.run(10) {
2406            VmResult::Trap(Fault::BadJump {
2407                target: 101,
2408                code_len: len,
2409            }) if len == code_len => Ok(()),
2410            other => Err(format!("expected BadJump(101), got {other:?}").into()),
2411        }
2412    }
2413}