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.

17.5 KB
Raw Blame
//! Differential parity for the event-name fan-out gate: the same event sequence with gating ON
//! (evaluate only the event's name bucket) and OFF (full behavioral sweep) must yield byte-identical
//! `cf_behavioral` and the same leaf transitions.

// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
#![allow(clippy::disallowed_methods)]

use std::collections::BTreeMap;

use chrono_tz::UTC;
use cohort_stream_processor::consumers::CohortStreamEvent;
use cohort_stream_processor::filters::{CohortId, TeamFilters, TeamFiltersBuilder, TeamId};
use cohort_stream_processor::stage1::LeafTransition;
use cohort_stream_processor::store::{CohortStore, StoreConfig};
use cohort_stream_processor::workers::{process_event_gated, EventNameGating, EventOutcome};
use metrics_exporter_prometheus::PrometheusBuilder;
use serde_json::{json, Value};
use tempfile::TempDir;
use uuid::Uuid;

const TEAM: i32 = 7;
const PARTITION: u16 = 0;

const PAGEVIEW_HASH: [u8; 16] = *b"pageviewhash0001";
const PURCHASE_HASH: [u8; 16] = *b"purchasehash0002";
const ZERO_HASH: [u8; 16] = *b"zerohash00000003";
const ZERODOT_HASH: [u8; 16] = *b"zerodothash00004";
const PAGEVIEW_MULTIPLE_HASH: [u8; 16] = *b"pageviewmult0006";
const PERSON_HASH: [u8; 16] = *b"planhash00000005";

/// A `performed_event` leaf whose bytecode roots at `event == <event_name>`.
fn behavioral_leaf(event_name: &str, hash: &str) -> Value {
    json!({
        "type": "behavioral",
        "value": "performed_event",
        "key": event_name,
        "time_value": 7,
        "time_interval": "day",
        "conditionHash": hash,
        "bytecode": ["_H", 1, 32, event_name, 32, "event", 1, 1, 11],
    })
}

/// A `performed_event_multiple` leaf on `event_name`: the same `event == <name>` matcher bytecode,
/// but a count window that drives the `BehavioralDailyBuckets` write path rather than
/// `BehavioralSingle`. `gte 1` makes a single matching event flip it to member.
fn behavioral_multiple_leaf(event_name: &str, hash: &str) -> Value {
    json!({
        "type": "behavioral",
        "value": "performed_event_multiple",
        "key": event_name,
        "time_value": 7,
        "time_interval": "day",
        "operator": "gte",
        "operator_value": 1,
        "conditionHash": hash,
        "bytecode": ["_H", 1, 32, event_name, 32, "event", 1, 1, 11],
    })
}

/// A `plan == "pro"` person leaf, so the gate is shown not to disturb the person path.
fn person_leaf() -> Value {
    json!({
        "type": "person",
        "key": "plan",
        "value": "pro",
        "operator": "exact",
        "conditionHash": "planhash00000005",
        "bytecode": ["_H", 1, 32, "pro", 32, "plan", 32, "properties", 32, "person", 1, 3, 11],
    })
}

/// Four behavioral leaves across distinct event names (two numeric-looking) plus a person leaf.
fn catalog() -> TeamFilters {
    let mut builder = TeamFiltersBuilder::default();
    builder
        .add_cohort(
            CohortId(1),
            TeamId(TEAM),
            &json!({
                "properties": {
                    "type": "AND",
                    "values": [
                        behavioral_leaf("$pageview", "pageviewhash0001"),
                        behavioral_leaf("purchase", "purchasehash0002"),
                        behavioral_leaf("0", "zerohash00000003"),
                        behavioral_leaf("0.0", "zerodothash00004"),
                        person_leaf(),
                    ],
                }
            }),
        )
        .unwrap();
    builder.freeze(UTC)
}

/// A catalog whose behavioral condition reads `properties`, so a build parses that payload at all:
/// a team whose conditions name no payload never parses one, and so can never fail on a malformed
/// one.
fn properties_reading_catalog() -> TeamFilters {
    let mut leaf = behavioral_leaf("$pageview", "pageviewhash0001");
    // event == "$pageview" AND properties.x == "1"
    leaf["bytecode"] = json!([
        "_H",
        1,
        32,
        "$pageview",
        32,
        "event",
        1,
        1,
        11,
        32,
        "1",
        32,
        "x",
        32,
        "properties",
        1,
        2,
        11,
        3,
        2,
    ]);
    let mut builder = TeamFiltersBuilder::default();
    builder
        .add_cohort(
            CohortId(1),
            TeamId(TEAM),
            &json!({ "properties": { "type": "AND", "values": [leaf, person_leaf()] } }),
        )
        .unwrap();
    builder.freeze(UTC)
}

