: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(cymbal): support semver suppression rule comparisons (#81731)
Hugues Pouillot824d8b3ae08f
diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rsindex 1311cf8e4ece..5e3395b1627b 100644--- a/rust/common/hogvm/src/context.rs+++ b/rust/common/hogvm/src/context.rs@@ -45,8 +45,8 @@ pub struct ExecutionContext {pub max_stack_depth: usize,pub max_heap_size: usize,pub max_steps: usize,- /// Opt-in comparison semantics. `false` (the default) is the legacy/reference behavior shared by- /// every existing consumer (e.g. `cymbal`): ordering ops require numeric operands and `Eq`+ /// Opt-in comparison semantics. `false` (the default) is the strict behavior shared by+ /// consumers such as `cymbal`: ordering ops accept numbers and numeric arrays, while `Eq`/// compares temporals structurally. `true` makes ordering coerce across types and order temporals/// by epoch, and `Eq` compare two temporals by epoch — the ClickHouse/Python-TS-aligned semantics/// the realtime-cohort evaluator needs. Set via [`ExecutionContext::with_coercing_comparisons`].@@ -151,8 +151,8 @@ impl ExecutionContext {}/// Opt into coercing comparison semantics (cross-type ordering coercion + epoch ordering/equality- /// of temporals). Off by default; only the realtime-cohort evaluator opts in, so existing- /// consumers like `cymbal` keep the legacy strict behavior. See [`Self::coerce_comparisons`].+ /// of temporals). Off by default; only the realtime-cohort evaluator opts in, so consumers like+ /// `cymbal` keep strict behavior. See [`Self::coerce_comparisons`].pub fn with_coercing_comparisons(mut self) -> Self {self.coerce_comparisons = true;selfdiff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rsindex 05e4fb6bc7f7..07d272c0aeeb 100644--- a/rust/common/hogvm/src/values.rs+++ b/rust/common/hogvm/src/values.rs@@ -440,8 +440,9 @@ pub(crate) fn temporal_seconds_pair(/// 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 legacy path where a non-number operand errors, so this coercion does NOT change their-/// behavior. The semantics here match the Python/TS reference VMs (and ClickHouse for temporals).+/// 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).////// 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.diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rsindex 7beccd76a676..332f22a1fb92 100644--- a/rust/common/hogvm/src/vm.rs+++ b/rust/common/hogvm/src/vm.rs@@ -1,5 +1,6 @@use std::any::Any;use std::cell::RefCell;+use std::cmp::Ordering;use std::rc::Rc;use indexmap::IndexMap;@@ -929,26 +930,31 @@ 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+ /// `Gt`/`GtEq`/`Lt`/`LtEq` arm. The default path accepts numbers and lexicographically ordered+ /// numeric arrays. `sortableSemver` returns a numeric array, so server-side property filters need+ /// this narrow array case even when they retain strict comparison semantics. Other non-number+ /// operands still error, which lets cymbal auto-disable malformed rules. Only when the context+ /// opts into coercing comparisons does a non-number operand reach [`compare_values`]. `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.- let (a, b): (Num, Num) = (self.pop_stack_as()?, self.pop_stack_as()?);- return self.push_stack(Num::binary_op(op, &a, &b)?);- }let a = self.pop_stack()?;let b = self.pop_stack()?;// Scope the immutable heap borrows so the result is owned before the `&mut self` push.let result = {let a_lit = a.deref(&self.heap)?;let b_lit = b.deref(&self.heap)?;- compare_values(op, a_lit, b_lit, &self.heap)?+ if self.context.coerce_comparisons {+ compare_values(op, a_lit, b_lit, &self.heap)?+ } else if let (HogLiteral::Array(a_values), HogLiteral::Array(b_values)) =+ (a_lit, b_lit)+ {+ let ordering = compare_numeric_arrays(a_values, b_values, &self.heap)?;+ HogLiteral::Boolean(ordering_matches(op, ordering))+ } else {+ let a_num: &Num = a_lit.try_as()?;+ let b_num: &Num = b_lit.try_as()?;+ Num::binary_op(op, a_num, b_num)?+ }};self.push_stack(result)}@@ -1526,6 +1532,36 @@ fn failure(error: VmError, vm: Option<&HogVM>, step: usize) -> VmFailure {}}+fn compare_numeric_arrays(+ a: &[HogValue],+ b: &[HogValue],+ heap: &VmHeap,+) -> Result<Ordering, VmError> {+ for value in a.iter().chain(b) {+ let _: &Num = value.deref(heap)?.try_as()?;+ }++ for (a_value, b_value) in a.iter().zip(b) {+ let a_num: &Num = a_value.deref(heap)?.try_as()?;+ let b_num: &Num = b_value.deref(heap)?.try_as()?;+ let ordering = a_num.compare(b_num);+ if ordering != Ordering::Equal {+ return Ok(ordering);+ }+ }+ Ok(a.len().cmp(&b.len()))+}++fn ordering_matches(op: NumOp, ordering: Ordering) -> bool {+ match op {+ NumOp::Gt => ordering.is_gt(),+ NumOp::Gte => ordering.is_ge(),+ NumOp::Lt => ordering.is_lt(),+ NumOp::Lte => ordering.is_le(),+ _ => unreachable!("ordering comparison requires a comparison operation"),+ }+}+/// The reference's telemetry opcode label: `"<num>/<SCREAMING_SNAKE_NAME>"` (e.g. `2/CALL_GLOBAL`).fn op_telemetry_name(op: &Operation) -> String {let pascal = format!("{op:?}");diff --git a/rust/common/hogvm/tests/numeric_coercion.rs b/rust/common/hogvm/tests/numeric_coercion.rsindex f86fb5a19491..4c4b5a31f88d 100644--- a/rust/common/hogvm/tests/numeric_coercion.rs+++ b/rust/common/hogvm/tests/numeric_coercion.rs@@ -17,6 +17,7 @@ const OP_STRING: i64 = 32;const OP_INTEGER: i64 = 33;const OP_FLOAT: i64 = 34;const OP_RETURN: i64 = 38;+const OP_ARRAY: i64 = 43;/// `left <op> right`. The compiler emits operands as `[right…, left…, op]`.fn compare(left: &[Value], right: &[Value], op: i64) -> Vec<Value> {@@ -56,6 +57,12 @@ fn boolean(b: bool) -> Vec<Value> {vec![json!(if b { OP_TRUE } else { OP_FALSE })]}+fn array(values: &[Vec<Value>]) -> Vec<Value> {+ let mut bytecode = values.iter().flatten().cloned().collect::<Vec<_>>();+ bytecode.extend([json!(OP_ARRAY), json!(values.len())]);+ bytecode+}+#[test]fn number_vs_numeric_string_coerces_the_string() {// The exact cohort case: `bc_num gt "10"` (threshold compiled as a string).@@ -211,6 +218,23 @@ fn legacy_default_keeps_strict_comparisons_for_other_consumers() {run_legacy(compare(&boolean(true), &int(0), OP_GT)).is_err(),"bool vs number must error on the legacy path, not coerce",);+ for (label, left, right) in [+ (+ "shared numeric prefix",+ array(&[int(1), string("invalid")]),+ array(&[int(1)]),+ ),+ (+ "different numeric prefix",+ array(&[int(2), string("invalid")]),+ array(&[int(1)]),+ ),+ ] {+ assert!(+ run_legacy(compare(&left, &right, OP_GT)).is_err(),+ "a nonnumeric array suffix must error after a {label}",+ );+ }// Pure numeric comparisons are identical on both paths.assert_eq!(run_legacy(compare(&int(20), &int(10), OP_GT)).unwrap(),diff --git a/rust/common/hogvm/tests/stl.rs b/rust/common/hogvm/tests/stl.rsindex 0d5c326bedf5..881aca5a28b0 100644--- a/rust/common/hogvm/tests/stl.rs+++ b/rust/common/hogvm/tests/stl.rs@@ -8,6 +8,12 @@ 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_STRING: i64 = 32;const OP_INTEGER: i64 = 33;const OP_RETURN: i64 = 38;@@ -56,6 +62,33 @@ fn call_str(name: &str, arg: &str) -> Value {run(call(name, &[str_lit(arg)]))}+#[test]+fn sortable_semver_arrays_support_every_comparison_operation() {+ // Tilde, caret, and wildcard ranges compile to a lower-bound GT_EQ and an upper-bound LT.+ let cases = [+ ("equals", OP_EQ, "1.2.3", "1.2.3", true),+ ("equals", OP_EQ, "1.2.3", "1.2.4", false),+ ("not equals", OP_NOT_EQ, "1.2.3", "1.2.4", true),+ ("not equals", OP_NOT_EQ, "1.2.3", "1.2.3", false),+ ("greater than", OP_GT, "2.0.0", "1.9.9", true),+ ("greater than", OP_GT, "1.9.9", "2.0.0", false),+ ("greater than or equal", OP_GT_EQ, "2.0.0", "2.0.0", true),+ ("greater than or equal", OP_GT_EQ, "1.9.9", "2.0.0", false),+ ("less than", OP_LT, "2.9.0", "2.10.0", true),+ ("less than", OP_LT, "2.10.0", "2.10.0", false),+ ("less than or equal", OP_LT_EQ, "2.10.0", "2.10.0", true),+ ("less than or equal", OP_LT_EQ, "2.10.1", "2.10.0", false),+ ];++ for (label, operation, left, right, expected) in cases {+ let mut comparison = call("sortableSemver", &[str_lit(right)]);+ comparison.extend(call("sortableSemver", &[str_lit(left)]));+ comparison.push(json!(operation));++ assert_eq!(run(comparison), json!(expected), "{left} {label} {right}");+ }+}+#[test]fn crypto_and_encoding_known_answers() {// Known-answer vectors — these are RFC/spec fixed, so they pin both our wiring and the