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): rust vm parity fixes and shadow comparison cleanup (#68355)

José Sequeiraa132e0af8de0
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
index b6edfa265737..bed982887fc1 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.test.ts
@@ -170,6 +170,19 @@ describe('RustVmShadow', () => {
expect(await outcomeCounts()).toEqual({ dropped: 1, match: 1 })
})
+ it('functions calling nondeterministic stl fns are skipped at capture, not compared', async () => {
+ // CALL_GLOBAL randomFloat — two executions legitimately differ, comparison is meaningless.
+ shadow.capture({ ...capture('fn-rng', { name: 'a' }, 'ok'), bytecode: ['_H', 1, 2, 'randomFloat', 0, 38] })
+ // A string literal containing a fn name (preceded by the STRING op 32) must not skip.
+ shadow.capture({ ...capture('fn-str', { name: 'b' }, 'now'), bytecode: ['_H', 1, 32, 'now', 38] })
+
+ mockHogvmNode.executeBatch.mockResolvedValue([{ result: 'now', durationUs: 5 }])
+ await shadow.flush()
+
+ expect(mockHogvmNode.executeBatch).toHaveBeenCalledTimes(1)
+ expect(await outcomeCounts()).toEqual({ skipped_nondeterministic: 1, match: 1 })
+ })
+
it('captures beyond the buffer cap are counted as dropped, not as rust errors', async () => {
for (let i = 0; i < 10_001; i++) {
shadow.capture(capture('fn-a', { name: 'a' }, 'ok'))
diff --git a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
index 259a829268c8..64cbb0058a56 100644
--- a/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
+++ b/nodejs/src/cdp/hog-transformations/rust-vm-shadow.ts
@@ -21,6 +21,10 @@ import { KNOWN_BOT_IP_LIST, KNOWN_BOT_UA_LIST } from './bots/bots'
// The Rust VM budgets steps, not wall-clock time; generous so it never trips before the Node VM's
// timeout would.
const RUST_MAX_STEPS = 1_000_000
+// STL functions whose output legitimately differs between two executions — programs calling them
+// can never be compared, so they're skipped at capture time.
+const NONDETERMINISTIC_FNS = new Set(['randomFloat', 'generateUUIDv4', 'now', 'today'])
+const CALL_GLOBAL_OP = 2
// Safety cap so a stalled flush can't grow the buffer unboundedly.
const MAX_BUFFER_SIZE = 10_000
@@ -56,6 +60,7 @@ export type ShadowOutcome =
| 'status_mismatch'
| 'rust_error'
| 'skipped_unsupported'
+ | 'skipped_nondeterministic'
| 'dropped'
export interface ShadowNodeResult {
@@ -116,6 +121,7 @@ export class RustVmShadow {
private buffer: ShadowCapturedInvocation[] = []
private module_: HogvmNodeModule | null | undefined = undefined
private flushInFlight = false
+ private nondeterministicByFunction = new Map<string, boolean>()
constructor(
private options: {
@@ -133,6 +139,10 @@ export class RustVmShadow {
}
public capture(item: ShadowCapturedInvocation): void {
+ if (this.isNondeterministic(item.functionId, item.bytecode)) {
+ shadowComparison.inc({ outcome: 'skipped_nondeterministic' })
+ return
+ }
if (this.buffer.length >= MAX_BUFFER_SIZE) {
shadowComparison.inc({ outcome: 'dropped' })
return
@@ -140,6 +150,26 @@ export class RustVmShadow {
this.buffer.push(item)
}
+ // Every string literal in hog bytecode is preceded by the STRING op (32); only CALL_GLOBAL (2)
+ // is directly followed by the function name, so this pair scan cannot false-positive on string
+ // literals that merely contain a function name.
+ private isNondeterministic(functionId: string, bytecode: HogBytecode): boolean {
+ let cached = this.nondeterministicByFunction.get(functionId)
+ if (cached === undefined) {
+ cached = bytecode.some(
+ (token, index) =>
+ token === CALL_GLOBAL_OP &&
+ typeof bytecode[index + 1] === 'string' &&
+ NONDETERMINISTIC_FNS.has(bytecode[index + 1] as string)
+ )
+ if (this.nondeterministicByFunction.size >= MAX_BUFFER_SIZE) {
+ this.nondeterministicByFunction.clear()
+ }
+ this.nondeterministicByFunction.set(functionId, cached)
+ }
+ return cached
+ }
+
/**
* Execute everything captured since the last flush on the Rust VM and compare. Runs off the
* hot path (the transformer's afterBatch drain); callers wrap it in `mirrorCall` so it can
diff --git a/rust/common/hogvm/node/src/exec.rs b/rust/common/hogvm/node/src/exec.rs
index 449469606841..c3ff264aee8c 100644
--- a/rust/common/hogvm/node/src/exec.rs
+++ b/rust/common/hogvm/node/src/exec.rs
@@ -11,6 +11,10 @@ use crate::ext_fns::transformation_ext_fns;
const PARALLEL_CHUNK_SIZE: usize = 500;
+// The Node VM has no heap ceiling; the crate's 1MB default trips on real events with large
+// properties. A cap (not a preallocation), and rayon bounds how many contexts run at once.
+const MAX_HEAP_SIZE_BYTES: usize = 64 * 1024 * 1024;
+
#[napi(object)]
pub struct HogExecResult {
/// The program's return value; None when the execution errored.
@@ -55,7 +59,12 @@ fn run_chunk(tokens: &[Value], chunk: &[Value], max_steps: Option<usize>) -> Vec
}
};
- let mut ctx = ExecutionContext::with_defaults(program).with_ext_fns(transformation_ext_fns());
+ // Coercing comparisons are the TS reference's semantics (unifyComparisonTypes): ordering
+ // coerces across number/string/boolean/null instead of erroring.
+ let mut ctx = ExecutionContext::with_defaults(program)
+ .with_ext_fns(transformation_ext_fns())
+ .with_coercing_comparisons();
+ ctx.max_heap_size = MAX_HEAP_SIZE_BYTES;
if let Some(max_steps) = max_steps {
ctx.max_steps = max_steps;
}
@@ -180,6 +189,37 @@ mod tests {
assert!(results[0].error.is_some());
}
+ #[test]
+ fn comparisons_coerce_booleans_and_nulls_like_the_reference() {
+ // rev > 0 where rev is boolean (or-chains yield booleans): true coerces to 1.
+ let gt_true_zero = vec![
+ json!("_H"),
+ json!(1),
+ json!(33),
+ json!(0),
+ json!(29),
+ json!(13),
+ json!(38),
+ ];
+ let results = run_batch(&gt_true_zero, &[json!({})], false, None);
+ assert_eq!(results[0].error, None);
+ assert_eq!(results[0].result, Some(json!(true)));
+
+ // octet < 0 where octet is null: null coerces to 0.
+ let lt_zero_null = vec![
+ json!("_H"),
+ json!(1),
+ json!(33),
+ json!(0),
+ json!(31),
+ json!(15),
+ json!(38),
+ ];
+ let results = run_batch(&lt_zero_null, &[json!({})], false, None);
+ assert_eq!(results[0].error, None);
+ assert_eq!(results[0].result, Some(json!(false)));
+ }
+
#[test]
fn max_steps_budget_is_enforced() {
let results = run_batch(&add_program(), &[json!({})], false, Some(1));
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 3383a0ac5dc1..c37f2da15b37 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -936,7 +936,10 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"toUnixTimestamp",
native_func(|vm, args| {
assert(!args.is_empty(), "toUnixTimestamp requires at least one argument")?;
- let secs = temporal_seconds(vm, &args[0], "toUnixTimestamp")?;
+ let secs = match unix_timestamp_seconds(vm, &args, "toUnixTimestamp")? {
+ Some(secs) => secs,
+ None => return Ok(HogLiteral::Null.into()),
+ };
Ok(HogLiteral::Number(Num::Float(secs)).into())
}),
),
@@ -944,7 +947,10 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"toUnixTimestampMilli",
native_func(|vm, args| {
assert(!args.is_empty(), "toUnixTimestampMilli requires at least one argument")?;
- let secs = temporal_seconds(vm, &args[0], "toUnixTimestampMilli")?;
+ let secs = match unix_timestamp_seconds(vm, &args, "toUnixTimestampMilli")? {
+ Some(secs) => secs,
+ None => return Ok(HogLiteral::Null.into()),
+ };
Ok(HogLiteral::Number(Num::Integer((secs * 1000.0) as i64)).into())
}),
),
@@ -1884,6 +1890,31 @@ fn make_hog_datetime(dt: f64, zone: &str) -> Result<HogValue, VmError> {
}
// Epoch seconds of a Hog Date/DateTime value (the `dt` field, or UTC midnight for a Date).
+// toUnixTimestamp/toUnixTimestampMilli accept Date/DateTime like every temporal fn, but the
+// reference also parses ISO strings (honoring the optional zone arg) and yields NaN — observably
+// null once serialized — for unparseable ones, so a string that fails to parse maps to None.
+fn unix_timestamp_seconds(
+ vm: &HogVM,
+ args: &[HogValue],
+ name: &str,
+) -> Result<Option<f64>, VmError> {
+ if let HogLiteral::String(s) = args[0].deref(&vm.heap)? {
+ // The reference does `zone || 'UTC'`, so a null zone (an absent event
+ // property) silently falls back to UTC; any other non-string zone is an
+ // invalid luxon zone there, yielding NaN — observably null.
+ let zone = match args.get(1) {
+ Some(arg) => match arg.deref(&vm.heap)? {
+ HogLiteral::String(z) => Some(z.clone()),
+ HogLiteral::Null => None,
+ _ => return Ok(None),
+ },
+ None => None,
+ };
+ return Ok(parse_datetime_to_seconds(s, zone.as_deref()).ok());
+ }
+ temporal_seconds(vm, &args[0], name).map(Some)
+}
+
fn temporal_seconds(vm: &HogVM, value: &HogValue, name: &str) -> Result<f64, VmError> {
value
.deref(&vm.heap)?
diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rs
index 11569e001f26..eae320e6d054 100644
--- a/rust/common/hogvm/src/values.rs
+++ b/rust/common/hogvm/src/values.rs
@@ -130,8 +130,18 @@ impl HogValue {
match lit {
HogLiteral::Object(map) => {
- let key: &str = chain[0].deref(heap)?.try_as()?;
- let Some(found) = map.get(key) else {
+ // The reference VM keys objects with whatever scalar the program used (a JS Map),
+ // and integer keys are common (`{96: 'x'}`). We store string keys, so coerce
+ // numbers to their string form for lookup, matching the construction-time coercion.
+ // Any other key type (null included — `props[inputs.x]` with an unset input) is a
+ // 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::Number(n) => map.get(&num_key_string(n)),
+ _ => None,
+ };
+ let Some(found) = found else {
return Ok(None);
};
found.get_nested(&chain[1..], heap)
@@ -417,9 +427,15 @@ pub fn compare_values(
return Num::binary_op(op, &Num::Float(a_secs), &Num::Float(b_secs));
}
- use HogLiteral::{Boolean, Number, String as HString};
+ use HogLiteral::{Boolean, Null, Number, String as HString};
match (a, b) {
(Number(x), Number(y)) => Num::binary_op(op, x, y),
+ // JS relational coercion: null behaves as 0 against numbers and booleans.
+ (Null, Number(y)) => Num::binary_op(op, &Num::Integer(0), y),
+ (Number(x), Null) => Num::binary_op(op, x, &Num::Integer(0)),
+ (Null, Null) => Num::binary_op(op, &Num::Integer(0), &Num::Integer(0)),
+ (Null, Boolean(y)) => Num::binary_op(op, &Num::Integer(0), &bool_to_num(*y)),
+ (Boolean(x), Null) => Num::binary_op(op, &bool_to_num(*x), &Num::Integer(0)),
(Number(x), HString(s)) => Num::binary_op(op, x, &Num::from_str(s)?),
(HString(s), Number(y)) => Num::binary_op(op, &Num::from_str(s)?, y),
(Boolean(x), Number(y)) => Num::binary_op(op, &bool_to_num(*x), y),
@@ -817,6 +833,14 @@ impl Display for Closure {
/// `ExecutionContext::execute_native_function_call` correctly maps the return
/// value of the native function call to the VM's memory space, making values
/// constructed with this method safe to return from native extensions.
+// The string form a numeric object key coerces to, shared by dict construction and lookup.
+pub(crate) fn num_key_string(n: &Num) -> String {
+ match n {
+ Num::Integer(i) => i.to_string(),
+ Num::Float(f) => format!("{f}"),
+ }
+}
+
pub fn construct_free_standing(current: JsonValue, depth: usize) -> Result<HogValue, VmError> {
if depth > MAX_JSON_SERDE_DEPTH {
return Err(VmError::OutOfResource(
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 6552d79b3f3f..181372fd3fd0 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -265,23 +265,23 @@ impl<'a> HogVM<'a> {
self.push_stack(result)?;
}
Operation::Plus => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (a, b) = (self.pop_arith_operand()?, self.pop_arith_operand()?);
self.push_stack(Num::binary_op(NumOp::Add, &a, &b)?)?;
}
Operation::Minus => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (a, b) = (self.pop_arith_operand()?, self.pop_arith_operand()?);
self.push_stack(Num::binary_op(NumOp::Sub, &a, &b)?)?;
}
Operation::Mult => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (a, b) = (self.pop_arith_operand()?, self.pop_arith_operand()?);
self.push_stack(Num::binary_op(NumOp::Mul, &a, &b)?)?;
}
Operation::Div => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (a, b) = (self.pop_arith_operand()?, self.pop_arith_operand()?);
self.push_stack(Num::binary_op(NumOp::Div, &a, &b)?)?;
}
Operation::Mod => {
- let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (a, b) = (self.pop_arith_operand()?, self.pop_arith_operand()?);
self.push_stack(Num::binary_op(NumOp::Mod, &a, &b)?)?;
}
Operation::Eq => {
@@ -299,19 +299,19 @@ impl<'a> HogVM<'a> {
Operation::Lt => self.compare_op(NumOp::Lt)?,
Operation::LtEq => self.compare_op(NumOp::Lte)?,
Operation::Like => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (val, pat) = self.pop_like_operands()?;
self.push_stack(like(val, pat, true)?)?;
}
Operation::Ilike => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (val, pat) = self.pop_like_operands()?;
self.push_stack(like(val, pat, false)?)?;
}
Operation::NotLike => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (val, pat) = self.pop_like_operands()?;
self.push_stack(!like(val, pat, true)?)?;
}
Operation::NotIlike => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
+ let (val, pat) = self.pop_like_operands()?;
self.push_stack(!like(val, pat, false)?)?;
}
Operation::In => {
@@ -448,7 +448,14 @@ impl<'a> HogVM<'a> {
for _ in 0..element_count {
// Note we don't put references into collections ever
values.push(self.pop_stack()?);
- keys.push(self.pop_stack_as::<String>()?);
+ // Numeric keys coerce to their string form (the reference keys a JS Map with
+ // the raw scalar; see values::num_key_string).
+ let key_val = self.pop_stack()?;
+ let key = match key_val.deref(&self.heap)? {
+ HogLiteral::Number(n) => crate::values::num_key_string(n),
+ lit => lit.try_as::<str>()?.to_string(),
+ };
+ keys.push(key);
}
// keys/values were popped in reverse (stack order), so reverse the zip to restore
// the source insertion order in the IndexMap.
@@ -856,16 +863,45 @@ impl<'a> HogVM<'a> {
}
}
- /// `Gt`/`GtEq`/`Lt`/`LtEq` arm. The default (legacy) path requires numeric operands and errors
- /// otherwise — the behavior `cymbal` and every other existing shared-crate consumer relies on
- /// (a non-number operand erroring is what lets cymbal auto-disable a malformed rule). Only when
- /// the context opts into coercing comparisons (the realtime-cohort evaluator, via
- /// [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons))
- /// does a non-`Number` operand reach [`compare_values`]' coercion instead of erroring. `a` is the
- /// top of the stack.
- // `=~`/`!~` (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.
+ // The reference VM applies JS arithmetic coercion, where null behaves as 0 (`5 - null` is
+ // 5); real transformations do arithmetic on absent event properties.
+ fn pop_arith_operand(&mut self) -> Result<Num, VmError> {
+ let val = self.pop_stack()?;
+ match val.deref(&self.heap)? {
+ HogLiteral::Null => Ok(Num::Integer(0)),
+ lit => lit.try_as::<Num>().cloned(),
+ }
+ }
+
+ // The reference VM funnels both like/ilike operands through JS String coercion (the pattern
+ // via String(...), the value via RegExp.test(...)), so null, booleans, and numbers stringify
+ // instead of erroring — `null like '%x%'` tests the string "null". Containers stay errors: the
+ // reference would produce "[object Object]", which no real program relies on.
+ fn pop_like_operands(&mut self) -> Result<(String, String), VmError> {
+ let val = self.pop_stack()?;
+ let pat = self.pop_stack()?;
+ Ok((self.js_string_coerce(&val)?, self.js_string_coerce(&pat)?))
+ }
+
+ fn js_string_coerce(&self, value: &HogValue) -> Result<String, VmError> {
+ match value.deref(&self.heap)? {
+ HogLiteral::String(s) => Ok(s.clone()),
+ HogLiteral::Null => Ok("null".to_string()),
+ HogLiteral::Boolean(b) => Ok(b.to_string()),
+ HogLiteral::Number(n) => Ok(match n {
+ Num::Integer(i) => i.to_string(),
+ Num::Float(f) => format!("{f}"),
+ }),
+ other => Err(VmError::InvalidValue(
+ other.type_name().to_string(),
+ "String".to_string(),
+ )),
+ }
+ }
+
+ /// `=~`/`!~` (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.
fn regex_op(&mut self, case_sensitive: bool, negate: bool) -> Result<(), VmError> {
let val = self.pop_stack()?;
let pat = self.pop_stack()?;
@@ -885,6 +921,13 @@ impl<'a> HogVM<'a> {
self.push_stack(HogLiteral::Boolean(matched ^ negate))
}
+ /// `Gt`/`GtEq`/`Lt`/`LtEq` arm. The default (legacy) path requires numeric operands and errors
+ /// otherwise — the behavior `cymbal` and every other existing shared-crate consumer relies on
+ /// (a non-number operand erroring is what lets cymbal auto-disable a malformed rule). Only when
+ /// the context opts into coercing comparisons (the realtime-cohort evaluator, via
+ /// [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons))
+ /// does a non-`Number` operand reach [`compare_values`]' coercion instead of erroring. `a` is the
+ /// top of the stack.
fn compare_op(&mut self, op: NumOp) -> Result<(), VmError> {
if !self.context.coerce_comparisons {
// Legacy/reference path: both operands must be `Number` or this errors.
diff --git a/rust/common/hogvm/tests/js_coercion.rs b/rust/common/hogvm/tests/js_coercion.rs
new file mode 100644
index 000000000000..250ea7df127f
--- /dev/null
+++ b/rust/common/hogvm/tests/js_coercion.rs
@@ -0,0 +1,151 @@
+//! Reference-VM (JS) coercion semantics observed diverging on production transformations:
+//! integer dict keys ({96: 'x'} — a JS Map keyed by the raw scalar), null behaving as 0 in
+//! arithmetic, and toUnixTimestamp parsing ISO strings.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_MINUS: i64 = 7;
+const OP_NULL: i64 = 31;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+const OP_DICT: i64 = 42;
+const OP_GET_PROPERTY: i64 = 45;
+
+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")
+}
+
+#[test]
+fn integer_dict_keys_construct_and_look_up() {
+ // {96: 'x'}[96] — both the construction and the lookup coerce the numeric key.
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_INTEGER),
+ json!(96),
+ json!(OP_STRING),
+ json!("x"),
+ json!(OP_DICT),
+ json!(1),
+ json!(OP_INTEGER),
+ json!(96),
+ json!(OP_GET_PROPERTY),
+ json!(OP_RETURN),
+ ];
+ assert_eq!(run(bc), json!("x"));
+}
+
+#[test]
+fn null_behaves_as_zero_in_arithmetic() {
+ // 5 - null = 5 (operands push null first, then 5; MINUS pops top-first).
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_NULL),
+ json!(OP_INTEGER),
+ json!(5),
+ json!(OP_MINUS),
+ json!(OP_RETURN),
+ ];
+ assert_eq!(run(bc), json!(5));
+
+ // null - null = 0
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_NULL),
+ json!(OP_NULL),
+ json!(OP_MINUS),
+ json!(OP_RETURN),
+ ];
+ assert_eq!(run(bc), json!(0));
+}
+
+#[test]
+fn null_property_key_is_a_miss_not_an_error() {
+ // props[inputs.x] with an unset input: the reference's Map.get(null) misses.
+ let bc = vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_INTEGER),
+ json!(96),
+ json!(OP_STRING),
+ json!("x"),
+ json!(OP_DICT),
+ json!(1),
+ json!(OP_NULL),
+ json!(OP_GET_PROPERTY),
+ json!(OP_RETURN),
+ ];
+ assert_eq!(run(bc), Value::Null);
+}
+
+fn to_unix_timestamp_of(value: Value) -> Vec<Value> {
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(OP_STRING),
+ value,
+ json!(OP_CALL_GLOBAL),
+ json!("toUnixTimestamp"),
+ json!(1),
+ json!(OP_RETURN),
+ ]
+}
+
+#[test]
+fn to_unix_timestamp_parses_iso_strings() {
+ assert_eq!(
+ run(to_unix_timestamp_of(json!("2026-07-03T12:00:00.000Z"))),
+ json!(1783080000.0)
+ );
+}
+
+#[test]
+fn to_unix_timestamp_of_unparseable_string_is_null() {
+ // The reference yields NaN, which serializes to null.
+ assert_eq!(run(to_unix_timestamp_of(json!("not a date"))), Value::Null);
+}
+
+fn to_unix_timestamp_with_zone(ts: Value, push_zone: &[Value]) -> Vec<Value> {
+ let mut bc = vec![json!("_H"), json!(1), json!(OP_STRING), ts];
+ bc.extend_from_slice(push_zone);
+ bc.extend_from_slice(&[
+ json!(OP_CALL_GLOBAL),
+ json!("toUnixTimestamp"),
+ json!(2),
+ json!(OP_RETURN),
+ ]);
+ bc
+}
+
+#[test]
+fn to_unix_timestamp_null_zone_falls_back_to_utc() {
+ // The reference does `zone || 'UTC'`, so a null zone (an absent event
+ // property) parses the naive timestamp as UTC instead of erroring.
+ assert_eq!(
+ run(to_unix_timestamp_with_zone(
+ json!("2026-07-03T12:00:00"),
+ &[json!(OP_NULL)]
+ )),
+ json!(1783080000.0)
+ );
+}
+
+#[test]
+fn to_unix_timestamp_non_string_zone_is_null() {
+ // Any other non-string zone is an invalid luxon zone in the reference,
+ // yielding NaN — observably null — rather than an error.
+ assert_eq!(
+ run(to_unix_timestamp_with_zone(
+ json!("2026-07-03T12:00:00"),
+ &[json!(OP_INTEGER), json!(5)]
+ )),
+ Value::Null
+ );
+}
diff --git a/rust/common/hogvm/tests/like_null.rs b/rust/common/hogvm/tests/like_null.rs
new file mode 100644
index 000000000000..7036277e367f
--- /dev/null
+++ b/rust/common/hogvm/tests/like_null.rs
@@ -0,0 +1,63 @@
+//! The like/ilike operand family must coerce non-string scalars the way the TS reference does
+//! (String(...) / RegExp.test(...)): null stringifies to "null" instead of erroring. Real hog code
+//! hits this because `and` is not short-circuiting — `x != null and lower(x) like '%y%'` evaluates
+//! the like even when x is null.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+const OP_LIKE: i64 = 17;
+const OP_ILIKE: i64 = 18;
+const OP_NOT_LIKE: i64 = 19;
+const OP_NOT_ILIKE: i64 = 20;
+const OP_NULL: i64 = 31;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+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 value first).
+fn like_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 null_coerces_to_the_string_null_across_the_like_family() {
+ // String(null) is "null" in the reference, so it only matches null-ish
+ // patterns; the ILIKE variants match it case-insensitively.
+ let cases: &[(i64, &str, bool)] = &[
+ (OP_LIKE, "%null%", true),
+ (OP_LIKE, "%NULL%", false),
+ (OP_LIKE, "%evaluation%", false),
+ (OP_ILIKE, "%null%", true),
+ (OP_ILIKE, "%NULL%", true),
+ (OP_ILIKE, "%evaluation%", false),
+ (OP_NOT_LIKE, "%null%", false),
+ (OP_NOT_LIKE, "%evaluation%", true),
+ (OP_NOT_ILIKE, "%NULL%", false),
+ (OP_NOT_ILIKE, "%evaluation%", true),
+ ];
+ for (op, pattern, expected) in cases {
+ assert_eq!(
+ run(like_of(pattern, &[json!(OP_NULL)], *op)),
+ Value::Bool(*expected),
+ "op {op} with pattern {pattern}"
+ );
+ }
+}
+
+#[test]
+fn numbers_coerce_to_their_string_form() {
+ assert_eq!(
+ run(like_of("4%", &[json!(OP_INTEGER), json!(42)], OP_LIKE)),
+ Value::Bool(true)
+ );
+}