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
13fn dict_scalar(value: &Value) -> bool {
14    matches!(
15        value,
16        Value::Unit | Value::Bool(_) | Value::Int(_) | Value::Float(_)
17    )
18}
19
20/// Hard limit on call nesting. Frames are heap-allocated, so
21/// unbounded recursion would grow the Flow's memory instead of crashing
22/// the worker thread's native stack — which is worse, not better, without a
23/// limit. `4096` comfortably covers real recursive algorithms while keeping
24/// a runaway `fn f() { f() }` a `Fault`, not an OOM.
25pub const MAX_CALL_DEPTH: usize = 4096;
26
27/// One virtual Flow's execution state: call stack + registers. Cheap
28/// enough to construct that spawning a Flow is a handful of small heap
29/// allocations, not a native thread/stack (contrast: a `std::thread` reserves
30/// megabytes of stack whether it uses them or not).
31///
32/// `Vm` owns no scheduler, mailbox, or thread handle — see [`VmResult`] for
33/// why that separation is the whole point.
34pub struct Vm {
35    chunk: Arc<Chunk>,
36    natives: Arc<NativeTable>,
37    native_gate: NativeGate,
38    frames: Vec<Frame>,
39    /// Lifetime instruction counter, exposed for `FlowMetrics` (design
40    /// notes §26).
41    instructions_executed: u64,
42    /// Next `Message.request_id` for [`Opcode::FreshRequestId`] and for
43    /// hops that still carry `0` (“unset”) at the Send/Ask boundary.
44    next_request_id: u64,
45    /// Per-flow heap charge for `Str`/`Bytes` written into registers.
46    quota: Option<Arc<FlowQuota>>,
47    /// Process-wide memory ceiling (optional; set by the runtime).
48    memory: Option<Arc<crate::MemoryBudget>>,
49    /// Retained for API / `RuntimeConfig` wiring. Out-of-range jumps always
50    /// trap with [`Fault::BadJump`] (fail-closed); this flag no longer gates
51    /// the check.
52    #[allow(dead_code)]
53    paranoid_jumps: bool,
54    /// BEAM process dictionary. Allocated on first `DictPut` so the common
55    /// flow that never touches the dict pays nothing.
56    dict: Option<HashMap<i64, Value>>,
57}
58
59impl Vm {
60    /// Construct a `Vm` ready to run `function` (an index into
61    /// `chunk.functions`) with the given arguments loaded into `r0..argc`.
62    /// `natives` is the FFI table `Opcode::CallNative` dispatches through —
63    /// pass [`NativeTable::empty`] if the chunk never calls out to Rust.
64    ///
65    /// Native calls are **denied** until [`Self::with_native_gate`] installs
66    /// an allowlist (the runtime does this from the flow's attenuated Cap).
67    pub fn new(
68        chunk: Arc<Chunk>,
69        natives: Arc<NativeTable>,
70        function: u32,
71        args: &[Value],
72    ) -> Result<Self, Fault> {
73        let gate = NativeGate::deny(natives.len());
74        Self::with_native_gate(chunk, natives, gate, function, args)
75    }
76
77    pub fn with_native_gate(
78        chunk: Arc<Chunk>,
79        natives: Arc<NativeTable>,
80        native_gate: NativeGate,
81        function: u32,
82        args: &[Value],
83    ) -> Result<Self, Fault> {
84        let def = chunk.function(function).ok_or(Fault::BadFunction {
85            index: function,
86            table_size: chunk.functions.len() as u32,
87        })?;
88        let mut frame = Frame::new(function, def.num_registers, None);
89        frame.set_pc(def.entry as usize);
90        load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
91        Ok(Vm {
92            chunk,
93            natives,
94            native_gate,
95            frames: vec![frame],
96            instructions_executed: 0,
97            next_request_id: 1,
98            quota: None,
99            memory: None,
100            paranoid_jumps: false,
101            dict: None,
102        })
103    }
104
105    /// Historical API: out-of-range `Jump` / `Branch` always trap with
106    /// [`Fault::BadJump`]. The flag is retained for `RuntimeConfig` compatibility
107    /// but does not change jump semantics.
108    pub fn set_paranoid_jumps(&mut self, enabled: bool) {
109        self.paranoid_jumps = enabled;
110    }
111
112    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
113    ///
114    /// Charges the **total** current register heap in one reservation, then
115    /// installs the quota. A failed reservation leaves `self.quota` unset and
116    /// does not partially inflate the budget. Same `Arc` rewritten into the
117    /// same slot is not charged twice on later stores.
118    pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
119        let mut per_frame: Vec<usize> = Vec::with_capacity(self.frames.len());
120        let mut total = 0usize;
121        for frame in &self.frames {
122            let bytes: usize = frame.registers().iter().map(heap_charge_of).sum();
123            total = total.saturating_add(bytes);
124            per_frame.push(bytes);
125        }
126        charge_pair(&quota, self.memory.as_deref(), total)?;
127        for (frame, bytes) in self.frames.iter_mut().zip(per_frame) {
128            frame.set_heap_charge(bytes);
129        }
130        self.quota = Some(quota);
131        Ok(())
132    }
133
134    /// Attach the process-wide memory ceiling (call before or with [`Self::set_quota`]).
135    pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
136        self.memory = Some(memory);
137    }
138
139    /// Mint a per-flow correlation id.
140    ///
141    /// Stays in the `Value::Int` (`i64`) domain so
142    /// `FreshRequestId` → `Int` → [`request_id_from_value`] never produces a
143    /// negative id. Never returns `0` (`next_request_id` starts at 1).
144    pub fn fresh_request_id(&mut self) -> u64 {
145        let id = self.next_request_id;
146        if self.next_request_id < i64::MAX as u64 {
147            self.next_request_id += 1;
148        }
149        id
150    }
151
152    #[cfg(test)]
153    fn set_next_request_id_for_test(&mut self, id: u64) {
154        self.next_request_id = id;
155    }
156
157    pub fn instructions_executed(&self) -> u64 {
158        self.instructions_executed
159    }
160
161    /// Index into `chunk.functions` for the active (top) call frame.
162    /// Useful for diagnostics / supervisor logs when a Flow traps.
163    pub fn current_function(&self) -> u32 {
164        // Category D: frames must be non-empty while the VM is runnable.
165        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
166        // broken invariant cannot panic a worker; the next `run` will trap.
167        debug_assert!(!self.frames.is_empty(), "frames empty while running");
168        match self.frames.last() {
169            Some(frame) => frame.function(),
170            None => 0,
171        }
172    }
173
174    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
175    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
176    /// needing to know anything about `Chunk`'s internals — every Flow
177    /// spawned (transitively) from the same top-level `spawn()` call shares
178    /// one immutable chunk in memory, never copies it.
179    pub fn chunk_arc(&self) -> Arc<Chunk> {
180        self.chunk.clone()
181    }
182
183    /// A cheap `Arc` clone of this VM's native function table, for the same
184    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
185    /// `CallNative` through the identical table its parent uses.
186    pub fn natives_arc(&self) -> Arc<NativeTable> {
187        self.natives.clone()
188    }
189
190    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
191    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
192    /// into the register the instruction that suspended us was targeting,
193    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
194    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
195    /// destination register holding its previous (stale) value.
196    #[inline]
197    pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
198        self.set_reg(dest_reg, value)
199    }
200
201    /// Program counter of the active frame — used by the optional JIT hook.
202    pub fn current_pc(&self) -> Option<usize> {
203        self.frames.last().map(|f| f.pc())
204    }
205
206    /// Number of registers in the active frame.
207    pub fn current_num_registers(&self) -> Option<u8> {
208        self.frames.last().map(|f| f.registers().len() as u8)
209    }
210
211    /// Read-only view of the active register file.
212    pub fn top_registers(&self) -> Option<&[Value]> {
213        self.frames.last().map(|f| f.registers())
214    }
215
216    /// Mutable view of the active register file (JIT sync path).
217    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
218        self.frames.last_mut().map(|f| f.registers_mut())
219    }
220
221    /// Set the active frame's program counter.
222    pub fn set_pc(&mut self, pc: usize) {
223        if let Some(frame) = self.frames.last_mut() {
224            frame.set_pc(pc);
225        }
226    }
227
228    /// Write one register in the active frame (JIT sync path).
229    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
230        self.set_reg(reg, value)
231    }
232
233    /// Deliver a return value through the call stack.
234    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
235        self.pop_frame(value)
236    }
237
238    /// Top call frame. Empty stack is a broken invariant (category D) —
239    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
240    #[inline]
241    fn current(&mut self) -> Result<&mut Frame, Fault> {
242        debug_assert!(!self.frames.is_empty(), "frames empty while running");
243        self.frames
244            .last_mut()
245            .ok_or(Fault::Invariant("empty frame stack while running"))
246    }
247
248    #[inline]
249    fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
250        let frame = self
251            .frames
252            .last()
253            .ok_or(Fault::Invariant("empty frame stack while running"))?;
254        frame
255            .registers()
256            .get(reg as usize)
257            .cloned()
258            .ok_or(Fault::RegisterOutOfRange {
259                reg,
260                frame_size: frame.registers().len() as u8,
261            })
262    }
263
264    /// Write a register. Bounds-check the slot **before** any heap charge so
265    /// a failed store cannot inflate FlowQuota / MemoryBudget.
266    #[inline]
267    fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
268        let frame = self
269            .frames
270            .last()
271            .ok_or(Fault::Invariant("empty frame stack while running"))?;
272        let frame_size = frame.registers().len() as u8;
273        let old = frame
274            .registers()
275            .get(reg as usize)
276            .ok_or(Fault::RegisterOutOfRange { reg, frame_size })?;
277
278        // `old` is `&Value`; keep both sides as references for the helper.
279        let old_bytes = heap_charge_of(old);
280        let new_bytes = heap_charge_of(&value);
281
282        match (&value, old) {
283            (Value::Str(s), Value::Str(prev)) if Arc::ptr_eq(s, prev) => return Ok(()),
284            (Value::Bytes(b), Value::Bytes(prev)) if Arc::ptr_eq(b, prev) => return Ok(()),
285            _ => {}
286        }
287
288        if let Some(quota) = self.quota.as_ref() {
289            if new_bytes > old_bytes {
290                charge_pair(quota, self.memory.as_deref(), new_bytes - old_bytes)?;
291            } else if old_bytes > new_bytes {
292                release_pair(quota, self.memory.as_deref(), old_bytes - new_bytes);
293            }
294        }
295
296        let frame = self.current()?;
297        if new_bytes > old_bytes {
298            frame.add_heap_charge(new_bytes - old_bytes);
299        } else if old_bytes > new_bytes {
300            frame.sub_heap_charge(old_bytes - new_bytes);
301        }
302        match frame.registers_mut().get_mut(reg as usize) {
303            Some(slot) => {
304                *slot = value;
305                Ok(())
306            }
307            None => Err(Fault::RegisterOutOfRange {
308                reg,
309                frame_size: frame.registers().len() as u8,
310            }),
311        }
312    }
313
314    /// Fetch the next instruction and advance `pc`.
315    ///
316    /// `Ok(None)` if control fell off the end of the function body without an
317    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
318    /// (friendlier to hand-written bytecode that omits a trailing return).
319    /// `Err` if the frame stack is empty (invariant break).
320    ///
321    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
322    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
323    /// compile.
324    #[inline]
325    fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
326        let pc = self.current()?.pc();
327        let instr = self.chunk.code.get(pc).copied();
328        if instr.is_some() {
329            self.current()?.set_pc(pc + 1);
330        }
331        Ok(instr)
332    }
333
334    fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
335        let a = self.get_reg(lhs)?;
336        let b = self.get_reg(rhs)?;
337        let result = match (op, &a, &b) {
338            (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
339            (Opcode::Add, _, _) => Value::Float(as_f64(&a)? + as_f64(&b)?),
340            (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
341            (Opcode::Sub, _, _) => Value::Float(as_f64(&a)? - as_f64(&b)?),
342            (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
343            (Opcode::Mul, _, _) => Value::Float(as_f64(&a)? * as_f64(&b)?),
344            (Opcode::Div, Value::Int(x), Value::Int(y)) => {
345                if *y == 0 {
346                    return Err(Fault::DivideByZero);
347                }
348                Value::Int(x.wrapping_div(*y))
349            }
350            (Opcode::Div, _, _) => {
351                let denom = as_f64(&b)?;
352                Value::Float(as_f64(&a)? / denom)
353            }
354            (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
355                if *y == 0 {
356                    return Err(Fault::DivideByZero);
357                }
358                Value::Int(x.wrapping_rem(*y))
359            }
360            (Opcode::Mod, _, _) => {
361                let got = if !matches!(a, Value::Int(_)) {
362                    a.type_name()
363                } else {
364                    b.type_name()
365                };
366                return Err(Fault::TypeMismatch {
367                    expected: "int",
368                    got,
369                });
370            }
371            (Opcode::Eq, _, _) => Value::Bool(a == b),
372            (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
373            (Opcode::Lt, _, _) => Value::Bool(as_f64(&a)? < as_f64(&b)?),
374            (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
375            (Opcode::Le, _, _) => Value::Bool(as_f64(&a)? <= as_f64(&b)?),
376            _ => {
377                return Err(Fault::Invariant(
378                    "numeric_binop called with a non-arithmetic opcode",
379                ))
380            }
381        };
382        self.set_reg(dst, result)
383    }
384
385    #[inline]
386    fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
387        let v = self.get_reg(reg)?;
388        v.as_cap().ok_or(Fault::TypeMismatch {
389            expected: "cap",
390            got: v.type_name(),
391        })
392    }
393
394    #[inline]
395    fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
396        let v = self.get_reg(reg)?;
397        if v.as_message().is_none() {
398            return Err(Fault::TypeMismatch {
399                expected: "message",
400                got: v.type_name(),
401            });
402        }
403        Ok(v)
404    }
405
406    #[inline]
407    fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
408        match self.get_reg(reg)? {
409            Value::Str(s) => Ok(s),
410            other => Err(Fault::TypeMismatch {
411                expected: "str",
412                got: other.type_name(),
413            }),
414        }
415    }
416
417    #[inline]
418    fn int_from_reg(&self, reg: u8) -> Result<i64, Fault> {
419        match self.get_reg(reg)? {
420            Value::Int(n) => Ok(n),
421            other => Err(Fault::TypeMismatch {
422                expected: "int",
423                got: other.type_name(),
424            }),
425        }
426    }
427
428    #[inline]
429    fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
430        tag_from_value(&self.get_reg(reg)?)
431    }
432
433    #[inline]
434    fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
435        request_id_from_value(&self.get_reg(reg)?)
436    }
437
438    fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
439        let mut args = Vec::with_capacity(argc as usize);
440        for i in 0..argc {
441            let reg = reg_at(base, first_offset + u16::from(i))?;
442            args.push(self.get_reg(reg)?);
443        }
444        Ok(args)
445    }
446
447    /// Same policy as `Sleep`: non-negative `Int` only; never silent clamp.
448    #[inline]
449    fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
450        let millis = self.get_reg(reg)?;
451        match millis.as_int() {
452            Some(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
453            _ => Err(Fault::TypeMismatch {
454                expected: "non-negative int",
455                got: millis.type_name(),
456            }),
457        }
458    }
459
460    /// Apply a relative jump from the current (post-fetch) `pc`.
461    ///
462    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
463    /// Out-of-range targets always trap with [`Fault::BadJump`] (fail-closed).
464    fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
465        let code_len = self.chunk.code.len();
466        let frame = self.current()?;
467        let target_i = frame.pc() as i64 + i64::from(imm);
468        if target_i < 0 || target_i as usize > code_len {
469            let target = if target_i < 0 {
470                usize::MAX
471            } else {
472                target_i as usize
473            };
474            return Err(Fault::BadJump { target, code_len });
475        }
476        frame.set_pc(target_i as usize);
477        Ok(())
478    }
479
480    /// Run at most `budget` instructions (cooperative-preemption quantum,
481    /// design notes §10-11), or until the Flow completes / needs an
482    /// effect the scheduler must perform / faults.
483    ///
484    /// Every exit path is captured by [`VmResult`] — this function itself
485    /// never panics on malformed *verified* bytecode; faults are returned,
486    /// not thrown, so a buggy Flow can't take a worker thread down.
487    pub fn run(&mut self, budget: u32) -> VmResult {
488        macro_rules! trap {
489            ($e:expr) => {
490                match $e {
491                    Ok(v) => v,
492                    Err(fault) => return VmResult::Trap(fault),
493                }
494            };
495        }
496
497        for _ in 0..budget {
498            self.instructions_executed += 1;
499            let instr = match self.fetch() {
500                Ok(Some(i)) => i,
501                Ok(None) => {
502                    // Fell off the end of a function: implicit `return Unit`.
503                    match self.pop_frame(Value::Unit) {
504                        Ok(Some(result)) => return result,
505                        Ok(None) => continue,
506                        Err(fault) => return VmResult::Trap(fault),
507                    }
508                }
509                Err(fault) => return VmResult::Trap(fault),
510            };
511
512            match instr.op {
513                Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
514                Opcode::Nop => {}
515                Opcode::LoadConst => {
516                    let idx = instr.imm as u32;
517                    let konst = match self.chunk.constant(idx) {
518                        Some(v) => v.clone(),
519                        None => {
520                            return VmResult::Trap(Fault::BadConstant {
521                                index: idx,
522                                pool_size: self.chunk.constants.len() as u32,
523                            })
524                        }
525                    };
526                    trap!(self.set_reg(instr.a, konst));
527                }
528                Opcode::LoadImm => {
529                    trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
530                }
531                Opcode::Move => {
532                    let v = trap!(self.get_reg(instr.b));
533                    trap!(self.set_reg(instr.a, v));
534                }
535                Opcode::Add
536                | Opcode::Sub
537                | Opcode::Mul
538                | Opcode::Div
539                | Opcode::Mod
540                | Opcode::Eq
541                | Opcode::Lt
542                | Opcode::Le => {
543                    trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
544                }
545                Opcode::Neg => {
546                    let v = trap!(self.get_reg(instr.b));
547                    let negated = match v {
548                        Value::Int(x) => Value::Int(x.wrapping_neg()),
549                        Value::Float(x) => Value::Float(-x),
550                        other => {
551                            return VmResult::Trap(Fault::TypeMismatch {
552                                expected: "int or float",
553                                got: other.type_name(),
554                            })
555                        }
556                    };
557                    trap!(self.set_reg(instr.a, negated));
558                }
559                Opcode::Jump => {
560                    trap!(self.apply_relative_jump(instr.imm));
561                }
562                Opcode::Branch => {
563                    let cond = trap!(self.get_reg(instr.a));
564                    if !cond.is_truthy() {
565                        trap!(self.apply_relative_jump(instr.imm));
566                    }
567                }
568                Opcode::Call => {
569                    let function = instr.imm as u32;
570                    let argc = instr.b;
571                    let dst = instr.a;
572                    if self.frames.len() >= MAX_CALL_DEPTH {
573                        return VmResult::Trap(Fault::CallStackOverflow {
574                            depth: self.frames.len(),
575                        });
576                    }
577                    let (num_registers, arity, entry) = match self.chunk.function(function) {
578                        Some(d) => (d.num_registers, d.arity, d.entry as usize),
579                        None => {
580                            return VmResult::Trap(Fault::BadFunction {
581                                index: function,
582                                table_size: self.chunk.functions.len() as u32,
583                            })
584                        }
585                    };
586                    // `verify` rejects this statically. Direct `Vm::run` on an
587                    // unverified chunk must not drop extras or fill holes with
588                    // `Unit` — both hide a wrong call.
589                    if argc != arity {
590                        return VmResult::Trap(Fault::BadArity {
591                            passed: usize::from(argc),
592                            expected: arity,
593                        });
594                    }
595                    let args = trap!(self.gather_regs(dst, argc, 0));
596                    let mut new_frame = Frame::new(function, num_registers, Some(dst));
597                    new_frame.set_pc(entry);
598                    trap!(self.load_frame_args_charged(&mut new_frame, args, arity));
599                    self.frames.push(new_frame);
600                }
601                Opcode::CallNative => {
602                    let native_index = instr.imm as u32;
603                    let argc = instr.b;
604                    let dst = instr.a;
605                    if let Err(err) =
606                        check_native_gate(&self.native_gate, &self.natives, native_index)
607                    {
608                        return VmResult::Trap(match err {
609                            NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
610                                index,
611                                table_size: self.natives.len() as u32,
612                            },
613                            other => Fault::NativeDenied(other),
614                        });
615                    }
616                    let args = trap!(self.gather_regs(dst, argc, 0));
617                    // Runs inline on this worker thread — see
618                    // `NativeFn`'s doc comment on why natives must not
619                    // block. This is the actual FFI boundary (design
620                    // notes §30-31): plain Rust on one side, bytecode
621                    // registers on the other, with `Fault::NativeError`
622                    // as the only channel for a native-side failure to
623                    // become a Flow fault instead of a host panic.
624                    let result = match self.natives.get(native_index) {
625                        Some(native_fn) => native_fn(&args),
626                        None => {
627                            return VmResult::Trap(Fault::BadNative {
628                                index: native_index,
629                                table_size: self.natives.len() as u32,
630                            })
631                        }
632                    };
633                    match result {
634                        Ok(value) => trap!(self.set_reg(dst, value)),
635                        Err(fault) => return VmResult::Trap(fault),
636                    }
637                }
638                Opcode::Return => {
639                    let v = trap!(self.get_reg(instr.a));
640                    match self.pop_frame(v) {
641                        Ok(Some(result)) => return result,
642                        Ok(None) => {}
643                        Err(fault) => return VmResult::Trap(fault),
644                    }
645                }
646                Opcode::Spawn => {
647                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
648                    // child Cap. `a = 255` overflows on the first gather.
649                    let args = trap!(self.gather_regs(instr.a, instr.b, 1));
650                    return VmResult::Spawn {
651                        function: instr.imm as u32,
652                        args,
653                        dest_reg: instr.a,
654                        requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
655                    };
656                }
657                Opcode::Yield => return VmResult::Yield,
658                Opcode::Sleep => {
659                    return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
660                }
661                Opcode::Exit => {
662                    let v = trap!(self.get_reg(instr.a));
663                    return VmResult::Complete(v);
664                }
665                Opcode::SelfPid => {
666                    return VmResult::SelfPid { dest_reg: instr.a };
667                }
668                Opcode::Send => {
669                    let target_cap = trap!(self.expect_cap_reg(instr.a));
670                    let message = trap!(self.expect_message_value(instr.b));
671                    return VmResult::Send {
672                        target_cap,
673                        message,
674                    };
675                }
676                Opcode::Receive => {
677                    return VmResult::Receive {
678                        dest_reg: instr.a,
679                        timeout: None,
680                        match_tag: None,
681                        match_request_id: None,
682                        match_payload_kind: None,
683                        match_payload_eq: None,
684                    };
685                }
686                Opcode::ReceiveTimeout => {
687                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
688                    return VmResult::Receive {
689                        dest_reg: instr.a,
690                        timeout: Some(timeout),
691                        match_tag: None,
692                        match_request_id: None,
693                        match_payload_kind: None,
694                        match_payload_eq: None,
695                    };
696                }
697                Opcode::ReceiveMatch => {
698                    let tag = trap!(self.tag_from_reg(instr.b));
699                    return VmResult::Receive {
700                        dest_reg: instr.a,
701                        timeout: None,
702                        match_tag: Some(tag),
703                        match_request_id: None,
704                        match_payload_kind: None,
705                        match_payload_eq: None,
706                    };
707                }
708                Opcode::ReceiveMatchImm => {
709                    let tag = trap!(tag_from_imm(instr.imm));
710                    return VmResult::Receive {
711                        dest_reg: instr.a,
712                        timeout: None,
713                        match_tag: Some(tag),
714                        match_request_id: None,
715                        match_payload_kind: None,
716                        match_payload_eq: None,
717                    };
718                }
719                Opcode::ReceiveMatchTimeout => {
720                    let tag = trap!(self.tag_from_reg(instr.b));
721                    let timeout = trap!(self.duration_millis_from_reg(instr.c));
722                    return VmResult::Receive {
723                        dest_reg: instr.a,
724                        timeout: Some(timeout),
725                        match_tag: Some(tag),
726                        match_request_id: None,
727                        match_payload_kind: None,
728                        match_payload_eq: None,
729                    };
730                }
731                Opcode::ReceiveMatchImmTimeout => {
732                    let tag = trap!(tag_from_imm(instr.imm));
733                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
734                    return VmResult::Receive {
735                        dest_reg: instr.a,
736                        timeout: Some(timeout),
737                        match_tag: Some(tag),
738                        match_request_id: None,
739                        match_payload_kind: None,
740                        match_payload_eq: None,
741                    };
742                }
743                Opcode::IsAlive => {
744                    let target_cap = trap!(self.expect_cap_reg(instr.b));
745                    return VmResult::IsAlive {
746                        dest_reg: instr.a,
747                        target_cap,
748                    };
749                }
750                Opcode::ExitSignal => {
751                    let target_cap = trap!(self.expect_cap_reg(instr.a));
752                    let reason = trap!(self.int_from_reg(instr.b));
753                    let Ok(reason_u) = u64::try_from(reason) else {
754                        return VmResult::Trap(Fault::TypeMismatch {
755                            expected: "FlowExitReason 0..=6",
756                            got: "imm-out-of-range",
757                        });
758                    };
759                    if crate::FlowExitReason::from_u64(reason_u).is_none() {
760                        return VmResult::Trap(Fault::TypeMismatch {
761                            expected: "FlowExitReason 0..=6",
762                            got: "imm-out-of-range",
763                        });
764                    }
765                    return VmResult::ExitSignal {
766                        target_cap,
767                        reason: reason_u,
768                    };
769                }
770                Opcode::DictPut => {
771                    let key = trap!(self.int_from_reg(instr.b));
772                    let value = trap!(self.get_reg(instr.c));
773                    if !dict_scalar(&value) {
774                        return VmResult::Trap(Fault::TypeMismatch {
775                            expected: "dict scalar (unit/bool/int/float)",
776                            got: "heap-or-cap",
777                        });
778                    }
779                    let dict = self.dict.get_or_insert_with(HashMap::new);
780                    let old = match dict.insert(key, value) {
781                        Some(prev) => prev,
782                        None => Value::Unit,
783                    };
784                    trap!(self.set_reg(instr.a, old));
785                }
786                Opcode::DictGet => {
787                    let key = trap!(self.int_from_reg(instr.b));
788                    let value = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
789                        Some(v) => v,
790                        None => Value::Unit,
791                    };
792                    trap!(self.set_reg(instr.a, value));
793                }
794                Opcode::DictErase => {
795                    let key = trap!(self.int_from_reg(instr.b));
796                    let old = match self.dict.as_mut().and_then(|d| d.remove(&key)) {
797                        Some(v) => v,
798                        None => Value::Unit,
799                    };
800                    trap!(self.set_reg(instr.a, old));
801                }
802                Opcode::ReceiveMatchEq => {
803                    let tag = trap!(self.tag_from_reg(instr.b));
804                    let payload = trap!(self.int_from_reg(instr.c));
805                    return VmResult::Receive {
806                        dest_reg: instr.a,
807                        timeout: None,
808                        match_tag: Some(tag),
809                        match_request_id: None,
810                        match_payload_kind: None,
811                        match_payload_eq: Some(payload),
812                    };
813                }
814                Opcode::StartChild => {
815                    let function = match u32::try_from(instr.imm) {
816                        Ok(f) => f,
817                        Err(_) => u32::MAX,
818                    };
819                    if self.chunk.function(function).is_none() {
820                        return VmResult::Trap(Fault::BadFunction {
821                            index: function,
822                            table_size: self.chunk.functions.len() as u32,
823                        });
824                    }
825                    if crate::RestartPolicy::from_u8(instr.b).is_none() {
826                        return VmResult::Trap(Fault::TypeMismatch {
827                            expected: "restart policy 0..=2",
828                            got: "imm-out-of-range",
829                        });
830                    }
831                    return VmResult::StartChild {
832                        dest_reg: instr.a,
833                        function,
834                        policy: instr.b,
835                    };
836                }
837                Opcode::ReceiveMatchKind => {
838                    // Selective receive by payload wire-tag (`Value::wire_tag`,
839                    // 0..=8). Non-matching hops stay queued (FIFO skip).
840                    let kind = match u8::try_from(instr.imm) {
841                        Ok(k) if k <= 8 => k,
842                        _ => {
843                            return VmResult::Trap(Fault::TypeMismatch {
844                                expected: "payload kind 0..=8",
845                                got: "imm-out-of-range",
846                            })
847                        }
848                    };
849                    return VmResult::Receive {
850                        dest_reg: instr.a,
851                        timeout: None,
852                        match_tag: None,
853                        match_request_id: None,
854                        match_payload_kind: Some(kind),
855                        match_payload_eq: None,
856                    };
857                }
858                Opcode::FreshRequestId => {
859                    let id = self.fresh_request_id();
860                    trap!(self.set_reg(instr.a, Value::Int(id as i64)));
861                }
862                Opcode::ReceiveMatchCorr => {
863                    let tag = trap!(self.tag_from_reg(instr.b));
864                    let rid = trap!(self.request_id_from_reg(instr.c));
865                    return VmResult::Receive {
866                        dest_reg: instr.a,
867                        timeout: None,
868                        match_tag: Some(tag),
869                        match_request_id: Some(rid),
870                        match_payload_kind: None,
871                        match_payload_eq: None,
872                    };
873                }
874                Opcode::ReceiveMatchCorrImm => {
875                    let tag = trap!(tag_from_imm(instr.imm));
876                    let rid = trap!(self.request_id_from_reg(instr.b));
877                    return VmResult::Receive {
878                        dest_reg: instr.a,
879                        timeout: None,
880                        match_tag: Some(tag),
881                        match_request_id: Some(rid),
882                        match_payload_kind: None,
883                        match_payload_eq: None,
884                    };
885                }
886                Opcode::Ask => {
887                    let target_cap = trap!(self.expect_cap_reg(instr.b));
888                    let request = trap!(self.expect_message_value(instr.c));
889                    return VmResult::Ask {
890                        dest_reg: instr.a,
891                        target_cap,
892                        request,
893                        timeout: None,
894                    };
895                }
896                Opcode::AskTimeout => {
897                    let millis_reg = match u8::try_from(instr.imm) {
898                        Ok(r) => r,
899                        Err(_) => {
900                            return VmResult::Trap(Fault::TypeMismatch {
901                                expected: "millis register",
902                                got: "imm-out-of-range",
903                            })
904                        }
905                    };
906                    let timeout = trap!(self.duration_millis_from_reg(millis_reg));
907                    let target_cap = trap!(self.expect_cap_reg(instr.b));
908                    let request = trap!(self.expect_message_value(instr.c));
909                    return VmResult::Ask {
910                        dest_reg: instr.a,
911                        target_cap,
912                        request,
913                        timeout: Some(timeout),
914                    };
915                }
916                Opcode::Monitor => {
917                    let target_cap = trap!(self.expect_cap_reg(instr.b));
918                    return VmResult::Monitor {
919                        dest_reg: instr.a,
920                        target_cap,
921                    };
922                }
923                Opcode::Demonitor => {
924                    return VmResult::Demonitor {
925                        monitor_reg: instr.a,
926                    };
927                }
928                Opcode::Link => {
929                    let target_cap = trap!(self.expect_cap_reg(instr.b));
930                    return VmResult::Link {
931                        dest_reg: instr.a,
932                        target_cap,
933                    };
934                }
935                Opcode::Unlink => {
936                    return VmResult::Unlink { link_reg: instr.a };
937                }
938                Opcode::SetTrapExit => {
939                    let enabled = trap!(self.get_reg(instr.a)).is_truthy();
940                    return VmResult::SetTrapExit { enabled };
941                }
942                Opcode::SetRestartPolicy => {
943                    // Flow-local OTP restart policy for the host Supervisor
944                    // (`0` Always / `1` OnFailure / `2` Never).
945                    let policy = match instr.imm {
946                        0..=2 => instr.imm as u8,
947                        _ => {
948                            return VmResult::Trap(Fault::TypeMismatch {
949                                expected: "restart policy 0..=2",
950                                got: "imm-out-of-range",
951                            })
952                        }
953                    };
954                    return VmResult::SetRestartPolicy { policy };
955                }
956                Opcode::HostAwait => {
957                    let args = trap!(self.get_reg(instr.b));
958                    let op = if instr.imm < 0 {
959                        return VmResult::Trap(Fault::TypeMismatch {
960                            expected: "HostAwait op >= 0",
961                            got: "imm-negative",
962                        });
963                    } else {
964                        instr.imm as u32
965                    };
966                    return VmResult::HostAwait {
967                        dest_reg: instr.a,
968                        op,
969                        args,
970                    };
971                }
972                Opcode::RegisterName => {
973                    return VmResult::RegisterName {
974                        name: trap!(self.expect_str_reg(instr.a)),
975                    };
976                }
977                Opcode::Whereis => {
978                    return VmResult::Whereis {
979                        dest_reg: instr.a,
980                        name: trap!(self.expect_str_reg(instr.b)),
981                    };
982                }
983                Opcode::Delegate => {
984                    let src_cap = trap!(self.expect_cap_reg(instr.b));
985                    let want_native_cap = if instr.c == 255 {
986                        None
987                    } else {
988                        Some(trap!(self.expect_cap_reg(instr.c)))
989                    };
990                    return VmResult::Delegate {
991                        dest_reg: instr.a,
992                        src_cap,
993                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
994                        want_native_cap,
995                    };
996                }
997                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
998            }
999        }
1000        VmResult::Yield
1001    }
1002
1003    /// Pop the current frame, delivering `value` to the caller (or
1004    /// finishing the Flow if this was the outermost frame). Returns
1005    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
1006    ///
1007    /// Releases the finished frame's heap charge (except the escaping
1008    /// return value on the outermost `Complete` path, which stays charged
1009    /// until flow finalize — matching prior MemoryBudget semantics).
1010    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
1011        let finished = self
1012            .frames
1013            .pop()
1014            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
1015        match finished.dest_reg() {
1016            Some(dest) => {
1017                if let Some(quota) = self.quota.as_ref() {
1018                    release_pair(quota, self.memory.as_deref(), finished.heap_charge());
1019                }
1020                self.set_reg(dest, value)?;
1021                Ok(None)
1022            }
1023            None => {
1024                if let Some(quota) = self.quota.as_ref() {
1025                    let keep = heap_charge_of(&value);
1026                    let release = finished.heap_charge().saturating_sub(keep);
1027                    release_pair(quota, self.memory.as_deref(), release);
1028                }
1029                Ok(Some(VmResult::Complete(value)))
1030            }
1031        }
1032    }
1033
1034    /// Load call arguments into a not-yet-pushed frame, charging heap for
1035    /// any `Str`/`Bytes`. Rolls back a partial charge if a later arg fails.
1036    fn load_frame_args_charged(
1037        &self,
1038        frame: &mut Frame,
1039        args: impl IntoIterator<Item = Value>,
1040        arity: u8,
1041    ) -> Result<(), Fault> {
1042        let frame_size = frame.registers().len() as u8;
1043        let mut charged = 0usize;
1044        for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1045            let bytes = heap_charge_of(&a);
1046            if bytes > 0 {
1047                if let Some(quota) = self.quota.as_ref() {
1048                    if let Err(e) = charge_pair(quota, self.memory.as_deref(), bytes) {
1049                        if charged > 0 {
1050                            release_pair(quota, self.memory.as_deref(), charged);
1051                        }
1052                        frame.set_heap_charge(0);
1053                        return Err(e);
1054                    }
1055                }
1056                charged = charged.saturating_add(bytes);
1057                frame.add_heap_charge(bytes);
1058            }
1059            match frame.registers_mut().get_mut(i) {
1060                Some(slot) => *slot = a,
1061                None => {
1062                    if charged > 0 {
1063                        if let Some(quota) = self.quota.as_ref() {
1064                            release_pair(quota, self.memory.as_deref(), charged);
1065                        }
1066                        frame.set_heap_charge(0);
1067                    }
1068                    return Err(Fault::RegisterOutOfRange {
1069                        reg: i as u8,
1070                        frame_size,
1071                    });
1072                }
1073            }
1074        }
1075        Ok(())
1076    }
1077}
1078
1079/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
1080/// if that sum leaves the register index space.
1081///
1082/// Every multi-operand opcode gathers its arguments from consecutive
1083/// registers. Written as a plain `base + offset` on `u8`, that addition
1084/// panics in debug and **wraps** in release — so a release build silently
1085/// reads the wrong register instead of failing, which is the worst of the
1086/// two outcomes and the one a debug-mode test suite never sees. The sum is
1087/// therefore computed in a wider type and narrowed explicitly.
1088#[inline]
1089fn load_frame_args(
1090    frame: &mut Frame,
1091    args: impl IntoIterator<Item = Value>,
1092    arity: u8,
1093) -> Result<(), Fault> {
1094    let frame_size = frame.registers().len() as u8;
1095    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1096        match frame.registers_mut().get_mut(i) {
1097            Some(slot) => *slot = a,
1098            None => {
1099                return Err(Fault::RegisterOutOfRange {
1100                    reg: i as u8,
1101                    frame_size,
1102                })
1103            }
1104        }
1105    }
1106    Ok(())
1107}
1108
1109fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
1110    match u8::try_from(u32::from(base) + u32::from(offset)) {
1111        Ok(reg) => Ok(reg),
1112        Err(_) => Err(Fault::RegisterIndexOverflow {
1113            base,
1114            offset: match u8::try_from(offset) {
1115                Ok(o) => o,
1116                Err(_) => u8::MAX,
1117            },
1118        }),
1119    }
1120}
1121
1122/// Bytes charged for a register-resident heap value (`Str` / `Bytes` len).
1123#[inline]
1124fn heap_charge_of(value: &Value) -> usize {
1125    match value {
1126        Value::Str(s) => s.len(),
1127        Value::Bytes(b) => b.len(),
1128        _ => 0,
1129    }
1130}
1131
1132/// Reserve `bytes` on the flow quota and optional runtime budget.
1133/// Rolls back the flow charge if the global budget refuses.
1134fn charge_pair(
1135    quota: &FlowQuota,
1136    memory: Option<&crate::MemoryBudget>,
1137    bytes: usize,
1138) -> Result<(), Fault> {
1139    if bytes == 0 {
1140        return Ok(());
1141    }
1142    quota
1143        .alloc(bytes)
1144        .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
1145    if let Some(mem) = memory {
1146        if let Err(e) = mem.try_charge(bytes) {
1147            quota.free(bytes);
1148            return Err(Fault::QuotaExceeded(e.to_string()));
1149        }
1150    }
1151    Ok(())
1152}
1153
1154fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
1155    if bytes == 0 {
1156        return;
1157    }
1158    quota.free(bytes);
1159    if let Some(mem) = memory {
1160        mem.release(bytes);
1161    }
1162}
1163
1164fn as_f64(v: &Value) -> Result<f64, Fault> {
1165    match v {
1166        Value::Int(i) => Ok(*i as f64),
1167        Value::Float(f) => Ok(*f),
1168        other => Err(Fault::TypeMismatch {
1169            expected: "int or float",
1170            got: other.type_name(),
1171        }),
1172    }
1173}
1174
1175/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
1176#[inline]
1177fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
1178    match u16::try_from(imm) {
1179        Ok(t) if imm >= 0 => Ok(t),
1180        _ => Err(Fault::TypeMismatch {
1181            expected: "tag u16",
1182            got: "imm-out-of-range",
1183        }),
1184    }
1185}
1186
1187fn tag_from_value(v: &Value) -> Result<u16, Fault> {
1188    match v.as_int() {
1189        Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
1190        Some(_) => Err(Fault::TypeMismatch {
1191            expected: "tag u16",
1192            got: "int-out-of-range",
1193        }),
1194        None => Err(Fault::TypeMismatch {
1195            expected: "int",
1196            got: v.type_name(),
1197        }),
1198    }
1199}
1200
1201/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
1202#[inline]
1203fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
1204    match v.as_int() {
1205        Some(i) if i >= 0 => Ok(i as u64),
1206        Some(_) => Err(Fault::TypeMismatch {
1207            expected: "request_id u64",
1208            got: "negative-int",
1209        }),
1210        None => Err(Fault::TypeMismatch {
1211            expected: "int",
1212            got: v.type_name(),
1213        }),
1214    }
1215}
1216
1217#[cfg(test)]
1218mod tests {
1219    use super::*;
1220    use crate::bytecode::builder::ChunkBuilder;
1221
1222    type TestResult = Result<(), Box<dyn std::error::Error>>;
1223
1224    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
1225    /// already leaves the register space. This used to panic in debug and —
1226    /// far worse — wrap around to `r0` in release, silently spawning with the
1227    /// wrong argument.
1228    #[test]
1229    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1230        let mut b = ChunkBuilder::new("t");
1231        b.begin_function("main", 0, 2);
1232        b.emit_spawn(255, 0, 1);
1233        b.emit_return(0);
1234        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1235        match vm.run(10) {
1236            VmResult::Trap(Fault::RegisterIndexOverflow {
1237                base: 255,
1238                offset: 1,
1239            }) => Ok(()),
1240            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1241        }
1242    }
1243
1244    /// `Vm::new` is public and reachable without `verify`, and its panic
1245    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
1246    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
1247    #[test]
1248    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1249        let mut b = ChunkBuilder::new("t");
1250        b.begin_function("main", 3, 1);
1251        b.emit_return(0);
1252        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1253        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1254            Err(Fault::RegisterOutOfRange {
1255                reg: 1,
1256                frame_size: 1,
1257            }) => Ok(()),
1258            Err(e) => Err(format!("unexpected fault: {e}").into()),
1259            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1260        }
1261    }
1262
1263    #[test]
1264    fn call_with_the_wrong_argc_traps_instead_of_padding() -> TestResult {
1265        let mut b = ChunkBuilder::new("t");
1266        let callee = b.begin_function("callee", 0, 1);
1267        b.emit_load_imm(0, 1);
1268        b.emit_return(0);
1269        let main = b.begin_function("main", 0, 2);
1270        b.emit_load_imm(0, 7);
1271        b.emit_call(0, callee, 1);
1272        b.emit_return(0);
1273        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1274        match vm.run(20) {
1275            VmResult::Trap(Fault::BadArity {
1276                passed: 1,
1277                expected: 0,
1278            }) => Ok(()),
1279            other => Err(format!("expected BadArity, got {other:?}").into()),
1280        }
1281    }
1282
1283    #[test]
1284    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1285        let mut b = ChunkBuilder::new("t");
1286        let callee = b.begin_function("callee", 3, 1);
1287        b.emit_return(0);
1288        let main = b.begin_function("main", 0, 4);
1289        b.emit_load_imm(0, 7);
1290        b.emit_load_imm(1, 8);
1291        b.emit_load_imm(2, 9);
1292        b.emit_call(0, callee, 3);
1293        b.emit_return(0);
1294        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1295        match vm.run(50) {
1296            VmResult::Trap(Fault::RegisterOutOfRange {
1297                reg: 1,
1298                frame_size: 1,
1299            }) => Ok(()),
1300            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1301        }
1302    }
1303
1304    /// The boundary case that must keep working: gathering right up to the
1305    /// last register is legal, it is only going *past* it that faults.
1306    #[test]
1307    fn gathering_up_to_the_last_register_still_works() -> TestResult {
1308        let mut b = ChunkBuilder::new("t");
1309        let callee = b.begin_function("callee", 1, 1);
1310        b.emit_return(0);
1311        let main = b.begin_function("main", 0, 255);
1312        b.emit_load_imm(254, 5);
1313        // Argument at r254 — the highest index a 255-register frame has.
1314        b.emit_call(254, callee, 1);
1315        b.emit_return(254);
1316        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1317        match vm.run(100) {
1318            VmResult::Complete(_) => Ok(()),
1319            other => Err(format!("expected completion, got {other:?}").into()),
1320        }
1321    }
1322
1323    #[test]
1324    fn neg_i64_min_wrapping() -> TestResult {
1325        let mut b = ChunkBuilder::new("t");
1326        b.begin_function("main", 0, 1);
1327        let k = b.const_(Value::Int(i64::MIN));
1328        b.emit_load_const(0, k);
1329        b.emit_neg(0, 0);
1330        b.emit_return(0);
1331        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1332        match vm.run(10) {
1333            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1334            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1335        }
1336    }
1337
1338    #[test]
1339    fn mod_non_int_type_mismatch() -> TestResult {
1340        let mut b = ChunkBuilder::new("t");
1341        b.begin_function("main", 0, 3);
1342        b.emit_load_imm(0, 10);
1343        let kf = b.const_(Value::Float(3.0));
1344        b.emit_load_const(1, kf);
1345        b.emit_binop(Opcode::Mod, 2, 0, 1);
1346        b.emit_return(2);
1347        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1348        match vm.run(20) {
1349            VmResult::Trap(Fault::TypeMismatch {
1350                expected: "int",
1351                got: "float",
1352            }) => Ok(()),
1353            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1354        }
1355    }
1356
1357    #[test]
1358    fn receive_timeout_negative_traps() -> TestResult {
1359        let mut b = ChunkBuilder::new("t");
1360        b.begin_function("main", 0, 2);
1361        b.emit_load_imm(1, -1);
1362        b.emit_receive_timeout(0, 1);
1363        b.emit_return(0);
1364        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1365        match vm.run(10) {
1366            VmResult::Trap(Fault::TypeMismatch {
1367                expected: "non-negative int",
1368                ..
1369            }) => Ok(()),
1370            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1371        }
1372    }
1373
1374    #[test]
1375    fn ask_timeout_negative_traps() -> TestResult {
1376        let mut b = ChunkBuilder::new("t");
1377        b.begin_function("main", 0, 4);
1378        b.emit_load_imm(3, -5);
1379        // Cap/message regs are garbage; millis is checked first.
1380        b.emit_ask_timeout(0, 1, 2, 3);
1381        b.emit_return(0);
1382        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1383        match vm.run(10) {
1384            VmResult::Trap(Fault::TypeMismatch {
1385                expected: "non-negative int",
1386                ..
1387            }) => Ok(()),
1388            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1389        }
1390    }
1391
1392    #[test]
1393    fn paranoid_jump_out_of_range_traps() -> TestResult {
1394        let mut b = ChunkBuilder::new("t");
1395        b.begin_function("main", 0, 1);
1396        b.emit_load_imm(0, 0);
1397        b.emit_return(0);
1398        let mut chunk = b.finish();
1399        let code_len = chunk.code.len();
1400        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1401        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1402        vm.set_paranoid_jumps(true);
1403        match vm.run(10) {
1404            VmResult::Trap(Fault::BadJump {
1405                target: 101,
1406                code_len: len,
1407            }) if len == code_len => Ok(()),
1408            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1409        }
1410    }
1411
1412    #[test]
1413    fn overwrite_releases_previous_heap_charge() -> TestResult {
1414        let mut b = ChunkBuilder::new("t");
1415        let k1 = b.const_(Value::Str("a".repeat(100).into()));
1416        let k2 = b.const_(Value::Str("b".repeat(100).into()));
1417        b.begin_function("main", 0, 1);
1418        b.emit_load_const(0, k1);
1419        b.emit_load_const(0, k2);
1420        b.emit_return(0);
1421        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1422        // Limit 150: first 100 fits; without release the second 100 would fail.
1423        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1424            crate::QuotaConfig {
1425                mem_limit: 150,
1426                ..crate::QuotaConfig::permissive()
1427            },
1428        ));
1429        let memory = Arc::new(crate::MemoryBudget::new(10_000));
1430        vm.set_memory_budget(Arc::clone(&memory));
1431        vm.set_quota(Arc::clone(&quota))?;
1432        match vm.run(20) {
1433            VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1434                assert_eq!(quota.mem_used(), 100);
1435                assert_eq!(memory.used(), 100);
1436                Ok(())
1437            }
1438            other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1439        }
1440    }
1441
1442    #[test]
1443    fn return_releases_callee_heap_before_caller_writeback() -> TestResult {
1444        let mut b = ChunkBuilder::new("t");
1445        let k = b.const_(Value::Str("x".repeat(200).into()));
1446        let callee = b.begin_function("callee", 0, 1);
1447        b.emit_load_const(0, k);
1448        b.emit_return(0);
1449        let main = b.begin_function("main", 0, 1);
1450        b.emit_call(0, callee, 0);
1451        b.emit_return(0);
1452        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1453        // Old bug: callee charged 200 and return writeback charged again without
1454        // release → QuotaExceeded at 250. Correct path releases then recharges.
1455        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1456        vm.set_quota(Arc::clone(&quota))?;
1457        match vm.run(50) {
1458            VmResult::Complete(Value::Str(s)) if s.len() == 200 => {
1459                assert_eq!(quota.mem_used(), 200);
1460                Ok(())
1461            }
1462            other => Err(format!("expected Complete(200-byte Str), got {other:?}").into()),
1463        }
1464    }
1465
1466    #[test]
1467    fn set_reg_out_of_range_does_not_charge() -> TestResult {
1468        let mut b = ChunkBuilder::new("t");
1469        b.begin_function("main", 0, 1);
1470        b.emit_return(0);
1471        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1472        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1473            crate::QuotaConfig {
1474                mem_limit: 10_000,
1475                ..crate::QuotaConfig::permissive()
1476            },
1477        ));
1478        vm.set_quota(Arc::clone(&quota))?;
1479        let big = Value::Str("z".repeat(500).into());
1480        match vm.set_register(255, big) {
1481            Err(Fault::RegisterOutOfRange {
1482                reg: 255,
1483                frame_size: 1,
1484            }) => {
1485                assert_eq!(quota.mem_used(), 0);
1486                Ok(())
1487            }
1488            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1489        }
1490    }
1491
1492    #[test]
1493    fn set_quota_is_transactional() -> TestResult {
1494        let mut b = ChunkBuilder::new("t");
1495        b.begin_function("main", 0, 2);
1496        b.emit_return(0);
1497        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1498        // Two 100-byte Strs already in registers; limit 150 must refuse the
1499        // whole attach without leaving a partial charge on the quota object.
1500        vm.set_register(0, Value::Str("a".repeat(100).into()))?;
1501        vm.set_register(1, Value::Str("b".repeat(100).into()))?;
1502        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1503            crate::QuotaConfig {
1504                mem_limit: 150,
1505                ..crate::QuotaConfig::permissive()
1506            },
1507        ));
1508        match vm.set_quota(Arc::clone(&quota)) {
1509            Err(Fault::QuotaExceeded(_)) => {
1510                assert_eq!(
1511                    quota.mem_used(),
1512                    0,
1513                    "failed set_quota must not leave a partial charge"
1514                );
1515                Ok(())
1516            }
1517            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
1518        }
1519    }
1520
1521    #[test]
1522    fn fresh_request_id_stays_in_i64_domain() -> TestResult {
1523        let mut b = ChunkBuilder::new("t");
1524        b.begin_function("main", 0, 1);
1525        b.emit_return(0);
1526        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1527        vm.set_next_request_id_for_test(i64::MAX as u64);
1528        let id = vm.fresh_request_id();
1529        assert_eq!(id, i64::MAX as u64);
1530        assert_eq!(vm.fresh_request_id(), i64::MAX as u64);
1531        assert!((id as i64) >= 0);
1532        Ok(())
1533    }
1534
1535    #[test]
1536    fn call_native_without_gate_is_typed_denied() -> TestResult {
1537        let mut b = ChunkBuilder::new("t");
1538        b.begin_function("main", 0, 1);
1539        b.emit_call_native(0, 0, 0);
1540        b.emit_return(0);
1541        let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1542        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1543        match vm.run(10) {
1544            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1545            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1546        }
1547    }
1548
1549    #[test]
1550    fn bad_jump_fail_closes_even_without_paranoid_flag() -> TestResult {
1551        let mut b = ChunkBuilder::new("t");
1552        b.begin_function("main", 0, 1);
1553        b.emit_load_imm(0, 7);
1554        b.emit_return(0);
1555        let mut chunk = b.finish();
1556        let code_len = chunk.code.len();
1557        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1558        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1559        // Flag retained for API compat; jumps always fail closed.
1560        vm.set_paranoid_jumps(false);
1561        match vm.run(10) {
1562            VmResult::Trap(Fault::BadJump {
1563                target: 101,
1564                code_len: len,
1565            }) if len == code_len => Ok(()),
1566            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1567        }
1568    }
1569}