Skip to main content

byteflow/vm/machine/
mod.rs

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