:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(hogvm): cut transformation execution ~35% in prod, ~2x on geoip (#74117)
José Sequeirac851fc010814
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 32a9efa72695..161aaafe2f93 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -5500,6 +5500,7 @@ dependencies = [name = "hogvm"version = "0.1.0"dependencies = [+ "ahash 0.8.12","base64 0.22.1","chrono","chrono-tz",diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.tomlindex af787b7b0f05..298fb525f4e9 100644--- a/rust/common/hogvm/Cargo.toml+++ b/rust/common/hogvm/Cargo.toml@@ -15,6 +15,7 @@ rand.workspace = truechrono.workspace = truechrono-tz.workspace = trueindexmap = "2"+ahash.workspace = truemd-5 = "0.10"sha2.workspace = truesha1.workspace = truediff --git a/rust/common/hogvm/node/Cargo.lock b/rust/common/hogvm/node/Cargo.lockindex 8832a78ae170..65f6ed171e91 100644--- a/rust/common/hogvm/node/Cargo.lock+++ b/rust/common/hogvm/node/Cargo.lock@@ -286,6 +286,7 @@ dependencies = [name = "hogvm"version = "0.1.0"dependencies = [+ "ahash","base64","chrono","chrono-tz",@@ -298,6 +299,7 @@ dependencies = ["regex","serde","serde_json",+ "sha1","sha2","thiserror",]@@ -313,6 +315,7 @@ dependencies = ["napi-derive","rayon","serde_json",+ "tikv-jemallocator",][[package]]@@ -749,6 +752,17 @@ dependencies = ["zmij",]+[[package]]+name = "sha1"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "sha2"version = "0.10.9"@@ -821,6 +835,26 @@ dependencies = ["syn",]+[[package]]+name = "tikv-jemalloc-sys"+version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd8aa5b2ab86a2cefa406d889139c162cbb230092f7d1d7cbc1716405d852a3b"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "tikv-jemallocator"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0359b4327f954e0567e69fb191cf1436617748813819c94b8cd4a431422d053a"+dependencies = [+ "libc",+ "tikv-jemalloc-sys",+]+[[package]]name = "typenum"version = "1.20.1"diff --git a/rust/common/hogvm/node/Cargo.toml b/rust/common/hogvm/node/Cargo.tomlindex cb501de8ed23..22a7bfc5a00c 100644--- a/rust/common/hogvm/node/Cargo.toml+++ b/rust/common/hogvm/node/Cargo.toml@@ -23,6 +23,8 @@ napi = { version = "2", default-features = false, features = ["napi8", "serde-jsnapi-derive = "2"rayon = "1.10"serde_json = "1.0"+# Not common-alloc: a dlopen'ed cdylib needs jemalloc built without initial-exec TLS (see lib.rs).+tikv-jemallocator = { version = "0.6", features = ["disable_initial_exec_tls"] }[build-dependencies]napi-build = "2"diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rsindex b74e5d1eb118..90f8e0d8ece5 100644--- a/rust/common/hogvm/node/src/exec.rs+++ b/rust/common/hogvm/node/src/exec.rs@@ -35,34 +35,25 @@ pub struct HogExecResult {pub logs_truncated: bool,}+/// Build a `Program` (validating + pre-decoding the token stream once) from a raw bytecode+/// array. The `Err` string is in the shape the per-event results carry.+pub fn build_program(tokens: Vec<Value>) -> Result<Program, String> {+ if tokens.is_empty() {+ return Err("invalid program: bytecode must be a non-empty array".to_string());+ }+ Program::new(tokens).map_err(|e| format!("invalid program: {e}"))+}+pub fn run_batch(tokens: &[Value],events: &[Value],parallel: bool,max_steps: Option<usize>,) -> Vec<HogExecResult> {- if tokens.is_empty() {- return events- .iter()- .map(|_| error_result("invalid program: bytecode must be a non-empty array", 0.0))- .collect();+ match build_program(tokens.to_vec()) {+ Ok(program) => run_batch_program(&program, events, parallel, max_steps),+ Err(e) => events.iter().map(|_| error_result(&e, 0.0)).collect(),}-- if !parallel {- return run_chunk(tokens, events, max_steps);- }-- // Chunk size follows the batch so any batch worth parallelizing splits across the rayon- // pool; a fixed size tied to the caller's max batch size would put the whole batch in one- // chunk and never fan out.- let chunk_size = events- .len()- .div_ceil(rayon::current_num_threads())- .max(MIN_PARALLEL_CHUNK_SIZE);- events- .par_chunks(chunk_size)- .flat_map_iter(|chunk| run_chunk(tokens, chunk, max_steps).into_iter())- .collect()}/// Like [`run_batch`], but tolerates events whose JS→JSON conversion failed at the napi boundary:@@ -98,18 +89,35 @@ pub fn run_batch_salvaged(.collect()}+/// Like `run_batch` but from an already-built `Program` — no per-call copy, validation, or+/// token decode. This is the registered-program path.+pub fn run_batch_program(+ program: &Program,+ events: &[Value],+ parallel: bool,+ max_steps: Option<usize>,+) -> Vec<HogExecResult> {+ if !parallel {+ return run_chunk(program, events, max_steps);+ }++ // Chunk size follows the batch so any batch worth parallelizing splits across the rayon+ // pool; a fixed size tied to the caller's max batch size would put the whole batch in one+ // chunk and never fan out.+ let chunk_size = events+ .len()+ .div_ceil(rayon::current_num_threads())+ .max(MIN_PARALLEL_CHUNK_SIZE);+ events+ .par_chunks(chunk_size)+ .flat_map_iter(|chunk| run_chunk(program, chunk, max_steps).into_iter())+ .collect()+}+// Run a slice of events through one reused ExecutionContext (STL and ext fns built once, globals-// swapped per event).-fn run_chunk(tokens: &[Value], chunk: &[Value], max_steps: Option<usize>) -> Vec<HogExecResult> {- let program = match Program::new(tokens.to_vec()) {- Ok(p) => p,- Err(e) => {- return chunk- .iter()- .map(|_| error_result(&format!("invalid program: {e}"), 0.0))- .collect();- }- };+// swapped per event), sequentially on the calling thread.+fn run_chunk(program: &Program, chunk: &[Value], max_steps: Option<usize>) -> Vec<HogExecResult> {+ let program = program.clone();// Coercing comparisons are the TS reference's semantics (unifyComparisonTypes): ordering// coerces across number/string/boolean/null instead of erroring.diff --git a/rust/common/hogvm/node/src/ext_fns.rs b/rust/common/hogvm/node/src/ext_fns.rsindex 243b2dfc0f46..e3e7e7c8287c 100644--- a/rust/common/hogvm/node/src/ext_fns.rs+++ b/rust/common/hogvm/node/src/ext_fns.rs@@ -57,7 +57,7 @@ pub fn transformation_ext_fns() -> HashMap<String, NativeFunction> {let mut parts: Vec<String> = Vec::with_capacity(args.len());for arg in &args {let part = match arg.deref(&vm.heap)? {- HogLiteral::String(value) => value.clone(),+ HogLiteral::String(value) => value.to_string(),_ => serde_json::to_string(&vm.hog_to_json(arg)?).map_err(|e| VmError::NativeCallFailed(e.to_string()))?,};@@ -128,7 +128,7 @@ pub fn transformation_ext_fns() -> HashMap<String, NativeFunction> {let HogLiteral::String(ip) = arg.deref(&vm.heap)? else {return Ok(HogLiteral::Boolean(false).into());};- let known = list.iter().any(|known_ip| known_ip == ip);+ let known = list.iter().any(|known_ip| known_ip == ip.as_str());Ok(HogLiteral::Boolean(known).into())}),);diff --git a/rust/common/hogvm/node/src/lib.rs b/rust/common/hogvm/node/src/lib.rsindex 5d0f3a3a079a..fb5e5deb2863 100644--- a/rust/common/hogvm/node/src/lib.rs+++ b/rust/common/hogvm/node/src/lib.rs@@ -12,6 +12,14 @@//! can't support fails the execution with an `unsupported_ext_fn:<name>` error so the caller can//! fall back to the Node VM.+// jemalloc: the interpreter's small-allocation churn was a measured ~33% of self-time under+// glibc malloc. Not via `common_alloc`: node dlopens this cdylib after its other native modules,+// and jemalloc's default initial-exec TLS then needs static TLS space the process may already+// have spent, failing the load with "cannot allocate memory in static TLS block". The+// `disable_initial_exec_tls` feature builds jemalloc with the global-dynamic TLS model instead.+#[global_allocator]+static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;+mod exec;mod ext_fns;mod geoip;@@ -25,7 +33,10 @@ use napi::{Env, JsUnknown, NapiRaw, Task};use napi_derive::napi;use serde_json::Value;-pub use exec::{run_batch, run_batch_salvaged, HogExecResult, MARSHAL_ERROR_PREFIX};+pub use exec::{+ build_program, run_batch, run_batch_program, run_batch_salvaged, HogExecResult,+ MARSHAL_ERROR_PREFIX,+};#[napi(object)]pub struct InitOptions {diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rsindex 5e3395b1627b..efb13d3807c3 100644--- a/rust/common/hogvm/src/context.rs+++ b/rust/common/hogvm/src/context.rs@@ -1,4 +1,3 @@-use indexmap::IndexMap;use once_cell::sync::Lazy;use serde_json::{json, Value as JsonValue};use std::collections::{HashMap, HashSet};@@ -6,7 +5,7 @@ use std::sync::Arc;use crate::{error::VmError,- program::{ExportedFunction, Module, Program},+ program::{ExportedFunction, Module, Program, Token},stl::{hog_stl_map, stl_map, NativeFunction},vm::HogVM,HogLiteral, HogValue,@@ -223,7 +222,7 @@ impl ExecutionContext {pub fn get_symbol(&self, symbol: &Symbol) -> Result<&ExportedFunction, VmError> {self.symbol_table.get(symbol)- .ok_or(VmError::UnknownSymbol(symbol.to_string()))+ .ok_or_else(|| VmError::UnknownSymbol(symbol.to_string()))}// Whether `name` is a registered native (STL/ext) function — used to resolve first-class@@ -255,7 +254,20 @@ impl ExecutionContext {None => self.program.get(ip),};- res.ok_or(VmError::EndOfProgram(ip))+ res.ok_or_else(|| VmError::EndOfProgram(ip))+ }++ /// The full decoded token slice for a chunk (root program or module function) — cached by+ /// the VM per chunk so per-step fetches skip the symbol match and table lookup entirely.+ pub fn chunk_tokens(&self, symbol: &Option<Symbol>) -> Result<&[Token], VmError> {+ match symbol {+ Some(symbol) => Ok(self+ .symbol_table+ .get(symbol)+ .ok_or_else(|| VmError::UnknownSymbol(symbol.to_string()))?+ .body_tokens()),+ None => Ok(self.program.body_tokens()),+ }}pub fn version(&self) -> u64 {@@ -340,12 +352,16 @@ fn walk_emplacing(vm: &mut HogVM, value: HogValue) -> Result<HogValue, VmError>vm.heap.emplace(emplaced_arr).map(|ptr| ptr.into())}}- HogLiteral::Object(obj) => {- let emplaced_obj: Result<IndexMap<String, HogValue>, _> = obj- .into_iter()- .map(|(k, v)| Ok((k, walk_emplacing(vm, v)?)))- .collect();- let emplaced_obj = HogLiteral::Object(emplaced_obj?);+ HogLiteral::Object(mut obj) => {+ // Emplace children in place — no fresh map, so keys are neither re-hashed nor+ // re-inserted (the collect-based rebuild here was a measured allocation hot spot for+ // native fns returning nested objects, e.g. the geoip record).+ // Flat children take the `_` arm of the recursive call and come straight back.+ for v in obj.values_mut() {+ let taken = std::mem::replace(v, HogValue::Lit(HogLiteral::Null));+ *v = walk_emplacing(vm, taken)?;+ }+ let emplaced_obj = HogLiteral::Object(obj);if let Some(ptr) = existing_location {// As above, if this was already heap allocated, replace it with the new onediff --git a/rust/common/hogvm/src/lib.rs b/rust/common/hogvm/src/lib.rsindex b8a872eb2800..b1eae0cc6b17 100644--- a/rust/common/hogvm/src/lib.rs+++ b/rust/common/hogvm/src/lib.rs@@ -1,3 +1,9 @@+// This lint suggests `ok_or(VmError::...)` over `ok_or_else(|| VmError::...)` when the error is+// "trivial" to build. On the interpreter's per-token fetch path that eager construction of the+// large VmError enum is a measured end-to-end regression, so the crate deliberately stays lazy+// everywhere on the hot path.+#![allow(clippy::unnecessary_lazy_evaluations)]+mod context;mod error;mod memory;@@ -17,6 +23,7 @@ pub use context::ExecutionContext;pub use program::ExportedFunction;pub use program::Module;pub use program::Program;+pub use program::Token;// The opcode vocabulary, for consumers that read bytecode without running itpub use ops::Operation;@@ -53,6 +60,8 @@ pub use values::Closure;pub use values::FromHogLiteral;pub use values::FromHogRef;pub use values::HogLiteral;+pub use values::HogMap;+pub use values::HogStr;pub use values::HogValue;pub use values::LocalCallable;pub use values::Num;diff --git a/rust/common/hogvm/src/ops.rs b/rust/common/hogvm/src/ops.rsindex 7e88e50a6aeb..0f4ae7613e07 100644--- a/rust/common/hogvm/src/ops.rs+++ b/rust/common/hogvm/src/ops.rs@@ -78,13 +78,18 @@ impl TryFrom<Value> for Operation {let Some(num) = val.as_i64() else {return Err(VmError::NotAnOperation(val));};+ Self::from_i64(num)+ }+}+impl Operation {+ pub fn from_i64(num: i64) -> Result<Self, VmError> {if num >= Self::GetGlobal as i64 && num <= Self::CloseUpvalue as i64 {// TODO - this is deeply unhinged// nosemgrep: rust.lang.security.unsafe-usage.unsafe-usageOk(unsafe { std::mem::transmute::<u8, Operation>(num as u8) })} else {- Err(VmError::InvalidOperation(val))+ Err(VmError::InvalidOperation(Value::from(num)))}}}diff --git a/rust/common/hogvm/src/print.rs b/rust/common/hogvm/src/print.rsindex f7ac56d634bf..b1b0663a0d20 100644--- a/rust/common/hogvm/src/print.rs+++ b/rust/common/hogvm/src/print.rs@@ -5,7 +5,7 @@//! (which is `toString` semantics) on purpose — the two are subtly different and the//! parity loop is what reconciles them.-use indexmap::IndexMap;+use crate::values::HogMap;use crate::{memory::{HeapReference, VmHeap},@@ -41,7 +41,7 @@ pub fn escape_string(value: &str) -> String {/// else (including strings nested inside arrays/objects) goes through [`print_hog_value`].pub fn print_hog_string_output(heap: &VmHeap, value: &HogValue) -> Result<String, crate::VmError> {match value.deref(heap)? {- HogLiteral::String(s) => Ok(s.clone()),+ HogLiteral::String(s) => Ok(s.to_string()),_ => print_hog_value(heap, value, &mut Vec::new(), 0),}}@@ -131,7 +131,7 @@ fn format_literal(return Ok(format!("sql({})", HogQLPrinter::new(heap).print_node(obj)?));}let mut parts = Vec::with_capacity(obj.len());- for (key, val) in obj {+ for (key, val) in obj.iter() {parts.push(format!("{}: {}",escape_string(key),@@ -163,10 +163,7 @@ fn print_callable(callable: &Callable) -> String {// Render the Hog temporal duck-types: `{__hogDateTime__: true, dt, zone}` -> `DateTime(dt, 'zone')`// and `{__hogDate__: true, year, month, day}` -> `Date(y, m, d)`. Returns None for plain objects.-fn format_temporal(- heap: &VmHeap,- obj: &IndexMap<String, HogValue>,-) -> Result<Option<String>, crate::VmError> {+fn format_temporal(heap: &VmHeap, obj: &HogMap) -> Result<Option<String>, crate::VmError> {if marker(heap, obj.get("__hogDateTime__"))? {let dt = number(heap, obj.get("dt"))?.unwrap_or(0.0);let zone = string(heap, obj.get("zone"))?.unwrap_or_else(|| "UTC".to_string());@@ -189,7 +186,7 @@ fn format_temporal(// `Type('message')` or `Type('message', payload)`. Returns None for plain objects.fn format_error(heap: &VmHeap,- obj: &IndexMap<String, HogValue>,+ obj: &HogMap,marked: &mut Vec<HeapReference>,depth: usize,) -> Result<Option<String>, crate::VmError> {@@ -230,7 +227,7 @@ fn number(heap: &VmHeap, v: Option<&HogValue>) -> Result<Option<f64>, crate::VmEfn string(heap: &VmHeap, v: Option<&HogValue>) -> Result<Option<String>, crate::VmError> {match v {Some(v) => Ok(match v.deref(heap)? {- HogLiteral::String(s) => Some(s.clone()),+ HogLiteral::String(s) => Some(s.to_string()),_ => None,}),None => Ok(None),@@ -297,7 +294,7 @@ impl<'a> HogQLPrinter<'a> {}// Entry point: an already-dereferenced AST object.- fn print_node(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn print_node(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {self.depth += 1;let result = self.dispatch(obj);self.depth -= 1;@@ -314,7 +311,7 @@ impl<'a> HogQLPrinter<'a> {}}- fn dispatch(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn dispatch(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let node_type = self.str_field(obj, "__hx_ast")?.ok_or_else(|| {crate::VmError::NativeCallFailed("HogQL node missing __hx_ast".to_string())})?;@@ -347,7 +344,7 @@ impl<'a> HogQLPrinter<'a> {}}- fn select_query(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn select_query(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let is_top_level = self.depth <= 1;let distinct = if self.bool_field(obj, "distinct")? {" DISTINCT"@@ -405,10 +402,7 @@ impl<'a> HogQLPrinter<'a> {})}- fn select_set_query(- &mut self,- obj: &IndexMap<String, HogValue>,- ) -> Result<String, crate::VmError> {+ fn select_set_query(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {// The reference decrements/increments the indent around the set query; with pretty=false that// only affects the parenthesisation check, which we approximate via depth.let mut result = self.visit_child(obj, "initial_select_query")?;@@ -442,7 +436,7 @@ impl<'a> HogQLPrinter<'a> {self.visit(node)}- fn join_expr(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn join_expr(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let mut parts = Vec::new();let table = self.visit_child(obj, "table")?;match self.str_field(obj, "alias")? {@@ -489,7 +483,7 @@ impl<'a> HogQLPrinter<'a> {Ok(parts.join(" "))}- fn call(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn call(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let name = self.str_field(obj, "name")?.unwrap_or_default();Ok(format!("{name}({})",@@ -497,11 +491,11 @@ impl<'a> HogQLPrinter<'a> {))}- fn field(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn field(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let chain = self.array_field(obj, "chain")?;if chain.len() == 1 {if let HogLiteral::String(s) = chain[0].deref(self.heap)? {- if s == "*" {+ if s.as_str() == "*" {return Ok("*".to_string());}}@@ -513,7 +507,7 @@ impl<'a> HogQLPrinter<'a> {Ok(parts.join("."))}- fn alias(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn alias(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {if self.bool_field(obj, "hidden")? {return self.visit_child(obj, "expr");}@@ -522,11 +516,7 @@ impl<'a> HogQLPrinter<'a> {Ok(format!("{inside} AS {}", escape_identifier(&alias)))}- fn logical(- &mut self,- obj: &IndexMap<String, HogValue>,- func: &str,- ) -> Result<String, crate::VmError> {+ fn logical(&mut self, obj: &HogMap, func: &str) -> Result<String, crate::VmError> {let exprs = self.exprs_field(obj, "exprs")?;match exprs.len() {0 => Ok(String::new()),@@ -535,7 +525,7 @@ impl<'a> HogQLPrinter<'a> {}}- fn compare(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn compare(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let left = self.visit_child(obj, "left")?;let right = self.visit_child(obj, "right")?;let op = self.str_field(obj, "op")?.unwrap_or_default();@@ -563,7 +553,7 @@ impl<'a> HogQLPrinter<'a> {})}- fn arithmetic(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn arithmetic(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let left = self.visit_child(obj, "left")?;let right = self.visit_child(obj, "right")?;let func = match self.str_field(obj, "op")?.as_deref() {@@ -581,7 +571,7 @@ impl<'a> HogQLPrinter<'a> {Ok(format!("{func}({left}, {right})"))}- fn lambda(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {+ fn lambda(&mut self, obj: &HogMap) -> Result<String, crate::VmError> {let args = self.array_field(obj, "args")?;let escaped: Vec<String> = args.iter()@@ -599,15 +589,11 @@ impl<'a> HogQLPrinter<'a> {}// ── helpers ──- fn exprs(&mut self, obj: &IndexMap<String, HogValue>) -> Result<Vec<String>, crate::VmError> {+ fn exprs(&mut self, obj: &HogMap) -> Result<Vec<String>, crate::VmError> {self.exprs_field(obj, "exprs")}- fn exprs_field(- &mut self,- obj: &IndexMap<String, HogValue>,- key: &str,- ) -> Result<Vec<String>, crate::VmError> {+ fn exprs_field(&mut self, obj: &HogMap, key: &str) -> Result<Vec<String>, crate::VmError> {let items = self.array_field(obj, key)?;let mut out = Vec::with_capacity(items.len());for item in &items {@@ -616,22 +602,14 @@ impl<'a> HogQLPrinter<'a> {Ok(out)}- fn visit_child(- &mut self,- obj: &IndexMap<String, HogValue>,- key: &str,- ) -> Result<String, crate::VmError> {+ fn visit_child(&mut self, obj: &HogMap, key: &str) -> Result<String, crate::VmError> {match obj.get(key) {Some(v) => self.visit(v),None => Ok(String::new()),}}- fn array_field(- &self,- obj: &IndexMap<String, HogValue>,- key: &str,- ) -> Result<Vec<HogValue>, crate::VmError> {+ fn array_field(&self, obj: &HogMap, key: &str) -> Result<Vec<HogValue>, crate::VmError> {match obj.get(key) {Some(v) => Ok(match v.deref(self.heap)? {HogLiteral::Array(a) | HogLiteral::Tuple(a) => a.clone(),@@ -641,19 +619,11 @@ impl<'a> HogQLPrinter<'a> {}}- fn str_field(- &self,- obj: &IndexMap<String, HogValue>,- key: &str,- ) -> Result<Option<String>, crate::VmError> {+ fn str_field(&self, obj: &HogMap, key: &str) -> Result<Option<String>, crate::VmError> {string(self.heap, obj.get(key))}- fn bool_field(- &self,- obj: &IndexMap<String, HogValue>,- key: &str,- ) -> Result<bool, crate::VmError> {+ fn bool_field(&self, obj: &HogMap, key: &str) -> Result<bool, crate::VmError> {marker(self.heap, obj.get(key))}diff --git a/rust/common/hogvm/src/program.rs b/rust/common/hogvm/src/program.rsindex 9f59edc9dc90..09bbd0d17da5 100644--- a/rust/common/hogvm/src/program.rs+++ b/rust/common/hogvm/src/program.rs@@ -5,10 +5,65 @@ use serde_json::{Number, Value as JsonValue};use crate::VmError;+/// A bytecode token pre-decoded out of its `JsonValue` representation, so the interpreter's+/// per-step fetches are enum matches instead of serde deserializations. Decoded once per+/// program/module body, index-aligned with the raw token array (jump offsets and `ip` semantics+/// are unchanged).+#[derive(Debug, Clone)]+pub enum Token {+ Null,+ Bool(bool),+ Int(i64),+ Float(f64),+ Str(Arc<str>),+ /// Anything else (arrays/objects, numbers representable neither as i64 nor f64). Rare —+ /// consumers fall back to their `JsonValue` handling.+ Json(JsonValue),+}++impl Token {+ fn from_json(value: &JsonValue) -> Token {+ match value {+ JsonValue::Null => Token::Null,+ JsonValue::Bool(b) => Token::Bool(*b),+ JsonValue::Number(n) => {+ if let Some(i) = n.as_i64() {+ Token::Int(i)+ } else if let Some(f) = n.as_f64() {+ Token::Float(f)+ } else {+ Token::Json(value.clone())+ }+ }+ JsonValue::String(s) => Token::Str(Arc::from(s.as_str())),+ other => Token::Json(other.clone()),+ }+ }++ pub fn type_name(&self) -> &'static str {+ match self {+ Token::Null => "null",+ Token::Bool(_) => "bool",+ Token::Int(_) | Token::Float(_) => "number",+ Token::Str(_) => "string",+ Token::Json(JsonValue::Array(_)) => "array",+ Token::Json(JsonValue::Object(_)) => "object",+ Token::Json(_) => "json",+ }+ }+}++pub(crate) fn decode_tokens(tokens: &[JsonValue]) -> Vec<Token> {+ tokens.iter().map(Token::from_json).collect()+}+// A top-level hog program - functionally the body of a "main" function, if hog had such a thing.-// `bytecode` is `Arc`-shared so building a program from shared bytecode is a refcount bump.+// `bytecode` is `Arc`-shared so building a program from shared bytecode is a refcount bump, and+// the decoded token stream is shared the same way — cloning a `Program` never re-decodes.+#[derive(Clone)]pub struct Program {bytecode: Arc<Vec<JsonValue>>,+ decoded: Arc<Vec<Token>>,version: u64,program_start_offset: usize,}@@ -23,6 +78,7 @@ pub struct Module {pub struct ExportedFunction {arg_count: usize,body: Vec<JsonValue>,+ decoded: Vec<Token>,}impl Program {@@ -51,9 +107,9 @@ impl Program {}let version = version.unwrap_or(JsonValue::Number(Number::from(0)));match version {- JsonValue::Number(n) => n.as_u64().ok_or(VmError::InvalidBytecode(- "Invalid version number".to_string(),- ))?,+ JsonValue::Number(n) => n.as_u64().ok_or_else(|| {+ VmError::InvalidBytecode("Invalid version number".to_string())+ })?,_ => {return Err(VmError::InvalidBytecode("Invalid version number".to_string(),@@ -69,6 +125,7 @@ impl Program {};let program = Program {+ decoded: Arc::new(decode_tokens(&bytecode)),bytecode,version,program_start_offset: to_skip,@@ -81,6 +138,12 @@ impl Program {self.bytecode.get(idx + self.program_start_offset)}+ /// The decoded body (header stripped), index-aligned with `get(idx)`. The VM caches this+ /// slice per chunk to keep the per-step fetch a plain bounds-checked index.+ pub fn body_tokens(&self) -> &[Token] {+ &self.decoded[self.program_start_offset..]+ }+pub fn version(&self) -> u64 {self.version}@@ -119,6 +182,7 @@ impl ExportedFunction {pub fn new(arg_count: usize, bytecode: Vec<JsonValue>) -> Self {ExportedFunction {arg_count,+ decoded: decode_tokens(&bytecode),body: bytecode,}}@@ -130,4 +194,9 @@ impl ExportedFunction {pub fn get(&self, idx: usize) -> Option<&JsonValue> {self.body.get(idx)}++ /// The decoded body as a slice (see [`Program::body_tokens`]).+ pub fn body_tokens(&self) -> &[Token] {+ &self.decoded+ }}diff --git a/rust/common/hogvm/src/state.rs b/rust/common/hogvm/src/state.rsindex d031e091f49e..d18499512aca 100644--- a/rust/common/hogvm/src/state.rs+++ b/rust/common/hogvm/src/state.rs@@ -19,7 +19,7 @@ use std::cell::RefCell;use std::collections::HashMap;use std::rc::Rc;-use indexmap::IndexMap;+use crate::values::HogMap;use serde::{Deserialize, Serialize};use serde_json::{json, Value as JsonValue};@@ -214,7 +214,7 @@ pub fn value_to_json(HogLiteral::Null => JsonValue::Null,HogLiteral::Boolean(b) => json!(b),HogLiteral::Number(n) => JsonValue::Number(n.clone().try_into()?),- HogLiteral::String(s) => json!(s),+ HogLiteral::String(s) => json!(s.as_str()),HogLiteral::Array(items) => {let mut out = Vec::with_capacity(items.len());for item in items {@@ -233,7 +233,7 @@ pub fn value_to_json(}HogLiteral::Object(map) => {let mut out = serde_json::Map::with_capacity(map.len());- for (k, v) in map {+ for (k, v) in map.iter() {out.insert(k.clone(), value_to_json(v, heap, registry, header_len)?);}JsonValue::Object(out)@@ -317,7 +317,7 @@ pub fn value_from_json(JsonValue::Null => Ok(HogLiteral::Null.into()),JsonValue::Bool(b) => Ok(HogLiteral::Boolean(*b).into()),JsonValue::Number(n) => Ok(HogLiteral::Number(n.clone().into()).into()),- JsonValue::String(s) => Ok(HogLiteral::String(s.clone()).into()),+ JsonValue::String(s) => Ok(HogLiteral::from(s.clone()).into()),JsonValue::Array(items) => {let mut out = Vec::with_capacity(items.len());for item in items {@@ -336,18 +336,18 @@ fn object_from_json(header_len: usize,) -> Result<HogValue, VmError> {if map.contains_key("__hogClosure__") {- return Ok(HogLiteral::Closure(closure_from_json(+ return Ok(HogLiteral::Closure(Box::new(closure_from_json(&JsonValue::Object(map.clone()),cells,header_len,- )?)+ )?)).into());}if map.contains_key("__hogCallable__") {- return Ok(HogLiteral::Callable(callable_from_json(+ return Ok(HogLiteral::Callable(Box::new(callable_from_json(&JsonValue::Object(map.clone()),header_len,- )?)+ )?)).into());}if map.get("__hogTuple__").and_then(|v| v.as_bool()) == Some(true) {@@ -363,11 +363,11 @@ fn object_from_json(}// A plain object (including reference duck-types like __hogDateTime__, which Rust also models as// marked objects) — preserve key order.- let mut out = IndexMap::with_capacity(map.len());+ let mut out = HogMap::with_capacity_and_hasher(map.len(), Default::default());for (k, v) in map {out.insert(k.clone(), value_from_json(v, heap, cells, header_len)?);}- Ok(heap.emplace(HogLiteral::Object(out))?.into())+ Ok(heap.emplace(HogLiteral::Object(Box::new(out)))?.into())}pub fn closure_from_json(diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex a114431e7746..7eb1657241df 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -2,13 +2,13 @@ use core::str;use std::collections::HashMap;use std::sync::Arc;+use crate::values::HogMap;use base64::Engine as _;use chrono::{DateTime, Datelike, FixedOffset, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike,};use hmac::digest::KeyInit;use hmac::{Hmac, Mac};-use indexmap::IndexMap;use md5::Md5;use once_cell::sync::Lazy;use rand::Rng;@@ -60,7 +60,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {// Can't just use a ToString trait implementation, because ToString requires heap access to chase// references in arrays and dictsassert_argc(&args, 1, "toString")?;- to_string(&vm.heap, &args[0], 0).map(|s| HogLiteral::String(s).into())+ to_string(&vm.heap, &args[0], 0).map(|s| HogLiteral::from(s).into())}),),(@@ -96,7 +96,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {HogLiteral::Callable(_) | HogLiteral::Closure(_) => "function",HogLiteral::Null => "null",};- Ok(HogLiteral::String(t.to_string()).into())+ Ok(HogLiteral::from(t.to_string()).into())}),),(@@ -290,7 +290,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {for val in vals.iter() {parts.push(to_string(&vm.heap, val, 0)?);}- Ok(HogLiteral::String(parts.join(sep)).into())+ Ok(HogLiteral::from(parts.join(sep)).into())}),),(@@ -379,11 +379,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {if matches!(args[0].deref(&vm.heap)?, HogLiteral::Null)|| matches!(args[1].deref(&vm.heap)?, HogLiteral::Null){- return Ok(HogLiteral::String(String::new()).into());+ return Ok(HogLiteral::from(String::new()).into());}let haystack = args[0].deref(&vm.heap)?.try_as::<str>()?;let pattern = args[1].deref(&vm.heap)?.try_as::<str>()?;- Ok(HogLiteral::String(regex_extract(haystack, pattern)?).into())+ Ok(HogLiteral::from(regex_extract(haystack, pattern)?).into())})),),(@@ -470,7 +470,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {out.push_str(&print_hog_string_output(&vm.heap, arg)?);}}- Ok(HogLiteral::String(out).into())+ Ok(HogLiteral::from(out).into())}),),(@@ -479,7 +479,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert_argc(&args, 1, "lower")?;match args[0].deref(&vm.heap)? {HogLiteral::Null => Ok(HogLiteral::Null.into()),- HogLiteral::String(s) => Ok(HogLiteral::String(s.to_lowercase()).into()),+ HogLiteral::String(s) => Ok(HogLiteral::from(s.to_lowercase()).into()),other => Err(VmError::NativeCallFailed(format!("lower() expects a string, got {}",other.type_name()@@ -492,7 +492,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "upper")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;- Ok(HogLiteral::String(s.to_uppercase()).into())+ Ok(HogLiteral::from(s.to_uppercase()).into())}),),(@@ -501,7 +501,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert_argc(&args, 1, "reverse")?;match args[0].deref(&vm.heap)? {HogLiteral::String(s) => {- Ok(HogLiteral::String(s.chars().rev().collect()).into())+ Ok(HogLiteral::from(s.chars().rev().collect::<String>()).into())}HogLiteral::Array(arr) => {let mut a = arr.clone();@@ -550,7 +550,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {"jsonStringify requires at least one argument",)?;let s = json_stringify(&vm.heap, &args[0], &mut Vec::new(), 0)?;- Ok(HogLiteral::String(s).into())+ Ok(HogLiteral::from(s).into())}),),(@@ -661,7 +661,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert_argc(&args, 1, "keys")?;match args[0].deref(&vm.heap)? {HogLiteral::Object(o) => Ok(HogLiteral::Array(- o.keys().map(|k| HogLiteral::String(k.clone()).into()).collect(),+ o.keys().map(|k| HogLiteral::from(k.clone()).into()).collect(),).into()),// Arrays/tuples -> 0-based index list, matching the reference.@@ -748,7 +748,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {}let chars: Vec<char> = match args[0].deref(&vm.heap)? {HogLiteral::String(s) => s.chars().collect(),- _ => return Ok(HogLiteral::String(String::new()).into()),+ _ => return Ok(HogLiteral::from(String::new()).into()),};// start is 1-based.let start_idx = args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer() - 1;@@ -758,11 +758,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {chars.len() as i64 - start_idx};if start_idx < 0 || length < 0 || start_idx >= chars.len() as i64 {- return Ok(HogLiteral::String(String::new()).into());+ return Ok(HogLiteral::from(String::new()).into());}let s_u = start_idx as usize;let e_u = ((start_idx + length) as usize).min(chars.len());- Ok(HogLiteral::String(chars[s_u..e_u].iter().collect()).into())+ Ok(HogLiteral::from(chars[s_u..e_u].iter().collect::<String>()).into())}),),(@@ -772,7 +772,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let s: &str = args[0].deref(&vm.heap)?.try_as()?;let from: &str = args[1].deref(&vm.heap)?.try_as()?;let to: &str = args[2].deref(&vm.heap)?.try_as()?;- Ok(HogLiteral::String(s.replacen(from, to, 1)).into())+ Ok(HogLiteral::from(s.replacen(from, to, 1)).into())}),),(@@ -782,7 +782,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let s: &str = args[0].deref(&vm.heap)?.try_as()?;let from: &str = args[1].deref(&vm.heap)?.try_as()?;let to: &str = args[2].deref(&vm.heap)?.try_as()?;- Ok(HogLiteral::String(s.replace(from, to)).into())+ Ok(HogLiteral::from(s.replace(from, to)).into())}),),(@@ -801,11 +801,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let max = if max < 0 { 0 } else { max as usize };s.split(sep).take(max)- .map(|p| HogLiteral::String(p.to_string()).into())+ .map(|p| HogLiteral::from(p.to_string()).into()).collect()} else {s.split(sep)- .map(|p| HogLiteral::String(p.to_string()).into())+ .map(|p| HogLiteral::from(p.to_string()).into()).collect()};Ok(HogLiteral::Array(parts).into())@@ -863,12 +863,12 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert(!args.is_empty(), "JSONExtractString requires at least one argument")?;let res = match json_path_value(vm, &args)? {None | Some(JsonValue::Null) => HogLiteral::Null,- Some(JsonValue::String(s)) => HogLiteral::String(s),+ Some(JsonValue::String(s)) => HogLiteral::from(s),Some(JsonValue::Bool(b)) => {- HogLiteral::String(if b { "True" } else { "False" }.to_string())+ HogLiteral::from(if b { "True" } else { "False" }.to_string())}- Some(JsonValue::Number(n)) => HogLiteral::String(n.to_string()),- Some(other) => HogLiteral::String(other.to_string()),+ Some(JsonValue::Number(n)) => HogLiteral::from(n.to_string()),+ Some(other) => HogLiteral::from(other.to_string()),};Ok(res.into())}),@@ -1150,7 +1150,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "sha256HmacChainHex")?;let digest = hmac_chain::<HmacSha256>(vm, &args[0], "sha256HmacChain")?;- Ok(HogLiteral::String(to_hex(&digest)).into())+ Ok(HogLiteral::from(to_hex(&digest)).into())}),),(@@ -1163,7 +1163,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {}let digest = hmac_chain::<HmacSha256>(vm, &args[0], "sha256HmacChain")?;let encoding = encoding_arg(vm, &args, 1)?;- Ok(HogLiteral::String(encode_digest(&digest, &encoding)?).into())+ Ok(HogLiteral::from(encode_digest(&digest, &encoding)?).into())}),),(@@ -1171,7 +1171,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "sha1HmacChainHex")?;let digest = hmac_chain::<HmacSha1>(vm, &args[0], "sha1HmacChain")?;- Ok(HogLiteral::String(to_hex(&digest)).into())+ Ok(HogLiteral::from(to_hex(&digest)).into())}),),(@@ -1184,7 +1184,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {}let digest = hmac_chain::<HmacSha1>(vm, &args[0], "sha1HmacChain")?;let encoding = encoding_arg(vm, &args, 1)?;- Ok(HogLiteral::String(encode_digest(&digest, &encoding)?).into())+ Ok(HogLiteral::from(encode_digest(&digest, &encoding)?).into())}),),(@@ -1193,7 +1193,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert_argc(&args, 1, "base64Encode")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;let out = base64::engine::general_purpose::STANDARD.encode(s.as_bytes());- Ok(HogLiteral::String(out).into())+ Ok(HogLiteral::from(out).into())}),),(@@ -1201,7 +1201,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "base64Decode")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;- Ok(HogLiteral::String(base64_decode_to_string(s)?).into())+ Ok(HogLiteral::from(base64_decode_to_string(s)?).into())}),),(@@ -1210,7 +1210,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {assert_argc(&args, 1, "tryBase64Decode")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;// Reference returns "" on failure (Buffer.from never throws, but mirror the intent).- Ok(HogLiteral::String(base64_decode_to_string(s).unwrap_or_default()).into())+ Ok(HogLiteral::from(base64_decode_to_string(s).unwrap_or_default()).into())}),),(@@ -1218,7 +1218,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "encodeURLComponent")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;- Ok(HogLiteral::String(encode_uri_component(s)).into())+ Ok(HogLiteral::from(encode_uri_component(s)).into())}),),(@@ -1226,7 +1226,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {assert_argc(&args, 1, "decodeURLComponent")?;let s: &str = args[0].deref(&vm.heap)?.try_as()?;- decode_uri_component(s).map(|d| HogLiteral::String(d).into())+ decode_uri_component(s).map(|d| HogLiteral::from(d).into())}),),(@@ -1236,7 +1236,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let s: &str = args[0].deref(&vm.heap)?.try_as()?;// Reference returns null on malformed input rather than erroring.Ok(match decode_uri_component(s) {- Ok(d) => HogLiteral::String(d).into(),+ Ok(d) => HogLiteral::from(d).into(),Err(_) => HogLiteral::Null.into(),})}),@@ -1246,14 +1246,14 @@ pub fn stl() -> Vec<(String, NativeFunction)> {native_func(|vm, args| {// Reference `toUUID` is just `toString`.assert_argc(&args, 1, "toUUID")?;- to_string(&vm.heap, &args[0], 0).map(|s| HogLiteral::String(s).into())+ to_string(&vm.heap, &args[0], 0).map(|s| HogLiteral::from(s).into())}),),("generateUUIDv4",native_func(|_vm, args| {assert_argc(&args, 0, "generateUUIDv4")?;- Ok(HogLiteral::String(generate_uuid_v4()).into())+ Ok(HogLiteral::from(generate_uuid_v4()).into())}),),(@@ -1267,7 +1267,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {}let zone = match args.first() {Some(v) => match v.deref(&vm.heap)? {- HogLiteral::String(s) => s.clone(),+ HogLiteral::String(s) => s.to_string(),_ => "UTC".to_string(),},None => "UTC".to_string(),@@ -1487,7 +1487,7 @@ fn to_string(heap: &VmHeap, val: &HogValue, _depth: usize) -> Result<String, VmE// Render a Hog datetime as Luxon's `DateTime.fromSeconds(dt, {zone}).toISO()` does: millisecond// precision, `Z` for UTC and a `+HH:MM` offset otherwise.-fn hog_datetime_to_iso(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> Result<String, VmError> {+fn hog_datetime_to_iso(heap: &VmHeap, obj: &HogMap) -> Result<String, VmError> {let dt = obj_number(heap, obj, "dt")?.unwrap_or(0.0);let zone = obj_string(heap, obj, "zone")?.unwrap_or_else(|| "UTC".to_string());// Luxon keeps millisecond precision; round to whole millis first to avoid float drift turning@@ -1511,18 +1511,14 @@ fn hog_datetime_to_iso(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> ResulOk(formatted)}-fn obj_marker(heap: &VmHeap, obj: &IndexMap<String, HogValue>, key: &str) -> Result<bool, VmError> {+fn obj_marker(heap: &VmHeap, obj: &HogMap, key: &str) -> Result<bool, VmError> {match obj.get(key) {Some(v) => Ok(matches!(v.deref(heap)?, HogLiteral::Boolean(true))),None => Ok(false),}}-fn obj_number(- heap: &VmHeap,- obj: &IndexMap<String, HogValue>,- key: &str,-) -> Result<Option<f64>, VmError> {+fn obj_number(heap: &VmHeap, obj: &HogMap, key: &str) -> Result<Option<f64>, VmError> {match obj.get(key) {Some(v) => Ok(match v.deref(heap)? {HogLiteral::Number(n) => Some(n.to_float()),@@ -1532,14 +1528,10 @@ fn obj_number(}}-fn obj_string(- heap: &VmHeap,- obj: &IndexMap<String, HogValue>,- key: &str,-) -> Result<Option<String>, VmError> {+fn obj_string(heap: &VmHeap, obj: &HogMap, key: &str) -> Result<Option<String>, VmError> {match obj.get(key) {Some(v) => Ok(match v.deref(heap)? {- HogLiteral::String(s) => Some(s.clone()),+ HogLiteral::String(s) => Some(s.to_string()),_ => None,}),None => Ok(None),@@ -1547,7 +1539,7 @@ fn obj_string(}// Whole days from the Unix epoch to a Hog date (reference: `day.diff(epoch, 'days').days` floored).-fn hog_date_epoch_days(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> Result<i64, VmError> {+fn hog_date_epoch_days(heap: &VmHeap, obj: &HogMap) -> Result<i64, VmError> {let year = obj_number(heap, obj, "year")?.unwrap_or(0.0) as i32;let month = obj_number(heap, obj, "month")?.unwrap_or(0.0) as u32;let day = obj_number(heap, obj, "day")?.unwrap_or(0.0) as u32;@@ -1825,10 +1817,10 @@ impl<'de> Visitor<'de> for HogJsonVisitor {Ok(HogLiteral::Number(Num::Float(v)))}fn visit_str<E>(self, v: &str) -> Result<HogLiteral, E> {- Ok(HogLiteral::String(v.to_string()))+ Ok(HogLiteral::from(v.to_string()))}fn visit_string<E>(self, v: String) -> Result<HogLiteral, E> {- Ok(HogLiteral::String(v))+ Ok(HogLiteral::from(v))}fn visit_none<E>(self) -> Result<HogLiteral, E> {Ok(HogLiteral::Null)@@ -1844,11 +1836,11 @@ impl<'de> Visitor<'de> for HogJsonVisitor {Ok(HogLiteral::Array(vals))}fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<HogLiteral, A::Error> {- let mut obj = IndexMap::new();+ let mut obj = HogMap::default();while let Some((k, HogJson(v))) = map.next_entry::<String, HogJson>()? {obj.insert(k, v);}- Ok(HogLiteral::Object(obj))+ Ok(HogLiteral::Object(Box::new(obj)))}}@@ -1901,7 +1893,7 @@ fn json_stringify(}HogLiteral::Object(map) => {let mut parts = Vec::with_capacity(map.len());- for (k, v) in map {+ for (k, v) in map.iter() {parts.push(format!("{}: {}",escape(k)?,@@ -1984,7 +1976,7 @@ fn position_impl(ci: bool,) -> Result<i64, VmError> {let s = match haystack.deref(&vm.heap)? {- HogLiteral::String(s) => s.clone(),+ HogLiteral::String(s) => s.to_string(),_ => return Ok(0),};let n = to_string(&vm.heap, needle, 0)?; // str(needle)@@ -2036,7 +2028,7 @@ fn trim_impl(vm: &HogVM, args: Vec<HogValue>, side: TrimSide) -> Result<HogValueTrimSide::Right => s.trim_end().to_string(),}};- Ok(HogLiteral::String(result).into())+ Ok(HogLiteral::from(result).into())}fn make_hog_datetime(dt: f64, zone: &str) -> Result<HogValue, VmError> {@@ -2087,7 +2079,7 @@ fn hog_datetime_parts(vm: &HogVM, value: &HogValue, name: &str) -> Result<(f64,.ok_or_else(|| VmError::NativeCallFailed(format!("{name} expects a DateTime")))?;let zone = match lit {HogLiteral::Object(map) => match map.get("zone").map(|z| z.deref(&vm.heap)) {- Some(Ok(HogLiteral::String(s))) => s.clone(),+ Some(Ok(HogLiteral::String(s))) => s.to_string(),_ => "UTC".to_string(),},_ => "UTC".to_string(),@@ -2171,7 +2163,7 @@ fn zone_local_timestamp(zone: &str, naive: &NaiveDateTime) -> Result<f64, VmErrofn make_hog_interval(vm: &HogVM, args: &[HogValue], unit: &str) -> Result<HogValue, VmError> {assert_argc(args, 1, "toInterval")?;let n = args[0].deref(&vm.heap)?.try_as::<Num>()?.clone();- let mut map = IndexMap::new();+ let mut map = HogMap::default();map.insert("__hogInterval__".to_string(),HogLiteral::Boolean(true).into(),@@ -2179,9 +2171,9 @@ fn make_hog_interval(vm: &HogVM, args: &[HogValue], unit: &str) -> Result<HogValmap.insert("value".to_string(), HogLiteral::Number(n).into());map.insert("unit".to_string(),- HogLiteral::String(unit.to_string()).into(),+ HogLiteral::from(unit.to_string()).into(),);- Ok(HogLiteral::Object(map).into())+ Ok(HogLiteral::Object(Box::new(map)).into())}// Add an interval to a DateTime. day/hour/minute/second are absolute durations; month is wall-clock@@ -2321,7 +2313,7 @@ fn format_datetime_impl(vm: &HogVM, args: &[HogValue]) -> Result<HogValue, VmErr))}};- Ok(HogLiteral::String(dt.format(&translated).to_string()).into())+ Ok(HogLiteral::from(dt.format(&translated).to_string()).into())}// Translate the reference's ClickHouse-style format tokens (% + token) to chrono strftime codes.@@ -2509,7 +2501,7 @@ fn hash_with_encoding(HogLiteral::Null => Ok(HogLiteral::Null.into()),lit => {let data: &str = lit.try_as()?;- Ok(HogLiteral::String(encode_digest(&hasher(data.as_bytes()), encoding)?).into())+ Ok(HogLiteral::from(encode_digest(&hasher(data.as_bytes()), encoding)?).into())}}}@@ -2585,7 +2577,7 @@ fn encode_digest(digest: &[u8], encoding: &str) -> Result<String, VmError> {fn encoding_arg(vm: &HogVM, args: &[HogValue], idx: usize) -> Result<String, VmError> {match args.get(idx) {Some(v) => match v.deref(&vm.heap)? {- HogLiteral::String(s) => Ok(s.clone()),+ HogLiteral::String(s) => Ok(s.to_string()),_ => Ok("hex".to_string()),},None => Ok("hex".to_string()),@@ -2712,16 +2704,16 @@ fn new_hog_error(message: String,payload: Option<&HogValue>,) -> Result<HogValue, VmError> {- let mut map = IndexMap::new();+ let mut map = HogMap::default();map.insert("__hogError__".to_string(), HogLiteral::Boolean(true).into());- map.insert("type".to_string(), HogLiteral::String(type_str).into());- map.insert("message".to_string(), HogLiteral::String(message).into());+ map.insert("type".to_string(), HogLiteral::from(type_str).into());+ map.insert("message".to_string(), HogLiteral::from(message).into());if let Some(p) = payload {if !matches!(p.deref(&vm.heap)?, HogLiteral::Null) {map.insert("payload".to_string(), p.clone());}}- Ok(HogLiteral::Object(map).into())+ Ok(HogLiteral::Object(Box::new(map)).into())}// Resolve a string arg with the reference's `value || default` falsiness: missing, null, or empty@@ -2736,7 +2728,7 @@ fn arg_string_or(None => Ok(default.to_string()),Some(v) => match v.deref(&vm.heap)? {HogLiteral::String(s) if s.is_empty() => Ok(default.to_string()),- HogLiteral::String(s) => Ok(s.clone()),+ HogLiteral::String(s) => Ok(s.to_string()),HogLiteral::Null => Ok(default.to_string()),_ => to_string(&vm.heap, v, 0),},diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rsindex ae49ad80c9d1..91185f83ed83 100644--- a/rust/common/hogvm/src/values.rs+++ b/rust/common/hogvm/src/values.rs@@ -1,4 +1,7 @@-use std::{cell::RefCell, cmp::Ordering, collections::HashMap, fmt::Display, rc::Rc, str::FromStr};+use std::{+ cell::RefCell, cmp::Ordering, collections::HashMap, fmt::Display, rc::Rc, str::FromStr,+ sync::Arc,+};use chrono::NaiveDate;use indexmap::IndexMap;@@ -87,11 +90,83 @@ impl From<LocalCallable> for Callable {// hog has "primitives", which are copied by e.g, "get_local", and "objects", which are passed around by reference. This is distinct from the// "Heap" allocated stuff, which is used for things which must outlive all references to themselves on the stack, e.g. upvalues.+/// The object map used by [`HogLiteral::Object`]. Insertion-ordered like the reference VMs;+/// hashed with `ahash` instead of the default SipHash — object keys sit under every property+/// read/write and SipHash was a measured ~5% of interpreter self-time. ahash stays a keyed,+/// DoS-resistant hash, which matters because keys come from user programs.+pub type HogMap = IndexMap<String, HogValue, ahash::RandomState>;++/// The payload of [`HogLiteral::String`]. `Owned` is a plain heap string (globals, native-fn+/// results, computed strings); `Shared` is a refcounted slice of the pre-decoded token stream,+/// so pushing a string *constant* is a refcount bump instead of a malloc+copy (the ~90-write+/// geoip loop pushes ~3 constants per write, two of which are popped and dropped within a few+/// ops). Equality is content-based across the two arms.+#[derive(Debug, Clone)]+pub enum HogStr {+ Owned(String),+ Shared(Arc<str>),+}++impl std::ops::Deref for HogStr {+ type Target = str;++ fn deref(&self) -> &str {+ match self {+ HogStr::Owned(s) => s,+ HogStr::Shared(s) => s,+ }+ }+}++impl PartialEq for HogStr {+ fn eq(&self, other: &Self) -> bool {+ **self == **other+ }+}++impl HogStr {+ pub fn as_str(&self) -> &str {+ self+ }++ /// Extract an owned `String`, moving without a copy when this is `Owned`.+ pub fn into_string(self) -> String {+ match self {+ HogStr::Owned(s) => s,+ HogStr::Shared(s) => (*s).to_string(),+ }+ }+}++impl From<String> for HogStr {+ fn from(value: String) -> Self {+ HogStr::Owned(value)+ }+}++impl From<&str> for HogStr {+ fn from(value: &str) -> Self {+ HogStr::Owned(value.to_string())+ }+}++impl From<Arc<str>> for HogStr {+ fn from(value: Arc<str>) -> Self {+ HogStr::Shared(value)+ }+}++impl Display for HogStr {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self)+ }+}+#[derive(Debug, Clone, PartialEq)]pub enum HogLiteral {Number(Num),Boolean(bool),- String(String),+ String(HogStr),Array(Vec<HogValue>),// A tuple is an array that prints as `(a, b)` and whose `typeof` is "tuple"; for every other// operation it behaves exactly like an array (the reference duck-types it as an array with an@@ -99,9 +174,12 @@ pub enum HogLiteral {Tuple(Vec<HogValue>),// Insertion-ordered (IndexMap, not HashMap) to match the reference VMs: object literals,// `keys()`/`values()`, JSON serialization, and `print` all preserve the order keys were added.- Object(IndexMap<String, HogValue>),- Callable(Callable),- Closure(Closure),+ // Object/Callable/Closure payloads are boxed so the enum stays small (~32 bytes instead of+ // 120): every stack push/pop, clone, and heap emplacement moves the enum by value, and the+ // memmove of the large inline payloads was a measured hot spot.+ Object(Box<HogMap>),+ Callable(Box<Callable>),+ Closure(Box<Closure>),Null,}@@ -161,7 +239,7 @@ impl HogValue {// plain miss for the reference (Map.get), never an error.let key_lit = chain[0].deref(heap)?;let found = match key_lit {- HogLiteral::String(key) => map.get(key),+ HogLiteral::String(key) => map.get(key.as_str()),HogLiteral::Number(n) => map.get(&num_key_string(n)),_ => None,};@@ -573,7 +651,7 @@ impl FromHogLiteral for String {"String".to_string(),));};- Ok(s)+ Ok(s.into_string())}}@@ -666,6 +744,12 @@ impl From<bool> for HogLiteral {impl From<String> for HogLiteral {fn from(value: String) -> Self {+ Self::String(HogStr::Owned(value))+ }+}++impl From<HogStr> for HogLiteral {+ fn from(value: HogStr) -> Self {Self::String(value)}}@@ -692,13 +776,19 @@ impl From<HashMap<String, HogValue>> for HogLiteral {fn from(value: HashMap<String, HogValue>) -> Self {// External callers handing us an unordered HashMap get arbitrary key order; internal// object construction (Dict op, json_to_hog) builds the IndexMap directly, in order.- Self::Object(value.into_iter().collect())+ Self::Object(Box::new(value.into_iter().collect()))}}impl From<IndexMap<String, HogValue>> for HogLiteral {fn from(value: IndexMap<String, HogValue>) -> Self {- Self::Object(value)+ Self::Object(Box::new(value.into_iter().collect()))+ }+}++impl From<HogMap> for HogLiteral {+ fn from(value: HogMap) -> Self {+ Self::Object(Box::new(value))}}@@ -770,7 +860,7 @@ impl TryFrom<Num> for serde_json::Number {match value {// All my homies hate floating point numbersNum::Float(value) => serde_json::Number::from_f64(value)- .ok_or(VmError::InvalidNumber(format!("{value:?}"))),+ .ok_or_else(|| VmError::InvalidNumber(format!("{value:?}"))),Num::Integer(value) => Ok(value.into()),}}@@ -915,7 +1005,7 @@ pub fn construct_free_standing(current: JsonValue, depth: usize) -> Result<HogVaJsonValue::Null => Ok(HogLiteral::Null.into()),JsonValue::Bool(b) => Ok(HogLiteral::Boolean(b).into()),JsonValue::Number(n) => Ok(HogLiteral::Number(n.into()).into()),- JsonValue::String(s) => Ok(HogLiteral::String(s).into()),+ JsonValue::String(s) => Ok(HogLiteral::from(s).into()),JsonValue::Array(arr) => {let mut values = Vec::new();for value in arr {@@ -924,11 +1014,11 @@ pub fn construct_free_standing(current: JsonValue, depth: usize) -> Result<HogVaOk(HogLiteral::Array(values).into())}JsonValue::Object(obj) => {- let mut map = IndexMap::new();+ let mut map = HogMap::default();for (key, value) in obj {map.insert(key, construct_free_standing(value, depth + 1)?);}- Ok(HogLiteral::Object(map).into())+ Ok(HogLiteral::Object(Box::new(map)).into())}}}diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rsindex afbef49b733f..9e1d4e5e6823 100644--- a/rust/common/hogvm/src/vm.rs+++ b/rust/common/hogvm/src/vm.rs@@ -1,10 +1,8 @@-use std::any::Any;use std::cell::RefCell;use std::cmp::Ordering;use std::rc::Rc;+use std::sync::Arc;-use indexmap::IndexMap;-use serde::de::DeserializeOwned;use serde_json::{json, Value as JsonValue};use crate::{@@ -12,6 +10,7 @@ use crate::{error::VmError,memory::{HeapReference, VmHeap},ops::Operation,+ program::Token,state::{chunk_str, chunk_to_symbol, close_over_cells, closure_from_json, closure_to_json,collect_cells, rebuild_cells, root_closure_json, value_from_json, value_to_json,@@ -20,7 +19,7 @@ use crate::{util::{get_json_nested, like, regex_match},values::{compare_values, temporal_seconds_pair, Callable, Closure, FromHogLiteral, HogLiteral,- HogValue, LocalCallable, Num, NumOp, Upvalue, UpvalueCell,+ HogMap, HogStr, HogValue, LocalCallable, Num, NumOp, Upvalue, UpvalueCell,},};@@ -83,6 +82,10 @@ pub struct HogVM<'a> {// the pointer is currently pointing into to e.g. "arrayExists", as part of the function call that branches into// that function.current_symbol: Option<Symbol>,+ // The decoded token slice of the chunk `current_symbol` names, kept in lockstep with it (via+ // `set_chunk`) so the per-step fetch is a bounds-checked index instead of a symbol match plus+ // table lookup. Borrows from the context, like every other program view.+ current_tokens: &'a [Token],}struct CallFrame {@@ -114,6 +117,7 @@ impl<'a> HogVM<'a> {ops: 0,telemetry: Vec::new(),current_symbol: None,+ current_tokens: context.chunk_tokens(&None)?,context,heap: VmHeap::new(context.max_heap_size),})@@ -121,7 +125,7 @@ impl<'a> HogVM<'a> {/// Step the virtual machine, writing some debug information to the provided output function.pub fn debug_step(&mut self, output: &dyn Fn(String)) -> Result<StepOutcome, VmError> {- let op: Operation = self.next()?;+ let op: Operation = self.next_op()?;let mut surrounding = Vec::new();let start = self.ip.saturating_sub(2);for i in 0..5 {@@ -141,7 +145,7 @@ impl<'a> HogVM<'a> {/// Step the virtual machine one cycle.pub fn step(&mut self) -> Result<StepOutcome, VmError> {let pre_ip = self.ip;- let op: Operation = match self.next() {+ let op: Operation = match self.next_op() {Ok(op) => op,// The reference VMs halt gracefully when the instruction pointer runs off the// end of the top-level program (it has no trailing RETURN), yielding the top of@@ -179,7 +183,7 @@ impl<'a> HogVM<'a> {// GetGlobal is used to do 1 of 2 things, either push a value from a global variable onto the stack, or push a new// function reference (referred to in other impls as a "closure") onto the stack - either a native one, or a hog onelet mut chain = Vec::new();- let count: usize = self.next()?;+ let count: usize = self.next_usize()?;for _ in 0..count {chain.push(self.pop_stack()?);}@@ -193,7 +197,7 @@ impl<'a> HogVM<'a> {if let Some(found) = get_json_nested(&context.globals, &chain, self)? {let val = self.json_to_hog(found)?;self.push_stack(val)?;- } else if let Ok(closure) = self.get_fn_reference(&chain) {+ } else if let Some(closure) = self.get_fn_reference(&chain) {self.push_stack(closure)?;} else if get_json_nested(&context.globals, &chain[..1], self)?.is_some() {// If the first element of the chain is a global, push null onto the stack, e.g.@@ -214,16 +218,20 @@ impl<'a> HogVM<'a> {Operation::CallGlobal => {// The TS impl here has a bunch of special case handling for functions with particular names.// I'm hoping I can simplify that here by unifying the native call interface a bit- let name: String = self.next()?;- let arg_count: usize = self.next()?;+ let name = self.next_str()?;+ let arg_count: usize = self.next_usize()?;// NOTE - the TS implementation has a clause here that looks for the name in the// "declared functions" - basically, the legacy way of declaring a function before Callable// and closures were introduced. We leave it out because, as above, DeclareFn isn't supportedlet available_args = self.stack.len() - self.current_frame_base();if available_args < arg_count {- return Err(VmError::NotEnoughArguments(name, available_args, arg_count));+ return Err(VmError::NotEnoughArguments(+ name.to_string(),+ available_args,+ arg_count,+ ));}- let symbol = Symbol::new("stl", &name);+ let symbol = Symbol::new("stl", name);if self.context.has_symbol(&symbol) {// Cross module calls are done in a manner very similar to CallLocal, just with some// messing around with the current state module.@@ -243,10 +251,10 @@ impl<'a> HogVM<'a> {// This VM does native calls like so: it returns a "native call" struct, which the// executing environment dispatches — inline for a native, or as a suspension for a// registered async function (handled in the resumable driver).- return Ok(self.prep_native_call(name, args));+ return Ok(self.prep_native_call(name.to_string(), args));}Operation::And => {- let count: usize = self.next()?;+ let count: usize = self.next_usize()?;let mut acc: HogLiteral = true.into();for _ in 0..count {let value = self.pop_stack()?;@@ -256,7 +264,7 @@ impl<'a> HogVM<'a> {self.push_stack(acc)?;}Operation::Or => {- let count: usize = self.next()?;+ let count: usize = self.next_usize()?;let mut acc: HogLiteral = false.into();for _ in 0..count {let value = self.pop_stack()?;@@ -346,52 +354,50 @@ impl<'a> HogVM<'a> {self.push_stack(HogLiteral::Null)?;}Operation::String => {- let val: String = self.next()?;- self.push_stack(val)?;+ let val = self.next_str()?;+ // Constants push a shared view of the pre-decoded token — no allocation.+ self.push_stack(HogLiteral::String(HogStr::Shared(val.clone())))?;}Operation::Float => {- let val: f64 = self.next()?;+ let val: f64 = self.next_f64()?;self.push_stack(val)?;}// The reference's INTEGER opcode is untyped `pushStack(next())`; the SQL-AST compiler// emits it with a boolean operand. Fast-path the overwhelmingly common i64 (this is a hot// opcode — loop counters etc.), and fall back to pushing the raw token for anything else.- Operation::Integer => {- let as_int = self- .context- .get_bytecode(self.ip, &self.current_symbol)?- .as_i64();- if let Some(i) = as_int {- self.ip += 1;- self.push_stack(i)?;- } else {- let token = self- .context- .get_bytecode(self.ip, &self.current_symbol)?- .clone();- self.ip += 1;- let val = self.json_to_hog(&token)?;+ Operation::Integer => match self.next_token()? {+ Token::Int(i) => self.push_stack(*i)?,+ Token::Bool(b) => self.push_stack(*b)?,+ Token::Float(f) => self.push_stack(*f)?,+ Token::Str(s) => self.push_stack(HogLiteral::String(HogStr::Shared(s.clone())))?,+ Token::Null => self.push_stack(HogLiteral::Null)?,+ Token::Json(token) => {+ let val = self.json_to_hog(token)?;self.push_stack(val)?;}- }+ },Operation::Pop => {self.pop_stack()?;}Operation::GetLocal => {let base = self.current_frame_base();// Usize as a positive offset from the current frame- let offset: usize = self.next()?;- let ptr = self.hoist(base.checked_add(offset).ok_or(VmError::IntegerOverflow)?)?;+ let offset: usize = self.next_usize()?;+ let ptr = self.hoist(+ base.checked_add(offset)+ .ok_or_else(|| VmError::IntegerOverflow)?,+ )?;self.push_stack(ptr)?;}Operation::SetLocal => {// Replace some item "lower" in the stack with the top one.let base = self.current_frame_base();// Usize as a positive offset from the current frame- let offset: usize = self.next()?;+ let offset: usize = self.next_usize()?;let value = self.pop_stack()?;self.set_stack_val(- base.checked_add(offset).ok_or(VmError::IntegerOverflow)?,+ base.checked_add(offset)+ .ok_or_else(|| VmError::IntegerOverflow)?,value,)?;}@@ -407,32 +413,33 @@ impl<'a> HogVM<'a> {// return Ok(StepOutcome::Finished(result.deref(&self.heap)?.clone()));// };//- self.current_symbol = frame.ret_symbol;+ self.set_chunk(frame.ret_symbol)?;self.truncate_stack(frame.stack_start)?;self.ip = frame.ret_ptr;self.push_stack(result)?;}Operation::Jump => {// i32 to permit branching backwards- let offset: i32 = self.next()?;+ let offset: i32 = self.next_i32()?;self.ip = ((self.ip as i64).checked_add(offset as i64)- .ok_or(VmError::IntegerOverflow)?) as usize;+ .ok_or_else(|| VmError::IntegerOverflow)?) as usize;}Operation::JumpIfFalse => {// i32 to permit branching backwards- let offset: i32 = self.next()?;+ let offset: i32 = self.next_i32()?;// The reference coerces with `!popStack()`, so any falsy value (0, "", null, …) branches.let val = self.pop_stack()?;if !val.deref(&self.heap)?.truthy() {self.ip = ((self.ip as i64).checked_add(offset as i64)- .ok_or(VmError::IntegerOverflow)?) as usize;+ .ok_or_else(|| VmError::IntegerOverflow)?)+ as usize;}}Operation::JumpIfStackNotNull => {// i32 to permit branching backwards- let offset: i32 = self.next()?;+ let offset: i32 = self.next_i32()?;// Weirdly, this operation doesn't pop the value from the stack. This is mostly a random choice.if !self.stack.is_empty() {let item = self.clone_stack_item(self.stack.len() - 1)?;@@ -440,13 +447,13 @@ impl<'a> HogVM<'a> {if !matches!(item, HogLiteral::Null) {self.ip = ((self.ip as i64).checked_add(offset as i64)- .ok_or(VmError::IntegerOverflow)?)+ .ok_or_else(|| VmError::IntegerOverflow)?)as usize;}}}Operation::Dict => {- let element_count: usize = self.next()?;+ let element_count: usize = self.next_usize()?;let mut keys = Vec::with_capacity(element_count);let mut values = Vec::with_capacity(element_count);// The keys and values are pushed into the stack in key:value, key:value pairs, but we're@@ -465,8 +472,8 @@ impl<'a> HogVM<'a> {}// keys/values were popped in reverse (stack order), so reverse the zip to restore// the source insertion order in the IndexMap.- let map: IndexMap<String, HogValue> = keys.into_iter().zip(values).rev().collect();- let obj = HogLiteral::Object(map);+ let map: HogMap = keys.into_iter().zip(values).rev().collect();+ let obj = HogLiteral::Object(Box::new(map));// For the non-primitive types below (objects, arrays, "tuples"), we /always/ heap allocate them. The reason// is that the pattern for e.g. nestedly setting an array value is to GetLocal followed by GetProperty, followed// by a SetProperty. If the array is "flat", as in, element 3 is a HogLiteral rather than Value, that SetProperty@@ -479,7 +486,7 @@ impl<'a> HogVM<'a> {self.push_stack(ptr)?;}Operation::Array => {- let element_count: usize = self.next()?;+ let element_count: usize = self.next_usize()?;let mut elements = Vec::with_capacity(element_count);for _ in 0..element_count {elements.push(self.pop_stack()?);@@ -494,7 +501,7 @@ impl<'a> HogVM<'a> {Operation::Tuple => {// A tuple behaves like an array but prints as `(a, b)` and has typeof "tuple", so it// gets its own literal variant rather than reusing Array.- let element_count: usize = self.next()?;+ let element_count: usize = self.next_usize()?;let mut elements = Vec::with_capacity(element_count);for _ in 0..element_count {elements.push(self.pop_stack()?);@@ -562,13 +569,14 @@ impl<'a> HogVM<'a> {}Operation::Try => {// i32 to permit setting a catch offset lower than the IP- let catch_offset: i32 = self.next()?;+ let catch_offset: i32 = self.next_i32()?;// The reference computes `catchIp = <TRY position> + 1 + offset`. After reading the// opcode and offset, self.ip points two past the TRY position, so subtract one to land// on the same instruction (the compiler's offset already skips the POP_TRY).let catch_ip = (self.ip as i64).checked_add(catch_offset as i64 - 1)- .ok_or(VmError::IntegerOverflow)? as usize;+ .ok_or_else(|| VmError::IntegerOverflow)?+ as usize;let frame = ThrowFrame {catch_ptr: catch_ip,catch_symbol: self.current_symbol.clone(),@@ -611,34 +619,34 @@ impl<'a> HogVM<'a> {self.truncate_stack(frame.stack_start)?;self.stack_frames.truncate(frame.call_depth);self.ip = frame.catch_ptr;- self.current_symbol = frame.catch_symbol;+ self.set_chunk(frame.catch_symbol)?;self.push_stack(exception)?;}Operation::Callable => {// Construct a locally callable object - this is how e.g. fn decl's work- let name: String = self.next()?;- let stack_arg_count: usize = self.next()?;- let captured_arg_count: usize = self.next()?;- let body_length: usize = self.next()?;+ let name = self.next_str()?;+ let stack_arg_count: usize = self.next_usize()?;+ let captured_arg_count: usize = self.next_usize()?;+ let body_length: usize = self.next_usize()?;let callable: Callable = LocalCallable {- name,+ name: name.to_string(),stack_arg_count,capture_count: captured_arg_count,ip: self.ip,symbol: self.current_symbol.clone(), // Cross-module jumps are currently only done via CallGlobal}.into();- self.push_stack(HogLiteral::Callable(callable))?;+ self.push_stack(HogLiteral::Callable(Box::new(callable)))?;self.ip = self.ip.checked_add(body_length)- .ok_or(VmError::IntegerOverflow)?;+ .ok_or_else(|| VmError::IntegerOverflow)?;}// A closure is a callable, plus some captured arguments from the scope// it was constructed in.Operation::Closure => {let callable: Callable = self.pop_stack_as()?;- let capture_count: usize = self.next()?;+ let capture_count: usize = self.next_usize()?;// Only hog-local callables are wrapped by the CLOSURE opcode; native (STL) callables// are produced already-closed by GetGlobal, so they should never reach here.let Callable::Local(unwrapped) = &callable else {@@ -657,13 +665,13 @@ impl<'a> HogVM<'a> {for _ in 0..capture_count {// Indicates whether this captured value is a local in this frame's stack, or an// upvalue already captured by this frame's closure.- let is_local: bool = self.next()?;- let offset: usize = self.next()?;+ let is_local: bool = self.next_bool()?;+ let offset: usize = self.next_usize()?;if is_local {let location = self.current_frame_base().checked_add(offset)- .ok_or(VmError::IntegerOverflow)?;+ .ok_or_else(|| VmError::IntegerOverflow)?;captures.push(self.capture_upvalue(location));} else {// Nested closure: share the parent frame's upvalue cell.@@ -672,11 +680,11 @@ impl<'a> HogVM<'a> {}let closure = Closure { callable, captures };- self.push_stack(HogLiteral::Closure(closure))?;+ self.push_stack(HogLiteral::Closure(Box::new(closure)))?;}Operation::CallLocal => {let closure: Closure = self.pop_stack_as()?;- let arg_count: usize = self.next()?;+ let arg_count: usize = self.next_usize()?;// Extract the scalar callable fields up front so `closure` can be moved into the frame// (which now retains it for snapshotting). A native-function value dispatches inline.let (ip, symbol, stack_arg_count) = match &closure.callable {@@ -718,11 +726,11 @@ impl<'a> HogVM<'a> {closure,};self.stack_frames.push(frame);- self.current_symbol = symbol; // Prep to jump across the module boundary, if that's what we're doing+ self.set_chunk(symbol)?; // Prep to jump across the module boundary, if that's what we're doingself.ip = ip; // Do the jump}Operation::GetUpvalue => {- let index: usize = self.next()?;+ let index: usize = self.next_usize()?;let cell = self.frame_capture(index)?;// Open: read through to the live stack slot. Closed: read the snapshot it owns.let val = {@@ -733,13 +741,13 @@ impl<'a> HogVM<'a> {self.stack.get(uv.location).cloned()- .ok_or(VmError::StackIndexOutOfBounds)?+ .ok_or_else(|| VmError::StackIndexOutOfBounds)?}};self.push_stack(val)?;}Operation::SetUpvalue => {- let index: usize = self.next()?;+ let index: usize = self.next_usize()?;let cell = self.frame_capture(index)?;let val = self.pop_stack()?;// Open: write through to the live stack slot. Closed: store into the snapshot.@@ -783,7 +791,7 @@ impl<'a> HogVM<'a> {.captures.get(index).cloned()- .ok_or(VmError::CaptureOutOfBounds(index))+ .ok_or_else(|| VmError::CaptureOutOfBounds(index))}// Capture the stack slot at `location` as an open upvalue, deduplicating so all closures that@@ -835,26 +843,82 @@ impl<'a> HogVM<'a> {}}- fn next<T>(&mut self) -> Result<T, VmError>- where- T: DeserializeOwned + Any,- {- let next = self.context.get_bytecode(self.ip, &self.current_symbol)?;+ // Change the chunk being executed, keeping `current_tokens` in lockstep with+ // `current_symbol`. Every assignment of `current_symbol` must go through here.+ fn set_chunk(&mut self, symbol: Option<Symbol>) -> Result<(), VmError> {+ self.current_tokens = self.context.chunk_tokens(&symbol)?;+ self.current_symbol = symbol;+ Ok(())+ }++ // Instruction fetches read the pre-decoded token stream — enum matches, no serde and no+ // allocation per step. Error strings are built only on an actual mismatch (malformed+ // bytecode), never on the hot path. The returned borrow is tied to the context's lifetime+ // (`'a`), not to `&mut self`, so callers can keep it across further VM mutation.+ fn next_token(&mut self) -> Result<&'a Token, VmError> {+ let token = self+ .current_tokens+ .get(self.ip)+ .ok_or_else(|| VmError::EndOfProgram(self.ip))?;self.ip += 1;- // Borrow-deserialize straight from the &JsonValue (serde_json implements Deserializer for- // &Value) instead of cloning the whole value and deserializing an owned copy on every- // single instruction fetch. The error type-name strings are built lazily, only on an actual- // mismatch, rather than allocating one per token read on the hot path.- T::deserialize(next).map_err(|_| {- VmError::InvalidValue(next_type_name(next), std::any::type_name::<T>().to_string())- })+ Ok(token)+ }++ fn invalid_token(token: &Token, expected: &str) -> VmError {+ VmError::InvalidValue(token.type_name().to_string(), expected.to_string())+ }++ fn next_op(&mut self) -> Result<Operation, VmError> {+ match self.next_token()? {+ Token::Int(i) => Operation::from_i64(*i),+ token => Err(Self::invalid_token(token, "Operation")),+ }+ }++ fn next_usize(&mut self) -> Result<usize, VmError> {+ match self.next_token()? {+ Token::Int(i) if *i >= 0 => Ok(*i as usize),+ token => Err(Self::invalid_token(token, "usize")),+ }+ }++ fn next_i32(&mut self) -> Result<i32, VmError> {+ match self.next_token()? {+ Token::Int(i) => {+ i32::try_from(*i).map_err(|_| Self::invalid_token(&Token::Int(*i), "i32"))+ }+ token => Err(Self::invalid_token(token, "i32")),+ }+ }++ fn next_bool(&mut self) -> Result<bool, VmError> {+ match self.next_token()? {+ Token::Bool(b) => Ok(*b),+ token => Err(Self::invalid_token(token, "bool")),+ }+ }++ // Serde deserialized integer tokens into f64 fetches transparently; keep accepting both.+ fn next_f64(&mut self) -> Result<f64, VmError> {+ match self.next_token()? {+ Token::Float(f) => Ok(*f),+ Token::Int(i) => Ok(*i as f64),+ token => Err(Self::invalid_token(token, "f64")),+ }+ }++ fn next_str(&mut self) -> Result<&'a Arc<str>, VmError> {+ match self.next_token()? {+ Token::Str(s) => Ok(s),+ token => Err(Self::invalid_token(token, "String")),+ }}fn pop_stack(&mut self) -> Result<HogValue, VmError> {if self.stack.len() <= self.current_frame_base() {return Err(VmError::StackUnderflow);}- self.stack.pop().ok_or(VmError::StackUnderflow)+ self.stack.pop().ok_or_else(|| VmError::StackUnderflow)}// As above, but with a handy pointer chase and a cast/unwrap. Necessarily clones@@ -891,7 +955,7 @@ impl<'a> HogVM<'a> {fn js_string_coerce(&self, value: &HogValue) -> Result<String, VmError> {match value.deref(&self.heap)? {- HogLiteral::String(s) => Ok(s.clone()),+ HogLiteral::String(s) => Ok(s.to_string()),HogLiteral::Null => Ok("null".to_string()),HogLiteral::Boolean(b) => Ok(b.to_string()),HogLiteral::Number(n) => Ok(match n {@@ -998,7 +1062,7 @@ impl<'a> HogVM<'a> {// TODO - revisit this, idk about itself.stack.get_mut(idx)- .ok_or(VmError::StackIndexOutOfBounds)+ .ok_or_else(|| VmError::StackIndexOutOfBounds).map(|v| *v = value.into())}@@ -1025,22 +1089,29 @@ impl<'a> HogVM<'a> {// and filters are generally trivial// Resolve a global name referenced as a first-class function value. Currently supports native// (STL) functions — `let f := base64Encode` yields a closure that dispatches to the native fn.- fn get_fn_reference(&self, chain: &[HogValue]) -> Result<HogLiteral, VmError> {+ // Returns None when the chain isn't a reference to a known native function — the caller's+ // GetGlobal falls through to its next resolution strategy. A plain miss here is normal+ // control flow, so it must not construct an error (this sat on the hot path allocating+ // discarded error strings).+ fn get_fn_reference(&self, chain: &[HogValue]) -> Option<HogLiteral> {if chain.len() != 1 {- return Err(VmError::NotImplemented("imports".to_string()));+ return None;}- let name: &str = chain[0].deref(&self.heap)?.try_as()?;+ let name: &str = chain[0].deref(&self.heap).ok()?.try_as().ok()?;if self.context.has_native(name) {- return Ok(HogLiteral::Closure(Closure {+ return Some(HogLiteral::Closure(Box::new(Closure {callable: Callable::Stl(name.to_string()),captures: Vec::new(),- }));+ })));}- Err(VmError::NotImplemented("imports".to_string()))+ None}fn clone_stack_item(&self, idx: usize) -> Result<HogValue, VmError> {- self.stack.get(idx).cloned().ok_or(VmError::StackUnderflow)+ self.stack+ .get(idx)+ .cloned()+ .ok_or_else(|| VmError::StackUnderflow)}fn prep_native_call(&self, name: String, args: Vec<HogValue>) -> StepOutcome {@@ -1087,7 +1158,7 @@ impl<'a> HogVM<'a> {};self.stack_frames.push(frame);- self.current_symbol = Some(symbol);+ self.set_chunk(Some(symbol))?;self.ip = 0;Ok(StepOutcome::Continue)@@ -1119,7 +1190,7 @@ impl<'a> HogVM<'a> {JsonValue::Null => Ok(HogLiteral::Null.into()),JsonValue::Bool(b) => Ok(HogLiteral::Boolean(*b).into()),JsonValue::Number(n) => Ok(HogLiteral::Number(n.clone().into()).into()),- JsonValue::String(s) => Ok(HogLiteral::String(s.clone()).into()),+ JsonValue::String(s) => Ok(HogLiteral::from(s.clone()).into()),JsonValue::Array(arr) => {let mut values = Vec::new();for value in arr {@@ -1130,11 +1201,11 @@ impl<'a> HogVM<'a> {Ok(ptr.into())}JsonValue::Object(obj) => {- let mut map = IndexMap::new();- for (key, value) in obj {+ let mut map = HogMap::default();+ for (key, value) in obj.iter() {map.insert(key.clone(), self.json_to_hog_impl(value, depth + 1)?);}- let to_emplace = HogLiteral::Object(map);+ let to_emplace = HogLiteral::Object(Box::new(map));let ptr = self.heap.emplace(to_emplace)?;Ok(ptr.into())}@@ -1159,7 +1230,7 @@ impl<'a> HogVM<'a> {HogLiteral::Null => Ok(JsonValue::Null),HogLiteral::Boolean(b) => Ok(JsonValue::Bool(*b)),HogLiteral::Number(n) => Ok(JsonValue::Number(n.clone().try_into()?)),- HogLiteral::String(s) => Ok(JsonValue::String(s.clone())),+ HogLiteral::String(s) => Ok(JsonValue::String(s.to_string())),HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {let mut json_arr = Vec::new();for elem in arr {@@ -1169,7 +1240,7 @@ impl<'a> HogVM<'a> {}HogLiteral::Object(obj) => {let mut map = serde_json::Map::new();- for (key, value) in obj {+ for (key, value) in obj.iter() {map.insert(key.clone(), self.hog_to_json_impl(value, depth + 1)?);}Ok(JsonValue::Object(map))@@ -1361,7 +1432,7 @@ impl<'a> HogVM<'a> {return Err(VmError::Other("snapshot callStack is empty".to_string()));};vm.ip = Self::rust_ip(active.ip, &active.chunk, context);- vm.current_symbol = chunk_to_symbol(&active.chunk);+ vm.set_chunk(chunk_to_symbol(&active.chunk))?;let n = call_stack.len() - 1;let mut stack_frames = Vec::with_capacity(n);@@ -1575,14 +1646,3 @@ fn op_telemetry_name(op: &Operation) -> String {}format!("{}/{}", *op as u8, name)}--fn next_type_name(next: &JsonValue) -> String {- match next {- JsonValue::Null => "null".to_string(),- JsonValue::Bool(_) => "bool".to_string(),- JsonValue::Number(_) => "number".to_string(),- JsonValue::String(_) => "string".to_string(),- JsonValue::Array(_) => "array".to_string(),- JsonValue::Object(_) => "object".to_string(),- }-}diff --git a/rust/common/hogvm/tests/async_resume.rs b/rust/common/hogvm/tests/async_resume.rsindex 300f7d9753be..56a7ab8466d2 100644--- a/rust/common/hogvm/tests/async_resume.rs+++ b/rust/common/hogvm/tests/async_resume.rs@@ -16,6 +16,7 @@ const PLUS: i64 = 6;const INTEGER: i64 = 33;const GET_LOCAL: i64 = 36;const RETURN: i64 = 38;+const ARRAY: i64 = 43;const CALLABLE: i64 = 52;const CLOSURE: i64 = 53;const CALL_LOCAL: i64 = 54;@@ -145,6 +146,49 @@ fn nested_call_suspend_round_trips() {assert_eq!(result, json!(42));}+#[test]+fn stl_frame_suspend_round_trips() {+ // return arrayMap(x -> asyncFetch(x) + 1, [1, 2])+ // arrayMap is a Hog-written STL function, so each suspension happens with an stl/arrayMap+ // frame on the call stack. The snapshot must carry that non-root chunk and the resume must+ // restore it, so the lambda's RETURN lands back in module code (not the root token stream).+ // injecting 10 => [11, 11].+ let result = run_injecting(+ vec![+ json!("_H"),+ json!(1),+ json!(CALLABLE),+ json!("lambda"),+ json!(1),+ json!(0),+ json!(9),+ json!(GET_LOCAL),+ json!(0), // x+ json!(CALL_GLOBAL),+ json!("asyncFetch"),+ json!(1), // suspend inside the lambda, under the arrayMap frame+ json!(INTEGER),+ json!(1),+ json!(PLUS),+ json!(RETURN), // returns into stl/arrayMap's bytecode+ json!(CLOSURE),+ json!(0),+ json!(INTEGER),+ json!(1),+ json!(INTEGER),+ json!(2),+ json!(ARRAY),+ json!(2), // [1, 2]+ json!(CALL_GLOBAL),+ json!("arrayMap"),+ json!(2),+ json!(RETURN),+ ],+ json!(10),+ );+ assert_eq!(result, json!([11, 11]));+}+#[test]fn sleep_is_builtin_async() {// sleep(1) suspends as async even with no host-registered async functions, mirroring thediff --git a/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hog b/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hognew file mode 100644index 000000000000..31df22ecf08e--- /dev/null+++ b/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hog@@ -0,0 +1,13 @@+fun boom(x) {+ throw Error('boom');+}++let caught := false;+try {+ arrayMap(x -> boom(x), [1, 2]);+} catch (e) {+ caught := e.message == 'boom';+}++fun after() { return true; }+return caught and after();diff --git a/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hoge b/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hogenew file mode 100644index 000000000000..7ea9fe3ec118--- /dev/null+++ b/rust/common/hogvm/tests/static/test_programs/chunk_switch_unwind.hoge@@ -0,0 +1,4 @@+["_H", 1, 52, "boom", 1, 0, 8, 32, "boom", 2, "Error", 1, 49, 31, 38, 53, 0, 30, 50, 30, 52, "lambda", 1, 1, 7, 36, 0,+55, 0, 54, 1, 38, 53, 1, true, 0, 33, 1, 33, 2, 43, 2, 2, "arrayMap", 2, 35, 51, 39, 21, 36, 2, 32, "type", 45, 32,+"boom", 36, 2, 32, "message", 45, 11, 37, 1, 39, 2, 35, 49, 35, 35, 52, "after", 0, 0, 2, 29, 38, 53, 0, 36, 1, 36, 2,+54, 0, 3, 2, 38, 35, 35, 57]diff --git a/rust/common/hogvm/tests/token_decode.rs b/rust/common/hogvm/tests/token_decode.rsnew file mode 100644index 000000000000..50598735e916--- /dev/null+++ b/rust/common/hogvm/tests/token_decode.rs@@ -0,0 +1,45 @@+//! Coverage for the pre-decoded token stream on uncommon operand shapes. The parity corpus only+//! exercises the common ones (int under INTEGER, fractional float under FLOAT, strings), so these+//! lock in the decode fallbacks: INTEGER is untyped `pushStack(next())` in the reference VM (the+//! SQL-AST compiler emits it with a boolean operand), FLOAT accepts an integer operand (serde+//! deserialized those transparently), and an integer above `i64::MAX` decodes as a float.++use hogvm::{sync_execute, ExecutionContext, Program};+use serde_json::{json, Value};++// Opcode numeric values (mirror common/hogvm/python/operation.py).+const OP_INTEGER: i64 = 33;+const OP_FLOAT: i64 = 34;+const OP_RETURN: i64 = 38;++fn run(operand: Value, op: i64) -> Value {+ let bytecode = vec![json!("_H"), json!(1), json!(op), operand, json!(OP_RETURN)];+ let program = Program::new(bytecode).expect("valid program");+ let ctx = ExecutionContext::with_defaults(program);+ sync_execute(&ctx, false).expect("execution succeeds")+}++#[test]+fn integer_opcode_with_bool_operand() {+ assert_eq!(run(json!(true), OP_INTEGER), json!(true));+ assert_eq!(run(json!(false), OP_INTEGER), json!(false));+}++#[test]+fn integer_opcode_with_float_operand() {+ assert_eq!(run(json!(2.5), OP_INTEGER), json!(2.5));+}++#[test]+fn integer_opcode_with_operand_above_i64_max() {+ // 2^63 doesn't fit an i64, so the token decodes as a float and pushes a number.+ assert_eq!(+ run(json!(9_223_372_036_854_775_808u64), OP_INTEGER),+ json!(9.223372036854776e18)+ );+}++#[test]+fn float_opcode_with_integer_operand() {+ assert_eq!(run(json!(1), OP_FLOAT), json!(1.0));+}