: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): fix interpreter allocation hot paths (#66275)
José Sequeira2c1a995a6f9f
diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rsindex 63f547204c47..875f08696553 100644--- a/rust/common/hogvm/src/context.rs+++ b/rust/common/hogvm/src/context.rs@@ -208,9 +208,17 @@ fn walk_emplacing(vm: &mut HogVM, value: HogValue) -> Result<HogValue, VmError>match literal {HogLiteral::Array(arr) => {- let emplaced_arr: Result<Vec<HogValue>, _> =- arr.into_iter().map(|i| walk_emplacing(vm, i)).collect();- let emplaced_arr = HogLiteral::Array(emplaced_arr?);+ // Fast path: when every element is a plain (non-container, non-reference) literal there+ // is nothing to emplace, so skip the per-element walk + re-collect entirely. Native STL+ // results are overwhelmingly flat numeric/string arrays, and this walk was the single+ // hottest function in the interpreter (~25% of instructions) before this guard.+ let emplaced_arr = if arr.iter().all(is_flat_literal) {+ HogLiteral::Array(arr)+ } else {+ let walked: Result<Vec<HogValue>, _> =+ arr.into_iter().map(|i| walk_emplacing(vm, i)).collect();+ HogLiteral::Array(walked?)+ };if let Some(ptr) = existing_location {// If this was already a heap-allocated array, replace it with the new one@@ -244,3 +252,20 @@ fn walk_emplacing(vm: &mut HogVM, value: HogValue) -> Result<HogValue, VmError>.unwrap_or(literal.into())),}}++// A value that needs no emplacing: a literal that isn't itself a nested container (so it holds no+// child values that must be hoisted onto the heap). References are excluded — they already point at+// heap state, but the walk preserves the original conservative behavior for them.+fn is_flat_literal(v: &HogValue) -> bool {+ matches!(+ v,+ HogValue::Lit(+ HogLiteral::Number(_)+ | HogLiteral::Boolean(_)+ | HogLiteral::String(_)+ | HogLiteral::Null+ | HogLiteral::Callable(_)+ | HogLiteral::Closure(_)+ )+ )+}diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex 55d18b5828e8..770ef06ef0bc 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -187,22 +187,8 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let array = args[0].deref(&vm.heap)?;match array {HogLiteral::Array(arr) => {- let (vals, errs): (Vec<_>, Vec<_>) = arr- .iter()- .map(|v| v.deref(&vm.heap).and_then(|v| v.try_as::<Num>()).cloned())- .partition(Result::is_ok);- if errs.is_empty() {- let mut vals = vals.into_iter().map(|v| v.unwrap()).collect::<Vec<_>>();- vals.sort_unstable_by(|a, b| a.compare(b));- Ok(- HogLiteral::Array(vals.into_iter().map(|v| v.into()).collect())- .into(),- )- } else {- Err(VmError::NativeCallFailed(- "arraySort() only supports arrays of numbers".to_string(),- ))- }+ let nums = collect_sorted_nums(&vm.heap, arr, "arraySort")?;+ Ok(HogLiteral::Array(nums.into_iter().map(|n| n.into()).collect()).into())}_ => Err(VmError::NativeCallFailed("arraySort() only supports arrays".to_string(),@@ -234,23 +220,9 @@ pub fn stl() -> Vec<(String, NativeFunction)> {let array = args[0].deref(&vm.heap)?;match array {HogLiteral::Array(arr) => {- let (vals, errs): (Vec<_>, Vec<_>) = arr- .iter()- .map(|v| v.deref(&vm.heap).and_then(|v| v.try_as::<Num>()).cloned())- .partition(Result::is_ok);- if errs.is_empty() {- let mut vals = vals.into_iter().map(|v| v.unwrap()).collect::<Vec<_>>();- vals.sort_unstable_by(|a, b| a.compare(b));- vals.reverse();- Ok(- HogLiteral::Array(vals.into_iter().map(|v| v.into()).collect())- .into(),- )- } else {- Err(VmError::NativeCallFailed(- "arrayReverseSort() only supports arrays of numbers".to_string(),- ))- }+ let mut nums = collect_sorted_nums(&vm.heap, arr, "arrayReverseSort")?;+ nums.reverse();+ Ok(HogLiteral::Array(nums.into_iter().map(|n| n.into()).collect()).into())}_ => Err(VmError::NativeCallFailed("arrayReverseSort() only supports arrays".to_string(),@@ -590,6 +562,21 @@ fn datetime_to_seconds<Tz: TimeZone>(dt: DateTime<Tz>) -> f64 {dt.timestamp() as f64 + f64::from(dt.timestamp_subsec_nanos()) / 1_000_000_000.0}+// Extract every element as a Num and return them sorted ascending. Single allocation + early error,+// rather than partitioning into (oks, errs) Vecs and unwrapping — the old path allocated several+// intermediate Vecs per call, which showed up under profiling for sort-heavy workloads.+fn collect_sorted_nums(heap: &VmHeap, arr: &[HogValue], name: &str) -> Result<Vec<Num>, VmError> {+ let mut nums = Vec::with_capacity(arr.len());+ for v in arr {+ let n = v.deref(heap)?.try_as::<Num>().map_err(|_| {+ VmError::NativeCallFailed(format!("{name}() only supports arrays of numbers"))+ })?;+ nums.push(n.clone());+ }+ nums.sort_unstable_by(|a, b| a.compare(b));+ Ok(nums)+}+fn assert(test: bool, msg: impl AsRef<str>) -> Result<(), VmError> {if test {Ok(())diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rsindex 26a7d14723dd..97893a278ca6 100644--- a/rust/common/hogvm/src/vm.rs+++ b/rust/common/hogvm/src/vm.rs@@ -692,11 +692,13 @@ impl<'a> HogVM<'a> {{let next = self.context.get_bytecode(self.ip, &self.current_symbol)?;self.ip += 1;- let next_type_name = next_type_name(next);- let expected = std::any::type_name::<T>();-- serde_json::from_value(next.clone())- .map_err(|_| VmError::InvalidValue(next_type_name, expected.to_string()))+ // 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())+ })}fn pop_stack(&mut self) -> Result<HogValue, VmError> {