Skip to content

: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.

fix(hogvm): match node reference for regex coercion and json depth (#68665)

José Sequeira545b1e5a8674
diff --git a/rust/common/hogvm/src/lib.rs b/rust/common/hogvm/src/lib.rs
index aabd83dec707..cd501accd90f 100644
--- a/rust/common/hogvm/src/lib.rs
+++ b/rust/common/hogvm/src/lib.rs
@@ -23,6 +23,7 @@ pub use vm::sync_execute;
pub use vm::HogVM;
pub use vm::StepOutcome;
pub use vm::VmFailure;
+pub use vm::MAX_JSON_SERDE_DEPTH;
// Suspend/resume (async-coroutine) execution and state serialization
pub use state::Resumable;
diff --git a/rust/common/hogvm/src/util.rs b/rust/common/hogvm/src/util.rs
index 8b5b65229b42..cf8f7c743483 100644
--- a/rust/common/hogvm/src/util.rs
+++ b/rust/common/hogvm/src/util.rs
@@ -95,7 +95,11 @@ fn like_to_regex(pattern: &str) -> String {
} else if c == '\\' {
escape = true;
} else if c == '%' {
- result.push_str(".*");
+ // `%` matches any run of characters, newline included (as in ClickHouse and the
+ // reference VM's unanchored matcher). The regex crate's `.` excludes `\n`, so `.*` would
+ // make `elements_chain ilike '%foo%'` miss when the chain wraps across lines. `_` stays
+ // `.` (single non-newline char) to match the reference's `_` -> `.`.
+ result.push_str("[\\s\\S]*");
} else if c == '_' {
result.push('.');
} else {
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 181372fd3fd0..455d725f3ad4 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -23,7 +23,12 @@ use crate::{
},
};
-pub const MAX_JSON_SERDE_DEPTH: usize = 64;
+// Recursion guard for walking nested JSON/Hog containers (input deserialization, output
+// serialization, deep clones, json stringify). The reference VMs impose no explicit JSON-nesting
+// limit, so a low cap here shows up as a shadow `status_mismatch` (Rust errors where Node succeeds)
+// on legitimately deep event properties. 256 clears any realistic event nesting by a wide margin
+// while still bounding native recursion well within a worker thread's stack.
+pub const MAX_JSON_SERDE_DEPTH: usize = 256;
/// The outcome of a virtual machine step.
#[derive(Debug, Clone)]
@@ -899,21 +904,24 @@ impl<'a> HogVM<'a> {
}
}
- /// `=~`/`!~` (and the case-insensitive variants). The stack holds the pattern below the value;
- /// either operand being null never matches (the reference's external matcher returns false), so
- /// `=~` is false and `!~` is true.
+ /// `=~`/`!~` (and the case-insensitive variants). The stack holds the pattern below the value.
+ /// Mirrors the reference's `regexMatch`: `pattern && value ? external.match(pattern, value) :
+ /// false`, where the external matcher (RE2/RegExp `.test`) JS-String-coerces the value. So a
+ /// falsy pattern or value (null, `false`, `0`, `""`, `NaN`) never matches, and scalar values
+ /// (numbers, booleans) stringify just like `like`/`ilike` via `js_string_coerce`. Containers
+ /// still error, matching the deliberate `pop_like_operands` deviation.
fn regex_op(&mut self, case_sensitive: bool, negate: bool) -> Result<(), VmError> {
let val = self.pop_stack()?;
let pat = self.pop_stack()?;
let matched = {
let val_lit = val.deref(&self.heap)?;
let pat_lit = pat.deref(&self.heap)?;
- if matches!(val_lit, HogLiteral::Null) || matches!(pat_lit, HogLiteral::Null) {
+ if !val_lit.truthy() || !pat_lit.truthy() {
false
} else {
regex_match(
- val_lit.try_as::<str>()?,
- pat_lit.try_as::<str>()?,
+ &self.js_string_coerce(&val)?,
+ &self.js_string_coerce(&pat)?,
case_sensitive,
)?
}
diff --git a/rust/common/hogvm/tests/json_depth.rs b/rust/common/hogvm/tests/json_depth.rs
new file mode 100644
index 000000000000..94e77627e91f
--- /dev/null
+++ b/rust/common/hogvm/tests/json_depth.rs
@@ -0,0 +1,55 @@
+//! The json->hog deserialization recursion guard (`MAX_JSON_SERDE_DEPTH`) must clear any realistic
+//! event nesting. The reference VMs impose no explicit JSON-nesting limit, so an over-tight cap here
+//! surfaces as a shadow `status_mismatch` (Rust errors where Node succeeds) on legitimately deep
+//! event properties. Accessing a nested global runs it through `json_to_hog`, so this exercises the
+//! guard end to end.
+
+use hogvm::{sync_execute, ExecutionContext, Program, MAX_JSON_SERDE_DEPTH};
+use serde_json::{json, Value};
+
+const OP_GET_GLOBAL: i64 = 1;
+const OP_STRING: i64 = 32;
+const OP_RETURN: i64 = 38;
+
+// A value nested `depth` arrays deep: [[[ ... 1 ... ]]].
+fn nested_array(depth: usize) -> Value {
+ let mut v = json!(1);
+ for _ in 0..depth {
+ v = json!([v]);
+ }
+ v
+}
+
+// Program: `return globals.deep` — forces json_to_hog over the whole nested subtree on access.
+fn return_deep_global(globals: Value) -> Result<Value, hogvm::VmFailure> {
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_STRING),
+ json!("deep"),
+ json!(OP_GET_GLOBAL),
+ json!(1),
+ json!(OP_RETURN),
+ ];
+ let program = Program::new(bc).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(globals);
+ sync_execute(&ctx, false)
+}
+
+#[test]
+fn nesting_within_the_cap_deserializes() {
+ // Just under the cap (and well past the old value of 64): must round-trip unchanged.
+ let value = nested_array(MAX_JSON_SERDE_DEPTH - 50);
+ let result = return_deep_global(json!({ "deep": value.clone() })).expect("execution succeeds");
+ assert_eq!(result, value);
+}
+
+#[test]
+fn nesting_past_the_cap_still_errors() {
+ // The guard is raised, not removed — pathologically deep input still errors rather than risking
+ // native stack exhaustion.
+ assert!(
+ return_deep_global(json!({ "deep": nested_array(MAX_JSON_SERDE_DEPTH + 50) })).is_err(),
+ "nesting beyond MAX_JSON_SERDE_DEPTH should still error"
+ );
+}
diff --git a/rust/common/hogvm/tests/like_multiline.rs b/rust/common/hogvm/tests/like_multiline.rs
new file mode 100644
index 000000000000..9b82b001edd6
--- /dev/null
+++ b/rust/common/hogvm/tests/like_multiline.rs
@@ -0,0 +1,55 @@
+//! `LIKE`/`ILIKE` `%` must span newlines, matching ClickHouse and the reference VM's unanchored
+//! matcher. The pattern compiles to an anchored regex, and the regex crate's `.` excludes `\n`, so
+//! mapping `%` to `.*` silently missed matches when the haystack wrapped across lines — e.g.
+//! `elements_chain ilike '%onetrust%'`, since element chains carry newlines in their text and
+//! attributes. `_` stays `.` (a single non-newline char), matching the reference's `_` -> `.`.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+const OP_LIKE: i64 = 17;
+const OP_ILIKE: i64 = 18;
+const OP_STRING: i64 = 32;
+const OP_RETURN: i64 = 38;
+
+fn run(bytecode: Vec<Value>) -> Value {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program);
+ sync_execute(&ctx, false).expect("execution succeeds")
+}
+
+// Stack order: pattern is pushed first, then the value (the VM pops the value first).
+fn like_of(pattern: &str, value: &str, op: i64) -> Vec<Value> {
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_STRING),
+ json!(pattern),
+ json!(OP_STRING),
+ json!(value),
+ json!(op),
+ json!(OP_RETURN),
+ ]
+}
+
+#[test]
+fn percent_wildcard_spans_newlines() {
+ let chain = "button:attr__class=\"btn\"\nonetrust-accept-btn-handler\nspan";
+ assert_eq!(
+ run(like_of("%onetrust-accept-btn-handler%", chain, OP_ILIKE)),
+ Value::Bool(true),
+ "%% wildcard should cross the newline before the token"
+ );
+ // A token that never appears is still no match.
+ assert_eq!(
+ run(like_of("%missing-handler%", chain, OP_ILIKE)),
+ Value::Bool(false)
+ );
+}
+
+#[test]
+fn underscore_stays_a_single_non_newline_char() {
+ // `_` -> `.`, matching the reference; it does not cross a newline.
+ assert_eq!(run(like_of("a_b", "aXb", OP_LIKE)), Value::Bool(true));
+ assert_eq!(run(like_of("a_b", "a\nb", OP_LIKE)), Value::Bool(false));
+}
diff --git a/rust/common/hogvm/tests/regex_coercion.rs b/rust/common/hogvm/tests/regex_coercion.rs
new file mode 100644
index 000000000000..5b43f11211cd
--- /dev/null
+++ b/rust/common/hogvm/tests/regex_coercion.rs
@@ -0,0 +1,101 @@
+//! `=~`/`!~` (and the case-insensitive variants) coerce non-string scalar operands like the TS
+//! reference's `regexMatch`: `pattern && value ? external.match(pattern, value) : false`, where the
+//! external matcher (RE2 `.test`) JS-String-coerces the value. So numbers and booleans stringify
+//! and match, a falsy pattern or value (null, `false`, `0`, `""`) never matches, and containers
+//! (arrays/objects) still error — the same deliberate deviation `like`/`ilike` make. Contrast
+//! `like_null.rs`, where `like` stringifies null to "null" and has no falsy guard. Real hog code
+//! hits this because `and` is not short-circuiting: `typeof(x) = 'string' and x =~ '/y'` evaluates
+//! the regex even when x is a number or array.
+
+use hogvm::{sync_execute, ExecutionContext, Program, VmFailure};
+use serde_json::{json, Value};
+
+const OP_REGEX: i64 = 23;
+const OP_NOT_REGEX: i64 = 24;
+const OP_IREGEX: i64 = 25;
+const OP_TRUE: i64 = 29;
+const OP_FALSE: i64 = 30;
+const OP_NULL: i64 = 31;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+const OP_ARRAY: i64 = 43;
+
+fn run_result(bytecode: Vec<Value>) -> Result<Value, VmFailure> {
+ let program = Program::new(bytecode).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program);
+ sync_execute(&ctx, false)
+}
+
+fn run(bytecode: Vec<Value>) -> Value {
+ run_result(bytecode).expect("execution succeeds")
+}
+
+// Stack order: the pattern is pushed first, then the value (the VM pops the value first).
+fn regex_of(pattern: &str, push_value: &[Value], op: i64) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1), json!(OP_STRING), json!(pattern)];
+ bc.extend_from_slice(push_value);
+ bc.extend_from_slice(&[json!(op), json!(OP_RETURN)]);
+ bc
+}
+
+#[test]
+fn numbers_and_booleans_coerce_to_their_string_form() {
+ // 42 stringifies to "42" and matches, instead of erroring on the non-string operand.
+ assert_eq!(
+ run(regex_of("4", &[json!(OP_INTEGER), json!(42)], OP_REGEX)),
+ Value::Bool(true)
+ );
+ assert_eq!(
+ run(regex_of("^9", &[json!(OP_INTEGER), json!(42)], OP_REGEX)),
+ Value::Bool(false)
+ );
+ // `true` stringifies to "true"; IREGEX matches it case-insensitively.
+ assert_eq!(
+ run(regex_of("TRUE", &[json!(OP_TRUE)], OP_IREGEX)),
+ Value::Bool(true)
+ );
+}
+
+#[test]
+fn falsy_operands_never_match() {
+ // Unlike `like` (null -> "null"), the regex family applies the reference's `pattern && value`
+ // guard, so any falsy operand short-circuits to no match — regardless of the pattern.
+ let falsy_values: &[(&str, &[Value])] = &[
+ ("null", &[json!(OP_NULL)]),
+ ("zero", &[json!(OP_INTEGER), json!(0)]),
+ ("empty string", &[json!(OP_STRING), json!("")]),
+ ("false", &[json!(OP_FALSE)]),
+ ];
+ for (label, push) in falsy_values {
+ // `.*` matches any string, so a non-false result would mean the guard failed to fire.
+ assert_eq!(
+ run(regex_of(".*", push, OP_REGEX)),
+ Value::Bool(false),
+ "value {label} =~ '.*' should be false"
+ );
+ // `!~` is the negation: a falsy value never matches, so `!~` is true.
+ assert_eq!(
+ run(regex_of(".*", push, OP_NOT_REGEX)),
+ Value::Bool(true),
+ "value {label} !~ '.*' should be true"
+ );
+ }
+ // A falsy pattern (empty string) also short-circuits even against a truthy value.
+ assert_eq!(
+ run(regex_of("", &[json!(OP_STRING), json!("hello")], OP_REGEX)),
+ Value::Bool(false)
+ );
+}
+
+#[test]
+fn container_operands_still_error() {
+ // Arrays are truthy, so they reach string coercion — which errors, matching the deliberate
+ // `like`/`ilike` container deviation (the reference would stringify to "a,b,c", but no real
+ // program relies on regex-matching a stringified container).
+ let empty_array = &[json!(OP_ARRAY), json!(0)];
+ assert!(
+ run_result(regex_of("x", empty_array, OP_REGEX)).is_err(),
+ "regex against an array operand should error"
+ );
+}