/// A `$pageview` bucket holding two distinct behavioral leaves — a `performed_event`
/// (`BehavioralSingle`) and a `performed_event_multiple` (`BehavioralDailyBuckets`) — so one event
/// name maps to 2 conditionHashes across 2 write paths.
fn multi_condition_catalog() -> TeamFilters {
    let mut builder = TeamFiltersBuilder::default();
    builder
        .add_cohort(
            CohortId(1),
            TeamId(TEAM),
            &json!({
                "properties": {
                    "type": "AND",
                    "values": [
                        behavioral_leaf("$pageview", "pageviewhash0001"),
                        behavioral_multiple_leaf("$pageview", "pageviewmult0006"),
                    ],
                }
            }),
        )
        .unwrap();
    builder.freeze(UTC)
}

/// Only the `$pageview` bucket needs `pdi`, so the two buckets get different globals plans.
fn pdi_catalog() -> TeamFilters {
    let pdi_leaf = json!({
        "type": "behavioral",
        "value": "performed_event",
        "key": "$pageview",
        "time_value": 7,
        "time_interval": "day",
        "conditionHash": "pdipageviewhash1",
        // event == "$pageview" AND pdi.person.properties.plan == "pro"
        "bytecode": [
            "_H", 1,
            32, "$pageview", 32, "event", 1, 1, 11,
            32, "pro", 32, "plan", 32, "properties", 32, "person", 32, "pdi", 1, 4, 11,
            3, 2,
        ],
    });
    let mut builder = TeamFiltersBuilder::default();
    builder
        .add_cohort(
            CohortId(1),
            TeamId(TEAM),
            &json!({
                "properties": {
                    "type": "AND",
                    "values": [pdi_leaf, behavioral_leaf("purchase", "purchasehash0002")],
                }
            }),
        )
        .unwrap();
    builder.freeze(UTC)
}

fn event(person: Uuid, event_name: &str, offset: i64, timestamp: &str) -> CohortStreamEvent {
    CohortStreamEvent {
        team_id: TEAM,
        person_id: person.to_string(),
        distinct_id: "d".to_string(),
        uuid: format!("uuid-{offset}"),
        event: event_name.to_string(),
        timestamp: timestamp.to_string(),
        properties: Some("{}".to_string()),
        // Never matches the `pro` person leaf, so the person path writes state but flips nothing.
        person_properties: Some(r#"{"plan":"free"}"#.to_string()),
        elements_chain: None,
        source_offset: offset,
        source_partition: 0,
        redirected_from: None,
        redirect_hops: 0,
    }
}

fn temp_store() -> (TempDir, CohortStore) {
    let dir = TempDir::new().unwrap();
    let store = CohortStore::open(&StoreConfig {
        path: dir.path().join("db"),
        ..StoreConfig::default()
    })
    .unwrap();
    (dir, store)
}

/// The partition's full `cf_behavioral`, keyed by encoded key bytes. Two byte-identical runs compare
/// equal regardless of write order.
fn dump_stage1(store: &CohortStore) -> BTreeMap<Vec<u8>, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut cursor: Option<Vec<u8>> = None;
    loop {
        let page = store
            .scan_behavioral(PARTITION, cursor.as_deref(), 4096)
            .unwrap();
        if page.is_empty() {
            break;
        }
        let page_len = page.len();
        cursor = page.last().map(|(key, _)| key.encode().to_vec());
        for (key, value) in page {
            out.insert(key.encode().to_vec(), value);
        }
        if page_len < 4096 {
            break;
        }
    }
    out
}

/// Sort transitions by debug form so two runs compare as multisets — the gated and full sweeps push
/// applies in different orders.
fn sorted_transitions(transitions: &[LeafTransition]) -> Vec<LeafTransition> {
    let mut sorted = transitions.to_vec();
    sorted.sort_by_cached_key(|t| format!("{t:?}"));
    sorted
}

/// Feeds each event to two independent stores, gating ON and OFF, and asserts parity after every
/// step. Gating is the only varying axis, and it varies the globals dict too: the gated arm builds
/// from one bucket's plan and the ungated arm from the union over every bucket.
struct GatingParity {
    _on_dir: TempDir,
    _off_dir: TempDir,
    on_store: CohortStore,
    off_store: CohortStore,
    /// What each arm emitted on the last [`Self::feed`]. Two arms that agree on every output can
    /// still disagree on the work they did to get there, and only the counters show that.
    on_metrics: String,
    off_metrics: String,
}

