Skip to main content

byteflow/vm/machine/
mod.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
13mod heap;
14#[cfg(test)]
15mod tests;
16
17use heap::{
18    as_f64, charge_pair, dict_owned_bytes, heap_charge_of, load_frame_args, reg_at, release_pair,
19    request_id_from_value, require_int, tag_from_imm, tag_from_value,
20};
21
22pub(crate) use heap::in_flight_hop_charge;
23
24/// Hard limit on call nesting. Frames are heap-allocated, so
25/// unbounded recursion would grow the Flow's memory instead of crashing
26/// the worker thread's native stack — which is worse, not better, without a
27/// limit. `4096` comfortably covers real recursive algorithms while keeping
28/// a runaway `fn f() { f() }` a `Fault`, not an OOM.
29pub const MAX_CALL_DEPTH: usize = 4096;
30
31/// One virtual Flow's execution state: call stack + registers. Cheap
32/// enough to construct that spawning a Flow is a handful of small heap
33/// allocations, not a native thread/stack (contrast: a `std::thread` reserves
34/// megabytes of stack whether it uses them or not).
35///
36/// `Vm` owns no scheduler, mailbox, or thread handle — see [`VmResult`] for
37/// why that separation is the whole point.
38pub struct Vm {
39    chunk: Arc<Chunk>,
40    natives: Arc<NativeTable>,
41    native_gate: NativeGate,
42    frames: Vec<Frame>,
43    /// Lifetime instruction counter, exposed for `FlowMetrics` (design
44    /// notes §26).
45    instructions_executed: u64,
46    /// Next `Message.request_id` for [`Opcode::FreshRequestId`] and for
47    /// hops that still carry `0` (“unset”) at the Send/Ask boundary.
48    next_request_id: u64,
49    /// Per-flow heap charge for `Str`/`Bytes` written into registers.
50    quota: Option<Arc<FlowQuota>>,
51    /// Process-wide memory ceiling (optional; set by the runtime).
52    memory: Option<Arc<crate::MemoryBudget>>,
53    /// BEAM process dictionary. Allocated on first `DictPut` so the common
54    /// flow that never touches the dict pays nothing.
55    dict: Option<HashMap<i64, Value>>,
56    /// Heap bytes charged for `Str` / `Bytes` stored in [`Self::dict`].
57    /// Separate from frame charges: overwriting the source register must not
58    /// free a buffer the dictionary still owns.
59    dict_bytes: usize,
60}
61
62impl Vm {
63    /// Construct a `Vm` ready to run `function` (an index into
64    /// `chunk.functions`) with the given arguments loaded into `r0..argc`.
65    /// `natives` is the FFI table `Opcode::CallNative` dispatches through —
66    /// pass [`NativeTable::empty`] if the chunk never calls out to Rust.
67    ///
68    /// Native calls are **denied** until [`Self::with_native_gate`] installs
69    /// an allowlist (the runtime does this from the flow's attenuated Cap).
70    pub fn new(
71        chunk: Arc<Chunk>,
72        natives: Arc<NativeTable>,
73        function: u32,
74        args: &[Value],
75    ) -> Result<Self, Fault> {
76        let gate = NativeGate::deny(natives.len());
77        Self::with_native_gate(chunk, natives, gate, function, args)
78    }
79
80    pub fn with_native_gate(
81        chunk: Arc<Chunk>,
82        natives: Arc<NativeTable>,
83        native_gate: NativeGate,
84        function: u32,
85        args: &[Value],
86    ) -> Result<Self, Fault> {
87        let def = chunk.function(function).ok_or(Fault::BadFunction {
88            index: function,
89            table_size: chunk.functions.len() as u32,
90        })?;
91        let mut frame = Frame::new(function, def.num_registers, None);
92        frame.set_pc(def.entry as usize);
93        load_frame_args(&mut frame, args.iter().cloned(), def.arity)?;
94        let mut vm = Vm {
95            chunk,
96            natives,
97            native_gate,
98            frames: Vec::with_capacity(16),
99            instructions_executed: 0,
100            next_request_id: 1,
101            quota: None,
102            memory: None,
103            dict: None,
104            dict_bytes: 0,
105        };
106        vm.frames.push(frame);
107        Ok(vm)
108    }
109
110    /// Attach the flow's quota so register stores of `Str`/`Bytes` charge heap.
111    ///
112    /// Charges the **total** current register heap in one reservation, then
113    /// installs the quota. A failed reservation leaves `self.quota` unset and
114    /// does not partially inflate the budget. Same `Arc` rewritten into the
115    /// same slot is not charged twice on later stores.
116    pub fn set_quota(&mut self, quota: Arc<FlowQuota>) -> Result<(), Fault> {
117        let mut per_frame: Vec<usize> = Vec::with_capacity(self.frames.len());
118        let mut total = 0usize;
119        for frame in &self.frames {
120            let mut bytes = 0usize;
121            for value in frame.registers() {
122                let part = heap_charge_of(value)?;
123                bytes = match bytes.checked_add(part) {
124                    Some(sum) => sum,
125                    None => {
126                        return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
127                    }
128                };
129            }
130            total = match total.checked_add(bytes) {
131                Some(sum) => sum,
132                None => return Err(Fault::QuotaExceeded("heap charge does not fit".into())),
133            };
134            per_frame.push(bytes);
135        }
136        total = match total.checked_add(self.dict_bytes) {
137            Some(sum) => sum,
138            None => return Err(Fault::QuotaExceeded("heap charge does not fit".into())),
139        };
140        charge_pair(&quota, self.memory.as_deref(), total)?;
141        for (frame, bytes) in self.frames.iter_mut().zip(per_frame) {
142            frame.set_heap_charge(bytes);
143        }
144        self.quota = Some(quota);
145        Ok(())
146    }
147
148    /// Attach the process-wide memory ceiling (call before or with [`Self::set_quota`]).
149    pub fn set_memory_budget(&mut self, memory: Arc<crate::MemoryBudget>) {
150        self.memory = Some(memory);
151    }
152
153    /// Mint a per-flow correlation id.
154    ///
155    /// Stays in the `Value::Int` (`i64`) domain so
156    /// `FreshRequestId` → `Int` → `request_id_from_value` never produces a
157    /// negative id. Never returns `0` (`next_request_id` starts at 1).
158    /// Saturates at `i64::MAX` instead of wrapping.
159    pub fn fresh_request_id(&mut self) -> u64 {
160        const MAX: u64 = i64::MAX as u64;
161        if self.next_request_id == 0 {
162            self.next_request_id = 1;
163        }
164        let id = self.next_request_id;
165        if id >= MAX {
166            self.next_request_id = MAX;
167            return MAX;
168        }
169        self.next_request_id = id + 1;
170        id
171    }
172
173    #[cfg(test)]
174    fn set_next_request_id_for_test(&mut self, id: u64) {
175        self.next_request_id = id;
176    }
177
178    pub fn instructions_executed(&self) -> u64 {
179        self.instructions_executed
180    }
181
182    /// Count instructions a compiled trace already ran. The interpreter
183    /// counts its own steps in [`Self::run`].
184    #[cfg(feature = "jit")]
185    pub(crate) fn record_instructions(&mut self, count: u64) {
186        self.instructions_executed = self.instructions_executed.saturating_add(count);
187    }
188
189    /// Index into `chunk.functions` for the active (top) call frame.
190    /// Useful for diagnostics / supervisor logs when a Flow traps.
191    pub fn current_function(&self) -> u32 {
192        // Category D: frames must be non-empty while the VM is runnable.
193        // We still avoid `.expect` — return 0 as a diagnostic fallback so a
194        // broken invariant cannot panic a worker; the next `run` will trap.
195        debug_assert!(!self.frames.is_empty(), "frames empty while running");
196        match self.frames.last() {
197            Some(frame) => frame.function(),
198            None => 0,
199        }
200    }
201
202    /// A cheap `Arc` clone of the chunk this VM is executing. Used by the
203    /// scheduler to construct a child `Vm` for `Opcode::Spawn` without
204    /// needing to know anything about `Chunk`'s internals — every Flow
205    /// spawned (transitively) from the same top-level `spawn()` call shares
206    /// one immutable chunk in memory, never copies it.
207    pub fn chunk_arc(&self) -> Arc<Chunk> {
208        self.chunk.clone()
209    }
210
211    /// A cheap `Arc` clone of this VM's native function table, for the same
212    /// reason as [`Vm::chunk_arc`]: a `Spawn`-created child must dispatch
213    /// `CallNative` through the identical table its parent uses.
214    pub fn natives_arc(&self) -> Arc<NativeTable> {
215        self.natives.clone()
216    }
217
218    /// Deliver a value the scheduler produced on our behalf (a **Cap** from
219    /// `Spawn` / `SelfPid`, or a dequeued mailbox message from a `Receive`)
220    /// into the register the instruction that suspended us was targeting,
221    /// ahead of the next [`Vm::run`] call. A no-op is never valid to skip:
222    /// calling `run` without this after a `Spawn`/`Receive` result leaves the
223    /// destination register holding its previous (stale) value.
224    #[inline]
225    pub fn resume_with(&mut self, dest_reg: u8, value: Value) -> Result<(), Fault> {
226        self.set_reg(dest_reg, value)
227    }
228
229    /// Program counter of the active frame — used by the optional JIT hook.
230    pub fn current_pc(&self) -> Option<usize> {
231        self.frames.last().map(|f| f.pc())
232    }
233
234    /// Number of registers in the active frame.
235    pub fn current_num_registers(&self) -> Option<usize> {
236        self.frames.last().map(|f| f.registers().len())
237    }
238
239    /// Read-only view of the active register file.
240    pub fn top_registers(&self) -> Option<&[Value]> {
241        self.frames.last().map(|f| f.registers())
242    }
243
244    /// Mutable view of the active register file (JIT sync path).
245    pub fn top_registers_mut(&mut self) -> Option<&mut [Value]> {
246        self.frames.last_mut().map(|f| f.registers_mut())
247    }
248
249    /// Set the active frame's program counter.
250    pub fn set_pc(&mut self, pc: usize) {
251        if let Some(frame) = self.frames.last_mut() {
252            frame.set_pc(pc);
253        }
254    }
255
256    /// Write the active frame back to the state a JIT call left it in, then
257    /// push the callees the trace already entered.
258    ///
259    /// The caller is the frame that was live when the trace started. `frames`
260    /// are the nested activations, outermost first. Nothing is pushed when
261    /// the installed stack would pass [`MAX_CALL_DEPTH`].
262    #[cfg(feature = "jit")]
263    pub(crate) fn install_jit_frames(
264        &mut self,
265        caller_pc: usize,
266        caller_regs: &[(u8, Value)],
267        frames: Vec<(u32, u8, usize, Vec<Value>)>,
268    ) -> Result<(), Fault> {
269        if self.frames.len().saturating_add(frames.len()) > MAX_CALL_DEPTH {
270            return Err(Fault::CallStackOverflow {
271                depth: MAX_CALL_DEPTH,
272            });
273        }
274        let frame_size = self
275            .frames
276            .last()
277            .ok_or(Fault::Invariant(
278                "empty frame stack while installing jit frames",
279            ))?
280            .registers()
281            .len();
282        for (reg, _) in caller_regs {
283            if usize::from(*reg) >= frame_size {
284                return Err(Fault::RegisterOutOfRange {
285                    reg: *reg,
286                    frame_size: frame_size as u8,
287                });
288            }
289        }
290        self.set_pc(caller_pc);
291        for (reg, value) in caller_regs {
292            self.set_register(*reg, value.clone())?;
293        }
294        for (function, dest_reg, pc, registers) in frames {
295            let Some(num_registers) = u8::try_from(registers.len()).ok() else {
296                return Err(Fault::Invariant("jit frame is wider than a register file"));
297            };
298            let mut frame = Frame::new(function, num_registers, Some(dest_reg));
299            frame.set_pc(pc);
300            for (slot, value) in frame.registers_mut().iter_mut().zip(registers) {
301                *slot = value;
302            }
303            self.frames.push(frame);
304        }
305        Ok(())
306    }
307
308    /// Write one register in the active frame (JIT sync path).
309    pub fn set_register(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
310        self.set_reg(reg, value)
311    }
312
313    /// Deliver a return value through the call stack.
314    pub fn return_value(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
315        self.pop_frame(value)
316    }
317
318    /// Top call frame. Empty stack is a broken invariant (category D) —
319    /// returned as [`Fault::Invariant`], never as `unwrap`/`expect`.
320    #[inline]
321    fn current(&mut self) -> Result<&mut Frame, Fault> {
322        debug_assert!(!self.frames.is_empty(), "frames empty while running");
323        self.frames
324            .last_mut()
325            .ok_or(Fault::Invariant("empty frame stack while running"))
326    }
327
328    #[inline]
329    fn get_reg_ref(&self, reg: u8) -> Result<&Value, Fault> {
330        let frame = self
331            .frames
332            .last()
333            .ok_or(Fault::Invariant("empty frame stack while running"))?;
334        frame
335            .registers()
336            .get(reg as usize)
337            .ok_or(Fault::RegisterOutOfRange {
338                reg,
339                frame_size: frame.registers().len() as u8,
340            })
341    }
342
343    #[inline]
344    fn get_reg(&self, reg: u8) -> Result<Value, Fault> {
345        self.get_reg_ref(reg).cloned()
346    }
347
348    /// Write a register. Bounds-check the slot **before** any heap charge so
349    /// a failed store cannot inflate FlowQuota / MemoryBudget.
350    #[inline]
351    fn set_reg(&mut self, reg: u8, value: Value) -> Result<(), Fault> {
352        let frame = self
353            .frames
354            .last()
355            .ok_or(Fault::Invariant("empty frame stack while running"))?;
356        let frame_size = frame.registers().len() as u8;
357        let old = frame
358            .registers()
359            .get(reg as usize)
360            .ok_or(Fault::RegisterOutOfRange { reg, frame_size })?;
361
362        // Fast-path: both old and new are scalars (0 heap bytes).
363        // Bypasses recursive value inspection and quota bookkeeping.
364        if old.is_scalar() && value.is_scalar() {
365            let frame = self.current()?;
366            frame.registers_mut()[reg as usize] = value;
367            return Ok(());
368        }
369
370        // `old` is `&Value`; keep both sides as references for the helper.
371        let old_bytes = heap_charge_of(old)?;
372        let new_bytes = heap_charge_of(&value)?;
373
374        match (&value, old) {
375            (Value::Str(s), Value::Str(prev)) if Arc::ptr_eq(s, prev) => return Ok(()),
376            (Value::Bytes(b), Value::Bytes(prev)) if Arc::ptr_eq(b, prev) => return Ok(()),
377            _ => {}
378        }
379
380        if let Some(quota) = self.quota.as_ref() {
381            if new_bytes > old_bytes {
382                charge_pair(quota, self.memory.as_deref(), new_bytes - old_bytes)?;
383            } else if old_bytes > new_bytes {
384                release_pair(quota, self.memory.as_deref(), old_bytes - new_bytes);
385            }
386        }
387
388        let frame = self.current()?;
389        if new_bytes > old_bytes {
390            let delta = new_bytes - old_bytes;
391            if !frame.try_add_heap_charge(delta) {
392                if let Some(quota) = self.quota.as_ref() {
393                    release_pair(quota, self.memory.as_deref(), delta);
394                }
395                return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
396            }
397        } else if old_bytes > new_bytes {
398            frame.sub_heap_charge(old_bytes - new_bytes);
399        }
400        match frame.registers_mut().get_mut(reg as usize) {
401            Some(slot) => {
402                *slot = value;
403                Ok(())
404            }
405            None => Err(Fault::RegisterOutOfRange {
406                reg,
407                frame_size: frame.registers().len() as u8,
408            }),
409        }
410    }
411
412    /// Fetch the next instruction and advance `pc`.
413    ///
414    /// `Ok(None)` if control fell off the end of the function body without an
415    /// explicit `Return`/`Halt` — treated as an implicit `Return Unit`
416    /// (friendlier to hand-written bytecode that omits a trailing return).
417    /// `Err` if the frame stack is empty (invariant break).
418    ///
419    /// Borrows are split on purpose: hold `pc`, look up `chunk.code`, then
420    /// write `pc+1` — a single `&mut Frame` across `self.chunk` would not
421    /// compile.
422    #[inline]
423    fn fetch(&mut self) -> Result<Option<Instruction>, Fault> {
424        let pc = self.current()?.pc();
425        let instr = self.chunk.code.get(pc).copied();
426        if instr.is_some() {
427            self.current()?.set_pc(pc + 1);
428        }
429        Ok(instr)
430    }
431
432    fn add_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
433        let addend = i64::from(imm);
434        let result = match *self.get_reg_ref(src)? {
435            Value::Int(x) => Value::Int(x.wrapping_add(addend)),
436            Value::Float(x) => Value::Float(x + (addend as f64)),
437            ref other => {
438                return Err(Fault::TypeMismatch {
439                    expected: "int or float",
440                    got: other.type_name(),
441                })
442            }
443        };
444        self.set_reg(dst, result)
445    }
446
447    fn sub_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
448        let subtrahend = i64::from(imm);
449        let result = match *self.get_reg_ref(src)? {
450            Value::Int(x) => Value::Int(x.wrapping_sub(subtrahend)),
451            Value::Float(x) => Value::Float(x - (subtrahend as f64)),
452            ref other => {
453                return Err(Fault::TypeMismatch {
454                    expected: "int or float",
455                    got: other.type_name(),
456                })
457            }
458        };
459        self.set_reg(dst, result)
460    }
461
462    fn lt_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
463        let rhs = i64::from(imm);
464        let result = match *self.get_reg_ref(src)? {
465            Value::Int(x) => Value::Bool(x < rhs),
466            Value::Float(x) => Value::Bool(x < (rhs as f64)),
467            ref other => {
468                return Err(Fault::TypeMismatch {
469                    expected: "int or float",
470                    got: other.type_name(),
471                })
472            }
473        };
474        self.set_reg(dst, result)
475    }
476
477    fn mul_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
478        let factor = i64::from(imm);
479        let result = match *self.get_reg_ref(src)? {
480            Value::Int(x) => Value::Int(x.wrapping_mul(factor)),
481            Value::Float(x) => Value::Float(x * (factor as f64)),
482            ref other => {
483                return Err(Fault::TypeMismatch {
484                    expected: "int or float",
485                    got: other.type_name(),
486                })
487            }
488        };
489        self.set_reg(dst, result)
490    }
491
492    fn eq_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
493        let is_eq = match self.get_reg_ref(src)? {
494            Value::Int(x) => *x == i64::from(imm),
495            _ => false,
496        };
497        self.set_reg(dst, Value::Bool(is_eq))
498    }
499
500    fn ne_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
501        let is_ne = match self.get_reg_ref(src)? {
502            Value::Int(x) => *x != i64::from(imm),
503            _ => true,
504        };
505        self.set_reg(dst, Value::Bool(is_ne))
506    }
507
508    fn le_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
509        let rhs = i64::from(imm);
510        let result = match *self.get_reg_ref(src)? {
511            Value::Int(x) => Value::Bool(x <= rhs),
512            Value::Float(x) => Value::Bool(x <= (rhs as f64)),
513            ref other => {
514                return Err(Fault::TypeMismatch {
515                    expected: "int or float",
516                    got: other.type_name(),
517                })
518            }
519        };
520        self.set_reg(dst, result)
521    }
522
523    fn gt_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
524        let rhs = i64::from(imm);
525        let result = match *self.get_reg_ref(src)? {
526            Value::Int(x) => Value::Bool(x > rhs),
527            Value::Float(x) => Value::Bool(x > (rhs as f64)),
528            ref other => {
529                return Err(Fault::TypeMismatch {
530                    expected: "int or float",
531                    got: other.type_name(),
532                })
533            }
534        };
535        self.set_reg(dst, result)
536    }
537
538    fn ge_imm(&mut self, dst: u8, src: u8, imm: i32) -> Result<(), Fault> {
539        let rhs = i64::from(imm);
540        let result = match *self.get_reg_ref(src)? {
541            Value::Int(x) => Value::Bool(x >= rhs),
542            Value::Float(x) => Value::Bool(x >= (rhs as f64)),
543            ref other => {
544                return Err(Fault::TypeMismatch {
545                    expected: "int or float",
546                    got: other.type_name(),
547                })
548            }
549        };
550        self.set_reg(dst, result)
551    }
552
553    fn bit_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
554        let x = self.int_from_reg(lhs)?;
555        let y = self.int_from_reg(rhs)?;
556        let amount = (y as u32) & 63;
557        let result = match op {
558            Opcode::BitAnd => x & y,
559            Opcode::BitOr => x | y,
560            Opcode::BitXor => x ^ y,
561            Opcode::Shl => x.wrapping_shl(amount),
562            Opcode::Shr => x >> amount,
563            Opcode::Ushr => ((x as u64) >> amount) as i64,
564            _ => {
565                return Err(Fault::Invariant(
566                    "bit_binop called with a non-bitwise opcode",
567                ))
568            }
569        };
570        self.set_reg(dst, Value::Int(result))
571    }
572
573    fn bit_not(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
574        let x = self.int_from_reg(src)?;
575        self.set_reg(dst, Value::Int(!x))
576    }
577
578    fn list_pack(&mut self, dst: u8, base: u8, count: i32) -> Result<(), Fault> {
579        if !(0..=crate::bytecode::MAX_LIST_LEN as i32).contains(&count) {
580            return Err(Fault::TypeMismatch {
581                expected: "list length 0..=256",
582                got: "imm-out-of-range",
583            });
584        }
585        let mut items = Vec::with_capacity(count as usize);
586        for offset in 0..count {
587            let reg = reg_at(base, offset as u16)?;
588            items.push(self.get_reg(reg)?);
589        }
590        let list = match Value::try_list(items) {
591            Some(list) => list,
592            None => return Err(Fault::QuotaExceeded("value nesting exceeds limit".into())),
593        };
594        self.set_reg(dst, list)
595    }
596
597    fn list_get(&mut self, dst: u8, src: u8, index: i32) -> Result<(), Fault> {
598        if index < 0 {
599            return Err(Fault::TypeMismatch {
600                expected: "list index",
601                got: "negative-int",
602            });
603        }
604        let item = match self.get_reg_ref(src)? {
605            Value::List(items) => {
606                items
607                    .get(index as usize)
608                    .cloned()
609                    .ok_or(Fault::TypeMismatch {
610                        expected: "list index",
611                        got: "out-of-range",
612                    })?
613            }
614            other => {
615                return Err(Fault::TypeMismatch {
616                    expected: "list",
617                    got: other.type_name(),
618                });
619            }
620        };
621        self.set_reg(dst, item)
622    }
623
624    fn list_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
625        let len = match self.get_reg_ref(src)? {
626            Value::List(items) => items.len() as i64,
627            other => {
628                return Err(Fault::TypeMismatch {
629                    expected: "list",
630                    got: other.type_name(),
631                });
632            }
633        };
634        self.set_reg(dst, Value::Int(len))
635    }
636
637    fn record_pack(&mut self, dst: u8, base: u8, count: i32) -> Result<(), Fault> {
638        if !(0..=crate::bytecode::MAX_RECORD_LEN as i32).contains(&count) {
639            return Err(Fault::TypeMismatch {
640                expected: "record length 0..=256",
641                got: "imm-out-of-range",
642            });
643        }
644        let mut fields = Vec::with_capacity(count as usize);
645        for offset in 0..count {
646            let reg = reg_at(base, offset as u16)?;
647            fields.push(self.get_reg(reg)?);
648        }
649        let record = match Value::try_record(fields) {
650            Some(record) => record,
651            None => return Err(Fault::QuotaExceeded("value nesting exceeds limit".into())),
652        };
653        self.set_reg(dst, record)
654    }
655
656    fn record_get(&mut self, dst: u8, src: u8, index: i32) -> Result<(), Fault> {
657        if index < 0 {
658            return Err(Fault::TypeMismatch {
659                expected: "record index",
660                got: "negative-int",
661            });
662        }
663        let item = match self.get_reg_ref(src)? {
664            Value::Record(fields) => {
665                fields
666                    .get(index as usize)
667                    .cloned()
668                    .ok_or(Fault::TypeMismatch {
669                        expected: "record index",
670                        got: "out-of-range",
671                    })?
672            }
673            other => {
674                return Err(Fault::TypeMismatch {
675                    expected: "record",
676                    got: other.type_name(),
677                });
678            }
679        };
680        self.set_reg(dst, item)
681    }
682
683    fn record_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
684        let len = match self.get_reg_ref(src)? {
685            Value::Record(fields) => fields.len() as i64,
686            other => {
687                return Err(Fault::TypeMismatch {
688                    expected: "record",
689                    got: other.type_name(),
690                });
691            }
692        };
693        self.set_reg(dst, Value::Int(len))
694    }
695
696    fn map_pack(&mut self, dst: u8, base: u8, count: i32) -> Result<(), Fault> {
697        if !(0..=crate::bytecode::MAX_MAP_LEN as i32).contains(&count) {
698            return Err(Fault::TypeMismatch {
699                expected: "map length 0..=256",
700                got: "imm-out-of-range",
701            });
702        }
703        let mut entries = Vec::with_capacity(count as usize);
704        for index in 0..count {
705            let key_reg = reg_at(base, (index as u16).saturating_mul(2))?;
706            let value_reg = reg_at(base, (index as u16).saturating_mul(2).saturating_add(1))?;
707            let key = match self.get_reg(key_reg)? {
708                Value::Int(n) => crate::bytecode::MapKey::Int(n),
709                Value::Str(text) => crate::bytecode::MapKey::Str(text),
710                other => {
711                    return Err(Fault::TypeMismatch {
712                        expected: "map key (int or str)",
713                        got: other.type_name(),
714                    })
715                }
716            };
717            entries.push((key, self.get_reg(value_reg)?));
718        }
719        let map = match Value::try_map(entries) {
720            Some(map) => map,
721            None => {
722                return Err(Fault::TypeMismatch {
723                    expected: "map",
724                    got: "duplicate-key-or-nested",
725                })
726            }
727        };
728        self.set_reg(dst, map)
729    }
730
731    fn map_get(&mut self, dst: u8, src: u8, key: u8) -> Result<(), Fault> {
732        let found = {
733            let map_val = self.get_reg_ref(src)?;
734            let Value::Map(entries) = map_val else {
735                return Err(Fault::TypeMismatch {
736                    expected: "map",
737                    got: map_val.type_name(),
738                });
739            };
740            let key_val = self.get_reg_ref(key)?;
741            let key_ref = match key_val {
742                Value::Int(n) => crate::bytecode::MapKey::Int(*n),
743                Value::Str(text) => crate::bytecode::MapKey::Str(Arc::clone(text)),
744                other => {
745                    return Err(Fault::TypeMismatch {
746                        expected: "map key (int or str)",
747                        got: other.type_name(),
748                    })
749                }
750            };
751            entries
752                .iter()
753                .find(|(existing, _)| existing == &key_ref)
754                .map(|(_, item)| item.clone())
755                .unwrap_or(Value::Unit)
756        };
757        self.set_reg(dst, found)
758    }
759
760    fn map_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
761        let len = match self.get_reg_ref(src)? {
762            Value::Map(entries) => entries.len() as i64,
763            other => {
764                return Err(Fault::TypeMismatch {
765                    expected: "map",
766                    got: other.type_name(),
767                });
768            }
769        };
770        self.set_reg(dst, Value::Int(len))
771    }
772
773    fn str_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
774        let len = match self.get_reg_ref(src)? {
775            Value::Str(s) => s.len() as i64,
776            other => {
777                return Err(Fault::TypeMismatch {
778                    expected: "str",
779                    got: other.type_name(),
780                });
781            }
782        };
783        self.set_reg(dst, Value::Int(len))
784    }
785
786    fn bytes_len(&mut self, dst: u8, src: u8) -> Result<(), Fault> {
787        let len = match self.get_reg_ref(src)? {
788            Value::Bytes(b) => b.len() as i64,
789            other => {
790                return Err(Fault::TypeMismatch {
791                    expected: "bytes",
792                    got: other.type_name(),
793                });
794            }
795        };
796        self.set_reg(dst, Value::Int(len))
797    }
798
799    fn numeric_binop(&mut self, op: Opcode, dst: u8, lhs: u8, rhs: u8) -> Result<(), Fault> {
800        let result = {
801            let a = self.get_reg_ref(lhs)?;
802            let b = self.get_reg_ref(rhs)?;
803            match (op, a, b) {
804                (Opcode::Add, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_add(*y)),
805                (Opcode::Add, _, _) => Value::Float(as_f64(a)? + as_f64(b)?),
806                (Opcode::Sub, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_sub(*y)),
807                (Opcode::Sub, _, _) => Value::Float(as_f64(a)? - as_f64(b)?),
808                (Opcode::Mul, Value::Int(x), Value::Int(y)) => Value::Int(x.wrapping_mul(*y)),
809                (Opcode::Mul, _, _) => Value::Float(as_f64(a)? * as_f64(b)?),
810                (Opcode::Div, Value::Int(x), Value::Int(y)) => {
811                    if *y == 0 {
812                        return Err(Fault::DivideByZero);
813                    }
814                    Value::Int(x.wrapping_div(*y))
815                }
816                (Opcode::Div, _, _) => {
817                    let denom = as_f64(b)?;
818                    Value::Float(as_f64(a)? / denom)
819                }
820                (Opcode::Mod, Value::Int(x), Value::Int(y)) => {
821                    if *y == 0 {
822                        return Err(Fault::DivideByZero);
823                    }
824                    Value::Int(x.wrapping_rem(*y))
825                }
826                (Opcode::Mod, _, _) => {
827                    let got = if !matches!(a, Value::Int(_)) {
828                        a.type_name()
829                    } else {
830                        b.type_name()
831                    };
832                    return Err(Fault::TypeMismatch {
833                        expected: "int",
834                        got,
835                    });
836                }
837                (Opcode::Eq, _, _) => Value::Bool(a == b),
838                (Opcode::Ne, _, _) => Value::Bool(a != b),
839                (Opcode::Lt, Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
840                (Opcode::Lt, _, _) => Value::Bool(as_f64(a)? < as_f64(b)?),
841                (Opcode::Le, Value::Int(x), Value::Int(y)) => Value::Bool(x <= y),
842                (Opcode::Le, _, _) => Value::Bool(as_f64(a)? <= as_f64(b)?),
843                (Opcode::Gt, Value::Int(x), Value::Int(y)) => Value::Bool(x > y),
844                (Opcode::Gt, _, _) => Value::Bool(as_f64(a)? > as_f64(b)?),
845                (Opcode::Ge, Value::Int(x), Value::Int(y)) => Value::Bool(x >= y),
846                (Opcode::Ge, _, _) => Value::Bool(as_f64(a)? >= as_f64(b)?),
847                _ => {
848                    return Err(Fault::Invariant(
849                        "numeric_binop called with a non-arithmetic opcode",
850                    ))
851                }
852            }
853        };
854        self.set_reg(dst, result)
855    }
856
857    #[inline]
858    fn expect_cap_reg(&self, reg: u8) -> Result<CapId, Fault> {
859        let v = self.get_reg_ref(reg)?;
860        v.as_cap().ok_or(Fault::TypeMismatch {
861            expected: "cap",
862            got: v.type_name(),
863        })
864    }
865
866    #[inline]
867    fn expect_message_value(&self, reg: u8) -> Result<Value, Fault> {
868        let v = self.get_reg_ref(reg)?;
869        if v.as_message().is_none() {
870            return Err(Fault::TypeMismatch {
871                expected: "message",
872                got: v.type_name(),
873            });
874        }
875        Ok(v.clone())
876    }
877
878    #[inline]
879    fn expect_str_reg(&self, reg: u8) -> Result<Arc<str>, Fault> {
880        match self.get_reg_ref(reg)? {
881            Value::Str(s) => Ok(Arc::clone(s)),
882            other => Err(Fault::TypeMismatch {
883                expected: "str",
884                got: other.type_name(),
885            }),
886        }
887    }
888
889    #[inline]
890    fn int_from_reg(&self, reg: u8) -> Result<i64, Fault> {
891        match self.get_reg_ref(reg)? {
892            Value::Int(n) => Ok(*n),
893            other => Err(Fault::TypeMismatch {
894                expected: "int",
895                got: other.type_name(),
896            }),
897        }
898    }
899
900    #[inline]
901    fn tag_from_reg(&self, reg: u8) -> Result<u16, Fault> {
902        tag_from_value(self.get_reg_ref(reg)?)
903    }
904
905    #[inline]
906    fn request_id_from_reg(&self, reg: u8) -> Result<u64, Fault> {
907        request_id_from_value(self.get_reg_ref(reg)?)
908    }
909
910    fn gather_regs(&self, base: u8, argc: u8, first_offset: u16) -> Result<Vec<Value>, Fault> {
911        let mut args = Vec::with_capacity(argc as usize);
912        for i in 0..argc {
913            let reg = reg_at(base, first_offset + u16::from(i))?;
914            args.push(self.get_reg(reg)?);
915        }
916        Ok(args)
917    }
918
919    /// Move `old_bytes` of dictionary charge to `new_bytes`.
920    ///
921    /// The counter is not the register frame. `pop_frame` must not release it.
922    fn adjust_dict_quota(&mut self, old_bytes: usize, new_bytes: usize) -> Result<(), Fault> {
923        if new_bytes > old_bytes {
924            let delta = new_bytes - old_bytes;
925            if let Some(quota) = self.quota.as_ref() {
926                charge_pair(quota, self.memory.as_deref(), delta)?;
927            }
928            self.dict_bytes = match self.dict_bytes.checked_add(delta) {
929                Some(next) => next,
930                None => {
931                    if let Some(quota) = self.quota.as_ref() {
932                        release_pair(quota, self.memory.as_deref(), delta);
933                    }
934                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
935                }
936            };
937        } else if old_bytes > new_bytes {
938            let delta = old_bytes - new_bytes;
939            if let Some(quota) = self.quota.as_ref() {
940                release_pair(quota, self.memory.as_deref(), delta);
941            }
942            self.dict_bytes = self.dict_bytes.saturating_sub(delta);
943        }
944        Ok(())
945    }
946
947    /// Non-negative `Int` only. `Bool` is not a duration.
948    fn duration_millis_from_reg(&self, reg: u8) -> Result<Duration, Fault> {
949        let millis = self.get_reg_ref(reg)?;
950        match require_int(millis) {
951            Ok(ms) if ms >= 0 => Ok(Duration::from_millis(ms as u64)),
952            Ok(_) => Err(Fault::TypeMismatch {
953                expected: "non-negative int",
954                got: "negative-int",
955            }),
956            Err(fault) => Err(fault),
957        }
958    }
959
960    /// Apply a relative jump from the current (post-fetch) `pc`.
961    ///
962    /// Valid targets are `0..=code.len()` (one past the end = implicit return).
963    /// Out-of-range targets always trap with [`Fault::BadJump`] (fail-closed).
964    fn apply_relative_jump(&mut self, imm: i32) -> Result<(), Fault> {
965        let code_len = self.chunk.code.len();
966        let frame = self.current()?;
967        let target_i = frame.pc() as i64 + i64::from(imm);
968        if target_i < 0 || target_i as usize > code_len {
969            let target = if target_i < 0 {
970                usize::MAX
971            } else {
972                target_i as usize
973            };
974            return Err(Fault::BadJump { target, code_len });
975        }
976        frame.set_pc(target_i as usize);
977        Ok(())
978    }
979
980    /// Run at most `budget` instructions (cooperative-preemption quantum,
981    /// design notes §10-11), or until the Flow completes / needs an
982    /// effect the scheduler must perform / faults.
983    ///
984    /// Every exit path is captured by [`VmResult`] — this function itself
985    /// never panics on malformed *verified* bytecode; faults are returned,
986    /// not thrown, so a buggy Flow can't take a worker thread down.
987    pub fn run(&mut self, budget: u32) -> VmResult {
988        macro_rules! trap {
989            ($e:expr) => {
990                match $e {
991                    Ok(v) => v,
992                    Err(fault) => return VmResult::Trap(fault),
993                }
994            };
995        }
996
997        for _ in 0..budget {
998            self.instructions_executed += 1;
999            let instr = match self.fetch() {
1000                Ok(Some(i)) => i,
1001                Ok(None) => {
1002                    // Fell off the end of a function: implicit `return Unit`.
1003                    match self.pop_frame(Value::Unit) {
1004                        Ok(Some(result)) => return result,
1005                        Ok(None) => continue,
1006                        Err(fault) => return VmResult::Trap(fault),
1007                    }
1008                }
1009                Err(fault) => return VmResult::Trap(fault),
1010            };
1011
1012            match instr.op {
1013                Opcode::Halt => return VmResult::Complete(trap!(self.get_reg(0))),
1014                Opcode::Nop => {}
1015                Opcode::LoadConst => {
1016                    let idx = instr.imm as u32;
1017                    let konst = match self.chunk.constant(idx) {
1018                        Some(v) => v.clone(),
1019                        None => {
1020                            return VmResult::Trap(Fault::BadConstant {
1021                                index: idx,
1022                                pool_size: self.chunk.constants.len() as u32,
1023                            })
1024                        }
1025                    };
1026                    trap!(self.set_reg(instr.a, konst));
1027                }
1028                Opcode::LoadImm => {
1029                    trap!(self.set_reg(instr.a, Value::Int(instr.imm as i64)));
1030                }
1031                Opcode::AddImm => {
1032                    trap!(self.add_imm(instr.a, instr.b, instr.imm));
1033                }
1034                Opcode::SubImm => {
1035                    trap!(self.sub_imm(instr.a, instr.b, instr.imm));
1036                }
1037                Opcode::LtImm => {
1038                    trap!(self.lt_imm(instr.a, instr.b, instr.imm));
1039                }
1040                Opcode::MulImm => {
1041                    trap!(self.mul_imm(instr.a, instr.b, instr.imm));
1042                }
1043                Opcode::EqImm => {
1044                    trap!(self.eq_imm(instr.a, instr.b, instr.imm));
1045                }
1046                Opcode::NeImm => {
1047                    trap!(self.ne_imm(instr.a, instr.b, instr.imm));
1048                }
1049                Opcode::LeImm => {
1050                    trap!(self.le_imm(instr.a, instr.b, instr.imm));
1051                }
1052                Opcode::GtImm => {
1053                    trap!(self.gt_imm(instr.a, instr.b, instr.imm));
1054                }
1055                Opcode::GeImm => {
1056                    trap!(self.ge_imm(instr.a, instr.b, instr.imm));
1057                }
1058                Opcode::BitAnd
1059                | Opcode::BitOr
1060                | Opcode::BitXor
1061                | Opcode::Shl
1062                | Opcode::Shr
1063                | Opcode::Ushr => {
1064                    trap!(self.bit_binop(instr.op, instr.a, instr.b, instr.c));
1065                }
1066                Opcode::BitNot => {
1067                    trap!(self.bit_not(instr.a, instr.b));
1068                }
1069                Opcode::ListPack => {
1070                    trap!(self.list_pack(instr.a, instr.b, instr.imm));
1071                }
1072                Opcode::ListGet => {
1073                    trap!(self.list_get(instr.a, instr.b, instr.imm));
1074                }
1075                Opcode::ListLen => {
1076                    trap!(self.list_len(instr.a, instr.b));
1077                }
1078                Opcode::RecordPack => {
1079                    trap!(self.record_pack(instr.a, instr.b, instr.imm));
1080                }
1081                Opcode::RecordGet => {
1082                    trap!(self.record_get(instr.a, instr.b, instr.imm));
1083                }
1084                Opcode::RecordLen => {
1085                    trap!(self.record_len(instr.a, instr.b));
1086                }
1087                Opcode::StrLen => {
1088                    trap!(self.str_len(instr.a, instr.b));
1089                }
1090                Opcode::BytesLen => {
1091                    trap!(self.bytes_len(instr.a, instr.b));
1092                }
1093                Opcode::MapPack => {
1094                    trap!(self.map_pack(instr.a, instr.b, instr.imm));
1095                }
1096                Opcode::MapGet => {
1097                    trap!(self.map_get(instr.a, instr.b, instr.c));
1098                }
1099                Opcode::MapLen => {
1100                    trap!(self.map_len(instr.a, instr.b));
1101                }
1102                Opcode::ReceiveMatchCmp => {
1103                    let tag = trap!(self.tag_from_reg(instr.b));
1104                    let bound = trap!(self.int_from_reg(instr.c));
1105                    let Some(cmp) = crate::bytecode::IntCmp::from_imm(instr.imm) else {
1106                        return VmResult::Trap(Fault::TypeMismatch {
1107                            expected: "cmp 0..=2",
1108                            got: "imm-out-of-range",
1109                        });
1110                    };
1111                    return VmResult::Receive {
1112                        dest_reg: instr.a,
1113                        timeout: None,
1114                        match_tag: Some(tag),
1115                        match_request_id: None,
1116                        match_payload_kind: None,
1117                        match_payload_eq: None,
1118                        match_payload_value: None,
1119                        match_payload_cmp: Some((cmp, bound)),
1120                    };
1121                }
1122                Opcode::TableOpen => {
1123                    return VmResult::TableOpen {
1124                        dest_reg: instr.a,
1125                        name: trap!(self.expect_str_reg(instr.b)),
1126                    };
1127                }
1128                Opcode::TableGet => {
1129                    return VmResult::TableGet {
1130                        dest_reg: instr.a,
1131                        cap: trap!(self.expect_cap_reg(instr.b)),
1132                        key: trap!(self.get_reg(instr.c)),
1133                    };
1134                }
1135                Opcode::TablePut => {
1136                    return VmResult::TablePut {
1137                        cap: trap!(self.expect_cap_reg(instr.a)),
1138                        key: trap!(self.get_reg(instr.b)),
1139                        value: trap!(self.get_reg(instr.c)),
1140                    };
1141                }
1142                Opcode::Move => {
1143                    if instr.a != instr.b {
1144                        let v = trap!(self.get_reg(instr.b));
1145                        trap!(self.set_reg(instr.a, v));
1146                    }
1147                }
1148                Opcode::Add
1149                | Opcode::Sub
1150                | Opcode::Mul
1151                | Opcode::Div
1152                | Opcode::Mod
1153                | Opcode::Eq
1154                | Opcode::Ne
1155                | Opcode::Lt
1156                | Opcode::Le
1157                | Opcode::Gt
1158                | Opcode::Ge => {
1159                    trap!(self.numeric_binop(instr.op, instr.a, instr.b, instr.c));
1160                }
1161                Opcode::Neg => {
1162                    let negated = match *trap!(self.get_reg_ref(instr.b)) {
1163                        Value::Int(x) => Value::Int(x.wrapping_neg()),
1164                        Value::Float(x) => Value::Float(-x),
1165                        ref other => {
1166                            return VmResult::Trap(Fault::TypeMismatch {
1167                                expected: "int or float",
1168                                got: other.type_name(),
1169                            })
1170                        }
1171                    };
1172                    trap!(self.set_reg(instr.a, negated));
1173                }
1174                Opcode::Jump => {
1175                    trap!(self.apply_relative_jump(instr.imm));
1176                }
1177                Opcode::Branch => {
1178                    let is_truthy = trap!(self.get_reg_ref(instr.a)).is_truthy();
1179                    if !is_truthy {
1180                        trap!(self.apply_relative_jump(instr.imm));
1181                    }
1182                }
1183                Opcode::BranchTrue => {
1184                    let is_truthy = trap!(self.get_reg_ref(instr.a)).is_truthy();
1185                    if is_truthy {
1186                        trap!(self.apply_relative_jump(instr.imm));
1187                    }
1188                }
1189                Opcode::Call => {
1190                    let function = instr.imm as u32;
1191                    let argc = instr.b;
1192                    let dst = instr.a;
1193                    if self.frames.len() >= MAX_CALL_DEPTH {
1194                        return VmResult::Trap(Fault::CallStackOverflow {
1195                            depth: self.frames.len(),
1196                        });
1197                    }
1198                    let (num_registers, arity, entry) = match self.chunk.function(function) {
1199                        Some(d) => (d.num_registers, d.arity, d.entry as usize),
1200                        None => {
1201                            return VmResult::Trap(Fault::BadFunction {
1202                                index: function,
1203                                table_size: self.chunk.functions.len() as u32,
1204                            })
1205                        }
1206                    };
1207                    // `verify` rejects this statically. Direct `Vm::run` on an
1208                    // unverified chunk must not drop extras or fill holes with
1209                    // `Unit` — both hide a wrong call.
1210                    if argc != arity {
1211                        return VmResult::Trap(Fault::BadArity {
1212                            passed: usize::from(argc),
1213                            expected: arity,
1214                        });
1215                    }
1216                    let args = trap!(self.gather_regs(dst, argc, 0));
1217                    let mut new_frame = Frame::new(function, num_registers, Some(dst));
1218                    new_frame.set_pc(entry);
1219                    trap!(self.load_frame_args_charged(&mut new_frame, args, arity));
1220                    self.frames.push(new_frame);
1221                }
1222                Opcode::TailCall => {
1223                    let function = instr.imm as u32;
1224                    let argc = instr.b;
1225                    let dst = instr.a;
1226                    let (num_registers, arity, entry) = match self.chunk.function(function) {
1227                        Some(d) => (d.num_registers, d.arity, d.entry as usize),
1228                        None => {
1229                            return VmResult::Trap(Fault::BadFunction {
1230                                index: function,
1231                                table_size: self.chunk.functions.len() as u32,
1232                            })
1233                        }
1234                    };
1235                    if argc != arity {
1236                        return VmResult::Trap(Fault::BadArity {
1237                            passed: usize::from(argc),
1238                            expected: arity,
1239                        });
1240                    }
1241                    let args = trap!(self.gather_regs(dst, argc, 0));
1242                    let dest_reg = trap!(self.current()).dest_reg();
1243                    let finished = self
1244                        .frames
1245                        .pop()
1246                        .ok_or(Fault::Invariant("tailcall on empty stack"));
1247                    let finished = trap!(finished);
1248                    if let Some(quota) = self.quota.as_ref() {
1249                        release_pair(quota, self.memory.as_deref(), finished.heap_charge());
1250                    }
1251                    let mut new_frame = Frame::new(function, num_registers, dest_reg);
1252                    new_frame.set_pc(entry);
1253                    trap!(self.load_frame_args_charged(&mut new_frame, args, arity));
1254                    self.frames.push(new_frame);
1255                }
1256                Opcode::CallNative | Opcode::CallNativeFrom => {
1257                    let native_index = instr.imm as u32;
1258                    // `CallNative` reads and writes `r[a]`. `CallNativeFrom`
1259                    // reads `r[b]` and writes `r[a]`, so a one-arg unpack does
1260                    // not destroy the source.
1261                    let (arg_base, argc) = if instr.op == Opcode::CallNativeFrom {
1262                        (instr.b, 1)
1263                    } else {
1264                        (instr.a, instr.b)
1265                    };
1266                    let dst = instr.a;
1267                    if let Err(err) =
1268                        check_native_gate(&self.native_gate, &self.natives, native_index)
1269                    {
1270                        return VmResult::Trap(match err {
1271                            NativeCallError::IndexOutOfRange(index) => Fault::BadNative {
1272                                index,
1273                                table_size: self.natives.len() as u32,
1274                            },
1275                            other => Fault::NativeDenied(other),
1276                        });
1277                    }
1278                    let args = trap!(self.gather_regs(arg_base, argc, 0));
1279                    // Runs inline on this worker thread — see
1280                    // `NativeFn`'s doc comment on why natives must not
1281                    // block. This is the actual FFI boundary (design
1282                    // notes §30-31): plain Rust on one side, bytecode
1283                    // registers on the other, with `Fault::NativeError`
1284                    // as the only channel for a native-side failure to
1285                    // become a Flow fault instead of a host panic.
1286                    let result = match self.natives.get(native_index) {
1287                        Some(native_fn) => native_fn(&args),
1288                        None => {
1289                            return VmResult::Trap(Fault::BadNative {
1290                                index: native_index,
1291                                table_size: self.natives.len() as u32,
1292                            })
1293                        }
1294                    };
1295                    match result {
1296                        Ok(value) => trap!(self.set_reg(dst, value)),
1297                        Err(fault) => return VmResult::Trap(fault),
1298                    }
1299                }
1300                Opcode::Return => {
1301                    let v = trap!(self.get_reg(instr.a));
1302                    match self.pop_frame(v) {
1303                        Ok(Some(result)) => return result,
1304                        Ok(None) => {}
1305                        Err(fault) => return VmResult::Trap(fault),
1306                    }
1307                }
1308                Opcode::Spawn => {
1309                    // Args at r[a+1 .. a+1+argc] — `a` itself receives the
1310                    // child Cap. `a = 255` overflows on the first gather.
1311                    let args = trap!(self.gather_regs(instr.a, instr.b, 1));
1312                    return VmResult::Spawn {
1313                        function: instr.imm as u32,
1314                        args,
1315                        dest_reg: instr.a,
1316                        requested_rights: crate::bytecode::CapRights::from_u8(instr.c),
1317                    };
1318                }
1319                Opcode::Yield => return VmResult::Yield,
1320                Opcode::Sleep => {
1321                    return VmResult::Sleep(trap!(self.duration_millis_from_reg(instr.a)));
1322                }
1323                Opcode::Exit => {
1324                    let v = trap!(self.get_reg(instr.a));
1325                    return VmResult::Complete(v);
1326                }
1327                Opcode::SelfPid => {
1328                    return VmResult::SelfPid { dest_reg: instr.a };
1329                }
1330                Opcode::Send => {
1331                    let target_cap = trap!(self.expect_cap_reg(instr.a));
1332                    let message = trap!(self.expect_message_value(instr.b));
1333                    return VmResult::Send {
1334                        target_cap,
1335                        message,
1336                    };
1337                }
1338                Opcode::Receive => {
1339                    return VmResult::Receive {
1340                        dest_reg: instr.a,
1341                        timeout: None,
1342                        match_tag: None,
1343                        match_request_id: None,
1344                        match_payload_kind: None,
1345                        match_payload_eq: None,
1346                        match_payload_value: None,
1347                        match_payload_cmp: None,
1348                    };
1349                }
1350                Opcode::ReceiveTimeout => {
1351                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
1352                    return VmResult::Receive {
1353                        dest_reg: instr.a,
1354                        timeout: Some(timeout),
1355                        match_tag: None,
1356                        match_request_id: None,
1357                        match_payload_kind: None,
1358                        match_payload_eq: None,
1359                        match_payload_value: None,
1360                        match_payload_cmp: None,
1361                    };
1362                }
1363                Opcode::ReceiveMatch => {
1364                    let tag = trap!(self.tag_from_reg(instr.b));
1365                    return VmResult::Receive {
1366                        dest_reg: instr.a,
1367                        timeout: None,
1368                        match_tag: Some(tag),
1369                        match_request_id: None,
1370                        match_payload_kind: None,
1371                        match_payload_eq: None,
1372                        match_payload_value: None,
1373                        match_payload_cmp: None,
1374                    };
1375                }
1376                Opcode::ReceiveMatchImm => {
1377                    let tag = trap!(tag_from_imm(instr.imm));
1378                    return VmResult::Receive {
1379                        dest_reg: instr.a,
1380                        timeout: None,
1381                        match_tag: Some(tag),
1382                        match_request_id: None,
1383                        match_payload_kind: None,
1384                        match_payload_eq: None,
1385                        match_payload_value: None,
1386                        match_payload_cmp: None,
1387                    };
1388                }
1389                Opcode::ReceiveMatchTimeout => {
1390                    let tag = trap!(self.tag_from_reg(instr.b));
1391                    let timeout = trap!(self.duration_millis_from_reg(instr.c));
1392                    return VmResult::Receive {
1393                        dest_reg: instr.a,
1394                        timeout: Some(timeout),
1395                        match_tag: Some(tag),
1396                        match_request_id: None,
1397                        match_payload_kind: None,
1398                        match_payload_eq: None,
1399                        match_payload_value: None,
1400                        match_payload_cmp: None,
1401                    };
1402                }
1403                Opcode::ReceiveMatchImmTimeout => {
1404                    let tag = trap!(tag_from_imm(instr.imm));
1405                    let timeout = trap!(self.duration_millis_from_reg(instr.b));
1406                    return VmResult::Receive {
1407                        dest_reg: instr.a,
1408                        timeout: Some(timeout),
1409                        match_tag: Some(tag),
1410                        match_request_id: None,
1411                        match_payload_kind: None,
1412                        match_payload_eq: None,
1413                        match_payload_value: None,
1414                        match_payload_cmp: None,
1415                    };
1416                }
1417                Opcode::IsAlive => {
1418                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1419                    return VmResult::IsAlive {
1420                        dest_reg: instr.a,
1421                        target_cap,
1422                    };
1423                }
1424                Opcode::ExitSignal => {
1425                    let target_cap = trap!(self.expect_cap_reg(instr.a));
1426                    let reason = trap!(self.int_from_reg(instr.b));
1427                    let Ok(reason_u) = u64::try_from(reason) else {
1428                        return VmResult::Trap(Fault::TypeMismatch {
1429                            expected: "FlowExitReason 0..=6",
1430                            got: "imm-out-of-range",
1431                        });
1432                    };
1433                    if crate::FlowExitReason::from_u64(reason_u).is_none() {
1434                        return VmResult::Trap(Fault::TypeMismatch {
1435                            expected: "FlowExitReason 0..=6",
1436                            got: "imm-out-of-range",
1437                        });
1438                    }
1439                    return VmResult::ExitSignal {
1440                        target_cap,
1441                        reason: reason_u,
1442                    };
1443                }
1444                Opcode::DictPut => {
1445                    let key = trap!(self.int_from_reg(instr.b));
1446                    let value = trap!(self.get_reg(instr.c));
1447                    let new_bytes = trap!(dict_owned_bytes(&value));
1448                    let previous = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
1449                        Some(prev) => prev,
1450                        None => Value::Unit,
1451                    };
1452                    let old_bytes = trap!(dict_owned_bytes(&previous));
1453                    // Charge first, write the register second, and only then
1454                    // replace the slot. `set_reg` of the previous value can
1455                    // refuse (the old buffer moves into `ra` while `rc` and
1456                    // the dictionary both still hold the new one). Rolling
1457                    // the charge back leaves the slot untouched.
1458                    if let Err(fault) = self.adjust_dict_quota(old_bytes, new_bytes) {
1459                        return VmResult::Trap(fault);
1460                    }
1461                    if let Err(fault) = self.set_reg(instr.a, previous) {
1462                        if let Err(rollback) = self.adjust_dict_quota(new_bytes, old_bytes) {
1463                            return VmResult::Trap(rollback);
1464                        }
1465                        return VmResult::Trap(fault);
1466                    }
1467                    self.dict
1468                        .get_or_insert_with(|| HashMap::with_capacity(8))
1469                        .insert(key, value);
1470                }
1471                Opcode::DictGet => {
1472                    let key = trap!(self.int_from_reg(instr.b));
1473                    let value = match self.dict.as_ref().and_then(|d| d.get(&key).cloned()) {
1474                        Some(v) => v,
1475                        None => Value::Unit,
1476                    };
1477                    trap!(self.set_reg(instr.a, value));
1478                }
1479                Opcode::DictErase => {
1480                    let key = trap!(self.int_from_reg(instr.b));
1481                    // A bad destination must not drop the entry on the way out.
1482                    trap!(self.get_reg(instr.a));
1483                    let Some(old) = self.dict.as_mut().and_then(|d| d.remove(&key)) else {
1484                        trap!(self.set_reg(instr.a, Value::Unit));
1485                        continue;
1486                    };
1487                    let old_bytes = trap!(dict_owned_bytes(&old));
1488                    if let Err(fault) = self.adjust_dict_quota(old_bytes, 0) {
1489                        self.dict
1490                            .get_or_insert_with(|| HashMap::with_capacity(8))
1491                            .insert(key, old);
1492                        return VmResult::Trap(fault);
1493                    }
1494                    if let Err(fault) = self.set_reg(instr.a, old.clone()) {
1495                        self.dict
1496                            .get_or_insert_with(|| HashMap::with_capacity(8))
1497                            .insert(key, old);
1498                        if let Err(rollback) = self.adjust_dict_quota(0, old_bytes) {
1499                            return VmResult::Trap(rollback);
1500                        }
1501                        return VmResult::Trap(fault);
1502                    }
1503                }
1504                Opcode::ReceiveMatchEq => {
1505                    let tag = trap!(self.tag_from_reg(instr.b));
1506                    let payload = trap!(self.int_from_reg(instr.c));
1507                    return VmResult::Receive {
1508                        dest_reg: instr.a,
1509                        timeout: None,
1510                        match_tag: Some(tag),
1511                        match_request_id: None,
1512                        match_payload_kind: None,
1513                        match_payload_eq: Some(payload),
1514                        match_payload_value: None,
1515                        match_payload_cmp: None,
1516                    };
1517                }
1518                Opcode::ReceiveMatchValue => {
1519                    let tag = trap!(self.tag_from_reg(instr.b));
1520                    let payload = trap!(self.get_reg(instr.c));
1521                    return VmResult::Receive {
1522                        dest_reg: instr.a,
1523                        timeout: None,
1524                        match_tag: Some(tag),
1525                        match_request_id: None,
1526                        match_payload_kind: None,
1527                        match_payload_eq: None,
1528                        match_payload_value: Some(Arc::new(payload)),
1529                        match_payload_cmp: None,
1530                    };
1531                }
1532                Opcode::SendRemote => {
1533                    let node = trap!(self.int_from_reg(instr.a));
1534                    if node < 0 {
1535                        return VmResult::Trap(Fault::TypeMismatch {
1536                            expected: "node id >= 0",
1537                            got: "negative",
1538                        });
1539                    }
1540                    let name = match trap!(self.get_reg(instr.b)) {
1541                        Value::Str(name) => name,
1542                        _ => {
1543                            return VmResult::Trap(Fault::TypeMismatch {
1544                                expected: "str",
1545                                got: "not-str",
1546                            })
1547                        }
1548                    };
1549                    let message = trap!(self.expect_message_value(instr.c));
1550                    let Ok(node) = u64::try_from(node) else {
1551                        return VmResult::Trap(Fault::TypeMismatch {
1552                            expected: "node id",
1553                            got: "imm-out-of-range",
1554                        });
1555                    };
1556                    return VmResult::SendRemote {
1557                        node,
1558                        name,
1559                        message,
1560                    };
1561                }
1562                Opcode::StartSupervisor => {
1563                    let Ok(strategy) = u8::try_from(instr.imm) else {
1564                        return VmResult::Trap(Fault::TypeMismatch {
1565                            expected: "strategy 0..=2",
1566                            got: "imm-out-of-range",
1567                        });
1568                    };
1569                    if strategy > 2 {
1570                        return VmResult::Trap(Fault::TypeMismatch {
1571                            expected: "strategy 0..=2",
1572                            got: "imm-out-of-range",
1573                        });
1574                    }
1575                    return VmResult::StartSupervisor { strategy };
1576                }
1577                Opcode::StartChild => {
1578                    let function = match u32::try_from(instr.imm) {
1579                        Ok(f) => f,
1580                        Err(_) => u32::MAX,
1581                    };
1582                    if self.chunk.function(function).is_none() {
1583                        return VmResult::Trap(Fault::BadFunction {
1584                            index: function,
1585                            table_size: self.chunk.functions.len() as u32,
1586                        });
1587                    }
1588                    if crate::RestartPolicy::from_u8(instr.b).is_none() {
1589                        return VmResult::Trap(Fault::TypeMismatch {
1590                            expected: "restart policy 0..=2",
1591                            got: "imm-out-of-range",
1592                        });
1593                    }
1594                    return VmResult::StartChild {
1595                        dest_reg: instr.a,
1596                        function,
1597                        policy: instr.b,
1598                    };
1599                }
1600                Opcode::ReceiveMatchKind => {
1601                    // Selective receive by payload wire-tag (`Value::wire_tag`,
1602                    // 0..=10). Non-matching hops stay queued (FIFO skip).
1603                    let kind = match u8::try_from(instr.imm) {
1604                        Ok(k) if k <= 10 => k,
1605                        _ => {
1606                            return VmResult::Trap(Fault::TypeMismatch {
1607                                expected: "payload kind 0..=10",
1608                                got: "imm-out-of-range",
1609                            })
1610                        }
1611                    };
1612                    return VmResult::Receive {
1613                        dest_reg: instr.a,
1614                        timeout: None,
1615                        match_tag: None,
1616                        match_request_id: None,
1617                        match_payload_kind: Some(kind),
1618                        match_payload_eq: None,
1619                        match_payload_value: None,
1620                        match_payload_cmp: None,
1621                    };
1622                }
1623                Opcode::FreshRequestId => {
1624                    let id = self.fresh_request_id();
1625                    trap!(self.set_reg(instr.a, Value::from(id)));
1626                }
1627                Opcode::ReceiveMatchCorr => {
1628                    let tag = trap!(self.tag_from_reg(instr.b));
1629                    let rid = trap!(self.request_id_from_reg(instr.c));
1630                    return VmResult::Receive {
1631                        dest_reg: instr.a,
1632                        timeout: None,
1633                        match_tag: Some(tag),
1634                        match_request_id: Some(rid),
1635                        match_payload_kind: None,
1636                        match_payload_eq: None,
1637                        match_payload_value: None,
1638                        match_payload_cmp: None,
1639                    };
1640                }
1641                Opcode::ReceiveMatchCorrImm => {
1642                    let tag = trap!(tag_from_imm(instr.imm));
1643                    let rid = trap!(self.request_id_from_reg(instr.b));
1644                    return VmResult::Receive {
1645                        dest_reg: instr.a,
1646                        timeout: None,
1647                        match_tag: Some(tag),
1648                        match_request_id: Some(rid),
1649                        match_payload_kind: None,
1650                        match_payload_eq: None,
1651                        match_payload_value: None,
1652                        match_payload_cmp: None,
1653                    };
1654                }
1655                Opcode::Ask => {
1656                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1657                    let request = trap!(self.expect_message_value(instr.c));
1658                    return VmResult::Ask {
1659                        dest_reg: instr.a,
1660                        target_cap,
1661                        request,
1662                        timeout: None,
1663                    };
1664                }
1665                Opcode::AskTimeout => {
1666                    let millis_reg = match u8::try_from(instr.imm) {
1667                        Ok(r) => r,
1668                        Err(_) => {
1669                            return VmResult::Trap(Fault::TypeMismatch {
1670                                expected: "millis register",
1671                                got: "imm-out-of-range",
1672                            })
1673                        }
1674                    };
1675                    let timeout = trap!(self.duration_millis_from_reg(millis_reg));
1676                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1677                    let request = trap!(self.expect_message_value(instr.c));
1678                    return VmResult::Ask {
1679                        dest_reg: instr.a,
1680                        target_cap,
1681                        request,
1682                        timeout: Some(timeout),
1683                    };
1684                }
1685                Opcode::Monitor => {
1686                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1687                    return VmResult::Monitor {
1688                        dest_reg: instr.a,
1689                        target_cap,
1690                    };
1691                }
1692                Opcode::Demonitor => {
1693                    return VmResult::Demonitor {
1694                        monitor_reg: instr.a,
1695                    };
1696                }
1697                Opcode::Link => {
1698                    let target_cap = trap!(self.expect_cap_reg(instr.b));
1699                    return VmResult::Link {
1700                        dest_reg: instr.a,
1701                        target_cap,
1702                    };
1703                }
1704                Opcode::Unlink => {
1705                    return VmResult::Unlink { link_reg: instr.a };
1706                }
1707                Opcode::SetTrapExit => {
1708                    let enabled = trap!(self.get_reg_ref(instr.a)).is_truthy();
1709                    return VmResult::SetTrapExit { enabled };
1710                }
1711                Opcode::SetRestartPolicy => {
1712                    // Flow-local OTP restart policy for the host Supervisor
1713                    // (`0` Always / `1` OnFailure / `2` Never).
1714                    let policy = match instr.imm {
1715                        0..=2 => instr.imm as u8,
1716                        _ => {
1717                            return VmResult::Trap(Fault::TypeMismatch {
1718                                expected: "restart policy 0..=2",
1719                                got: "imm-out-of-range",
1720                            })
1721                        }
1722                    };
1723                    return VmResult::SetRestartPolicy { policy };
1724                }
1725                Opcode::HostAwait => {
1726                    let args = trap!(self.get_reg(instr.b));
1727                    let op = if instr.imm < 0 {
1728                        return VmResult::Trap(Fault::TypeMismatch {
1729                            expected: "HostAwait op >= 0",
1730                            got: "imm-negative",
1731                        });
1732                    } else {
1733                        instr.imm as u32
1734                    };
1735                    return VmResult::HostAwait {
1736                        dest_reg: instr.a,
1737                        op,
1738                        args,
1739                    };
1740                }
1741                Opcode::RegisterName => {
1742                    return VmResult::RegisterName {
1743                        name: trap!(self.expect_str_reg(instr.a)),
1744                    };
1745                }
1746                Opcode::Whereis => {
1747                    return VmResult::Whereis {
1748                        dest_reg: instr.a,
1749                        name: trap!(self.expect_str_reg(instr.b)),
1750                    };
1751                }
1752                Opcode::Delegate => {
1753                    let src_cap = trap!(self.expect_cap_reg(instr.b));
1754                    let want_native_cap = if instr.c == 255 {
1755                        None
1756                    } else {
1757                        Some(trap!(self.expect_cap_reg(instr.c)))
1758                    };
1759                    return VmResult::Delegate {
1760                        dest_reg: instr.a,
1761                        src_cap,
1762                        want_rights: crate::bytecode::CapRights::from_bits(instr.imm as u32),
1763                        want_native_cap,
1764                    };
1765                }
1766                Opcode::Trap => return VmResult::Trap(Fault::Explicit(instr.imm)),
1767            }
1768        }
1769        VmResult::Yield
1770    }
1771
1772    /// Pop the current frame, delivering `value` to the caller (or
1773    /// finishing the Flow if this was the outermost frame). Returns
1774    /// `Ok(Some(VmResult::Complete(_)))` only in the latter case.
1775    ///
1776    /// Releases the finished frame's heap charge (except the escaping
1777    /// return value on the outermost `Complete` path, which stays charged
1778    /// until flow finalize — matching prior MemoryBudget semantics).
1779    fn pop_frame(&mut self, value: Value) -> Result<Option<VmResult>, Fault> {
1780        let escaping = self
1781            .frames
1782            .last()
1783            .ok_or(Fault::Invariant("pop_frame on empty stack"))?
1784            .dest_reg()
1785            .is_none();
1786        // Charge the escaping value before the pop, so a chain past the
1787        // decoder ceiling fails without dropping the frame first.
1788        let keep = if escaping { heap_charge_of(&value)? } else { 0 };
1789        let finished = self
1790            .frames
1791            .pop()
1792            .ok_or(Fault::Invariant("pop_frame on empty stack"))?;
1793        match finished.dest_reg() {
1794            Some(dest) => {
1795                if let Some(quota) = self.quota.as_ref() {
1796                    release_pair(quota, self.memory.as_deref(), finished.heap_charge());
1797                }
1798                self.set_reg(dest, value)?;
1799                Ok(None)
1800            }
1801            None => {
1802                if let Some(quota) = self.quota.as_ref() {
1803                    let release = finished.heap_charge().saturating_sub(keep);
1804                    release_pair(quota, self.memory.as_deref(), release);
1805                }
1806                Ok(Some(VmResult::Complete(value)))
1807            }
1808        }
1809    }
1810
1811    /// Load call arguments into a not-yet-pushed frame, charging heap for
1812    /// any `Str`/`Bytes`. Rolls back a partial charge if a later arg fails.
1813    fn load_frame_args_charged(
1814        &self,
1815        frame: &mut Frame,
1816        args: impl IntoIterator<Item = Value>,
1817        arity: u8,
1818    ) -> Result<(), Fault> {
1819        let frame_size = frame.registers().len() as u8;
1820        let mut charged = 0usize;
1821        for (i, a) in args.into_iter().enumerate().take(arity as usize) {
1822            let bytes = heap_charge_of(&a)?;
1823            if bytes > 0 {
1824                if let Some(quota) = self.quota.as_ref() {
1825                    if let Err(e) = charge_pair(quota, self.memory.as_deref(), bytes) {
1826                        if charged > 0 {
1827                            release_pair(quota, self.memory.as_deref(), charged);
1828                        }
1829                        frame.set_heap_charge(0);
1830                        return Err(e);
1831                    }
1832                }
1833                let Some(next) = charged.checked_add(bytes) else {
1834                    if let Some(quota) = self.quota.as_ref() {
1835                        release_pair(quota, self.memory.as_deref(), charged);
1836                        release_pair(quota, self.memory.as_deref(), bytes);
1837                    }
1838                    frame.set_heap_charge(0);
1839                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
1840                };
1841                if !frame.try_add_heap_charge(bytes) {
1842                    if let Some(quota) = self.quota.as_ref() {
1843                        release_pair(quota, self.memory.as_deref(), next);
1844                    }
1845                    frame.set_heap_charge(0);
1846                    return Err(Fault::QuotaExceeded("heap charge does not fit".into()));
1847                }
1848                charged = next;
1849            }
1850            match frame.registers_mut().get_mut(i) {
1851                Some(slot) => *slot = a,
1852                None => {
1853                    if charged > 0 {
1854                        if let Some(quota) = self.quota.as_ref() {
1855                            release_pair(quota, self.memory.as_deref(), charged);
1856                        }
1857                        frame.set_heap_charge(0);
1858                    }
1859                    return Err(Fault::RegisterOutOfRange {
1860                        reg: i as u8,
1861                        frame_size,
1862                    });
1863                }
1864            }
1865        }
1866        Ok(())
1867    }
1868}