Skip to main content

byteflow/vm/
machine.rs

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