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                    let args = trap!(self.gather_regs(dst, argc, 0));
587                    let mut new_frame = Frame::new(function, num_registers, Some(dst));
588                    new_frame.set_pc(entry);
589                    trap!(self.load_frame_args_charged(&mut new_frame, args, arity));
590                    self.frames.push(new_frame);
591                }
592                Opcode::CallNative => {
593                    let native_index = instr.imm as u32;
594                    let argc = instr.b;
595                    let dst = instr.a;
596                    if let Err(err) =
597                        check_native_gate(&self.native_gate, &self.natives, native_index)
598                    {
599                        return VmResult::Trap(match err {
600                            NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
601                                index,
602                                table_size: self.natives.len() as u32,
603                            },
604                            other => Fault::NativeDenied(other),
605                        });
606                    }
607                    let args = trap!(self.gather_regs(dst, argc, 0));
608                    // Runs inline on this worker thread — see
609                    // `NativeFn`'s doc comment on why natives must not
610                    // block. This is the actual FFI boundary (design
611                    // notes §30-31): plain Rust on one side, bytecode
612                    // registers on the other, with `Fault::NativeError`
613                    // as the only channel for a native-side failure to
614                    // become a Flow fault instead of a host panic.
615                    let result = match self.natives.get(native_index) {
616                        Some(native_fn) => native_fn(&args),
617                        None => {
618                            return VmResult::Trap(Fault::BadNative {
619                                index: native_index,
620                                table_size: self.natives.len() as u32,
621                            })
622                        }
623                    };
624                    match result {
625                        Ok(value) => trap!(self.set_reg(dst, value)),
626                        Err(fault) => return VmResult::Trap(fault),
627                    }
628                }
629                Opcode::Return => {
630                    let v = trap!(self.get_reg(instr.a));
631                    match self.pop_frame(v) {
632                        Ok(Some(result)) => return result,
633                        Ok(None) => {}
634                        Err(fault) => return VmResult::Trap(fault),
635                    }
636                }
637                Opcode::Spawn => {
638                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
639                    // child Cap. `a = 255` overflows on the first gather.
640                    let args = trap!(self.gather_regs(instr.a, instr.b, 1));
641                    return VmResult::Spawn {
642                        function: instr.imm as u32,
643                        args,
644                        dest_reg: instr.a,
645                        requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
646                    };
647                }
648                Opcode::Yield => return VmResult::Yield,
649                Opcode::Sleep => {
650                    return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
651                }
652                Opcode::Exit => {
653                    let v = trap!(self.get_reg(instr.a));
654                    return VmResult::Complete(v);
655                }
656                Opcode::SelfPid => {
657                    return VmResult::SelfPid { dest_reg: instr.a };
658                }
659                Opcode::Send => {
660                    let target_cap = trap!(self.expect_cap_reg(instr.a));
661                    let message = trap!(self.expect_message_value(instr.b));
662                    return VmResult::Send {
663                        target_cap,
664                        message,
665                    };
666                }
667                Opcode::Receive => {
668                    return VmResult::Receive {
669                        dest_reg: instr.a,
670                        timeout: None,
671                        match_tag: None,
672                        match_request_id: None,
673                        match_payload_kind: None,
674                        match_payload_eq: None,
675                    };
676                }
677                Opcode::ReceiveTimeout => {
678                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
679                    return VmResult::Receive {
680                        dest_reg: instr.a,
681                        timeout: Some(timeout),
682                        match_tag: None,
683                        match_request_id: None,
684                        match_payload_kind: None,
685                        match_payload_eq: None,
686                    };
687                }
688                Opcode::ReceiveMatch => {
689                    let tag = trap!(self.tag_from_reg(instr.b));
690                    return VmResult::Receive {
691                        dest_reg: instr.a,
692                        timeout: None,
693                        match_tag: Some(tag),
694                        match_request_id: None,
695                        match_payload_kind: None,
696                        match_payload_eq: None,
697                    };
698                }
699                Opcode::ReceiveMatchImm => {
700                    let tag = trap!(tag_from_imm(instr.imm));
701                    return VmResult::Receive {
702                        dest_reg: instr.a,
703                        timeout: None,
704                        match_tag: Some(tag),
705                        match_request_id: None,
706                        match_payload_kind: None,
707                        match_payload_eq: None,
708                    };
709                }
710                Opcode::ReceiveMatchTimeout => {
711                    let tag = trap!(self.tag_from_reg(instr.b));
712                    let timeout = trap!(self.duration_millis_from_reg(instr.c));
713                    return VmResult::Receive {
714                        dest_reg: instr.a,
715                        timeout: Some(timeout),
716                        match_tag: Some(tag),
717                        match_request_id: None,
718                        match_payload_kind: None,
719                        match_payload_eq: None,
720                    };
721                }
722                Opcode::ReceiveMatchImmTimeout => {
723                    let tag = trap!(tag_from_imm(instr.imm));
724                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
725                    return VmResult::Receive {
726                        dest_reg: instr.a,
727                        timeout: Some(timeout),
728                        match_tag: Some(tag),
729                        match_request_id: None,
730                        match_payload_kind: None,
731                        match_payload_eq: None,
732                    };
733                }
734                Opcode::IsAlive => {
735                    let target_cap = trap!(self.expect_cap_reg(instr.b));
736                    return VmResult::IsAlive {
737                        dest_reg: instr.a,
738                        target_cap,
739                    };
740                }
741                Opcode::ExitSignal => {
742                    let target_cap = trap!(self.expect_cap_reg(instr.a));
743                    let reason = trap!(self.int_from_reg(instr.b));
744                    let Ok(reason_u) = u64::try_from(reason) else {
745                        return VmResult::Trap(Fault::TypeMismatch {
746                            expected: "FlowExitReason 0..=6",
747                            got: "imm-out-of-range",
748                        });
749                    };
750                    if crate::FlowExitReason::from_u64(reason_u).is_none() {
751                        return VmResult::Trap(Fault::TypeMismatch {
752                            expected: "FlowExitReason 0..=6",
753                            got: "imm-out-of-range",
754                        });
755                    }
756                    return VmResult::ExitSignal {
757                        target_cap,
758                        reason: reason_u,
759                    };
760                }
761                Opcode::DictPut => {
762                    let key = trap!(self.int_from_reg(instr.b));
763                    let value = trap!(self.get_reg(instr.c));
764                    if !dict_scalar(&value) {
765                        return VmResult::Trap(Fault::TypeMismatch {
766                            expected: "dict scalar (unit/bool/int/float)",
767                            got: "heap-or-cap",
768                        });
769                    }
770                    let dict = self.dict.get_or_insert_with(HashMap::new);
771                    let old = match dict.insert(key, value) {
772                        Some(prev) => prev,
773                        None => Value::Unit,
774                    };
775                    trap!(self.set_reg(instr.a, old));
776                }
777                Opcode::DictGet => {
778                    let key = trap!(self.int_from_reg(instr.b));
779                    let value = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
780                        Some(v) => v,
781                        None => Value::Unit,
782                    };
783                    trap!(self.set_reg(instr.a, value));
784                }
785                Opcode::DictErase => {
786                    let key = trap!(self.int_from_reg(instr.b));
787                    let old = match self.dict.as_mut().and_then(|d| d.remove(&key)) {
788                        Some(v) => v,
789                        None => Value::Unit,
790                    };
791                    trap!(self.set_reg(instr.a, old));
792                }
793                Opcode::ReceiveMatchEq => {
794                    let tag = trap!(self.tag_from_reg(instr.b));
795                    let payload = trap!(self.int_from_reg(instr.c));
796                    return VmResult::Receive {
797                        dest_reg: instr.a,
798                        timeout: None,
799                        match_tag: Some(tag),
800                        match_request_id: None,
801                        match_payload_kind: None,
802                        match_payload_eq: Some(payload),
803                    };
804                }
805                Opcode::StartChild => {
806                    let function = match u32::try_from(instr.imm) {
807                        Ok(f) => f,
808                        Err(_) => u32::MAX,
809                    };
810                    if self.chunk.function(function).is_none() {
811                        return VmResult::Trap(Fault::BadFunction {
812                            index: function,
813                            table_size: self.chunk.functions.len() as u32,
814                        });
815                    }
816                    if crate::RestartPolicy::from_u8(instr.b).is_none() {
817                        return VmResult::Trap(Fault::TypeMismatch {
818                            expected: "restart policy 0..=2",
819                            got: "imm-out-of-range",
820                        });
821                    }
822                    return VmResult::StartChild {
823                        dest_reg: instr.a,
824                        function,
825                        policy: instr.b,
826                    };
827                }
828                Opcode::ReceiveMatchKind => {
829                    // Selective receive by payload wire-tag (`Value::wire_tag`,
830                    // 0..=8). Non-matching hops stay queued (FIFO skip).
831                    let kind = match u8::try_from(instr.imm) {
832                        Ok(k) if k <= 8 => k,
833                        _ => {
834                            return VmResult::Trap(Fault::TypeMismatch {
835                                expected: "payload kind 0..=8",
836                                got: "imm-out-of-range",
837                            })
838                        }
839                    };
840                    return VmResult::Receive {
841                        dest_reg: instr.a,
842                        timeout: None,
843                        match_tag: None,
844                        match_request_id: None,
845                        match_payload_kind: Some(kind),
846                        match_payload_eq: None,
847                    };
848                }
849                Opcode::FreshRequestId => {
850                    let id = self.fresh_request_id();
851                    trap!(self.set_reg(instr.a, Value::Int(id as i64)));
852                }
853                Opcode::ReceiveMatchCorr => {
854                    let tag = trap!(self.tag_from_reg(instr.b));
855                    let rid = trap!(self.request_id_from_reg(instr.c));
856                    return VmResult::Receive {
857                        dest_reg: instr.a,
858                        timeout: None,
859                        match_tag: Some(tag),
860                        match_request_id: Some(rid),
861                        match_payload_kind: None,
862                        match_payload_eq: None,
863                    };
864                }
865                Opcode::ReceiveMatchCorrImm => {
866                    let tag = trap!(tag_from_imm(instr.imm));
867                    let rid = trap!(self.request_id_from_reg(instr.b));
868                    return VmResult::Receive {
869                        dest_reg: instr.a,
870                        timeout: None,
871                        match_tag: Some(tag),
872                        match_request_id: Some(rid),
873                        match_payload_kind: None,
874                        match_payload_eq: None,
875                    };
876                }
877                Opcode::Ask => {
878                    let target_cap = trap!(self.expect_cap_reg(instr.b));
879                    let request = trap!(self.expect_message_value(instr.c));
880                    return VmResult::Ask {
881                        dest_reg: instr.a,
882                        target_cap,
883                        request,
884                        timeout: None,
885                    };
886                }
887                Opcode::AskTimeout => {
888                    let millis_reg = match u8::try_from(instr.imm) {
889                        Ok(r) => r,
890                        Err(_) => {
891                            return VmResult::Trap(Fault::TypeMismatch {
892                                expected: "millis register",
893                                got: "imm-out-of-range",
894                            })
895                        }
896                    };
897                    let timeout = trap!(self.duration_millis_from_reg(millis_reg));
898                    let target_cap = trap!(self.expect_cap_reg(instr.b));
899                    let request = trap!(self.expect_message_value(instr.c));
900                    return VmResult::Ask {
901                        dest_reg: instr.a,
902                        target_cap,
903                        request,
904                        timeout: Some(timeout),
905                    };
906                }
907                Opcode::Monitor => {
908                    let target_cap = trap!(self.expect_cap_reg(instr.b));
909                    return VmResult::Monitor {
910                        dest_reg: instr.a,
911                        target_cap,
912                    };
913                }
914                Opcode::Demonitor => {
915                    return VmResult::Demonitor {
916                        monitor_reg: instr.a,
917                    };
918                }
919                Opcode::Link => {
920                    let target_cap = trap!(self.expect_cap_reg(instr.b));
921                    return VmResult::Link {
922                        dest_reg: instr.a,
923                        target_cap,
924                    };
925                }
926                Opcode::Unlink => {
927                    return VmResult::Unlink { link_reg: instr.a };
928                }
929                Opcode::SetTrapExit => {
930                    let enabled = trap!(self.get_reg(instr.a)).is_truthy();
931                    return VmResult::SetTrapExit { enabled };
932                }
933                Opcode::SetRestartPolicy => {
934                    // Flow-local OTP restart policy for the host Supervisor
935                    // (`0` Always / `1` OnFailure / `2` Never).
936                    let policy = match instr.imm {
937                        0..=2 => instr.imm as u8,
938                        _ => {
939                            return VmResult::Trap(Fault::TypeMismatch {
940                                expected: "restart policy 0..=2",
941                                got: "imm-out-of-range",
942                            })
943                        }
944                    };
945                    return VmResult::SetRestartPolicy { policy };
946                }
947                Opcode::HostAwait => {
948                    let args = trap!(self.get_reg(instr.b));
949                    let op = if instr.imm < 0 {
950                        return VmResult::Trap(Fault::TypeMismatch {
951                            expected: "HostAwait op >= 0",
952                            got: "imm-negative",
953                        });
954                    } else {
955                        instr.imm as u32
956                    };
957                    return VmResult::HostAwait {
958                        dest_reg: instr.a,
959                        op,
960                        args,
961                    };
962                }
963                Opcode::RegisterName => {
964                    return VmResult::RegisterName {
965                        name: trap!(self.expect_str_reg(instr.a)),
966                    };
967                }
968                Opcode::Whereis => {
969                    return VmResult::Whereis {
970                        dest_reg: instr.a,
971                        name: trap!(self.expect_str_reg(instr.b)),
972                    };
973                }
974                Opcode::Delegate => {
975                    let src_cap = trap!(self.expect_cap_reg(instr.b));
976                    let want_native_cap = if instr.c == 255 {
977                        None
978                    } else {
979                        Some(trap!(self.expect_cap_reg(instr.c)))
980                    };
981                    return VmResult::Delegate {
982                        dest_reg: instr.a,
983                        src_cap,
984                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
985                        want_native_cap,
986                    };
987                }
988                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
989            }
990        }
991        VmResult::Yield
992    }
993
994    /// Pop the current frame, delivering `value` to the caller (or
995    /// finishing the Flow if this was the outermost frame). Returns
996    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
997    ///
998    /// Releases the finished frame's heap charge (except the escaping
999    /// return value on the outermost `Complete` path, which stays charged
1000    /// until flow finalize — matching prior MemoryBudget semantics).
1001    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
1002        let finished = self
1003            .frames
1004            .pop()
1005            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
1006        match finished.dest_reg() {
1007            Some(dest) => {
1008                if let Some(quota) = self.quota.as_ref() {
1009                    release_pair(quota, self.memory.as_deref(), finished.heap_charge());
1010                }
1011                self.set_reg(dest, value)?;
1012                Ok(None)
1013            }
1014            None => {
1015                if let Some(quota) = self.quota.as_ref() {
1016                    let keep = heap_charge_of(&value);
1017                    let release = finished.heap_charge().saturating_sub(keep);
1018                    release_pair(quota, self.memory.as_deref(), release);
1019                }
1020                Ok(Some(VmResult::Complete(value)))
1021            }
1022        }
1023    }
1024
1025    /// Load call arguments into a not-yet-pushed frame, charging heap for
1026    /// any `Str`/`Bytes`. Rolls back a partial charge if a later arg fails.
1027    fn load_frame_args_charged(
1028        &self,
1029        frame: &mut Frame,
1030        args: impl IntoIterator<Item = Value>,
1031        arity: u8,
1032    ) -> Result<(), Fault> {
1033        let frame_size = frame.registers().len() as u8;
1034        let mut charged = 0usize;
1035        for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1036            let bytes = heap_charge_of(&a);
1037            if bytes > 0 {
1038                if let Some(quota) = self.quota.as_ref() {
1039                    if let Err(e) = charge_pair(quota, self.memory.as_deref(), bytes) {
1040                        if charged > 0 {
1041                            release_pair(quota, self.memory.as_deref(), charged);
1042                        }
1043                        frame.set_heap_charge(0);
1044                        return Err(e);
1045                    }
1046                }
1047                charged = charged.saturating_add(bytes);
1048                frame.add_heap_charge(bytes);
1049            }
1050            match frame.registers_mut().get_mut(i) {
1051                Some(slot) => *slot = a,
1052                None => {
1053                    if charged > 0 {
1054                        if let Some(quota) = self.quota.as_ref() {
1055                            release_pair(quota, self.memory.as_deref(), charged);
1056                        }
1057                        frame.set_heap_charge(0);
1058                    }
1059                    return Err(Fault::RegisterOutOfRange {
1060                        reg: i as u8,
1061                        frame_size,
1062                    });
1063                }
1064            }
1065        }
1066        Ok(())
1067    }
1068}
1069
1070/// The register index `base + offset`, or [`Fault::RegisterIndexOverflow`]
1071/// if that sum leaves the register index space.
1072///
1073/// Every multi-operand opcode gathers its arguments from consecutive
1074/// registers. Written as a plain `base + offset` on `u8`, that addition
1075/// panics in debug and **wraps** in release — so a release build silently
1076/// reads the wrong register instead of failing, which is the worst of the
1077/// two outcomes and the one a debug-mode test suite never sees. The sum is
1078/// therefore computed in a wider type and narrowed explicitly.
1079#[inline]
1080fn load_frame_args(
1081    frame: &mut Frame,
1082    args: impl IntoIterator<Item = Value>,
1083    arity: u8,
1084) -> Result<(), Fault> {
1085    let frame_size = frame.registers().len() as u8;
1086    for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1087        match frame.registers_mut().get_mut(i) {
1088            Some(slot) => *slot = a,
1089            None => {
1090                return Err(Fault::RegisterOutOfRange {
1091                    reg: i as u8,
1092                    frame_size,
1093                })
1094            }
1095        }
1096    }
1097    Ok(())
1098}
1099
1100fn reg_at(base: u8, offset: u16) -> Result<u8, Fault> {
1101    match u8::try_from(u32::from(base) + u32::from(offset)) {
1102        Ok(reg) => Ok(reg),
1103        Err(_) => Err(Fault::RegisterIndexOverflow {
1104            base,
1105            offset: match u8::try_from(offset) {
1106                Ok(o) => o,
1107                Err(_) => u8::MAX,
1108            },
1109        }),
1110    }
1111}
1112
1113/// Bytes charged for a register-resident heap value (`Str` / `Bytes` len).
1114#[inline]
1115fn heap_charge_of(value: &Value) -> usize {
1116    match value {
1117        Value::Str(s) => s.len(),
1118        Value::Bytes(b) => b.len(),
1119        _ => 0,
1120    }
1121}
1122
1123/// Reserve `bytes` on the flow quota and optional runtime budget.
1124/// Rolls back the flow charge if the global budget refuses.
1125fn charge_pair(
1126    quota: &FlowQuota,
1127    memory: Option<&crate::MemoryBudget>,
1128    bytes: usize,
1129) -> Result<(), Fault> {
1130    if bytes == 0 {
1131        return Ok(());
1132    }
1133    quota
1134        .alloc(bytes)
1135        .map_err(|e| Fault::QuotaExceeded(e.to_string()))?;
1136    if let Some(mem) = memory {
1137        if let Err(e) = mem.try_charge(bytes) {
1138            quota.free(bytes);
1139            return Err(Fault::QuotaExceeded(e.to_string()));
1140        }
1141    }
1142    Ok(())
1143}
1144
1145fn release_pair(quota: &FlowQuota, memory: Option<&crate::MemoryBudget>, bytes: usize) {
1146    if bytes == 0 {
1147        return;
1148    }
1149    quota.free(bytes);
1150    if let Some(mem) = memory {
1151        mem.release(bytes);
1152    }
1153}
1154
1155fn as_f64(v: &Value) -> Result<f64, Fault> {
1156    match v {
1157        Value::Int(i) => Ok(*i as f64),
1158        Value::Float(f) => Ok(*f),
1159        other => Err(Fault::TypeMismatch {
1160            expected: "int or float",
1161            got: other.type_name(),
1162        }),
1163    }
1164}
1165
1166/// Decode a Message tag from a register value (`Int` in `0..=u16::MAX`).
1167#[inline]
1168fn tag_from_imm(imm: i32) -> Result<u16, Fault> {
1169    match u16::try_from(imm) {
1170        Ok(t) if imm >= 0 => Ok(t),
1171        _ => Err(Fault::TypeMismatch {
1172            expected: "tag u16",
1173            got: "imm-out-of-range",
1174        }),
1175    }
1176}
1177
1178fn tag_from_value(v: &Value) -> Result<u16, Fault> {
1179    match v.as_int() {
1180        Some(i) if (0..=i64::from(u16::MAX)).contains(&i) => Ok(i as u16),
1181        Some(_) => Err(Fault::TypeMismatch {
1182            expected: "tag u16",
1183            got: "int-out-of-range",
1184        }),
1185        None => Err(Fault::TypeMismatch {
1186            expected: "int",
1187            got: v.type_name(),
1188        }),
1189    }
1190}
1191
1192/// Decode a `request_id` from a register (`Int` in `0..=i64::MAX`).
1193#[inline]
1194fn request_id_from_value(v: &Value) -> Result<u64, Fault> {
1195    match v.as_int() {
1196        Some(i) if i >= 0 => Ok(i as u64),
1197        Some(_) => Err(Fault::TypeMismatch {
1198            expected: "request_id u64",
1199            got: "negative-int",
1200        }),
1201        None => Err(Fault::TypeMismatch {
1202            expected: "int",
1203            got: v.type_name(),
1204        }),
1205    }
1206}
1207
1208#[cfg(test)]
1209mod tests {
1210    use super::*;
1211    use crate::bytecode::builder::ChunkBuilder;
1212
1213    type TestResult = Result<(), Box<dyn std::error::Error>>;
1214
1215    /// `Spawn a=255` reads its arguments from `a+1`, so the first index
1216    /// already leaves the register space. This used to panic in debug and —
1217    /// far worse — wrap around to `r0` in release, silently spawning with the
1218    /// wrong argument.
1219    #[test]
1220    fn spawn_from_the_last_register_traps_instead_of_wrapping() -> TestResult {
1221        let mut b = ChunkBuilder::new("t");
1222        b.begin_function("main", 0, 2);
1223        b.emit_spawn(255, 0, 1);
1224        b.emit_return(0);
1225        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1226        match vm.run(10) {
1227            VmResult::Trap(Fault::RegisterIndexOverflow {
1228                base: 255,
1229                offset: 1,
1230            }) => Ok(()),
1231            other => Err(format!("expected RegisterIndexOverflow, got {other:?}").into()),
1232        }
1233    }
1234
1235    /// `Vm::new` is public and reachable without `verify`, and its panic
1236    /// landed on the caller's thread — the embedder's on `Runtime::spawn`, or
1237    /// a worker's on bytecode `Spawn`, outside the `catch_unwind`.
1238    #[test]
1239    fn entering_a_function_with_too_few_registers_faults() -> TestResult {
1240        let mut b = ChunkBuilder::new("t");
1241        b.begin_function("main", 3, 1);
1242        b.emit_return(0);
1243        let args = [Value::Int(1), Value::Int(2), Value::Int(3)];
1244        match Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &args) {
1245            Err(Fault::RegisterOutOfRange {
1246                reg: 1,
1247                frame_size: 1,
1248            }) => Ok(()),
1249            Err(e) => Err(format!("unexpected fault: {e}").into()),
1250            Ok(_) => Err("three arguments cannot be loaded into one register".into()),
1251        }
1252    }
1253
1254    #[test]
1255    fn calling_a_function_with_too_few_registers_traps() -> TestResult {
1256        let mut b = ChunkBuilder::new("t");
1257        let callee = b.begin_function("callee", 3, 1);
1258        b.emit_return(0);
1259        let main = b.begin_function("main", 0, 4);
1260        b.emit_load_imm(0, 7);
1261        b.emit_load_imm(1, 8);
1262        b.emit_load_imm(2, 9);
1263        b.emit_call(0, callee, 3);
1264        b.emit_return(0);
1265        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1266        match vm.run(50) {
1267            VmResult::Trap(Fault::RegisterOutOfRange {
1268                reg: 1,
1269                frame_size: 1,
1270            }) => Ok(()),
1271            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1272        }
1273    }
1274
1275    /// The boundary case that must keep working: gathering right up to the
1276    /// last register is legal, it is only going *past* it that faults.
1277    #[test]
1278    fn gathering_up_to_the_last_register_still_works() -> TestResult {
1279        let mut b = ChunkBuilder::new("t");
1280        let callee = b.begin_function("callee", 1, 1);
1281        b.emit_return(0);
1282        let main = b.begin_function("main", 0, 255);
1283        b.emit_load_imm(254, 5);
1284        // Argument at r254 — the highest index a 255-register frame has.
1285        b.emit_call(254, callee, 1);
1286        b.emit_return(254);
1287        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1288        match vm.run(100) {
1289            VmResult::Complete(_) => Ok(()),
1290            other => Err(format!("expected completion, got {other:?}").into()),
1291        }
1292    }
1293
1294    #[test]
1295    fn neg_i64_min_wrapping() -> TestResult {
1296        let mut b = ChunkBuilder::new("t");
1297        b.begin_function("main", 0, 1);
1298        let k = b.const_(Value::Int(i64::MIN));
1299        b.emit_load_const(0, k);
1300        b.emit_neg(0, 0);
1301        b.emit_return(0);
1302        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1303        match vm.run(10) {
1304            VmResult::Complete(Value::Int(v)) if v == i64::MIN => Ok(()),
1305            other => Err(format!("expected Complete(Int(i64::MIN)), got {other:?}").into()),
1306        }
1307    }
1308
1309    #[test]
1310    fn mod_non_int_type_mismatch() -> TestResult {
1311        let mut b = ChunkBuilder::new("t");
1312        b.begin_function("main", 0, 3);
1313        b.emit_load_imm(0, 10);
1314        let kf = b.const_(Value::Float(3.0));
1315        b.emit_load_const(1, kf);
1316        b.emit_binop(Opcode::Mod, 2, 0, 1);
1317        b.emit_return(2);
1318        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1319        match vm.run(20) {
1320            VmResult::Trap(Fault::TypeMismatch {
1321                expected: "int",
1322                got: "float",
1323            }) => Ok(()),
1324            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1325        }
1326    }
1327
1328    #[test]
1329    fn receive_timeout_negative_traps() -> TestResult {
1330        let mut b = ChunkBuilder::new("t");
1331        b.begin_function("main", 0, 2);
1332        b.emit_load_imm(1, -1);
1333        b.emit_receive_timeout(0, 1);
1334        b.emit_return(0);
1335        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1336        match vm.run(10) {
1337            VmResult::Trap(Fault::TypeMismatch {
1338                expected: "non-negative int",
1339                ..
1340            }) => Ok(()),
1341            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1342        }
1343    }
1344
1345    #[test]
1346    fn ask_timeout_negative_traps() -> TestResult {
1347        let mut b = ChunkBuilder::new("t");
1348        b.begin_function("main", 0, 4);
1349        b.emit_load_imm(3, -5);
1350        // Cap/message regs are garbage; millis is checked first.
1351        b.emit_ask_timeout(0, 1, 2, 3);
1352        b.emit_return(0);
1353        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1354        match vm.run(10) {
1355            VmResult::Trap(Fault::TypeMismatch {
1356                expected: "non-negative int",
1357                ..
1358            }) => Ok(()),
1359            other => Err(format!("expected TypeMismatch, got {other:?}").into()),
1360        }
1361    }
1362
1363    #[test]
1364    fn paranoid_jump_out_of_range_traps() -> TestResult {
1365        let mut b = ChunkBuilder::new("t");
1366        b.begin_function("main", 0, 1);
1367        b.emit_load_imm(0, 0);
1368        b.emit_return(0);
1369        let mut chunk = b.finish();
1370        let code_len = chunk.code.len();
1371        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1372        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1373        vm.set_paranoid_jumps(true);
1374        match vm.run(10) {
1375            VmResult::Trap(Fault::BadJump {
1376                target: 101,
1377                code_len: len,
1378            }) if len == code_len => Ok(()),
1379            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1380        }
1381    }
1382
1383    #[test]
1384    fn overwrite_releases_previous_heap_charge() -> TestResult {
1385        let mut b = ChunkBuilder::new("t");
1386        let k1 = b.const_(Value::Str("a".repeat(100).into()));
1387        let k2 = b.const_(Value::Str("b".repeat(100).into()));
1388        b.begin_function("main", 0, 1);
1389        b.emit_load_const(0, k1);
1390        b.emit_load_const(0, k2);
1391        b.emit_return(0);
1392        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1393        // Limit 150: first 100 fits; without release the second 100 would fail.
1394        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1395            crate::QuotaConfig {
1396                mem_limit: 150,
1397                ..crate::QuotaConfig::permissive()
1398            },
1399        ));
1400        let memory = Arc::new(crate::MemoryBudget::new(10_000));
1401        vm.set_memory_budget(Arc::clone(&memory));
1402        vm.set_quota(Arc::clone(&quota))?;
1403        match vm.run(20) {
1404            VmResult::Complete(Value::Str(s)) if s.len() == 100 => {
1405                assert_eq!(quota.mem_used(), 100);
1406                assert_eq!(memory.used(), 100);
1407                Ok(())
1408            }
1409            other => Err(format!("expected Complete(100-byte Str), got {other:?}").into()),
1410        }
1411    }
1412
1413    #[test]
1414    fn return_releases_callee_heap_before_caller_writeback() -> TestResult {
1415        let mut b = ChunkBuilder::new("t");
1416        let k = b.const_(Value::Str("x".repeat(200).into()));
1417        let callee = b.begin_function("callee", 0, 1);
1418        b.emit_load_const(0, k);
1419        b.emit_return(0);
1420        let main = b.begin_function("main", 0, 1);
1421        b.emit_call(0, callee, 0);
1422        b.emit_return(0);
1423        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), main, &[])?;
1424        // Old bug: callee charged 200 and return writeback charged again without
1425        // release → QuotaExceeded at 250. Correct path releases then recharges.
1426        let quota = Arc::new(crate::scheduler::FlowQuota::new(10_000, 250, 1, 1, 1, 1));
1427        vm.set_quota(Arc::clone(&quota))?;
1428        match vm.run(50) {
1429            VmResult::Complete(Value::Str(s)) if s.len() == 200 => {
1430                assert_eq!(quota.mem_used(), 200);
1431                Ok(())
1432            }
1433            other => Err(format!("expected Complete(200-byte Str), got {other:?}").into()),
1434        }
1435    }
1436
1437    #[test]
1438    fn set_reg_out_of_range_does_not_charge() -> TestResult {
1439        let mut b = ChunkBuilder::new("t");
1440        b.begin_function("main", 0, 1);
1441        b.emit_return(0);
1442        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1443        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1444            crate::QuotaConfig {
1445                mem_limit: 10_000,
1446                ..crate::QuotaConfig::permissive()
1447            },
1448        ));
1449        vm.set_quota(Arc::clone(&quota))?;
1450        let big = Value::Str("z".repeat(500).into());
1451        match vm.set_register(255, big) {
1452            Err(Fault::RegisterOutOfRange {
1453                reg: 255,
1454                frame_size: 1,
1455            }) => {
1456                assert_eq!(quota.mem_used(), 0);
1457                Ok(())
1458            }
1459            other => Err(format!("expected RegisterOutOfRange, got {other:?}").into()),
1460        }
1461    }
1462
1463    #[test]
1464    fn set_quota_is_transactional() -> TestResult {
1465        let mut b = ChunkBuilder::new("t");
1466        b.begin_function("main", 0, 2);
1467        b.emit_return(0);
1468        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1469        // Two 100-byte Strs already in registers; limit 150 must refuse the
1470        // whole attach without leaving a partial charge on the quota object.
1471        vm.set_register(0, Value::Str("a".repeat(100).into()))?;
1472        vm.set_register(1, Value::Str("b".repeat(100).into()))?;
1473        let quota = Arc::new(crate::scheduler::FlowQuota::from_config(
1474            crate::QuotaConfig {
1475                mem_limit: 150,
1476                ..crate::QuotaConfig::permissive()
1477            },
1478        ));
1479        match vm.set_quota(Arc::clone(&quota)) {
1480            Err(Fault::QuotaExceeded(_)) => {
1481                assert_eq!(
1482                    quota.mem_used(),
1483                    0,
1484                    "failed set_quota must not leave a partial charge"
1485                );
1486                Ok(())
1487            }
1488            other => Err(format!("expected QuotaExceeded, got {other:?}").into()),
1489        }
1490    }
1491
1492    #[test]
1493    fn fresh_request_id_stays_in_i64_domain() -> TestResult {
1494        let mut b = ChunkBuilder::new("t");
1495        b.begin_function("main", 0, 1);
1496        b.emit_return(0);
1497        let mut vm = Vm::new(Arc::new(b.finish()), NativeTable::empty(), 0, &[])?;
1498        vm.set_next_request_id_for_test(i64::MAX as u64);
1499        let id = vm.fresh_request_id();
1500        assert_eq!(id, i64::MAX as u64);
1501        assert_eq!(vm.fresh_request_id(), i64::MAX as u64);
1502        assert!((id as i64) >= 0);
1503        Ok(())
1504    }
1505
1506    #[test]
1507    fn call_native_without_gate_is_typed_denied() -> TestResult {
1508        let mut b = ChunkBuilder::new("t");
1509        b.begin_function("main", 0, 1);
1510        b.emit_call_native(0, 0, 0);
1511        b.emit_return(0);
1512        let table = NativeTable::builder().register("noop", |_| Ok(Value::Unit))?;
1513        let mut vm = Vm::new(Arc::new(b.finish()), table.build(), 0, &[])?;
1514        match vm.run(10) {
1515            VmResult::Trap(Fault::NativeDenied(NativeCallError::NoNativeRight)) => Ok(()),
1516            other => Err(format!("expected NativeDenied(NoNativeRight), got {other:?}").into()),
1517        }
1518    }
1519
1520    #[test]
1521    fn bad_jump_fail_closes_even_without_paranoid_flag() -> TestResult {
1522        let mut b = ChunkBuilder::new("t");
1523        b.begin_function("main", 0, 1);
1524        b.emit_load_imm(0, 7);
1525        b.emit_return(0);
1526        let mut chunk = b.finish();
1527        let code_len = chunk.code.len();
1528        chunk.code[0] = Instruction::only_imm(Opcode::Jump, 100);
1529        let mut vm = Vm::new(Arc::new(chunk), NativeTable::empty(), 0, &[])?;
1530        // Flag retained for API compat; jumps always fail closed.
1531        vm.set_paranoid_jumps(false);
1532        match vm.run(10) {
1533            VmResult::Trap(Fault::BadJump {
1534                target: 101,
1535                code_len: len,
1536            }) if len == code_len => Ok(()),
1537            other => Err(format!("expected BadJump(101), got {other:?}").into()),
1538        }
1539    }
1540}