impl GatingParity {
    fn new() -> Self {
        let (on_dir, on_store) = temp_store();
        let (off_dir, off_store) = temp_store();
        Self {
            _on_dir: on_dir,
            _off_dir: off_dir,
            on_store,
            off_store,
            on_metrics: String::new(),
            off_metrics: String::new(),
        }
    }

    fn feed(
        &mut self,
        filters: &TeamFilters,
        event: &CohortStreamEvent,
        label: &str,
    ) -> EventOutcome {
        let on_recorder = PrometheusBuilder::new().build_recorder();
        let on_handle = on_recorder.handle();
        let on = metrics::with_local_recorder(&on_recorder, || {
            process_event_gated(
                PARTITION,
                &self.on_store,
                filters,
                event,
                EventNameGating::Enabled,
            )
        })
        .unwrap();
        self.on_metrics = on_handle.render();

        let off_recorder = PrometheusBuilder::new().build_recorder();
        let off_handle = off_recorder.handle();
        let off = metrics::with_local_recorder(&off_recorder, || {
            process_event_gated(
                PARTITION,
                &self.off_store,
                filters,
                event,
                EventNameGating::Disabled,
            )
        })
        .unwrap();
        self.off_metrics = off_handle.render();

        assert_eq!(on.skipped, off.skipped, "{label}: skip reason");
        assert_eq!(on.event_ms, off.event_ms, "{label}: event_ms");
        assert_eq!(
            sorted_transitions(&on.transitions),
            sorted_transitions(&off.transitions),
            "{label}: transitions",
        );
        let (mut on_sched, mut off_sched) = (on.schedules.clone(), off.schedules.clone());
        on_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));
        off_sched.sort_by_key(|(key, deadline)| (key.encode(), *deadline));
        assert_eq!(on_sched, off_sched, "{label}: schedules");
        assert_eq!(
            dump_stage1(&self.on_store),
            dump_stage1(&self.off_store),
            "{label}: cf_behavioral bytes",
        );
        on
    }
}

#[test]
fn gating_matches_full_sweep_across_matching_missing_and_numeric_names() {
    let mut p = GatingParity::new();
    let alice = Uuid::from_u128(1);
    let filters = catalog();

    let s1 = p.feed(
        &filters,
        &event(alice, "$pageview", 0, "2026-05-26 10:00:00.000000"),
        "s1 $pageview",
    );
    assert_eq!(s1.transitions.len(), 1, "s1: only the $pageview leaf flips");
    assert_eq!(s1.transitions[0].condition_hash, PAGEVIEW_HASH);

    // `"0"` must not cross-match the `"0.0"` leaf: same-type string compare, no numeric coercion.
    let s2 = p.feed(
        &filters,
        &event(alice, "0", 1, "2026-05-26 11:00:00.000000"),
        "s2 numeric 0",
    );
    assert_eq!(
        s2.transitions.len(),
        1,
        "s2: \"0\" does not cross-match \"0.0\""
    );
    assert_eq!(s2.transitions[0].condition_hash, ZERO_HASH);

    let s3 = p.feed(
        &filters,
        &event(alice, "0.0", 2, "2026-05-26 12:00:00.000000"),
        "s3 numeric 0.0",
    );
    assert_eq!(
        s3.transitions.len(),
        1,
        "s3: \"0.0\" does not cross-match \"0\""
    );
    assert_eq!(s3.transitions[0].condition_hash, ZERODOT_HASH);

    let s4 = p.feed(
        &filters,
        &event(alice, "purchase", 3, "2026-05-26 13:00:00.000000"),
        "s4 purchase",
    );
    assert_eq!(s4.transitions.len(), 1);
    assert_eq!(s4.transitions[0].condition_hash, PURCHASE_HASH);

    let s5 = p.feed(
        &filters,
        &event(alice, "no_such_event", 4, "2026-05-26 14:00:00.000000"),
        "s5 unmatched",
    );
    assert!(
        s5.transitions.is_empty(),
        "s5: an unmatched event name flips nothing",
    );
}

