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