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