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.

feat(cohorts): build the behavioral globals by move and by plan (#95633)

Matheus Batistaf44a0fa2ad9e
diff --git a/rust/cohort-core/src/filters/loader.rs b/rust/cohort-core/src/filters/loader.rs
index 9fd43c0186ab..0b2c6eb48afa 100644
--- a/rust/cohort-core/src/filters/loader.rs
+++ b/rust/cohort-core/src/filters/loader.rs
@@ -10,8 +10,9 @@ use sqlx::PgPool;
use tracing::warn;
use crate::filters::catalog::FilterCatalog;
-use crate::filters::reverse_index::TeamFiltersBuilder;
+use crate::filters::reverse_index::{catalog_analysis_budget, TeamFiltersBuilder};
use crate::filters::{CohortId, FilterError, TeamId};
+use crate::hogvm::analysis::AnalysisBudget;
use crate::metrics::{
FILTER_CATALOG_COHORT_PARSE_ERRORS, FILTER_CATALOG_INVALID_SHAPE_HASH,
FILTER_CATALOG_TZ_FALLBACK,
@@ -48,6 +49,17 @@ pub async fn load_realtime_cohorts(pool: &PgPool) -> Result<Vec<CohortRow>, Filt
/// Group rows by team into a catalog. A cohort that fails to parse is counted, warned, and skipped
/// rather than poisoning the rest of the catalog.
pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> FilterCatalog {
+ build_catalog_within(rows, cascade_enabled, &mut catalog_analysis_budget())
+}
+
+/// [`build_catalog_from_rows`] analyzing every team's conditions against one `budget`. Teams
+/// freeze in id order, so the budget is spent the same way on every replica and the plans stay a
+/// pure function of the rows.
+fn build_catalog_within(
+ rows: Vec<CohortRow>,
+ cascade_enabled: bool,
+ budget: &mut AnalysisBudget,
+) -> FilterCatalog {
let mut builders: HashMap<TeamId, (TeamFiltersBuilder, Tz)> = HashMap::new();
for row in rows {
@@ -93,11 +105,27 @@ pub fn build_catalog_from_rows(rows: Vec<CohortRow>, cascade_enabled: bool) -> F
}
}
- FilterCatalog::from_teams(
- builders
- .into_iter()
- .map(|(team, (builder, tz))| (team, builder.freeze_with(tz, cascade_enabled))),
- )
+ let mut teams: Vec<(TeamId, (TeamFiltersBuilder, Tz))> = builders.into_iter().collect();
+ teams.sort_unstable_by_key(|(team, _)| *team);
+ // The team the budget ran out on, so an operator chasing a widened catalog has a place to start:
+ // it and every team after it in id order carry the conditions the budget refused.
+ let mut spent_on: Option<TeamId> = None;
+ let catalog = FilterCatalog::from_teams(teams.into_iter().map(|(team, (builder, tz))| {
+ let filters = builder.freeze_within(tz, cascade_enabled, budget);
+ if spent_on.is_none() && (budget.steps == 0 || budget.cells == 0) {
+ spent_on = Some(team);
+ }
+ (team, filters)
+ }));
+ if let Some(team_id) = spent_on {
+ warn!(
+ team_id = team_id.0,
+ steps_left = budget.steps,
+ cells_left = budget.cells,
+ "filter catalog analysis budget spent; the conditions it refused take every global root",
+ );
+ }
+ catalog
}
/// One persisted shape-hash column as a reconcile guard, or `None` when there is nothing to guard
@@ -278,6 +306,40 @@ mod tests {
assert_eq!(team.unique_condition_hashes.len(), 1);
}
+ #[test]
+ fn one_budget_spans_the_catalog_and_is_spent_in_team_order() {
+ use crate::hogvm::analysis::{GlobalRoot, GlobalsPlan};
+
+ // The higher team arrives first; the lower id is still the one that gets the budget.
+ let rows = vec![
+ row(1, 9, behavioral_cohort()),
+ row(2, 3, behavioral_cohort()),
+ ];
+ // STRING, STRING, GET_GLOBAL, EQ, RETURN: exactly what one condition spends.
+ let mut budget = AnalysisBudget {
+ steps: 5,
+ cells: usize::MAX,
+ };
+ let catalog = build_catalog_within(rows, false, &mut budget);
+
+ let plan = |team: i32| {
+ catalog
+ .team(TeamId(team))
+ .expect("team present")
+ .behavioral
+ .plan
+ };
+ assert!(
+ plan(3).reads(GlobalRoot::Event) && !plan(3).reads(GlobalRoot::Pdi),
+ "team 3 freezes first and narrows",
+ );
+ assert_eq!(
+ plan(9),
+ GlobalsPlan::FULL,
+ "team 9 finds the budget spent, so its condition takes every root",
+ );
+ }
+
#[test]
fn build_catalog_threads_the_cascade_gate_into_freeze() {
use crate::eligibility::{CohortEligibility, ExcludedReason};
diff --git a/rust/cohort-core/src/filters/mod.rs b/rust/cohort-core/src/filters/mod.rs
index b9e1bb6bfdbd..150646faa7cc 100644
--- a/rust/cohort-core/src/filters/mod.rs
+++ b/rust/cohort-core/src/filters/mod.rs
@@ -10,7 +10,7 @@ use thiserror::Error;
pub use catalog::{FilterCatalog, Generation};
pub use leaf_classifier::{classify_leaf, LeafClass, LeafDropReason};
pub use loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow, REALTIME_COHORTS_SQL};
-pub use reverse_index::{LeafStateMeta, TeamFilters, TeamFiltersBuilder};
+pub use reverse_index::{BehavioralCandidates, LeafStateMeta, TeamFilters, TeamFiltersBuilder};
pub use tree::{
parse_cohort_tree, BehavioralLeafConfig, BehavioralValue, BoolOp, CohortLeaf,
CohortRefLeafConfig, CohortTree, FilterNode, LeafSink, PersonLeafConfig,
diff --git a/rust/cohort-core/src/filters/reverse_index.rs b/rust/cohort-core/src/filters/reverse_index.rs
index ef4ee179fbb0..10ba76f5c582 100644
--- a/rust/cohort-core/src/filters/reverse_index.rs
+++ b/rust/cohort-core/src/filters/reverse_index.rs
@@ -14,6 +14,7 @@ use crate::filters::leaf_classifier::LeafDropReason;
use crate::filters::tree::{parse_cohort_tree, CohortLeaf, CohortTree, FilterNode, LeafSink};
use crate::filters::{CohortId, FilterError, TeamId};
use crate::fingerprint::CatalogFingerprint;
+use crate::hogvm::analysis::{analyze_condition_within, AnalysisBudget, GlobalsPlan, Projection};
use crate::hogvm::ConditionProgram;
use crate::leaf_state::key::LeafStateKey;
use crate::leaf_state::select::{
@@ -21,10 +22,37 @@ use crate::leaf_state::select::{
};
use crate::leaf_state::variant::StateVariant;
use crate::metrics::{
- COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_SKIPPED_LEAVES,
+ COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_CONDITION_PROJECTION,
+ FILTER_CATALOG_SKIPPED_LEAVES,
};
use crate::seed::{BehavioralShapeHash, PersonShapeHash};
+/// The behavioral conditions one globals dict has to serve, and the plan that builds it. One plan
+/// per set because one dict is.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct BehavioralCandidates {
+ /// Sorted, so the evaluation order is deterministic.
+ pub conditions: Vec<[u8; 16]>,
+ pub plan: GlobalsPlan,
+}
+
+impl BehavioralCandidates {
+ /// Derives the plan from the conditions, so the pair cannot drift: a condition added to the
+ /// list without its roots claimed would read a root the dict omits, and the VM raises
+ /// `VmError::UnknownGlobal` on an absent root.
+ fn new(conditions: Vec<[u8; 16]>, plan_of: impl Fn(&[u8; 16]) -> GlobalsPlan) -> Self {
+ let plan = conditions.iter().map(plan_of).collect();
+ Self { conditions, plan }
+ }
+
+ fn empty() -> Self {
+ Self {
+ conditions: Vec::new(),
+ plan: GlobalsPlan::NONE,
+ }
+ }
+}
+
#[derive(Debug, Clone, Copy)]
pub struct LeafStateMeta {
pub variant: StateVariant,
@@ -47,11 +75,13 @@ pub struct TeamFilters {
pub by_condition_to_program: HashMap<[u8; 16], ConditionProgram>,
pub unique_condition_hashes: HashSet<[u8; 16]>,
pub by_lsk: HashMap<LeafStateKey, LeafStateMeta>,
- /// conditionHashes whose leaves are behavioral. Disjoint from person-property conditions.
- pub behavioral_conditions: HashSet<[u8; 16]>,
- /// Event name → the behavioral conditionHashes whose bytecode roots at `event == <name>`; the
+ /// Every conditionHash whose leaves are behavioral, for the ungated fan-out. Disjoint from the
+ /// person-property conditions, and sorted, so neither the shared analysis budget nor the
+ /// fan-out depends on hash order.
+ pub behavioral: BehavioralCandidates,
+ /// Event name → the behavioral conditions whose bytecode roots at `event == <name>`; the
/// fan-out gate evaluates only the incoming event's bucket.
- pub behavioral_by_event_name: HashMap<String, Vec<[u8; 16]>>,
+ pub behavioral_by_event_name: HashMap<String, BehavioralCandidates>,
pub person_property_conditions: HashSet<[u8; 16]>,
/// `person_property_conditions` sorted — the stable order the person record's catalog fingerprint
/// is computed over.
@@ -88,7 +118,7 @@ impl Default for TeamFilters {
by_condition_to_program: HashMap::new(),
unique_condition_hashes: HashSet::new(),
by_lsk: HashMap::new(),
- behavioral_conditions: HashSet::new(),
+ behavioral: BehavioralCandidates::empty(),
behavioral_by_event_name: HashMap::new(),
person_property_conditions: HashSet::new(),
person_conditions_ordered: Vec::new(),
@@ -202,7 +232,23 @@ impl TeamFiltersBuilder {
/// Freeze into an immutable [`TeamFilters`]. When `cascade_enabled`, resolvable cycle-free
/// ref-bearing cohorts become [`CohortEligibility::Stage2ComposableRef`] and join the composable
/// emit-map by their own leaves; otherwise they stay `Excluded(HasCohortRef)`.
+ ///
+ /// Analyzes the behavioral conditions under a whole catalog budget of its own. A caller freezing
+ /// several teams shares one through [`Self::freeze_within`] instead.
pub fn freeze_with(self, timezone: Tz, cascade_enabled: bool) -> TeamFilters {
+ self.freeze_within(timezone, cascade_enabled, &mut catalog_analysis_budget())
+ }
+
+ /// [`Self::freeze_with`], analyzing against a budget the caller owns. One budget across every
+ /// team of a catalog bounds the build as a whole rather than each team of it. It is spent in
+ /// call order, so a caller that wants the same plans on every replica freezes its teams in a
+ /// fixed order.
+ pub fn freeze_within(
+ self,
+ timezone: Tz,
+ cascade_enabled: bool,
+ budget: &mut AnalysisBudget,
+ ) -> TeamFilters {
// Aggregate corrupt leaves per cohort so one large filter tree cannot flood each refresh.
for (cohort_id, flags) in &self.flags {
if flags.malformed_leaf_count > 0 {
@@ -306,12 +352,24 @@ impl TeamFiltersBuilder {
person_conditions_ordered.sort_unstable();
let catalog_fingerprint = CatalogFingerprint::of_sorted(&person_conditions_ordered);
+ let mut behavioral_conditions: Vec<[u8; 16]> = behavioral_conditions.into_iter().collect();
+ behavioral_conditions.sort_unstable();
+ let plans = condition_plans(
+ &self.by_condition_to_program,
+ &behavioral_conditions,
+ budget,
+ );
+ // One leaf populates both maps, so a miss is unreachable. `FULL` is the answer that would
+ // be slow rather than wrong if that ever stopped holding.
+ let plan_of = |hash: &[u8; 16]| plans.get(hash).copied().unwrap_or(GlobalsPlan::FULL);
+ let behavioral = BehavioralCandidates::new(behavioral_conditions, plan_of);
+
let behavioral_by_event_name = behavioral_by_event_name
.into_iter()
.map(|(name, hashes)| {
- let mut hashes: Vec<[u8; 16]> = hashes.into_iter().collect();
- hashes.sort_unstable();
- (name, hashes)
+ let mut conditions: Vec<[u8; 16]> = hashes.into_iter().collect();
+ conditions.sort_unstable();
+ (name, BehavioralCandidates::new(conditions, plan_of))
})
.collect();
let mut behavioral_shape_hashes = self.behavioral_shape_hashes;
@@ -325,7 +383,7 @@ impl TeamFiltersBuilder {
by_condition_to_program: self.by_condition_to_program,
unique_condition_hashes: self.unique_condition_hashes,
by_lsk,
- behavioral_conditions,
+ behavioral,
behavioral_by_event_name,
person_property_conditions,
person_conditions_ordered,
@@ -358,6 +416,50 @@ fn collect_leaf_state_keys(node: &FilterNode, out: &mut HashSet<LeafStateKey>) {
}
}
+/// How many worst-case conditions one catalog analysis may cost, as one budget every condition of
+/// every team shares.
+///
+/// A constant rather than a function of the catalog. A budget of `conditions × ceiling` is the
+/// per-condition ceiling over again, and nothing caps the conditions a catalog carries, so the
+/// build would have no bound of its own. The unit is the worst program the analyzer accepts, and
+/// this many of them keep a build's analysis to a few seconds. A realistic condition spends one
+/// step per instruction and copies nothing, so this many step ceilings cover far more conditions
+/// than any catalog holds. Past the budget a condition takes [`GlobalsPlan::FULL`], which
+/// evaluates the same and only parses roots it did not need.
+const CATALOG_WORST_CASE_CONDITIONS: usize = 8;
+
+/// The budget one catalog build analyzes under. See [`CATALOG_WORST_CASE_CONDITIONS`].
+pub(crate) fn catalog_analysis_budget() -> AnalysisBudget {
+ AnalysisBudget::for_conditions(CATALOG_WORST_CASE_CONDITIONS)
+}
+
+/// Walked in order against the caller's [`AnalysisBudget`], so a catalog classifies the same way
+/// whatever order its rows arrived in. A condition the spent budget refuses takes
+/// [`GlobalsPlan::FULL`] under the budget's own reason, which the counter reports.
+fn condition_plans(
+ programs_by_hash: &HashMap<[u8; 16], ConditionProgram>,
+ sorted_hashes: &[[u8; 16]],
+ budget: &mut AnalysisBudget,
+) -> HashMap<[u8; 16], GlobalsPlan> {
+ sorted_hashes
+ .iter()
+ .map(|hash| {
+ let Some(program) = programs_by_hash.get(hash) else {
+ counter!(FILTER_CATALOG_CONDITION_PROJECTION, "outcome" => "missing_bytecode")
+ .increment(1);
+ return (*hash, GlobalsPlan::FULL);
+ };
+ let projection = analyze_condition_within(program.tokens(), budget).projection;
+ let outcome = match &projection {
+ Projection::Reads(_) => "reads",
+ Projection::FullColumns(reason) => reason.as_str(),
+ };
+ counter!(FILTER_CATALOG_CONDITION_PROJECTION, "outcome" => outcome).increment(1);
+ (*hash, GlobalsPlan::of(&projection))
+ })
+ .collect()
+}
+
fn collect_leaf_meta(
node: &FilterNode,
by_lsk: &mut HashMap<LeafStateKey, LeafStateMeta>,
@@ -441,6 +543,7 @@ mod tests {
use serde_json::json;
use crate::eligibility::ExcludedReason;
+ use crate::hogvm::analysis::GlobalRoot;
const HASH: [u8; 16] = *b"0123456789abcdef";
@@ -460,6 +563,18 @@ mod tests {
bc
}
+ fn behavioral_leaf(event_name: &str, condition_hash: &str, bytecode: Value) -> Value {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": event_name,
+ "time_value": 7,
+ "time_interval": "day",
+ "conditionHash": condition_hash,
+ "bytecode": bytecode,
+ })
+ }
+
/// A `performed_event` leaf on `$pageview` with a tunable window.
fn behavioral_performed_event(time_value: i64) -> Value {
json!({
@@ -796,8 +911,9 @@ mod tests {
assert_eq!(meta.window, None, "daily buckets carry no relative window");
assert_eq!(meta.window_days, Some(7));
assert_eq!(meta.predicate_op, Some(PredicateOp::Gte(3)));
- assert!(
- frozen.behavioral_conditions.contains(&HASH),
+ assert_eq!(
+ frozen.behavioral.conditions,
+ vec![HASH],
"the multiple leaf's conditionHash is behavioral",
);
}
@@ -822,7 +938,7 @@ mod tests {
assert_eq!(meta.window, None, "compressed carries no relative window");
assert_eq!(meta.window_days, Some(365), "year = 365 days");
assert_eq!(meta.predicate_op, Some(PredicateOp::Gte(3)));
- assert!(frozen.behavioral_conditions.contains(&HASH));
+ assert_eq!(frozen.behavioral.conditions, vec![HASH]);
}
#[test]
@@ -960,8 +1076,8 @@ mod tests {
let frozen = builder.freeze(UTC);
assert_eq!(
- frozen.behavioral_conditions,
- HashSet::from([HASH]),
+ frozen.behavioral.conditions,
+ vec![HASH],
"the performed_event conditionHash is behavioral",
);
assert_eq!(
@@ -969,9 +1085,11 @@ mod tests {
HashSet::from([PERSON_HASH]),
"the person conditionHash is person-property",
);
- assert!(frozen
- .behavioral_conditions
- .is_disjoint(&frozen.person_property_conditions));
+ assert!(!frozen
+ .behavioral
+ .conditions
+ .iter()
+ .any(|hash| frozen.person_property_conditions.contains(hash)));
}
#[test]
@@ -1109,9 +1227,12 @@ mod tests {
.unwrap();
let frozen = builder.freeze(UTC);
- assert_eq!(frozen.behavioral_by_event_name["$pageview"], vec![HASH]);
assert_eq!(
- frozen.behavioral_by_event_name["purchase"],
+ frozen.behavioral_by_event_name["$pageview"].conditions,
+ vec![HASH]
+ );
+ assert_eq!(
+ frozen.behavioral_by_event_name["purchase"].conditions,
vec![PURCHASE_HASH],
);
assert!(
@@ -1119,18 +1240,134 @@ mod tests {
"a person leaf is not bucketed by event name",
);
- let union: HashSet<[u8; 16]> = frozen
+ let mut union: Vec<[u8; 16]> = frozen
.behavioral_by_event_name
.values()
- .flatten()
- .copied()
+ .flat_map(|bucket| bucket.conditions.iter().copied())
.collect();
+ union.sort_unstable();
assert_eq!(
- union, frozen.behavioral_conditions,
+ union, frozen.behavioral.conditions,
"the buckets partition exactly the behavioral conditions",
);
}
+ #[test]
+ fn freeze_plans_each_bucket_from_the_bytecode_that_reads_it() {
+ // `pdi.person.properties.plan == "pro"`, the one shape that needs the `pdi` root.
+ let pdi_leaf = behavioral_leaf(
+ "checkout",
+ "pdihash000000001",
+ json!([
+ "_H",
+ 1,
+ 32,
+ "pro",
+ 32,
+ "plan",
+ 32,
+ "properties",
+ 32,
+ "person",
+ 32,
+ "pdi",
+ 1,
+ 4,
+ 11
+ ]),
+ );
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), pdi_leaf.clone()]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+
+ let checkout = &frozen.behavioral_by_event_name["checkout"].plan;
+ let pageview = &frozen.behavioral_by_event_name["$pageview"].plan;
+ assert!(checkout.reads(GlobalRoot::Pdi));
+ assert!(
+ !pageview.reads(GlobalRoot::Pdi),
+ "an `event ==` bucket does not need `pdi`, so building it there is wasted work",
+ );
+ assert!(pageview.reads(GlobalRoot::Event));
+ assert!(
+ frozen.behavioral.plan.reads(GlobalRoot::Pdi)
+ && frozen.behavioral.plan.reads(GlobalRoot::Event),
+ "the sweep evaluates every condition, so its plan is the union of the buckets'",
+ );
+ assert!(
+ frozen.behavioral.conditions.is_sorted(),
+ "the sweep order and the shared analysis budget both depend on this order",
+ );
+
+ // A `TRY` installs a handler the analysis does not follow, so it cannot narrow the read set.
+ let unanalyzable =
+ behavioral_leaf("signup", "tryhash000000002", json!(["_H", 1, 50, 1, 29]));
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(7),
+ &wrap(vec![behavioral_performed_event(7), pdi_leaf, unanalyzable]),
+ )
+ .unwrap();
+ let frozen = builder.freeze(UTC);
+ assert_eq!(
+ frozen.behavioral_by_event_name["signup"].plan,
+ GlobalsPlan::FULL,
+ "a condition the analysis cannot narrow has to claim every root",
+ );
+ assert_eq!(frozen.behavioral.plan, GlobalsPlan::FULL);
+ }
+
+ #[test]
+ fn a_spent_budget_widens_every_condition_after_it_to_every_root() {
+ // `HASH` sorts before this hash, so the `$pageview` condition is analyzed first.
+ let purchase = behavioral_leaf(
+ "purchase",
+ "purchasehash0002",
+ json!(["_H", 1, 32, "purchase", 32, "event", 1, 1, 11]),
+ );
+ let cohort = wrap(vec![behavioral_performed_event(7), purchase]);
+ let mut builder = TeamFiltersBuilder::default();
+ builder.add_cohort(CohortId(1), TeamId(7), &cohort).unwrap();
+ // STRING, STRING, GET_GLOBAL, EQ, RETURN: exactly what the first condition spends.
+ let mut budget = AnalysisBudget {
+ steps: 5,
+ cells: usize::MAX,
+ };
+ let frozen = builder.freeze_within(UTC, false, &mut budget);
+
+ assert_eq!(
+ budget.steps, 0,
+ "the first condition spent the whole budget"
+ );
+ let pageview = frozen.behavioral_by_event_name["$pageview"].plan;
+ assert!(
+ pageview.reads(GlobalRoot::Event) && !pageview.reads(GlobalRoot::Pdi),
+ "the condition within the budget still narrows",
+ );
+ assert_eq!(
+ frozen.behavioral_by_event_name["purchase"].plan,
+ GlobalsPlan::FULL,
+ "the condition the spent budget refuses takes every root",
+ );
+ assert_eq!(frozen.behavioral.plan, GlobalsPlan::FULL);
+
+ let mut builder = TeamFiltersBuilder::default();
+ builder.add_cohort(CohortId(1), TeamId(7), &cohort).unwrap();
+ assert!(
+ !builder.freeze(UTC).behavioral_by_event_name["purchase"]
+ .plan
+ .reads(GlobalRoot::Pdi),
+ "under the catalog budget the same condition narrows, so the budget was what widened it",
+ );
+ }
+
#[test]
fn same_event_name_collects_distinct_hashes_deduped_and_sorted() {
const HASH2: [u8; 16] = *b"0011223344556677";
@@ -1156,7 +1393,7 @@ mod tests {
let mut expected = [HASH, HASH2];
expected.sort_unstable();
assert_eq!(
- frozen.behavioral_by_event_name["$pageview"],
+ frozen.behavioral_by_event_name["$pageview"].conditions,
expected.to_vec(),
"the bucket dedupes the repeated leaf and sorts its two distinct hashes",
);
@@ -1180,7 +1417,7 @@ mod tests {
let frozen = builder.freeze(UTC);
assert_eq!(frozen.by_lsk.len(), 1);
- assert_eq!(frozen.behavioral_conditions, HashSet::from([HASH]));
+ assert_eq!(frozen.behavioral.conditions, vec![HASH]);
}
fn cohort_ref() -> Value {
diff --git a/rust/cohort-core/src/hogvm/analysis/mod.rs b/rust/cohort-core/src/hogvm/analysis/mod.rs
index 53cfa26351bd..6856ad6a3d20 100644
--- a/rust/cohort-core/src/hogvm/analysis/mod.rs
+++ b/rust/cohort-core/src/hogvm/analysis/mod.rs
@@ -23,18 +23,22 @@
//! program whose `GET_GLOBAL`s all resolve to literal paths cannot reach a global this analysis did
//! not record, however it combines those values afterwards.
//!
-//! A path whose root is outside [`GlobalRoot`] records nothing, which is sound because a projection
-//! narrows the values *under* a root and never removes one. A name no globals dict carries is
-//! absent from the projected event and from the full one alike, so it names no column. That rests
-//! on [`GlobalRoot`] covering every dict this crate builds, which
+//! A path whose root is outside [`GlobalRoot`] records nothing. A name no globals dict carries is
+//! absent from the narrowed event and from the full one alike, so it names no column and no root.
+//! That rests on [`GlobalRoot`] covering every dict this crate builds, which
//! `every_globals_dict_key_is_a_named_root` in `hogvm::globals` checks.
//!
+//! The two consumers narrow differently and [`Projection::Reads`] serves both: the seeder narrows
+//! the values under a root and keeps the root, while [`GlobalsPlan`] removes whole roots. So a read
+//! set is sound for both only because every path records its root as well as its segments.
+//!
//! Reading no event data is only half the obligation. A bare native name resolves to a closure
//! instead of a read, so such a root widens whenever calling it would read a value's spelling
//! rather than its value, the same way a direct call to it does.
mod decode;
mod event_only;
+mod plan;
mod projection;
use std::collections::BTreeSet;
@@ -43,6 +47,7 @@ use hogvm::Operation;
use serde_json::Value;
pub use decode::DecodeError;
+pub use plan::{GlobalsBuild, GlobalsPlan};
pub use projection::AnalysisBudget;
/// What a static pass could establish about one condition's bytecode.
@@ -233,6 +238,10 @@ impl GroupIndex {
pub const fn get(self) -> u8 {
self.0
}
+
+ pub fn all() -> impl Iterator<Item = Self> {
+ (0..Self::COUNT).map(Self)
+ }
}
/// Every root of every globals dict this crate builds, which is the whole surface a condition can
@@ -245,7 +254,7 @@ impl GroupIndex {
///
/// The other direction is benign. A variant no dict carries over-claims a read, which costs bytes
/// and never correctness, so nothing here has to chase it.
-#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum GlobalRoot {
Event,
Uuid,
@@ -300,6 +309,64 @@ impl GlobalRoot {
}
}
+ pub const COUNT: u8 = FIRST_GROUP_ORDINAL + 2 * GroupIndex::COUNT;
+
+ /// A dense index into `0..COUNT`, never persisted, that [`GlobalRoot::from_ordinal`] inverts.
+ pub fn ordinal(self) -> u8 {
+ match self {
+ Self::Event => 0,
+ Self::Uuid => 1,
+ Self::ElementsChain => 2,
+ Self::ElementsChainHref => 3,
+ Self::ElementsChainTexts => 4,
+ Self::ElementsChainIds => 5,
+ Self::ElementsChainElements => 6,
+ Self::Timestamp => 7,
+ Self::Properties => 8,
+ Self::Person => 9,
+ Self::Pdi => 10,
+ Self::DistinctId => 11,
+ Self::Variables => 12,
+ Self::Project => 13,
+ Self::DollarGroup(index) => FIRST_GROUP_ORDINAL + index.get(),
+ Self::Group(index) => FIRST_GROUP_ORDINAL + GroupIndex::COUNT + index.get(),
+ }
+ }
+
+ /// Every root, in ordinal order.
+ pub fn all() -> impl Iterator<Item = Self> {
+ (0..Self::COUNT).filter_map(Self::from_ordinal)
+ }
+
+ pub fn from_ordinal(ordinal: u8) -> Option<Self> {
+ let root = match ordinal {
+ 0 => Self::Event,
+ 1 => Self::Uuid,
+ 2 => Self::ElementsChain,
+ 3 => Self::ElementsChainHref,
+ 4 => Self::ElementsChainTexts,
+ 5 => Self::ElementsChainIds,
+ 6 => Self::ElementsChainElements,
+ 7 => Self::Timestamp,
+ 8 => Self::Properties,
+ 9 => Self::Person,
+ 10 => Self::Pdi,
+ 11 => Self::DistinctId,
+ 12 => Self::Variables,
+ 13 => Self::Project,
+ _ => {
+ let group = ordinal - FIRST_GROUP_ORDINAL;
+ return match GroupIndex::parse(group) {
+ Some(index) => Some(Self::DollarGroup(index)),
+ None => {
+ GroupIndex::parse(group.wrapping_sub(GroupIndex::COUNT)).map(Self::Group)
+ }
+ };
+ }
+ };
+ Some(root)
+ }
+
pub fn as_str(&self) -> &'static str {
match self {
Self::Event => "event",
@@ -322,6 +389,8 @@ impl GlobalRoot {
}
}
+const FIRST_GROUP_ORDINAL: u8 = 14;
+
const DOLLAR_GROUP_NAMES: [&str; GroupIndex::COUNT as usize] =
["$group_0", "$group_1", "$group_2", "$group_3", "$group_4"];
const GROUP_NAMES: [&str; GroupIndex::COUNT as usize] =
@@ -428,8 +497,31 @@ mod tests {
);
}
+ /// The compiler forces a new variant to take an ordinal, but not to update
+ /// [`GlobalRoot::COUNT`], and a stale one leaves `GlobalsPlan::FULL` short of a root.
#[test]
- fn every_global_root_round_trips_through_its_name() {
+ fn every_global_root_round_trips_through_its_name_and_ordinal() {
+ let by_ordinal: Vec<GlobalRoot> = (0..GlobalRoot::COUNT)
+ .map(|ordinal| {
+ GlobalRoot::from_ordinal(ordinal).unwrap_or_else(|| {
+ panic!("ordinal {ordinal} is below COUNT and resolved to no root")
+ })
+ })
+ .collect();
+ assert_eq!(
+ by_ordinal.iter().collect::<BTreeSet<_>>().len(),
+ GlobalRoot::COUNT as usize,
+ "two roots share an ordinal, so a bitset over them would conflate them",
+ );
+ assert_eq!(
+ GlobalRoot::from_ordinal(GlobalRoot::COUNT),
+ None,
+ "COUNT is not past the last ordinal, so `GlobalsPlan::FULL` would be short a root",
+ );
+ for root in &by_ordinal {
+ assert_eq!(GlobalRoot::from_ordinal(root.ordinal()), Some(*root));
+ }
+
let roots = [
GlobalRoot::Event,
GlobalRoot::Uuid,
@@ -447,12 +539,12 @@ mod tests {
GlobalRoot::Project,
];
for root in roots {
- assert_eq!(GlobalRoot::parse(root.as_str()), Some(root.clone()));
+ assert_eq!(GlobalRoot::parse(root.as_str()), Some(root));
}
for index in 0..GroupIndex::COUNT {
let index = GroupIndex::parse(index).unwrap();
for root in [GlobalRoot::DollarGroup(index), GlobalRoot::Group(index)] {
- assert_eq!(GlobalRoot::parse(root.as_str()), Some(root.clone()));
+ assert_eq!(GlobalRoot::parse(root.as_str()), Some(root));
}
}
}
diff --git a/rust/cohort-core/src/hogvm/analysis/plan.rs b/rust/cohort-core/src/hogvm/analysis/plan.rs
new file mode 100644
index 000000000000..3e4b6faf6cc2
--- /dev/null
+++ b/rust/cohort-core/src/hogvm/analysis/plan.rs
@@ -0,0 +1,265 @@
+//! Which globals a set of conditions can name, so a builder materializes only those.
+//!
+//! Omitting a root is sound because `GET_GLOBAL` is the VM's only path into the globals dict and
+//! [`super::Projection`] names every root a condition's `GET_GLOBAL`s can reach.
+//!
+//! Omitting one a condition does read is loud rather than silent: the VM raises
+//! `VmError::UnknownGlobal` for an absent root, and pushes null only for a missing key under a
+//! present one. A stub value under every root would turn the same bug into a wrong answer.
+
+use std::fmt;
+
+use super::{GlobalRoot, Projection};
+
+const _: () = assert!(GlobalRoot::COUNT as u32 <= u32::BITS);
+
+/// What a globals builder has to materialize for a set of conditions: every root any of them can
+/// name, as a bitset over [`GlobalRoot`] ordinals. Unioned over an event-name bucket, because one
+/// globals dict serves the whole bucket.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub struct GlobalsPlan(u32);
+
+impl GlobalsPlan {
+ /// Reads nothing. The identity of [`GlobalsPlan::union`].
+ pub const NONE: Self = Self(0);
+ /// Reads everything. The ordinals are dense over `0..COUNT`, so every root is the mask of their
+ /// bits.
+ pub const FULL: Self = Self(((1u64 << GlobalRoot::COUNT) - 1) as u32);
+
+ /// An `elements_chain` read needs `properties` too, for the `$elements_chain` fallback. No arm
+ /// here handles that because the analysis already records the fallback as its own path.
+ pub fn of(projection: &Projection) -> Self {
+ match projection {
+ Projection::FullColumns(_) => Self::FULL,
+ Projection::Reads(paths) => paths
+ .iter()
+ .fold(Self::NONE, |plan, path| plan.with(path.root)),
+ }
+ }
+
+ pub fn union(self, other: Self) -> Self {
+ Self(self.0 | other.0)
+ }
+
+ pub fn reads(self, root: GlobalRoot) -> bool {
+ self.0 & Self::bit(root) != 0
+ }
+
+ /// Whether `self` claims every root `other` does, which is what makes a narrowed
+ /// [`GlobalsBuild`] safe.
+ pub fn covers(self, other: Self) -> bool {
+ self.0 & other.0 == other.0
+ }
+
+ fn with(self, root: GlobalRoot) -> Self {
+ Self(self.0 | Self::bit(root))
+ }
+
+ fn bit(root: GlobalRoot) -> u32 {
+ 1u32 << root.ordinal()
+ }
+
+ /// Ordinal order, which is what makes [`fmt::Debug`] stable.
+ fn roots(self) -> impl Iterator<Item = GlobalRoot> {
+ GlobalRoot::all().filter(move |&root| self.reads(root))
+ }
+}
+
+impl FromIterator<GlobalsPlan> for GlobalsPlan {
+ fn from_iter<I: IntoIterator<Item = GlobalsPlan>>(plans: I) -> Self {
+ plans.into_iter().fold(Self::NONE, Self::union)
+ }
+}
+
+/// Root names rather than a bit pattern, so a failing assertion is readable.
+impl fmt::Debug for GlobalsPlan {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_set()
+ .entries(self.roots().map(|root| root.as_str()))
+ .finish()
+ }
+}
+
+/// The two plans one behavioral globals build runs under.
+///
+/// `materialize` is the plan of the conditions that will run against the dict — one event-name
+/// bucket's, under the fan-out gate. `parse` is every root the team's behavioral conditions can
+/// read, and it alone decides which of the event's JSON payloads are parsed at all.
+///
+/// `parse` has to be the wider one. Whether an event's payloads are malformed must not depend on
+/// which bucket the event landed in, or the fan-out gate would become a correctness switch: a
+/// bucket that parses nothing would evaluate an event that the ungated sweep drops for a payload
+/// neither of them reads.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct GlobalsBuild {
+ materialize: GlobalsPlan,
+ parse: GlobalsPlan,
+}
+
+impl GlobalsBuild {
+ /// A build narrowed to `materialize`, parsing whatever `parse` covers.
+ pub fn narrowed(materialize: GlobalsPlan, parse: GlobalsPlan) -> Self {
+ debug_assert!(
+ parse.covers(materialize),
+ "a build cannot materialize {materialize:?} out of a parse of {parse:?}",
+ );
+ Self { materialize, parse }
+ }
+
+ /// One plan for both, for a caller that evaluates every condition it planned for.
+ pub fn whole(plan: GlobalsPlan) -> Self {
+ Self {
+ materialize: plan,
+ parse: plan,
+ }
+ }
+
+ pub(crate) fn materialize(self) -> GlobalsPlan {
+ self.materialize
+ }
+
+ /// Whether the `properties` payload has to be parsed. An `elements_chain` read reaches
+ /// `properties.$elements_chain` as a fallback, which the analysis records as its own
+ /// `properties` path; naming the root here too keeps the builder from depending on that.
+ pub(crate) fn parses_properties(self) -> bool {
+ self.parse.reads(GlobalRoot::Properties) || self.parse.reads(GlobalRoot::ElementsChain)
+ }
+
+ /// Whether the `person_properties` payload has to be parsed: `person` carries it, and `pdi`
+ /// carries `person`.
+ pub(crate) fn parses_person_properties(self) -> bool {
+ self.parse.reads(GlobalRoot::Person) || self.parse.reads(GlobalRoot::Pdi)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::collections::BTreeSet;
+
+ use super::super::{FullColumnsReason, GroupIndex, ReadPath, UnanalyzableReason};
+ use super::*;
+
+ fn reads(paths: [ReadPath; 2]) -> Projection {
+ Projection::Reads(BTreeSet::from(paths))
+ }
+
+ fn path(root: GlobalRoot, segments: &[&str]) -> ReadPath {
+ ReadPath::new(root, segments.iter().map(|s| (*s).to_owned()).collect())
+ }
+
+ #[test]
+ fn a_full_plan_holds_every_root_and_an_empty_one_holds_none() {
+ let all: Vec<GlobalRoot> = GlobalRoot::all().collect();
+ assert_eq!(all.len(), GlobalRoot::COUNT as usize);
+ for root in &all {
+ assert!(GlobalsPlan::FULL.reads(*root), "FULL is missing {root:?}");
+ assert!(!GlobalsPlan::NONE.reads(*root), "NONE holds {root:?}");
+ assert_eq!(
+ GlobalsPlan::NONE.with(*root).roots().collect::<Vec<_>>(),
+ vec![*root],
+ );
+ }
+ assert_eq!(GlobalsPlan::NONE.roots().count(), 0);
+ assert!(
+ all.windows(2)
+ .all(|pair| pair[0].ordinal() < pair[1].ordinal()),
+ "iteration is not in ordinal order, so a Debug rendering would reorder unpredictably",
+ );
+ }
+
+ #[test]
+ fn a_plan_claims_the_read_sets_roots_and_widens_on_full_columns() {
+ let narrowed = GlobalsPlan::of(&reads([
+ path(GlobalRoot::Pdi, &["person", "properties", "plan"]),
+ path(GlobalRoot::Event, &[]),
+ ]));
+ assert!(narrowed.reads(GlobalRoot::Pdi));
+ assert!(narrowed.reads(GlobalRoot::Event));
+ assert!(!narrowed.reads(GlobalRoot::Person));
+ assert!(!narrowed.reads(GlobalRoot::Properties));
+
+ for reason in [
+ FullColumnsReason::BarePersonRoot,
+ FullColumnsReason::BarePropertiesRoot,
+ FullColumnsReason::RepresentationSensitiveCall,
+ FullColumnsReason::Unanalyzable(UnanalyzableReason::DynamicGlobalPath),
+ ] {
+ assert_eq!(
+ GlobalsPlan::of(&Projection::FullColumns(reason.clone())),
+ GlobalsPlan::FULL,
+ "{reason:?} did not widen to every root",
+ );
+ }
+
+ assert_eq!(
+ GlobalsPlan::of(&Projection::Reads(BTreeSet::new())),
+ GlobalsPlan::NONE,
+ );
+ }
+
+ #[test]
+ fn a_union_of_plans_is_the_union_of_their_roots() {
+ let event = GlobalsPlan::of(&reads([
+ path(GlobalRoot::Event, &[]),
+ path(
+ GlobalRoot::Group(GroupIndex::parse(3).unwrap()),
+ &["properties"],
+ ),
+ ]));
+ let person = GlobalsPlan::of(&reads([
+ path(GlobalRoot::Person, &["properties", "plan"]),
+ path(GlobalRoot::Timestamp, &[]),
+ ]));
+
+ let union = event.union(person);
+ for root in [
+ GlobalRoot::Event,
+ GlobalRoot::Group(GroupIndex::parse(3).unwrap()),
+ GlobalRoot::Person,
+ GlobalRoot::Timestamp,
+ ] {
+ assert!(union.reads(root), "the union dropped {root:?}");
+ }
+ assert!(!union.reads(GlobalRoot::Pdi));
+
+ assert_eq!([event, person].into_iter().collect::<GlobalsPlan>(), union);
+ assert_eq!(
+ std::iter::empty::<GlobalsPlan>().collect::<GlobalsPlan>(),
+ GlobalsPlan::NONE,
+ );
+ assert_eq!(event.union(GlobalsPlan::NONE), event);
+ assert_eq!(event.union(GlobalsPlan::FULL), GlobalsPlan::FULL);
+ assert!(union.covers(event) && union.covers(person));
+ assert!(!event.covers(union));
+ assert!(GlobalsPlan::FULL.covers(union) && union.covers(GlobalsPlan::NONE));
+ }
+
+ /// A plan that reads only `event` names no payload, which is what lets a build skip both JSON
+ /// parses; the two payload-bearing sides have to answer independently.
+ #[test]
+ fn a_build_parses_only_the_payloads_its_parse_plan_reaches() {
+ let plan = |root| GlobalsPlan::NONE.with(root);
+ let build = |root| GlobalsBuild::whole(plan(root));
+
+ assert!(!build(GlobalRoot::Event).parses_properties());
+ assert!(!build(GlobalRoot::Event).parses_person_properties());
+ for root in [GlobalRoot::Properties, GlobalRoot::ElementsChain] {
+ assert!(build(root).parses_properties(), "{root:?}");
+ assert!(!build(root).parses_person_properties(), "{root:?}");
+ }
+ for root in [GlobalRoot::Person, GlobalRoot::Pdi] {
+ assert!(build(root).parses_person_properties(), "{root:?}");
+ assert!(!build(root).parses_properties(), "{root:?}");
+ }
+ assert!(GlobalsBuild::whole(GlobalsPlan::FULL).parses_properties());
+ assert!(GlobalsBuild::whole(GlobalsPlan::FULL).parses_person_properties());
+
+ // The narrow side is what the dict holds; the wide side is what was parsed for it, so a
+ // bucket that reads only `event` still pays a parse its team needs elsewhere.
+ let team = plan(GlobalRoot::Event).with(GlobalRoot::Properties);
+ let narrowed = GlobalsBuild::narrowed(plan(GlobalRoot::Event), team);
+ assert_eq!(narrowed.materialize(), plan(GlobalRoot::Event));
+ assert!(narrowed.parses_properties());
+ }
+}
diff --git a/rust/cohort-core/src/hogvm/globals.rs b/rust/cohort-core/src/hogvm/globals.rs
index 58e35554c6e0..930de5a93b08 100644
--- a/rust/cohort-core/src/hogvm/globals.rs
+++ b/rust/cohort-core/src/hogvm/globals.rs
@@ -2,11 +2,12 @@
use chrono::{DateTime, NaiveDateTime};
use metrics::counter;
-use serde_json::{json, Value};
+use serde_json::{json, Map, Value};
use uuid::Uuid;
use crate::events::CohortStreamEvent;
use crate::filters::TeamId;
+use crate::hogvm::analysis::{GlobalRoot, GlobalsBuild, GlobalsPlan, GroupIndex};
use crate::metrics::STAGE1_GLOBALS_PARSE_ERROR;
/// A malformed `properties`/`person_properties` JSON payload.
@@ -18,46 +19,112 @@ pub struct GlobalsError {
pub source: serde_json::Error,
}
-pub fn build_behavioral_globals(event: &CohortStreamEvent) -> Result<Value, GlobalsError> {
- let properties = parse_optional_json(event.properties.as_deref(), "properties")?;
- let person_properties =
- parse_optional_json(event.person_properties.as_deref(), "person_properties")?;
+/// Holds every root `build` says the conditions can name; see [`crate::GlobalsPlan`] for why
+/// omitting one they do read raises rather than reads null.
+///
+/// A payload no condition of the team reads is never parsed, so it can also never be malformed. The
+/// parse side of `build` is the team's whole behavioral plan rather than this dict's, which is what
+/// keeps two callers evaluating one event against different plans agreeing on that.
+pub fn build_behavioral_globals(
+ event: &CohortStreamEvent,
+ build: GlobalsBuild,
+) -> Result<Value, GlobalsError> {
+ // An unparsed payload stands in as the empty object, which no root can reach: a root that would
+ // read one is in the materialize plan, and that is a subset of the parse plan.
+ let properties = if build.parses_properties() {
+ parse_optional_json(event.properties.as_deref(), "properties")?
+ } else {
+ Value::Object(Map::new())
+ };
+ let person_properties = if build.parses_person_properties() {
+ parse_optional_json(event.person_properties.as_deref(), "person_properties")?
+ } else {
+ Value::Object(Map::new())
+ };
+ let person = object([
+ ("id", text(&event.person_id)),
+ ("properties", person_properties),
+ ]);
+
+ let mut roots = Roots::new(build.materialize());
+ roots.set(GlobalRoot::Event, || text(&event.event));
+ roots.set(GlobalRoot::Uuid, || text(&event.uuid));
+ // Reads `properties`, which the `Properties` root below moves away.
+ roots.set(GlobalRoot::ElementsChain, || {
+ elements_chain(event, &properties)
+ });
+ roots.set(GlobalRoot::ElementsChainHref, || {
+ Value::String(String::new())
+ });
+ for root in [
+ GlobalRoot::ElementsChainTexts,
+ GlobalRoot::ElementsChainIds,
+ GlobalRoot::ElementsChainElements,
+ ] {
+ roots.set(root, || Value::Array(Vec::new()));
+ }
+ roots.set(GlobalRoot::Timestamp, || {
+ Value::String(normalize_timestamp(&event.timestamp))
+ });
+ roots.set(GlobalRoot::DistinctId, || text(&event.distinct_id));
+ for index in GroupIndex::all() {
+ roots.set(GlobalRoot::DollarGroup(index), || Value::Null);
+ roots.set(GlobalRoot::Group(index), empty_group);
+ }
+ roots.set(GlobalRoot::Variables, || Value::Object(Map::new()));
+ // Copies `person`, which the `Person` root below moves away.
+ roots.set(GlobalRoot::Pdi, || {
+ object([
+ ("distinct_id", text(&event.distinct_id)),
+ ("person_id", text(&event.person_id)),
+ ("person", person.clone()),
+ ])
+ });
+ roots.set(GlobalRoot::Person, || person);
+ roots.set(GlobalRoot::Properties, || properties);
+ Ok(roots.finish())
+}
- let elements_chain = elements_chain(event, &properties);
- let timestamp = normalize_timestamp(&event.timestamp);
+/// An unread root costs nothing, not even building its value, because `set` skips the closure.
+struct Roots {
+ plan: GlobalsPlan,
+ map: Map<String, Value>,
+}
- let person = json!({ "id": event.person_id.as_str(), "properties": person_properties });
- let pdi = json!({
- "distinct_id": event.distinct_id.as_str(),
- "person_id": event.person_id.as_str(),
- "person": person.clone(),
- });
+impl Roots {
+ fn new(plan: GlobalsPlan) -> Self {
+ Self {
+ plan,
+ map: Map::new(),
+ }
+ }
+
+ fn set(&mut self, root: GlobalRoot, value: impl FnOnce() -> Value) {
+ if self.plan.reads(root) {
+ self.map.insert(root.as_str().to_owned(), value());
+ }
+ }
+
+ fn finish(self) -> Value {
+ Value::Object(self.map)
+ }
+}
+
+fn text(value: &str) -> Value {
+ Value::String(value.to_owned())
+}
- Ok(json!({
- "event": event.event.as_str(),
- "uuid": event.uuid.as_str(),
- "elements_chain": elements_chain,
- "elements_chain_href": "",
- "elements_chain_texts": [],
- "elements_chain_ids": [],
- "elements_chain_elements": [],
- "timestamp": timestamp,
- "properties": properties,
- "person": person,
- "pdi": pdi,
- "distinct_id": event.distinct_id.as_str(),
- "$group_0": null,
- "$group_1": null,
- "$group_2": null,
- "$group_3": null,
- "$group_4": null,
- "group_0": { "properties": {} },
- "group_1": { "properties": {} },
- "group_2": { "properties": {} },
- "group_3": { "properties": {} },
- "group_4": { "properties": {} },
- "variables": {},
- }))
+fn object<const N: usize>(entries: [(&str, Value); N]) -> Value {
+ Value::Object(
+ entries
+ .into_iter()
+ .map(|(key, value)| (key.to_owned(), value))
+ .collect(),
+ )
+}
+
+fn empty_group() -> Value {
+ object([("properties", Value::Object(Map::new()))])
}
pub fn build_person_property_globals(event: &CohortStreamEvent) -> Result<Value, GlobalsError> {
@@ -139,10 +206,18 @@ fn normalize_timestamp(raw: &str) -> String {
#[cfg(test)]
mod tests {
- use crate::hogvm::analysis::GlobalRoot;
+ use std::collections::BTreeSet;
+
+ use hogvm::stl_map;
+
+ use crate::hogvm::analysis::{Projection, ReadPath};
use super::*;
+ /// The dict the VM must be handed for [`event`]. Nothing can re-derive it, so this constant is
+ /// the record: change it only for a reason that is not "the test failed".
+ const PINNED_FULL_GLOBALS: &str = r#"{"$group_0":null,"$group_1":null,"$group_2":null,"$group_3":null,"$group_4":null,"distinct_id":"d-1","elements_chain":"a:href=\"/x\"","elements_chain_elements":[],"elements_chain_href":"","elements_chain_ids":[],"elements_chain_texts":[],"event":"$pageview","group_0":{"properties":{}},"group_1":{"properties":{}},"group_2":{"properties":{}},"group_3":{"properties":{}},"group_4":{"properties":{}},"pdi":{"distinct_id":"d-1","person":{"id":"p-123","properties":{"email":"[email protected]"}},"person_id":"p-123"},"person":{"id":"p-123","properties":{"email":"[email protected]"}},"properties":{"$browser":"Chrome"},"timestamp":"2026-05-26T12:34:56.789Z","uuid":"01928aaa-bbbb-cccc-dddd-eeeeeeeeeeee","variables":{}}"#;
+
fn event() -> CohortStreamEvent {
CohortStreamEvent {
team_id: 42,
@@ -161,9 +236,89 @@ mod tests {
}
}
+ /// Key names alone do not pin this: a changed nesting, empty spelling, or string escaping reads
+ /// differently while every `contains_key` assertion still passes.
+ #[test]
+ fn a_full_plan_rebuilds_the_pinned_dict_and_a_narrower_plan_drops_only_its_roots() {
+ let event = event();
+ let full =
+ build_behavioral_globals(&event, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
+ assert_eq!(serde_json::to_string(&full).unwrap(), PINNED_FULL_GLOBALS);
+
+ let reads_every_root_but_pdi = GlobalsPlan::of(&Projection::Reads(
+ GlobalRoot::all()
+ .filter(|root| *root != GlobalRoot::Pdi)
+ .map(|root| ReadPath::new(root, Vec::new()))
+ .collect::<BTreeSet<_>>(),
+ ));
+ let mut expected = full.as_object().unwrap().clone();
+ expected.remove("pdi").expect("the full dict carries `pdi`");
+ assert_eq!(
+ build_behavioral_globals(&event, GlobalsBuild::whole(reads_every_root_but_pdi))
+ .unwrap(),
+ Value::Object(expected),
+ "dropping `pdi` from the plan changed more than the `pdi` key",
+ );
+
+ assert_eq!(
+ build_behavioral_globals(&event, GlobalsBuild::whole(GlobalsPlan::NONE)).unwrap(),
+ json!({}),
+ );
+ }
+
+ /// The parse is the bulk of a build's cost, and a payload no root reaches cannot change the
+ /// dict — so an unreadable one must not fail the build either.
+ #[test]
+ fn a_plan_that_reaches_no_payload_parses_neither_and_cannot_fail_on_one() {
+ let mut e = event();
+ e.properties = Some("{not json".to_string());
+ e.person_properties = Some("nope".to_string());
+
+ let reads_event_only =
+ GlobalsPlan::of(&Projection::Reads(BTreeSet::from([ReadPath::new(
+ GlobalRoot::Event,
+ Vec::new(),
+ )])));
+ assert_eq!(
+ build_behavioral_globals(&e, GlobalsBuild::whole(reads_event_only)).unwrap(),
+ json!({ "event": "$pageview" }),
+ );
+
+ // The same event under a plan that does reach `properties` still fails, so the gate is what
+ // spared it and not a swallowed parse error.
+ let reads_properties =
+ GlobalsPlan::of(&Projection::Reads(BTreeSet::from([ReadPath::new(
+ GlobalRoot::Properties,
+ vec!["$browser".to_owned()],
+ )])));
+ assert_eq!(
+ build_behavioral_globals(&e, GlobalsBuild::whole(reads_properties))
+ .unwrap_err()
+ .field,
+ "properties",
+ );
+ }
+
+ /// An omitted root raises `UnknownGlobal` unless a native shares its name, in which case
+ /// `GetGlobal` falls through to `get_fn_reference` and pushes that native as a closure. Only the
+ /// native table matters here; the hog STL reaches the VM through the `CallGlobal` symbol table.
+ #[test]
+ fn no_global_root_name_is_also_a_native_function() {
+ let natives = stl_map();
+ for root in GlobalRoot::all() {
+ assert!(
+ !natives.contains_key(root.as_str()),
+ "the native `{}` shadows a globals root, so omitting that root would push a \
+ closure instead of raising",
+ root.as_str(),
+ );
+ }
+ }
+
#[test]
fn behavioral_globals_emit_the_full_node_key_set() {
- let globals = build_behavioral_globals(&event()).unwrap();
+ let globals =
+ build_behavioral_globals(&event(), GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
let obj = globals.as_object().unwrap();
for key in [
"event",
@@ -208,7 +363,7 @@ mod tests {
// `scan_globals_are_byte_equal_to_event_globals_for_equal_inputs` already pins its output
// to `build_person_property_globals`, so its key set is covered here.
for globals in [
- build_behavioral_globals(&event).unwrap(),
+ build_behavioral_globals(&event, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap(),
build_person_property_globals(&event).unwrap(),
] {
for key in globals.as_object().unwrap().keys() {
@@ -223,7 +378,8 @@ mod tests {
#[test]
fn behavioral_globals_shape_matches_node() {
- let globals = build_behavioral_globals(&event()).unwrap();
+ let globals =
+ build_behavioral_globals(&event(), GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["event"], json!("$pageview"));
assert_eq!(
globals["uuid"],
@@ -263,7 +419,7 @@ mod tests {
let mut e = event();
e.properties = None;
e.person_properties = None;
- let globals = build_behavioral_globals(&e).unwrap();
+ let globals = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["properties"], json!({}));
assert_eq!(globals["person"]["properties"], json!({}));
@@ -288,7 +444,7 @@ mod tests {
let mut e = event();
e.properties = Some(String::new());
e.person_properties = Some(String::new());
- let globals = build_behavioral_globals(&e).unwrap();
+ let globals = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["properties"], json!({}));
assert_eq!(globals["person"]["properties"], json!({}));
assert_eq!(globals["pdi"]["person"]["properties"], json!({}));
@@ -330,7 +486,7 @@ mod tests {
fn malformed_properties_is_an_error() {
let mut e = event();
e.properties = Some("{not json".to_string());
- let err = build_behavioral_globals(&e).unwrap_err();
+ let err = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap_err();
assert_eq!(err.field, "properties");
}
@@ -339,7 +495,9 @@ mod tests {
let mut e = event();
e.person_properties = Some("nope".to_string());
assert_eq!(
- build_behavioral_globals(&e).unwrap_err().field,
+ build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL))
+ .unwrap_err()
+ .field,
"person_properties"
);
assert_eq!(
@@ -352,7 +510,7 @@ mod tests {
fn non_object_properties_pass_through_as_is() {
let mut e = event();
e.properties = Some("[1, 2, 3]".to_string());
- let globals = build_behavioral_globals(&e).unwrap();
+ let globals = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["properties"], json!([1, 2, 3]));
}
@@ -361,11 +519,11 @@ mod tests {
let mut e = event();
e.elements_chain = None;
e.properties = Some(r#"{"$elements_chain":"from-props"}"#.to_string());
- let globals = build_behavioral_globals(&e).unwrap();
+ let globals = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["elements_chain"], json!("from-props"));
e.properties = Some("{}".to_string());
- let globals = build_behavioral_globals(&e).unwrap();
+ let globals = build_behavioral_globals(&e, GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["elements_chain"], Value::Null);
}
@@ -391,7 +549,8 @@ mod tests {
#[test]
fn timestamp_in_built_globals_is_normalized() {
- let globals = build_behavioral_globals(&event()).unwrap();
+ let globals =
+ build_behavioral_globals(&event(), GlobalsBuild::whole(GlobalsPlan::FULL)).unwrap();
assert_eq!(globals["timestamp"], json!("2026-05-26T12:34:56.789Z"));
}
}
diff --git a/rust/cohort-core/src/hogvm/mod.rs b/rust/cohort-core/src/hogvm/mod.rs
index 8fd8d5a704aa..e39518fce205 100644
--- a/rust/cohort-core/src/hogvm/mod.rs
+++ b/rust/cohort-core/src/hogvm/mod.rs
@@ -15,6 +15,7 @@ mod executor;
mod globals;
mod program;
+pub use analysis::{GlobalsBuild, GlobalsPlan};
pub use executor::{
classify_vm_error, evaluate_detailed, CohortEvaluator, EvalOutcome, VmErrorClass,
};
diff --git a/rust/cohort-core/src/lib.rs b/rust/cohort-core/src/lib.rs
index 7f24b3509ab7..9ab63caa9410 100644
--- a/rust/cohort-core/src/lib.rs
+++ b/rust/cohort-core/src/lib.rs
@@ -45,7 +45,7 @@ pub use filters::{
pub use fingerprint::CatalogFingerprint;
pub use hogvm::{
build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortEvaluator,
- ConditionProgram, EvalOutcome, VmErrorClass,
+ ConditionProgram, EvalOutcome, GlobalsBuild, GlobalsPlan, VmErrorClass,
};
pub use leaf_state::{EvictionWindow, LeafStateKey, StateVariant};
pub use partitioner::{partition_for, COHORT_PARTITION_COUNT};
diff --git a/rust/cohort-core/src/metrics.rs b/rust/cohort-core/src/metrics.rs
index 13a67bbace94..615b626663e3 100644
--- a/rust/cohort-core/src/metrics.rs
+++ b/rust/cohort-core/src/metrics.rs
@@ -16,6 +16,11 @@ pub const FILTER_CATALOG_TZ_FALLBACK: &str = "filter_catalog_tz_fallback_total";
/// sustained non-zero level**, it signals drift between that kind's Python hash extractor and the
/// Rust bounds. The two extractors are independent, so alert per `kind` rather than on the sum.
pub const FILTER_CATALOG_INVALID_SHAPE_HASH: &str = "filter_catalog_invalid_shape_hash_total";
+/// Behavioral conditions analyzed at freeze, labelled by `outcome`: `reads` when the read set
+/// narrowed, `missing_bytecode` when the condition kept no program to analyze, otherwise the
+/// `FullColumnsReason` that widened it (counter). A catalog whose conditions mostly widen saves
+/// nothing, so watch the `reads` share rather than the absolute rate.
+pub const FILTER_CATALOG_CONDITION_PROJECTION: &str = "filter_catalog_condition_projection_total";
/// Cohorts classified by composition eligibility at freeze, labelled by `class` (counter).
pub const COHORT_ELIGIBILITY_TOTAL: &str = "cohort_eligibility_total";
/// Cohorts excluded because they sit in a cohort-reference cycle (counter).
diff --git a/rust/cohort-core/tests/analysis_equivalence.rs b/rust/cohort-core/tests/analysis_equivalence.rs
index cfb8d89311c5..8a29472ec158 100644
--- a/rust/cohort-core/tests/analysis_equivalence.rs
+++ b/rust/cohort-core/tests/analysis_equivalence.rs
@@ -13,7 +13,9 @@ use std::collections::{BTreeMap, BTreeSet};
use cohort_core::events::CohortStreamEvent;
use cohort_core::hogvm::analysis::{analyze_condition, GlobalRoot, Projection, ReadPath};
-use cohort_core::{build_behavioral_globals, evaluate_detailed, EvalOutcome};
+use cohort_core::{
+ build_behavioral_globals, evaluate_detailed, EvalOutcome, GlobalsBuild, GlobalsPlan,
+};
use proptest::prelude::*;
use serde_json::{json, Value};
@@ -373,7 +375,8 @@ fn verdict(outcome: EvalOutcome) -> String {
}
fn evaluate(bytecode: &[Value], event: &CohortStreamEvent) -> String {
- let globals = build_behavioral_globals(event).expect("generated payloads are valid JSON");
+ let globals = build_behavioral_globals(event, GlobalsBuild::whole(GlobalsPlan::FULL))
+ .expect("generated payloads are valid JSON");
verdict(evaluate_detailed(bytecode, globals))
}
diff --git a/rust/cohort-core/tests/analysis_parity_corpus.rs b/rust/cohort-core/tests/analysis_parity_corpus.rs
index d89138907c85..09687ac71936 100644
--- a/rust/cohort-core/tests/analysis_parity_corpus.rs
+++ b/rust/cohort-core/tests/analysis_parity_corpus.rs
@@ -14,10 +14,10 @@ use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
-use cohort_core::hogvm::analysis::{analyze_condition, Projection, ReadPath};
+use cohort_core::hogvm::analysis::{analyze_condition, GlobalRoot, Projection, ReadPath};
use cohort_core::{
build_behavioral_globals, classify_vm_error, evaluate_detailed, CohortStreamEvent, EvalOutcome,
- VmErrorClass,
+ GlobalsBuild, GlobalsPlan, VmErrorClass,
};
use serde_json::{json, Map, Value};
@@ -211,6 +211,35 @@ fn every_parity_fixture_decides_the_same_way_from_its_claimed_reads() {
}
}
+/// The root-level counterpart of [`project_globals`].
+fn project_roots(globals: &Value, plan: GlobalsPlan) -> Value {
+ Value::Object(
+ globals
+ .as_object()
+ .expect("a fixture's globals are an object")
+ .iter()
+ .filter(|(key, _)| GlobalRoot::parse(key).is_some_and(|root| plan.reads(root)))
+ .map(|(key, value)| (key.clone(), value.clone()))
+ .collect(),
+ )
+}
+
+/// The path-level equivalence above never runs `GlobalsPlan::of`. A plan that lost the root of a
+/// multi-segment path, claiming `person.properties.plan` but not `person`, would drop that root.
+#[test]
+fn every_parity_fixture_decides_the_same_way_from_its_planned_roots() {
+ for fixture in &fixtures() {
+ let plan = GlobalsPlan::of(&analyze_condition(&fixture.bytecode).projection);
+ let projected = project_roots(&fixture.globals, plan);
+ assert_eq!(
+ matched(&fixture.bytecode, projected, &fixture.name),
+ fixture.expected,
+ "fixture `{}` decided differently once its globals held only the planned roots {plan:?}",
+ fixture.name,
+ );
+ }
+}
+
/// The conditions the compiler lowers through jumps must narrow to a read set.
///
/// This is the regression that matters most: while the interpreter refused branches, every one of
@@ -278,7 +307,8 @@ fn an_absent_group_type_root_claims_no_reads_and_raises_either_way() {
paths.iter().map(ReadPath::render).collect::<Vec<_>>()
);
- let full = build_behavioral_globals(&event()).expect("the event's payloads are valid JSON");
+ let full = build_behavioral_globals(&event(), GlobalsBuild::whole(GlobalsPlan::FULL))
+ .expect("the event's payloads are valid JSON");
let projected = project_globals(&full, &paths);
assert_eq!(
projected,
diff --git a/rust/cohort-seeder/src/clickhouse/scanner.rs b/rust/cohort-seeder/src/clickhouse/scanner.rs
index 7b3620566095..04cdc7285879 100644
--- a/rust/cohort-seeder/src/clickhouse/scanner.rs
+++ b/rust/cohort-seeder/src/clickhouse/scanner.rs
@@ -544,7 +544,12 @@ fn active_event_names(run: &PinnedRun, active: &ActiveConditions) -> EventNameSe
run.filters
.behavioral_by_event_name
.get(*event_name)
- .is_some_and(|hashes| hashes.iter().any(|hash| active.get(hash).is_some()))
+ .is_some_and(|bucket| {
+ bucket
+ .conditions
+ .iter()
+ .any(|hash| active.get(hash).is_some())
+ })
})
.cloned(),
)
@@ -682,6 +687,32 @@ mod tests {
builder.freeze(UTC)
}
+ /// The same catalog, with the condition reading `properties` instead of `event`. A team whose
+ /// conditions name no payload never parses one, so only this catalog can fail on a malformed
+ /// `properties`.
+ fn filters_reading_properties() -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(2),
+ &json!({
+ "properties": { "type": "AND", "values": [{
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": "purchase",
+ "conditionHash": HASH,
+ "time_value": 7,
+ "time_interval": "day",
+ // properties.x == "1"
+ "bytecode": ["_H", 1, 32, "1", 32, "x", 32, "properties", 1, 2, 11]
+ }]}
+ }),
+ )
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
fn row(timestamp: &str) -> EventRow {
EventRow {
uuid: Uuid::from_u128(1).to_string(),
@@ -698,18 +729,20 @@ mod tests {
#[test]
fn scan_fold_skips_bad_timestamps_wrong_days_and_malformed_globals() {
let domain = domain();
- let filters = filters();
let active = ActiveConditions::new([ConditionHash::parse(HASH).unwrap()]);
let cases = [
(
+ filters(),
row("not-a-timestamp"),
ScanEventOutcome::Skipped(ScanSkipReason::TimestampParse),
),
(
+ filters(),
row("1970-01-03 12:00:00.000000"),
ScanEventOutcome::Skipped(ScanSkipReason::DayMismatch),
),
(
+ filters_reading_properties(),
EventRow {
properties: "not-json".to_string(),
..row("1970-01-02 12:00:00.000000")
@@ -717,7 +750,7 @@ mod tests {
ScanEventOutcome::Skipped(ScanSkipReason::GlobalsParseError),
),
];
- for (row, expected) in cases {
+ for (filters, row, expected) in cases {
let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();
assert_eq!(
fold_event(&domain, &mut accumulator, row_to_event(TeamId(2), row)).unwrap(),
diff --git a/rust/cohort-seeder/src/domain/aggregate.rs b/rust/cohort-seeder/src/domain/aggregate.rs
index 720e9efdde30..81324b4a6a8b 100644
--- a/rust/cohort-seeder/src/domain/aggregate.rs
+++ b/rust/cohort-seeder/src/domain/aggregate.rs
@@ -10,7 +10,7 @@ use cohort_core::events::CohortStreamEvent;
use cohort_core::filters::{TeamFilters, TeamId};
use cohort_core::hogvm::{
build_behavioral_globals, classify_vm_error, CohortEvaluator, ConditionProgram, EvalOutcome,
- VmErrorClass,
+ GlobalsBuild, VmErrorClass,
};
use uuid::Uuid;
@@ -75,6 +75,9 @@ struct ActiveCandidate {
pub struct ChunkAccumulator {
team_id: TeamId,
active_by_event_name: HashMap<String, Vec<ActiveCandidate>>,
+ /// The team's whole behavioral plan, the same one the live path parses under — a seed that
+ /// parsed a payload live never reads would diverge from live on a malformed one.
+ globals_build: GlobalsBuild,
evaluator: CohortEvaluator,
counts: HashMap<(Uuid, ConditionHash), NonZeroU32>,
}
@@ -88,8 +91,9 @@ impl ChunkAccumulator {
let active_by_event_name = filters
.behavioral_by_event_name
.iter()
- .map(|(event_name, candidates)| {
- let candidates = candidates
+ .map(|(event_name, bucket)| {
+ let candidates = bucket
+ .conditions
.iter()
.filter_map(|candidate| active.get(candidate).map(|hash| (candidate, hash)))
.map(|(candidate, hash)| {
@@ -111,6 +115,7 @@ impl ChunkAccumulator {
Ok(Self {
team_id,
active_by_event_name,
+ globals_build: GlobalsBuild::whole(filters.behavioral.plan),
evaluator: CohortEvaluator::new(),
counts: HashMap::new(),
})
@@ -135,7 +140,7 @@ impl ChunkAccumulator {
if self.active_by_event_name.is_empty() {
return Ok(RecordOutcome::Evaluated(RecordStats::default()));
}
- let Ok(globals) = build_behavioral_globals(event) else {
+ let Ok(globals) = build_behavioral_globals(event, self.globals_build) else {
return Ok(RecordOutcome::SkippedGlobals);
};
self.evaluator.set_globals(globals);
@@ -293,6 +298,26 @@ mod tests {
builder.freeze(UTC)
}
+ /// The same catalog, with condition `a` also reading `properties`. A team whose conditions name
+ /// no payload never parses one, so only this catalog can fail on a malformed `properties`.
+ fn filters_reading_properties() -> TeamFilters {
+ let mut builder = TeamFiltersBuilder::default();
+ builder
+ .add_cohort(
+ CohortId(1),
+ TeamId(2),
+ &json!({
+ "properties": { "type": "AND", "values": [
+ // event == "a" AND properties.x == "1"
+ { "type": "behavioral", "value": "performed_event", "key": "a", "conditionHash": HASH_A, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 32, "a", 32, "event", 1, 1, 11, 32, "1", 32, "x", 32, "properties", 1, 2, 11, 3, 2] },
+ { "type": "behavioral", "value": "performed_event", "key": "b", "conditionHash": HASH_B, "time_value": 7, "time_interval": "day", "bytecode": ["_H", 1, 32, "b", 32, "event", 1, 1, 11] },
+ ]}
+ }),
+ )
+ .unwrap();
+ builder.freeze(UTC)
+ }
+
fn event(person: Uuid, event_name: &str) -> CohortStreamEvent {
CohortStreamEvent {
team_id: 2,
@@ -437,12 +462,16 @@ mod tests {
#[test]
fn malformed_globals_skip_only_that_event_and_leave_counts_unchanged() {
- let filters = filters();
+ let filters = filters_reading_properties();
let active = active();
let mut accumulator = ChunkAccumulator::new(TeamId(2), &filters, &active).unwrap();
let person = Uuid::from_u128(1);
+ let matching = || CohortStreamEvent {
+ properties: Some(r#"{"x":"1"}"#.to_string()),
+ ..event(person, "a")
+ };
assert_eq!(
- evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,
+ evaluated(accumulator.record_event(&matching()).unwrap()).matched,
1
);
@@ -454,7 +483,7 @@ mod tests {
);
assert_eq!(accumulator.entry_count(), 1);
assert_eq!(
- evaluated(accumulator.record_event(&event(person, "a")).unwrap()).matched,
+ evaluated(accumulator.record_event(&matching()).unwrap()).matched,
1
);
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index b39e665ebb99..d96946fe26e9 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -5,8 +5,9 @@ use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle};
// The `cohort-core`-owned metric names this binary emits: its metric-surface manifest.
pub use cohort_core::metrics::{
COHORT_ELIGIBILITY_TOTAL, COHORT_IN_CYCLE_TOTAL, FILTER_CATALOG_COHORT_PARSE_ERRORS,
- FILTER_CATALOG_INVALID_SHAPE_HASH, FILTER_CATALOG_SKIPPED_LEAVES, FILTER_CATALOG_TZ_FALLBACK,
- STAGE1_GLOBALS_PARSE_ERROR, STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION,
+ FILTER_CATALOG_CONDITION_PROJECTION, FILTER_CATALOG_INVALID_SHAPE_HASH,
+ FILTER_CATALOG_SKIPPED_LEAVES, FILTER_CATALOG_TZ_FALLBACK, STAGE1_GLOBALS_PARSE_ERROR,
+ STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUNCTION,
};
/// Teams with ≥1 realtime cohort in the current catalog snapshot (gauge).
@@ -283,6 +284,10 @@ pub const STAGE1_EVENTS_PROCESSED: &str = "stage1_events_processed_total";
pub const STAGE1_EVENTS_SKIPPED: &str = "stage1_events_skipped_total";
/// HogVM evaluations, labelled by `kind` — one per unique conditionHash per event (counter).
pub const STAGE1_CONDITIONS_EVALUATED: &str = "stage1_conditions_evaluated_total";
+/// Behavioral globals builds, labelled by `result`: `built`, `no_candidates` when no condition can
+/// match so neither payload is parsed, or `parse_error` (counter). `no_candidates` conflates an
+/// unbucketed event name with a team that has no behavioral condition; scope by team to separate.
+pub const STAGE1_GLOBALS_BUILDS: &str = "stage1_globals_builds_total";
/// Condition evaluations skipped because the result was already known, labelled by `reason`
/// (`event_name_gate`) (counter).
pub const STAGE1_CONDITIONS_SKIPPED: &str = "stage1_conditions_skipped_total";
diff --git a/rust/cohort-stream-processor/src/workers/event_path.rs b/rust/cohort-stream-processor/src/workers/event_path.rs
index b08ff444c730..a6a73d677d2a 100644
--- a/rust/cohort-stream-processor/src/workers/event_path.rs
+++ b/rust/cohort-stream-processor/src/workers/event_path.rs
@@ -18,13 +18,15 @@ use metrics::{counter, histogram};
use uuid::Uuid;
use crate::consumers::events::CohortStreamEvent;
-use crate::filters::reverse_index::TeamFilters;
+use crate::filters::reverse_index::{BehavioralCandidates, TeamFilters};
use crate::filters::TeamId;
-use crate::hogvm::{build_behavioral_globals, build_person_property_globals, CohortEvaluator};
+use crate::hogvm::{
+ build_behavioral_globals, build_person_property_globals, CohortEvaluator, GlobalsBuild,
+};
use crate::observability::metrics::{
STAGE1_BEHAVIORAL_APPLIES, STAGE1_CONDITIONS_EVALUATED, STAGE1_CONDITIONS_SKIPPED,
- STAGE1_PERSON_RECORD_SIZE_BYTES, STAGE1_PERSON_RECORD_TOTAL, STAGE1_REPLAY_SKIPPED,
- STAGE1_SNAPSHOT_KEYS, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,
+ STAGE1_GLOBALS_BUILDS, STAGE1_PERSON_RECORD_SIZE_BYTES, STAGE1_PERSON_RECORD_TOTAL,
+ STAGE1_REPLAY_SKIPPED, STAGE1_SNAPSHOT_KEYS, STAGE1_STATE_DECODE_ERROR, STAGE1_STATE_WRITES,
STAGE1_UNSUPPORTED_VARIANT_SKIPPED,
};
use crate::stage1::bucket_tz::{
@@ -78,6 +80,8 @@ pub enum SkipReason {
UnparseablePersonId,
NoTeamFilters,
NoConditions,
+ /// `person_properties` failed to parse. A malformed `properties` does not reach here; it drops
+ /// the behavioral side and leaves the person side to run.
GlobalsParseError,
BadTimestamp,
}
@@ -403,35 +407,14 @@ pub(crate) fn plan_event(
.as_deref()
.and_then(|raw| Uuid::parse_str(raw).ok());
- let has_behavioral = !filters.behavioral_conditions.is_empty();
+ let has_behavioral = !filters.behavioral.conditions.is_empty();
let has_person = !filters.person_property_conditions.is_empty();
if !has_behavioral && !has_person {
return EventPlan::Skip(SkipReason::NoConditions);
}
- // Build behavioral globals before any evaluation, so a malformed payload skips the event before
- // any condition runs. The person side parses its own globals only on the evaluation arm, in the fold.
- let behavioral_globals = if has_behavioral {
- match build_behavioral_globals(event) {
- Ok(globals) => Some(globals),
- Err(_) => return EventPlan::Skip(SkipReason::GlobalsParseError),
- }
- } else {
- None
- };
-
- let mut evaluator = CohortEvaluator::new();
let mut behavioral: Vec<BehavioralApply> = Vec::new();
- if let Some(globals) = behavioral_globals {
- evaluator.set_globals(globals);
- collect_behavioral_applies(
- filters,
- &event.event,
- event_name_gating,
- &mut evaluator,
- &mut behavioral,
- );
- }
+ collect_behavioral_applies(filters, event, event_name_gating, &mut behavioral);
// Fingerprints are computed here; the record read and evaluation happen in the fold.
let person = match active_person_props(filters, event) {
@@ -793,37 +776,62 @@ fn active_person_props<'a>(filters: &TeamFilters, event: &'a CohortStreamEvent)
.filter(|raw| !raw.is_empty())
}
-/// Evaluate this event's behavioral conditions against the set globals, pushing a [`BehavioralApply`]
-/// per matching leaf. Under [`EventNameGating::Enabled`] only the event's name bucket is evaluated.
+/// Evaluate this event's behavioral conditions, pushing a [`BehavioralApply`] per matching leaf.
+///
+/// The candidates resolve before the globals are built, so an event no condition roots at pays for
+/// neither JSON parse. A malformed payload drops the behavioral side and leaves the person side to
+/// run: skipping the whole event here would make the gating flag a correctness switch, because an
+/// event outside every bucket is never parsed and so never skipped, while the sweep parses it,
+/// fails, and skips.
fn collect_behavioral_applies(
filters: &TeamFilters,
- event_name: &str,
+ event: &CohortStreamEvent,
gating: EventNameGating,
- evaluator: &mut CohortEvaluator,
applies: &mut Vec<BehavioralApply>,
) {
+ let Some(candidates) = behavioral_candidates(filters, &event.event, gating) else {
+ counter!(STAGE1_GLOBALS_BUILDS, "result" => "no_candidates").increment(1);
+ return;
+ };
+ // The whole team's plan decides which payloads are parsed, so the two gating arms agree on
+ // whether this event's payloads are malformed even though they materialize different roots.
+ let build = GlobalsBuild::narrowed(candidates.plan, filters.behavioral.plan);
+ let Ok(globals) = build_behavioral_globals(event, build) else {
+ counter!(STAGE1_GLOBALS_BUILDS, "result" => "parse_error").increment(1);
+ return;
+ };
+ counter!(STAGE1_GLOBALS_BUILDS, "result" => "built").increment(1);
+ let mut evaluator = CohortEvaluator::new();
+ evaluator.set_globals(globals);
+ for &hash in &candidates.conditions {
+ eval_behavioral_condition(filters, hash, &mut evaluator, applies);
+ }
+}
+
+/// What one event can match under `gating`, or `None` when nothing can — the case that skips both
+/// JSON parses. The `event_name_gate` count is emitted either way, so a gated-out condition still
+/// counts on an unparsed event.
+fn behavioral_candidates<'a>(
+ filters: &'a TeamFilters,
+ event_name: &str,
+ gating: EventNameGating,
+) -> Option<&'a BehavioralCandidates> {
match gating {
EventNameGating::Disabled => {
- for &hash in &filters.behavioral_conditions {
- eval_behavioral_condition(filters, hash, evaluator, applies);
- }
+ (!filters.behavioral.conditions.is_empty()).then_some(&filters.behavioral)
}
EventNameGating::Enabled => {
- let matched = filters
- .behavioral_by_event_name
- .get(event_name)
- .map_or(&[][..], Vec::as_slice);
- let skipped = filters
- .behavioral_conditions
+ let bucket = filters.behavioral_by_event_name.get(event_name);
+ let gated_out = filters
+ .behavioral
+ .conditions
.len()
- .saturating_sub(matched.len());
- if skipped > 0 {
+ .saturating_sub(bucket.map_or(0, |bucket| bucket.conditions.len()));
+ if gated_out > 0 {
counter!(STAGE1_CONDITIONS_SKIPPED, "reason" => "event_name_gate")
- .increment(skipped as u64);
- }
- for &hash in matched {
- eval_behavioral_condition(filters, hash, evaluator, applies);
+ .increment(gated_out as u64);
}
+ bucket
}
}
}
diff --git a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs b/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
index d43d4d52b7e1..2a8cb7d24fe7 100644
--- a/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
+++ b/rust/cohort-stream-processor/tests/event_name_gating_parity.rs
@@ -1,7 +1,6 @@
//! 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. Covers a matching name, a non-matching name, and
-//! numeric-looking names (`"0"` vs `"0.0"`) that must not cross-match.
+//! `cf_behavioral` and the same leaf transitions.
// Tests seed and assert through `CohortStore` directly — the sanctioned direct-store test surface.
#![allow(clippy::disallowed_methods)]
@@ -14,6 +13,7 @@ use cohort_stream_processor::filters::{CohortId, TeamFilters, TeamFiltersBuilder
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;
@@ -26,6 +26,7 @@ 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 {
@@ -93,6 +94,45 @@ fn catalog() -> TeamFilters {
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.
@@ -116,6 +156,39 @@ fn multi_condition_catalog() -> TeamFilters {
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,
@@ -177,14 +250,18 @@ fn sorted_transitions(transitions: &[LeafTransition]) -> Vec<LeafTransition> {
sorted
}
-/// Feeds each event to two independent stores — gating ON and OFF — and asserts parity after every
-/// step. Gating is the only varying axis; the person leaf never matches, so the person record is
-/// identical on both sides and the gate's effect is confined to `cf_behavioral`.
+/// 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 {
@@ -196,6 +273,8 @@ impl GatingParity {
_off_dir: off_dir,
on_store,
off_store,
+ on_metrics: String::new(),
+ off_metrics: String::new(),
}
}
@@ -205,22 +284,33 @@ impl GatingParity {
event: &CohortStreamEvent,
label: &str,
) -> EventOutcome {
- let on = process_event_gated(
- PARTITION,
- &self.on_store,
- filters,
- event,
- EventNameGating::Enabled,
- )
+ 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();
- let off = process_event_gated(
- PARTITION,
- &self.off_store,
- filters,
- event,
- EventNameGating::Disabled,
- )
+ 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");
@@ -310,7 +400,9 @@ fn gating_matches_full_sweep_on_a_multi_condition_event_name_bucket() {
// daily-bucket write path), and both leaves must flip.
let filters = multi_condition_catalog();
assert_eq!(
- filters.behavioral_by_event_name["$pageview"].len(),
+ filters.behavioral_by_event_name["$pageview"]
+ .conditions
+ .len(),
2,
"the $pageview bucket holds both conditionHashes",
);
@@ -337,3 +429,87 @@ fn gating_matches_full_sweep_on_a_multi_condition_event_name_bucket() {
"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);
+}
diff --git a/rust/cohort-stream-processor/tests/person_record_fold.rs b/rust/cohort-stream-processor/tests/person_record_fold.rs
index 7b20db0e3925..2c62ff13b653 100644
--- a/rust/cohort-stream-processor/tests/person_record_fold.rs
+++ b/rust/cohort-stream-processor/tests/person_record_fold.rs
@@ -304,6 +304,54 @@ fn row3_argmax_stale_event_advances_dedup_and_last_seen_but_not_membership() {
);
}
+/// Gives the team a behavioral condition, so the event path builds the behavioral globals.
+fn behavioral_leaf() -> Value {
+ json!({
+ "type": "behavioral", "value": "performed_event", "key": "$pageview",
+ "time_value": 7, "time_interval": "day",
+ "conditionHash": "pageviewhash0003",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ })
+}
+
+/// Row 3 with a behavioral condition, which is what makes the globals build parse
+/// `person_properties` this early. Guards the tempting repair: checking `GlobalsError::field` in
+/// `plan_event` would skip this event and break the gate's arm parity, because a gated-out event
+/// never runs that check.
+#[test]
+fn a_stale_event_with_malformed_person_properties_still_advances_the_record() {
+ let (_dir, store) = temp_store();
+ let f = filters(vec![email_leaf(), plan_leaf(), behavioral_leaf()]);
+ let alice = person(1);
+
+ feed(
+ &store,
+ &f,
+ &event(alice, PRO, 0, "2026-05-26 13:00:00.000000"),
+ );
+ let before = record(&store, alice).unwrap();
+
+ let older = CohortStreamEvent {
+ source_partition: 9,
+ ..event(alice, "{not json", 5, "2026-05-26 12:00:00.000000")
+ };
+ let out = feed(&store, &f, &older);
+
+ assert_eq!(out.skipped, None, "the event is folded, not skipped");
+ assert!(out.transitions.is_empty());
+ let after = record(&store, alice).unwrap();
+ assert_eq!(after.matched, before.matched, "no evaluation happened");
+ assert_eq!(after.stamp, before.stamp, "argMax kept the newer stamp");
+ assert_eq!(
+ after.props_fingerprint, before.props_fingerprint,
+ "a fingerprint from an unparseable payload would let a later copy of it reach SkipEval",
+ );
+ assert!(
+ after.applied_offsets.is_replay(9, 5),
+ "the stale event still recorded its offset",
+ );
+}
+
/// The stamp-advance counterexample: without row 4a advancing the stamp, an out-of-order event landing
/// between the old and new stamps would wrongly win argMax. Because 4a advances it, that middle event
/// is stale.
diff --git a/rust/cohort-stream-processor/tests/stage1_worker.rs b/rust/cohort-stream-processor/tests/stage1_worker.rs
index f58a6ddca47d..1a36a254b16b 100644
--- a/rust/cohort-stream-processor/tests/stage1_worker.rs
+++ b/rust/cohort-stream-processor/tests/stage1_worker.rs
@@ -413,7 +413,7 @@ fn c1_same_hash_two_windows_get_independent_state_and_deadlines() {
let lsks = &filters.by_condition_to_lsk[&BEHAVIORAL_HASH];
assert_eq!(lsks.len(), 2, "two distinct LSKs under one conditionHash");
assert_eq!(
- filters.behavioral_conditions.len(),
+ filters.behavioral.conditions.len(),
1,
"one unique conditionHash → one HogVM eval that fans out",
);
@@ -918,46 +918,89 @@ fn out_of_order_person_events_keep_the_latest_by_event_time() {
#[test]
fn whole_event_skips_carry_distinct_reasons() {
let (_dir, store) = temp_store();
- let filters = build_team_filters(vec![(
- CohortId(1),
- cohort(vec![behavioral_leaf(7), person_leaf()]),
- )]);
+ // `event == "$pageview" AND properties.x == "1"`. The behavioral condition has to read
+ // `properties` for the build to parse that payload at all, so that a malformed one can fail.
+ let mut behavioral = behavioral_leaf(7);
+ behavioral["bytecode"] = json!([
+ "_H",
+ 1,
+ 32,
+ "$pageview",
+ 32,
+ "event",
+ 1,
+ 1,
+ 11,
+ 32,
+ "1",
+ 32,
+ "x",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 11,
+ 3,
+ 2,
+ ]);
+ let filters = build_team_filters(vec![(CohortId(1), cohort(vec![behavioral, person_leaf()]))]);
- type SkipCase = (&'static str, fn(&mut CohortStreamEvent), SkipReason);
+ type SkipCase = (
+ &'static str,
+ fn(&mut CohortStreamEvent),
+ Option<SkipReason>,
+ &'static [[u8; 16]],
+ );
let cases: [SkipCase; 5] = [
(
"empty person id",
|e| e.person_id = String::new(),
- SkipReason::NullPersonId,
+ Some(SkipReason::NullPersonId),
+ &[],
),
(
"non-uuid person id",
|e| e.person_id = "not-a-uuid".to_string(),
- SkipReason::UnparseablePersonId,
+ Some(SkipReason::UnparseablePersonId),
+ &[],
),
(
"unparseable timestamp",
|e| e.timestamp = "nonsense".to_string(),
- SkipReason::BadTimestamp,
+ Some(SkipReason::BadTimestamp),
+ &[],
),
+ // `properties` is behavioral-only data, so a malformed payload drops the behavioral side
+ // and lets the person side run — the event's `person_properties` match the person leaf.
(
"malformed properties",
|e| e.properties = Some("{not json".to_string()),
- SkipReason::GlobalsParseError,
+ None,
+ &[PERSON_HASH],
),
(
"malformed person_properties",
|e| e.person_properties = Some("nope".to_string()),
- SkipReason::GlobalsParseError,
+ Some(SkipReason::GlobalsParseError),
+ &[],
),
];
- for (name, mutate, expected) in cases {
- let mut ev = event(person(1), 1, 0);
+ // One person and one offset per case: the malformed-`properties` case writes a person record,
+ // which would make the next case a replay and send it down an arm that never parses.
+ for (index, (name, mutate, expected, transitions)) in cases.into_iter().enumerate() {
+ let mut ev = event(person(index as u128 + 1), 1, index as i64);
mutate(&mut ev);
let out = process_event(PARTITION_ID, &store, &filters, &ev).unwrap();
- assert_eq!(out.skipped, Some(expected), "{name}");
- assert!(out.transitions.is_empty(), "{name}");
+ assert_eq!(out.skipped, expected, "{name}");
+ assert_eq!(
+ out.transitions
+ .iter()
+ .map(|transition| transition.condition_hash)
+ .collect::<Vec<_>>(),
+ transitions,
+ "{name}",
+ );
}
let empty = TeamFiltersBuilder::default().freeze(UTC);
diff --git a/rust/cohort-stream-processor/tests/sweep_worker.rs b/rust/cohort-stream-processor/tests/sweep_worker.rs
index b76ce677d019..9d8e6ed927cb 100644
--- a/rust/cohort-stream-processor/tests/sweep_worker.rs
+++ b/rust/cohort-stream-processor/tests/sweep_worker.rs
@@ -1821,7 +1821,7 @@ fn explicit_range_with_an_unparseable_bound_skips_the_leaf_entirely() {
"garbage",
)]);
assert!(
- explicit.behavioral_conditions.is_empty(),
+ explicit.behavioral.conditions.is_empty(),
"an unparseable bound leaves the leaf with no behavioral condition",
);
let alice = person(1);