#[test]
fn gating_matches_full_sweep_on_a_multi_condition_event_name_bucket() {
    // A hot event like `$pageview` is referenced by many cohorts, so its real bucket holds several
    // conditionHashes. The single-leaf-per-name catalog above never exercises a 2+ condition bucket,
    // so a gate that dropped or double-counted a hash within one bucket would diverge from the full
    // sweep silently. Feed a `$pageview` into a bucket holding both a `BehavioralSingle` and a
    // `BehavioralDailyBuckets` leaf: `feed` asserts byte-identical `cf_behavioral` (covering the
    // daily-bucket write path), and both leaves must flip.
    let filters = multi_condition_catalog();
    assert_eq!(
        filters.behavioral_by_event_name["$pageview"]
            .conditions
            .len(),
        2,
        "the $pageview bucket holds both conditionHashes",
    );

    let mut p = GatingParity::new();
    let alice = Uuid::from_u128(1);
    let outcome = p.feed(
        &filters,
        &event(alice, "$pageview", 0, "2026-05-26 10:00:00.000000"),
        "multi-condition $pageview",
    );

    let mut got: Vec<[u8; 16]> = outcome
        .transitions
        .iter()
        .map(|t| t.condition_hash)
        .collect();
    got.sort_unstable();
    let mut expected = [PAGEVIEW_HASH, PAGEVIEW_MULTIPLE_HASH];
    expected.sort_unstable();
    assert_eq!(
        got,
        expected.to_vec(),
        "both leaves in the bucket flip — the single and the daily-bucket write paths",
    );
}

/// Were a malformed payload to skip the whole event, the gate would become a correctness switch:
/// with gating on an unbucketed event is never parsed and so never skipped, while the ungated sweep
/// parses it, fails, and skips it, leaving the person record on one side only.
///
/// The counters carry the other half. The outcomes here are equal whether the gated arm skipped the
/// parse or ran it and failed, so only `stage1_globals_builds_total` distinguishes them — and
/// skipping the parse on an event nothing can match is the saving this gate exists for.
#[test]
fn a_malformed_properties_payload_keeps_both_arms_identical() {
    let mut p = GatingParity::new();
    let filters = properties_reading_catalog();
    let alice = Uuid::from_u128(1);

    let mut broken = event(alice, "no_such_event", 0, "2026-05-26 10:00:00.000000");
    broken.properties = Some("{not json".to_string());
    // Matches the `pro` person leaf, so the person side flipping is visible as a transition.
    broken.person_properties = Some(r#"{"plan":"pro"}"#.to_string());

    let outcome = p.feed(&filters, &broken, "malformed properties, unbucketed name");
    assert_eq!(
        outcome.skipped, None,
        "a malformed `properties` is behavioral-only data and must not skip the event",
    );
    assert_eq!(
        outcome.transitions.len(),
        1,
        "the person side still ran: {:?}",
        outcome.transitions,
    );
    assert_eq!(outcome.transitions[0].condition_hash, PERSON_HASH);
    assert!(
        dump_stage1(&p.on_store).is_empty(),
        "the behavioral side staged a row from a payload that never parsed",
    );

    assert!(
        p.on_metrics
            .contains("stage1_globals_builds_total{result=\"no_candidates\"} 1"),
        "the gated arm built globals for an event no bucket holds: {}",
        p.on_metrics,
    );
    assert!(
        !p.on_metrics.contains("result=\"parse_error\""),
        "the gated arm parsed the payload it was supposed to skip: {}",
        p.on_metrics,
    );
    assert!(
        p.off_metrics
            .contains("stage1_globals_builds_total{result=\"parse_error\"} 1"),
        "the ungated sweep has to parse, and this payload has to fail: {}",
        p.off_metrics,
    );
}

/// Every other fixture reads only `event`, so the builder could stop emitting `pdi` under every plan
/// and they would all still pass.
#[test]
fn a_condition_reading_pdi_matches_under_both_gating_arms() {
    const PDI_HASH: [u8; 16] = *b"pdipageviewhash1";
    let mut p = GatingParity::new();
    let filters = pdi_catalog();
    let alice = Uuid::from_u128(1);

    // The `purchase` bucket plans no `pdi`, so this exercises the narrower plan first.
    let purchase = p.feed(
        &filters,
        &event(alice, "purchase", 0, "2026-05-26 10:00:00.000000"),
        "purchase",
    );
    assert_eq!(purchase.transitions.len(), 1);
    assert_eq!(purchase.transitions[0].condition_hash, PURCHASE_HASH);

    let mut matching = event(alice, "$pageview", 1, "2026-05-26 11:00:00.000000");
    matching.person_properties = Some(r#"{"plan":"pro"}"#.to_string());
    let pageview = p.feed(&filters, &matching, "$pageview reading pdi");
    assert_eq!(
        pageview.transitions.len(),
        1,
        "the pdi-reading leaf did not flip: {:?}",
        pageview.transitions,
    );
    assert_eq!(pageview.transitions[0].condition_hash, PDI_HASH);
}