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.

5.9 KB
Raw Blame
//! 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_EQ: i64 = 11;
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_DICT: i64 = 42;
const OP_ARRAY: i64 = 43;
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
    );
}

/// The Node shadow binding needs the TS answer by default, and the cohort evaluator opts into
/// ClickHouse's.
#[test]
fn a_boolean_equals_a_string_as_text_only_under_the_opt_in() {
    let control_or_test = vec![
        json!(OP_STRING),
        json!("control"),
        json!(OP_STRING),
        json!("test"),
        json!(OP_ARRAY),
        json!(2),
    ];
    let call = |name: &str| vec![json!(OP_CALL_GLOBAL), json!(name), json!(2)];
    let off = || vec![json!(OP_FALSE)];
    let cases = [
        (
            "==",
            vec![
                json!(OP_STRING),
                json!("variant"),
                json!(OP_FALSE),
                json!(OP_EQ),
            ],
            json!(true),
            json!(false),
        ),
        (
            "has",
            [control_or_test.clone(), off(), call("has")].concat(),
            json!(true),
            json!(false),
        ),
        (
            "indexOf",
            [control_or_test.clone(), off(), call("indexOf")].concat(),
            json!(1),
            json!(0),
        ),
        (
            "in()",
            [off(), control_or_test, call("in")].concat(),
            json!(true),
            json!(false),
        ),
    ];
    for (label, body, by_default, as_text) in cases {
        let context = || {
            let bytecode = [
                vec![json!("_H"), json!(1)],
                body.clone(),
                vec![json!(OP_RETURN)],
            ]
            .concat();
            ExecutionContext::with_defaults(Program::new(bytecode).expect("valid program"))
                .with_coercing_comparisons()
        };
        let result = sync_execute(&context(), false).expect("execution succeeds");
        assert_eq!(result, by_default, "{label}");
        let result = sync_execute(&context().with_boolean_text_equality(), false)
            .expect("execution succeeds");
        assert_eq!(result, as_text, "{label}");
    }
}