: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
fix(hogvm): unify int and float equality (#91844)
Matheus Batistac3333ef16b24
diff --git a/common/hogvm/__tests__/__snapshots__/numericEquality.hoge b/common/hogvm/__tests__/__snapshots__/numericEquality.hogenew file mode 100644index 000000000000..0874f62d28a9--- /dev/null+++ b/common/hogvm/__tests__/__snapshots__/numericEquality.hoge@@ -0,0 +1,6 @@+["_H", 1, 33, 1, 34, 1.0, 33, 1000, 34, 1000.0, 32, "1.0", 36, 1, 36, 0, 11, 2, "print", 1, 35, 36, 1, 36, 0, 12, 2,+"print", 1, 35, 36, 1, 33, 2, 11, 2, "print", 1, 35, 36, 3, 36, 2, 11, 2, "print", 1, 35, 36, 1, 29, 11, 2, "print", 1,+35, 36, 4, 36, 0, 11, 2, "print", 1, 35, 36, 1, 32, "1", 11, 2, "print", 1, 35, 33, 1, 33, 2, 43, 2, 36, 1, 21, 2,+"print", 1, 35, 33, 1, 33, 2, 43, 2, 36, 1, 2, "has", 2, 2, "print", 1, 35, 34, 1.0, 34, 2.0, 43, 2, 33, 2, 2,+"indexOf", 2, 2, "print", 1, 35, 36, 0, 36, 1, 2, "equals", 2, 2, "print", 1, 35, 36, 0, 36, 1, 2, "notEquals", 2, 2,+"print", 1, 35, 35, 35, 35, 35, 35]diff --git a/common/hogvm/__tests__/__snapshots__/numericEquality.js b/common/hogvm/__tests__/__snapshots__/numericEquality.jsnew file mode 100644index 000000000000..e682ba07e83e--- /dev/null+++ b/common/hogvm/__tests__/__snapshots__/numericEquality.js@@ -0,0 +1,60 @@+function print (...args) { console.log(...args.map(__printHogStringOutput)) }+function notEquals(a, b) { return a !== b }+function indexOf (arrOrString, elem) { if (Array.isArray(arrOrString)) { return arrOrString.indexOf(elem) + 1 } else { return 0 } }+function has (arr, elem) { if (!Array.isArray(arr) || arr.length === 0) { return false } return arr.includes(elem) }+function equals(a, b) { return a === b }+function __printHogStringOutput(obj) { if (typeof obj === 'string') { return obj } return __printHogValue(obj) }+function __printHogValue(obj, marked = new Set()) {+ if (typeof obj === 'object' && obj !== null && obj !== undefined) {+ if (marked.has(obj) && !__isHogDateTime(obj) && !__isHogDate(obj) && !__isHogError(obj)) { return 'null'; }+ marked.add(obj);+ try {+ if (Array.isArray(obj)) {+ if (obj.__isHogTuple) { return obj.length < 2 ? `tuple(${obj.map((o) => __printHogValue(o, marked)).join(', ')})` : `(${obj.map((o) => __printHogValue(o, marked)).join(', ')})`; }+ return `[${obj.map((o) => __printHogValue(o, marked)).join(', ')}]`;+ }+ if (__isHogDateTime(obj)) { const millis = String(obj.dt); return `DateTime(${millis}${millis.includes('.') ? '' : '.0'}, ${__escapeString(obj.zone)})`; }+ if (__isHogDate(obj)) return `Date(${obj.year}, ${obj.month}, ${obj.day})`;+ if (__isHogError(obj)) { return `${String(obj.type)}(${__escapeString(obj.message)}${obj.payload ? `, ${__printHogValue(obj.payload, marked)}` : ''})`; }+ if (obj instanceof Map) { return `{${Array.from(obj.entries()).map(([key, value]) => `${__printHogValue(key, marked)}: ${__printHogValue(value, marked)}`).join(', ')}}`; }+ return `{${Object.entries(obj).map(([key, value]) => `${__printHogValue(key, marked)}: ${__printHogValue(value, marked)}`).join(', ')}}`;+ } finally {+ marked.delete(obj);+ }+ } else if (typeof obj === 'boolean') return obj ? 'true' : 'false';+ else if (obj === null || obj === undefined) return 'null';+ else if (typeof obj === 'string') return __escapeString(obj);+ if (typeof obj === 'function') return `fn<${__escapeIdentifier(obj.name || 'lambda')}(${obj.length})>`;+ return obj.toString();+}+function __isHogError(obj) {return obj && obj.__hogError__ === true}+function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }+function __isHogDate(obj) { return obj && obj.__hogDate__ === true }+function __escapeString(value) {+ const singlequoteEscapeCharsMap = { '\b': '\\b', '\f': '\\f', '\r': '\\r', '\n': '\\n', '\t': '\\t', '\0': '\\0', '\v': '\\v', '\\': '\\\\', "'": "\\'" }+ return `'${value.split('').map((c) => singlequoteEscapeCharsMap[c] || c).join('')}'`;+}+function __escapeIdentifier(identifier) {+ const backquoteEscapeCharsMap = { '\b': '\\b', '\f': '\\f', '\r': '\\r', '\n': '\\n', '\t': '\\t', '\0': '\\0', '\v': '\\v', '\\': '\\\\', '`': '``' }+ if (typeof identifier === 'number') return identifier.toString();+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier)) return identifier;+ return `\`${identifier.split('').map((c) => backquoteEscapeCharsMap[c] || c).join('')}\``;+}++let one = 1;+let oneFloat = 1.0;+let thousand = 1000;+let thousandFloat = 1000.0;+let floatString = "1.0";+print((one == oneFloat));+print((one != oneFloat));+print((2 == oneFloat));+print((thousand == thousandFloat));+print((true == oneFloat));+print((one == floatString));+print(("1" == oneFloat));+print(([1, 2].includes(oneFloat)));+print(has([1, 2], oneFloat));+print(indexOf([1.0, 2.0], 2));+print(equals(one, oneFloat));+print(notEquals(one, oneFloat));diff --git a/common/hogvm/__tests__/__snapshots__/numericEquality.stdout b/common/hogvm/__tests__/__snapshots__/numericEquality.stdoutnew file mode 100644index 000000000000..f95d7793896a--- /dev/null+++ b/common/hogvm/__tests__/__snapshots__/numericEquality.stdout@@ -0,0 +1,12 @@+true+false+false+true+true+true+true+true+true+2+true+falsediff --git a/common/hogvm/__tests__/numericEquality.hog b/common/hogvm/__tests__/numericEquality.hognew file mode 100644index 000000000000..98e1f1852a70--- /dev/null+++ b/common/hogvm/__tests__/numericEquality.hog@@ -0,0 +1,20 @@+// Integers and floats are one numeric domain for equality and membership: `1 == 1.0`.+// Operands are `let`-bound so the compiler emits the Eq/Float opcodes instead of folding.+let one := 1+let oneFloat := 1.0+let thousand := 1000+let thousandFloat := 1000.0+let floatString := '1.0'++print(one == oneFloat) // true+print(one != oneFloat) // false+print(2 == oneFloat) // false+print(thousand == thousandFloat) // true+print(true == oneFloat) // true+print(one == floatString) // true+print('1' == oneFloat) // true+print(oneFloat in [1, 2]) // true+print(has([1, 2], oneFloat)) // true+print(indexOf([1.0, 2.0], 2)) // 2+print(equals(one, oneFloat)) // true+print(notEquals(one, oneFloat)) // falsediff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rsindex 9ba2b5c72cbe..a114431e7746 100644--- a/rust/common/hogvm/src/stl.rs+++ b/rust/common/hogvm/src/stl.rs@@ -2758,6 +2758,8 @@ fn is_hog_empty(lit: &HogLiteral) -> bool {// `equals`/`notEquals` use strict equality (reference `a === b`): no cross-type coercion, so a// number and a numeric string are never equal. Differs from the coercing `==`/`!=` opcodes.+// Strictness applies across types, not within them: the int and float variants of a number unify,+// which matches the reference `===` where every number is f64.fn strict_equals(vm: &HogVM, a: &HogValue, b: &HogValue) -> Result<bool, VmError> {Ok(a.deref(&vm.heap)? == b.deref(&vm.heap)?)}diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rsindex 07d272c0aeeb..ae49ad80c9d1 100644--- a/rust/common/hogvm/src/values.rs+++ b/rust/common/hogvm/src/values.rs@@ -26,12 +26,35 @@ pub struct Upvalue {pub type UpvalueCell = Rc<RefCell<Upvalue>>;-#[derive(Debug, Clone, PartialEq)]+#[derive(Debug, Clone)]pub enum Num {Integer(i64),Float(f64),}+/// The reference VMs treat all numbers as one numeric domain, because JS has only f64 and Python's+/// `1 == 1.0` is true. Equality must therefore unify the variants. A mixed pair widens to f64 and+/// compares with IEEE `==`, which is what `Num::binary_op` does for `Lt`/`Gt`, so `a == b` stays+/// consistent with `!(a < b) && !(a > b)`. Two integers compare as i64, so values beyond 2^53 stay+/// exact against each other. A mixed pair above 2^53 rounds like the TS reference; Python compares+/// mixed pairs exactly and can disagree there.+///+/// Those two rules together are NOT transitive above 2^53: `Integer(2^53 + 1) == Float(2^53)` and+/// `Float(2^53) == Integer(2^53)`, yet the two integers stay unequal. Never feed `Num` to `dedup`,+/// `sort_by`, `binary_search` or a hash set, where that would make the result depend on input order.+///+/// Do not assume `Num::compare` agrees. It widens too, but then applies `total_cmp`, a total order+/// that ranks NaN and separates `-0.0` from `0`. IEEE `==` instead keeps NaN unequal to NaN and+/// calls `0` and `-0.0` equal, so the two disagree on those two inputs.+impl PartialEq for Num {+ fn eq(&self, other: &Self) -> bool {+ match (self, other) {+ (Num::Integer(a), Num::Integer(b)) => a == b,+ _ => self.to_float() == other.to_float(),+ }+ }+}+#[derive(Debug, Clone, PartialEq)]pub enum Callable {Local(LocalCallable),@@ -176,9 +199,12 @@ impl HogValue {}pub fn equals(&self, rhs: &HogValue, heap: &VmHeap) -> Result<HogLiteral, VmError> {- // Legacy structural equality, shared by every consumer. The cohort evaluator's temporal- // epoch-equality lives behind the opt-in flag in `HogVM::eq_op`, not here, so `Eq`/`in`/`has`- // stay unchanged for `cymbal` and other shared-crate users.+ // Top-level structural equality with numeric unification, shared by every consumer:+ // `1 == 1.0` is true here because both reference VMs treat all numbers as one domain (see+ // `PartialEq for Num`). Only the two operands are dereferenced, so a nested array or object+ // compares by heap reference, which matches the TS bytecode VM. The cohort evaluator's+ // temporal epoch-equality is the only opt-in part, and it lives behind the flag in+ // `HogVM::eq_op`, not here.let (lhs, rhs) = (self.deref(heap)?, rhs.deref(heap)?);lhs.equals(rhs)}@@ -346,6 +372,8 @@ impl HogLiteral {}fn equals(&self, rhs: &HogLiteral) -> Result<HogLiteral, VmError> {+ // Coercion runs first, so a numeric string equals a number. Membership (`in`, `has`,+ // `indexOf`) compares elements through here and inherits that, unlike the reference VMs.let Ok((lhs, rhs)) = self.coerce_types(rhs) else {return Ok(false.into()); // If we can't coerce types, they are not equal};@@ -438,11 +466,13 @@ pub(crate) fn temporal_seconds_pair(/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, two concerns in order:////// OPT-IN ONLY: this is reached exclusively from the coercing `compare_op` path, which the VM takes-/// only when the context sets [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons)-/// — today just the realtime-cohort evaluator. Every other shared-crate consumer (e.g. `cymbal`)-/// keeps the strict path where operands other than numbers and numeric arrays error, so this coercion-/// does NOT change their behavior. The semantics here match the Python/TS reference VMs (and-/// ClickHouse for temporals).+/// only when the context sets [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons),+/// today just the realtime-cohort evaluator. Every other shared-crate consumer (e.g. `cymbal`) keeps+/// the strict ordering path where operands other than numbers and numeric arrays error, so this+/// coercion of ORDERING operands does NOT change their behavior. It says nothing about equality:+/// `Eq`/`NotEq` unify the int and float variants of a number on every path (see+/// [`PartialEq for Num`](Num)). The semantics here match the Python/TS reference VMs (and ClickHouse+/// for temporals).////// 1. A temporal comparison ([`temporal_seconds_pair`]) orders by epoch seconds to match ClickHouse/// and the Python/TS reference VMs; see the [`crate::stl`] module note.@@ -929,4 +959,41 @@ mod tests {));}}++ #[test]+ fn int_float_equality_unifies() {+ assert_eq!(Num::Integer(1), Num::Float(1.0));+ assert_eq!(Num::Float(1.0), Num::Integer(1));+ assert_ne!(Num::Integer(2), Num::Float(1.0));+ assert_ne!(Num::Float(1.0), Num::Integer(2));+ // Signed zero is the second input where `Num::compare` disagrees; IEEE `==` unifies it.+ assert_eq!(Num::Integer(0), Num::Float(-0.0));+ }++ #[test]+ fn nan_is_never_equal() {+ // A NaN literal cannot be written in bytecode JSON, so the NaN contract is pinned here+ // rather than in a VM-level test. The VM can still produce one, for example `0.0 / 0.0`.+ assert_ne!(Num::Float(f64::NAN), Num::Float(f64::NAN));+ assert_ne!(Num::Integer(1), Num::Float(f64::NAN));+ assert_ne!(Num::Float(f64::NAN), Num::Integer(1));+ }++ #[test]+ fn integer_pairs_stay_exact_beyond_f64() {+ // Both operands are integers, so they must compare as i64. Widening everything to f64 would+ // round both to the same value and call them equal.+ assert_ne!(Num::Integer(1 << 53), Num::Integer((1 << 53) + 1));+ }++ #[test]+ fn mixed_pairs_beyond_2p53_follow_the_ts_oracle() {+ // Deliberate, documented divergence from Python: widening an integer past 2^53 rounds it, so+ // this pair is equal here and in the TS reference (which only has f64), while Python compares+ // int against float exactly and calls it unequal.+ assert_eq!(+ Num::Integer(9_007_199_254_740_993),+ Num::Float(9_007_199_254_740_992.0)+ );+ }}diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rsindex f3159e7234dd..afbef49b733f 100644--- a/rust/common/hogvm/src/vm.rs+++ b/rust/common/hogvm/src/vm.rs@@ -959,9 +959,10 @@ impl<'a> HogVM<'a> {self.push_stack(result)}- /// `Eq`/`NotEq` core. The default path is the legacy structural equality every existing- /// shared-crate consumer relies on. Only when the context opts into coercing comparisons (the- /// realtime-cohort evaluator) does a temporal pair compare by epoch seconds to match ClickHouse+ /// `Eq`/`NotEq` core. Both paths apply structural equality with numeric unification, so+ /// `1 == 1.0` holds for every shared-crate consumer (see [`PartialEq for Num`](crate::Num)).+ /// The flag gates only what sits on top: when the context opts into coercing comparisons (the+ /// realtime-cohort evaluator), a temporal pair compares by epoch seconds to match ClickHouse/// (`is_date_exact`); every non-temporal pair is unchanged either way.////// "Temporal pair" is [`temporal_seconds_pair`] — the same predicate [`compare_values`] uses fordiff --git a/rust/common/hogvm/tests/numeric_coercion.rs b/rust/common/hogvm/tests/numeric_coercion.rsindex 4c4b5a31f88d..2f89d63328e1 100644--- a/rust/common/hogvm/tests/numeric_coercion.rs+++ b/rust/common/hogvm/tests/numeric_coercion.rs@@ -1,16 +1,21 @@-//! Coverage for ordering-comparison coercion (`Gt`/`GtEq`/`Lt`/`LtEq`) over mixed scalar types.-//! Cohort numeric leaves compile the threshold as a string constant, so this must match the Python-//! (`unify_comparison_types`) and TS (`unifyComparisonTypes`) coercion exactly.+//! Coverage for numeric coercion across the comparison surface: ordering (`Gt`/`GtEq`/`Lt`/`LtEq`)+//! over mixed scalar types, and equality (`Eq`/`NotEq`) plus membership (`in`, `has`, `indexOf`)+//! over mixed int/float operands. Cohort numeric leaves compile the threshold as a string constant,+//! so this must match the Python (`unify_comparison_types`) and TS (`unifyComparisonTypes`)+//! coercion exactly.use hogvm::{sync_execute, ExecutionContext, Program, VmFailure};use serde_json::{json, Value};// Opcode numeric values (mirror common/hogvm/python/operation.py).+const OP_CALL_GLOBAL: i64 = 2;const OP_EQ: i64 = 11;+const OP_NOT_EQ: i64 = 12;const OP_GT: i64 = 13;const OP_GT_EQ: i64 = 14;const OP_LT: i64 = 15;const OP_LT_EQ: i64 = 16;+const OP_IN: i64 = 21;const OP_TRUE: i64 = 29;const OP_FALSE: i64 = 30;const OP_STRING: i64 = 32;@@ -63,6 +68,157 @@ fn array(values: &[Vec<Value>]) -> Vec<Value> {bytecode}+/// `needle in haystack`. The VM pops the needle first, so the haystack is emitted first.+fn in_op(needle: &[Value], haystack: &[Value]) -> Vec<Value> {+ compare(needle, haystack, OP_IN)+}++/// `name(args…)`. The compiler emits the args in order, then the call.+fn call(name: &str, args: &[Vec<Value>]) -> Vec<Value> {+ let mut bc = vec![json!("_H"), json!(1)];+ bc.extend(args.iter().flatten().cloned());+ bc.extend([+ json!(OP_CALL_GLOBAL),+ json!(name),+ json!(args.len()),+ json!(OP_RETURN),+ ]);+ bc+}++/// Numeric equality is unconditional, so it is not gated behind `with_coercing_comparisons`. Every+/// equality expectation must therefore hold on the coercing path and on the default path that+/// cymbal and every other shared-crate consumer runs.+fn assert_both_paths(bytecode: Vec<Value>, expected: Value, label: &str) {+ assert_eq!(run(bytecode.clone()), expected, "coercing path: {label}");+ assert_eq!(+ run_legacy(bytecode).expect("legacy execution succeeds"),+ expected,+ "default path: {label}",+ );+}++#[test]+fn int_float_equality_is_numeric_on_both_paths() {+ // `Integer(1)` and `Float(1.0)` are one value to both reference VMs, and the Rust VM's own+ // ordering ops already widen mixed pairs, so equality has to agree: otherwise `1 == 1.0` is+ // false while `1 >= 1.0` is true.+ assert_both_paths(+ compare(&int(1), &float(1.0), OP_EQ),+ json!(true),+ "1 == 1.0",+ );+ assert_both_paths(+ compare(&int(1), &float(1.0), OP_NOT_EQ),+ json!(false),+ "1 != 1.0",+ );+ assert_both_paths(+ compare(&int(2), &float(1.0), OP_EQ),+ json!(false),+ "2 == 1.0",+ );+ // A `1e3`-style literal compiles to a Float, so it must still equal the integer 1000.+ assert_both_paths(+ compare(&int(1000), &float(1000.0), OP_EQ),+ json!(true),+ "1000 == 1000.0",+ );+}++#[test]+fn string_coercion_equality_unifies_numeric_variants() {+ // The Number/String arm parses "1.0" to a Float, which then has to equal the integer operand.+ assert_both_paths(+ compare(&int(1), &string("1.0"), OP_EQ),+ json!(true),+ "1 == '1.0'",+ );+ assert_both_paths(+ compare(&string("1"), &float(1.0), OP_EQ),+ json!(true),+ "'1' == 1.0",+ );+ // Two strings short-circuit as strings rather than being parsed, matching both references.+ assert_both_paths(+ compare(&string("1"), &string("1.0"), OP_EQ),+ json!(false),+ "'1' == '1.0'",+ );+}++#[test]+fn bool_number_equality_widens() {+ assert_both_paths(+ compare(&boolean(true), &float(1.0), OP_EQ),+ json!(true),+ "true == 1.0",+ );+ assert_both_paths(+ compare(&boolean(false), &float(0.0), OP_EQ),+ json!(true),+ "false == 0.0",+ );+}++#[test]+fn array_equality_is_element_wise_numeric() {+ assert_both_paths(+ compare(+ &array(&[int(1), int(2)]),+ &array(&[float(1.0), float(2.0)]),+ OP_EQ,+ ),+ json!(true),+ "[1, 2] == [1.0, 2.0]",+ );+ assert_both_paths(+ compare(&array(&[int(1)]), &array(&[float(2.0)]), OP_EQ),+ json!(false),+ "[1] == [2.0]",+ );+}++#[test]+fn membership_uses_numeric_equality() {+ let ints = array(&[int(1), int(2)]);+ let floats = array(&[float(1.0), float(2.0)]);++ assert_both_paths(in_op(&float(1.0), &ints), json!(true), "1.0 in [1, 2]");+ assert_both_paths(in_op(&float(3.0), &ints), json!(false), "3.0 in [1, 2]");+ assert_both_paths(+ call("has", &[ints.clone(), float(1.0)]),+ json!(true),+ "has([1, 2], 1.0)",+ );+ assert_both_paths(+ call("indexOf", &[floats, int(2)]),+ json!(2),+ "indexOf([1.0, 2.0], 2)",+ );+ assert_both_paths(+ call("in", &[int(1), array(&[float(1.0)])]),+ json!(true),+ "in(1, [1.0])",+ );+}++#[test]+fn strict_equality_functions_unify_numeric_variants() {+ // `equals`/`notEquals` are the strict function forms. They stay strict across TYPES, but the+ // int/float variants of one number unify, matching the reference `===` where all numbers are f64.+ assert_both_paths(+ call("equals", &[int(1), float(1.0)]),+ json!(true),+ "equals(1, 1.0)",+ );+ assert_both_paths(+ call("notEquals", &[int(1), float(1.0)]),+ json!(false),+ "notEquals(1, 1.0)",+ );+}+#[test]fn number_vs_numeric_string_coerces_the_string() {// The exact cohort case: `bc_num gt "10"` (threshold compiled as a string).diff --git a/rust/common/hogvm/tests/parity.rs b/rust/common/hogvm/tests/parity.rsindex 998002dd6a7a..490c5874e308 100644--- a/rust/common/hogvm/tests/parity.rs+++ b/rust/common/hogvm/tests/parity.rs@@ -239,8 +239,8 @@ fn parity_report() {println!("===============================================================\n");// Regression gate: the Rust VM must match Node on every committed corpus program. The whole- // corpus passes today (36/36), so any mismatch (ran but diverged) or error (VM bailed) is a- // real parity regression and fails the test.+ // corpus passes, so any mismatch (ran but diverged) or error (VM bailed) is a real parity+ // regression and fails the test.assert!(total > 0, "no corpus programs found");assert!(mismatch.is_empty() && errored.is_empty(),